ATLAS Offline Software
pythonic_coracool.cxx
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3 */
4 
5 // Efficient pythonic CoraCool bindings
6 // Author: <peter.waller@cern.ch> Jan 2010
7 
8 #define likely(x) __builtin_expect((x),1)
9 #define unlikely(x) __builtin_expect((x),0)
10 
11 #include <Python.h>
12 
13 #include <CoolKernel/ChannelSelection.h>
14 #include <CoolKernel/IFolder.h>
15 #include <CoolKernel/IDatabase.h>
16 
17 #include "CoralBase/Attribute.h"
18 #include "CoralBase/AttributeList.h"
19 #include "CoralBase/AttributeListSpecification.h"
20 
27 
28 #include <functional>
29 
30 #include <string>
31 #include <iostream>
32 
35 
36 using std::cout;
37 using std::endl;
38 using std::string;
39 using std::vector;
40 
41 using std::bind;
42 using std::placeholders::_1;
43 using cool::IFolderPtr;
44 using cool::IDatabasePtr;
45 using cool::ChannelSelection;
46 using cool::ValidityKey;
47 using coral::Attribute;
48 using coral::AttributeSpecification;
50 
51 typedef std::function<PyObject* (const AttributeList&)>
53 
54 // A function to signal that a conversion object could not be found
56 
57 // Re-use these two functions from quick_retrieve.cxx
59 PyObject *qr_PyString_FromStdString(const string& str);
60 
61 template<typename T>
62 const T& fetch_attribute_data(const coral::Attribute& A)
63 {
64  return A.data<T>();
65 }
66 
67 // Returns a functor which returns a Python object for the attribute with
68 // a given name and type. Test type_name against a series of fetchers.
69 // If none are found, no_coral_conversion_available is returned.
71  const string& type_name)
72 {
73  // Test type against type_name. If true, return a functor for this type.
74  // Be sure to use only a copy of name --- the original may not be valid
75  // by the time the lambda is called.
76  std::string sname = name;
77  #define MAKE_FETCHER(type, converter) \
78  if (type_name == #type) { \
79  return [sname] (const AttributeList& l) -> PyObject* \
80  { return converter(fetch_attribute_data<type>(l[sname])); }; \
81  }
82 
83  // See the python c-api reference for python conversion functions
84  // Python/C API Reference Manual >> Concrete Objects Layer
85  // http://docs.python.org/c-api/concrete.html
86 
87  MAKE_FETCHER(short, PyLong_FromLong)
88  MAKE_FETCHER(int, PyLong_FromLong)
89  MAKE_FETCHER(long long, PyLong_FromLongLong)
90 
91  /*
92 
93  Types from COOL:
94  We need to build up a similar list from CORAL, it would be nice to know
95  where they came from.
96 
97  MAKE_FETCHER(Bool, PyBool_FromLong)
98  MAKE_FETCHER(Float, PyFloat_FromDouble)
99  MAKE_FETCHER(Double, PyFloat_FromDouble)
100  MAKE_FETCHER(UChar, PyLong_FromLong)
101  MAKE_FETCHER(UInt16, PyLong_FromUnsignedLong)
102  MAKE_FETCHER(UInt32, PyLong_FromUnsignedLong)
103  MAKE_FETCHER(UInt63, PyLong_FromUnsignedLongLong)
104  MAKE_FETCHER(UInt64, PyLong_FromUnsignedLongLong)
105  MAKE_FETCHER(String255, qr_PyString_FromStdString)
106  MAKE_FETCHER(String4k, qr_PyString_FromStdString)
107  MAKE_FETCHER(String64k, qr_PyString_FromStdString)
108  MAKE_FETCHER(String16M, qr_PyString_FromStdString)
109  MAKE_FETCHER(Blob16M, qr_PyString_FromBlob)
110  MAKE_FETCHER(Blob64k, qr_PyString_FromBlob)
111  */
112 
113  PyErr_Format(PyExc_RuntimeError,
114  "Type '%s' is not in type conversion table. "
115  "Please add it to pythonic_coracool.cxx. "
116  "Can't convert field '%s'.",
117  type_name.c_str(),
118  name);
120 }
121 
122 // From a list of python strings (to_fetch) (which are attribute names)
123 // Create a fetcher for each attribute, and insert them into the
124 // payload_fetchers vector
126  PyObject *to_fetch,
127  const AttributeList& attribute_list,
128  vector<coral_attribute_fetcher_t>& payload_fetchers)
129 {
130  const Py_ssize_t count = to_fetch ? PySequence_Size(to_fetch) : 0;
131 
132  for (Py_ssize_t i = 0; i < count; i++)
133  {
134  PyObject *py_name = PySequence_GetItem(to_fetch, i);
135  const char *name = _PyUnicode_AsString(py_name);
136  const string type = attribute_list[name].specification().typeName();
137 
139 
140  auto pff = pf.target<PyObject* (*)(const AttributeList&)>();
141  if ( pff && *pff == &no_coral_conversion_available)
142  return false; // Failure: A python exception was thrown above
143 
144  payload_fetchers.push_back(pf);
145  Py_DECREF(py_name);
146  }
147 
148  return true; // Success
149 }
150 
151 inline PyObject *apply_function(PyObject *function, PyObject *object)
152 {
153  // Convert object according to function, taking care of references
154  // If function is null, return unmodified object
155  if (!function || function == Py_None) return object;
156  PyObject *old_object = object;
157  PyObject *new_object = PyObject_CallObject(function, object);
158  Py_DECREF(old_object);
159  return new_object;
160 }
161 
162 CoraCoolFolderPtr fetch_coracool_folder(IDatabasePtr cooldb, const string & folder)
163 {
164  CoraCoolDatabaseSvc& corasvc = CoraCoolDatabaseSvcFactory::
165  databaseService();
166 
167  CoraCoolDatabasePtr coradb = corasvc.openDatabase(
168  cooldb->databaseId(), cooldb, true);
169 
170  return coradb->getFolder(folder);
171 }
172 
173 const cool::RecordSpecification
174  get_coracool_payload_spec(IDatabasePtr cooldb, const string & folder)
175 {
176  return fetch_coracool_folder(cooldb, folder)->payloadSpecification();
177 }
178 
179 inline PyObject* make_iov_key(PyObject *iovkey_wrapper,
180  unsigned long long value)
181 {
182  static const char * const argtypes = const_cast<char *>("K");
183  if (iovkey_wrapper && iovkey_wrapper != Py_None)
184  return PyObject_CallFunction(iovkey_wrapper, argtypes, value);
185  return PyLong_FromUnsignedLongLong(value);
186 }
187 
188 PyObject *browse_coracool(IDatabasePtr cooldb, const string & folder,
189  ValidityKey since, ValidityKey until,
190  const ChannelSelection &cs = ChannelSelection::all(),
191  const char *tag="",
192  PyObject *to_fetch = NULL,
193  PyObject *object_converter = NULL,
194  PyObject *inner_object_converter = NULL,
195  PyObject *iovkey_wrapper = NULL)
196 {
197  // Browse CoraCool objects
198  CoraCoolFolderPtr coralFolder = fetch_coracool_folder(cooldb, folder);
199  CoraCoolObjectIterPtr objects = coralFolder->browseObjects(since, until,
200  cs, tag);
201 
202  // Number of attributes to be fetched
203  const Py_ssize_t count = to_fetch ? PySequence_Size(to_fetch) : 0;
204 
205  PyObject* result = PyList_New(0); // List which is returned by this function
206  bool first = true; // Is this the first iteration?
207  CoraCoolObject::const_iterator payload; // Current payload
208 
209  // List of functors which convert an Attribute into a python value
210  vector<coral_attribute_fetcher_t> payload_fetchers;
211 
212  // Loop over IoVs
213  while (objects->hasNext())
214  {
215  const CoraCoolObjectPtr& object = objects->next();
216 
217  PyObject *py_payload_tuple = PyTuple_New(object->size());
218  unsigned int payload_index = 0;
219 
220  // Loop over multiple payloads per record
221  for (payload = object->begin();
222  payload != object->end();
223  ++payload, ++payload_index)
224  {
225  if (unlikely(first))
226  {
227  // On the first iteration, figure out the types and create
228  // specialised functions for retrieving them
229  first = false;
230  if (!make_fetchers(to_fetch, *payload, payload_fetchers))
231  return NULL; // Failure, throw python exception from above
232  }
233 
234  // Create a tuple for the payload and fill it from payload fetchers
235  PyObject *py_payload = PyTuple_New(count);
236  for (Py_ssize_t i = 0; i < count; i++)
237  PyTuple_SET_ITEM(py_payload, i, payload_fetchers[i](*payload));
238 
239  py_payload = apply_function(inner_object_converter, py_payload);
240 
241  if (!py_payload)
242  {
243  // apply_function returned an error
244  // We won't return the list to python so we need to tell python it
245  // can be deleted
246  Py_DECREF(py_payload_tuple);
247  Py_DECREF(result);
248  return NULL;
249  }
250 
251  PyTuple_SET_ITEM(py_payload_tuple, payload_index, py_payload);
252  }
253 
254  PyObject *one = PyTuple_New(4);
255 
256  PyTuple_SET_ITEM(one, 0, make_iov_key(iovkey_wrapper, object->since()));
257  PyTuple_SET_ITEM(one, 1, make_iov_key(iovkey_wrapper, object->until()));
258 
259  PyTuple_SET_ITEM(one, 2, PyLong_FromLong(object->channelId()));
260 
261  // SET_ITEM steals reference, no decref needed
262  PyTuple_SET_ITEM(one, 3, py_payload_tuple);
263 
264  one = apply_function(object_converter, one);
265  if (!one)
266  {
267  // apply_function returned an error
268  // We won't return the list to python so we need to tell python it
269  // can be deleted
270  Py_DECREF(result);
271  return NULL;
272  }
273 
274  PyList_Append(result, one);
275  Py_DECREF(one);
276  }
277 
278  return result;
279 }
get_generator_info.result
result
Definition: get_generator_info.py:21
make_fetchers
bool make_fetchers(PyObject *to_fetch, const AttributeList &attribute_list, vector< coral_attribute_fetcher_t > &payload_fetchers)
Definition: pythonic_coracool.cxx:125
LArConditions2Ntuple.objects
objects
Definition: LArConditions2Ntuple.py:64
CoraCoolDatabaseSvc.h
create_attribute_fetcher
coral_attribute_fetcher_t create_attribute_fetcher(const char *name, const string &type_name)
Definition: pythonic_coracool.cxx:70
Trk::one
@ one
Definition: TrkDetDescr/TrkSurfaces/TrkSurfaces/RealQuadraticEquation.h:22
python.subdetectors.tile.Blob
Blob
Definition: tile.py:17
athena.value
value
Definition: athena.py:124
CoraCoolDatabaseSvc
Definition: CoraCoolDatabaseSvc.h:25
python.PyKernel.AttributeList
AttributeList
Definition: PyKernel.py:36
python.CaloAddPedShiftConfig.type
type
Definition: CaloAddPedShiftConfig.py:42
XMLtoHeader.count
count
Definition: XMLtoHeader.py:84
CoraCoolObject.h
python.AthDsoLogger.argtypes
argtypes
Definition: AthDsoLogger.py:43
dq_defect_copy_defect_database.since
def since
Definition: dq_defect_copy_defect_database.py:54
dq_defect_copy_defect_database.until
def until
Definition: dq_defect_copy_defect_database.py:55
CoraCoolObject::const_iterator
AttrListVec::const_iterator const_iterator
Definition: CoraCoolObject.h:23
A
lumiFormat.i
int i
Definition: lumiFormat.py:85
get_coracool_payload_spec
const cool::RecordSpecification get_coracool_payload_spec(IDatabasePtr cooldb, const string &folder)
Definition: pythonic_coracool.cxx:174
unlikely
#define unlikely(x)
Definition: pythonic_coracool.cxx:9
apply_function
PyObject * apply_function(PyObject *function, PyObject *object)
Definition: pythonic_coracool.cxx:151
coral_attribute_fetcher_t
std::function< PyObject *(const AttributeList &)> coral_attribute_fetcher_t
Definition: pythonic_coracool.cxx:52
make_iov_key
PyObject * make_iov_key(PyObject *iovkey_wrapper, unsigned long long value)
Definition: pythonic_coracool.cxx:179
CoraCoolFolderPtr
boost::shared_ptr< CoraCoolFolder > CoraCoolFolderPtr
Definition: CoraCoolTypes.h:15
fetch_coracool_folder
CoraCoolFolderPtr fetch_coracool_folder(IDatabasePtr cooldb, const string &folder)
Definition: pythonic_coracool.cxx:162
CoraCoolDatabasePtr
boost::shared_ptr< CoraCoolDatabase > CoraCoolDatabasePtr
Definition: CoraCoolTypes.h:12
CoraCoolFolder.h
CoraCoolDatabaseSvc::openDatabase
CoraCoolDatabasePtr openDatabase(const std::string &dbconn, cool::IDatabasePtr cooldb, bool readonly=false)
Definition: CoraCoolDatabaseSvc.cxx:23
name
std::string name
Definition: Control/AthContainers/Root/debug.cxx:240
Cut::all
@ all
Definition: SUSYToolsAlg.cxx:67
PixelModuleFeMask_create_db.payload
string payload
Definition: PixelModuleFeMask_create_db.py:69
ATLAS_NO_CHECK_FILE_THREAD_SAFETY
ATLAS_NO_CHECK_FILE_THREAD_SAFETY
Definition: pythonic_coracool.cxx:34
MAKE_FETCHER
#define MAKE_FETCHER(type, converter)
CoraCoolObjectIterPtr
boost::shared_ptr< CoraCoolObjectIter > CoraCoolObjectIterPtr
Definition: CoraCoolTypes.h:21
python.output.AtlRunQueryRoot.pf
pf
Definition: AtlRunQueryRoot.py:988
DeMoScan.first
bool first
Definition: DeMoScan.py:534
CoraCoolObjectPtr
boost::shared_ptr< CoraCoolObject > CoraCoolObjectPtr
Definition: CoraCoolTypes.h:18
qr_PyString_FromStdString
PyObject * qr_PyString_FromStdString(const string &str)
Definition: quick_retrieve.cxx:105
qr_PyString_FromBlob
PyObject * qr_PyString_FromBlob(const coral::Blob &blob)
Definition: quick_retrieve.cxx:99
CoraCoolDatabase.h
CaloCondBlobAlgs_fillNoiseFromASCII.folder
folder
Definition: CaloCondBlobAlgs_fillNoiseFromASCII.py:55
fetch_attribute_data
const T & fetch_attribute_data(const coral::Attribute &A)
Definition: pythonic_coracool.cxx:62
CoraCoolObjectIter.h
pickleTool.object
object
Definition: pickleTool.py:29
str
Definition: BTagTrackIpAccessor.cxx:11
CaloCondBlobAlgs_fillNoiseFromASCII.tag
string tag
Definition: CaloCondBlobAlgs_fillNoiseFromASCII.py:23
CoraCoolDatabaseSvcFactory.h
checker_macros.h
Define macros for attributes used to control the static checker.
browse_coracool
PyObject * browse_coracool(IDatabasePtr cooldb, const string &folder, ValidityKey since, ValidityKey until, const ChannelSelection &cs=ChannelSelection::all(), const char *tag="", PyObject *to_fetch=NULL, PyObject *object_converter=NULL, PyObject *inner_object_converter=NULL, PyObject *iovkey_wrapper=NULL)
Definition: pythonic_coracool.cxx:188
PyObject
_object PyObject
Definition: IPyComponent.h:26
no_coral_conversion_available
PyObject * no_coral_conversion_available(const AttributeList &)
Definition: pythonic_coracool.cxx:55
TSU::T
unsigned long long T
Definition: L1TopoDataTypes.h:35
CaloCondBlobAlgs_fillNoiseFromASCII.blob
blob
Definition: CaloCondBlobAlgs_fillNoiseFromASCII.py:95