Source

mana-core-storegatebindings / src / SgPyDataModel.h

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// -*- C++ -*-
#ifndef STOREGATEBINDINGS_SGPYDATAMODEL_H
#define STOREGATEBINDINGS_SGPYDATAMODEL_H 1

// Hide this #include from checkreq so that it doesn't keep giving us warnings.
#define PYTHON_INC "Python.h"
#include PYTHON_INC

#include "StoreGateBindingsDict.h"
#include "SgPyMsg.h"

// Framework includes
#include "GaudiKernel/Bootstrap.h"
#include "GaudiKernel/ClassID.h"
#include "GaudiKernel/DataObject.h"
#include "AthenaKernel/IClassIDSvc.h"
#include "AthenaKernel/IDictLoaderSvc.h"

extern CLID PyCLID;

// SGTools includes
#include "SGTools/unordered_map.h" // move to STL once available
#include "SGTools/DataBucketBase.h"
#include "SGTools/BaseInfo.h"

// Reflex includes
#include "Reflex/Type.h"
#include "Reflex/Object.h"

// ROOT includes
#include "TClass.h"
#include "TClassEdit.h"
#include "TClassRef.h"
#include "TROOT.h"
#include "Api.h"

// PyROOT includes
// temporaryly duplicate PyROOT's API...
// Wim will fix that up
#include "AthenaPyRoot.h"

// fwd declares
namespace SG { struct PyProxyMgr; }
namespace SG { struct PyProxyDict; }

namespace SG {
  
  /**
   * @brief Concrete @c DataBucket that holds the object via a @c void*
   *        and uses the Root dictionary to do conversions.
   *
   * A concrete @c DataBucket instance holds a pointer to an arbitrary
   * object, and is able to further convert it to pointers to other
   * types related by inheritance.  This variant is used for PyAthena,
   * where don't have the type available at compile time and thus cannot
   * use templates.  However, we know that we do have the Root dictionary
   * available for the types, so we can use that information for the
   * conversions.
   */
  class PyDataBucket : public DataBucketBase
  {
  public:
    /**
     * @brief Constructor.
     * @param pyObj The (pyroot) object proxy to hold.
     * @param clid The class ID of the wrapped object.
     */
    PyDataBucket( PyObject* obj,
                  CLID clid );


    /**
     * @brief Destructor.
     */
    ~PyDataBucket() { Py_DECREF( m_pyObj ); }
    /**
     * @brief Return the held object.
     */
    virtual void* object() 
    { 
      return m_clid != PyCLID
        ? ObjectProxy_ASVOIDPTR(m_pyObj)
        : m_pyObj; 
    }


    /**
     * @brief Return the contents of the @c DataBucket,
     *        converted to type given by @a clid.  Note that only
     *        derived->base conversions are allowed here.
     * @param clid The class ID to which to convert.
     * @param irt To be called if we make a new instance.
     */
    virtual void* cast (CLID clid, IRegisterTransient* itr = 0) const;


    /**
     * @brief Return the contents of the @c DataBucket,
     *        converted to type given by @c std::type_info.  Note that only
     *        derived->base conversions are allowed here.
     * @param tinfo The @c std::type_info of the type to which to convert.
     * @param irt To be called if we make a new instance.
     */
    virtual void* cast (const std::type_info& tinfo,
                        IRegisterTransient* itr = 0) const;

    /**
     * @brief Retrieve reference to class definition structure
     */
    virtual const CLID& clID() const { return m_clid; }

    /**
     * @brief Return a new @c DataBucket whose payload has been cloned from the
     *        original one.
     */
    virtual SG::PyDataBucket* clone() const;

    /**
     * @brief Give up ownership of the  @c DataBucket contents.
     */
    virtual void relinquish() 
    {
      Py_DECREF( m_pyObj );
    }

  private:
    /// Pointer to the held pyroot object (or 'regular' PyObject)
    PyObject* m_pyObj;

    /// The class ID of the wrapped object.
    CLID m_clid;

    /// pointer to the @c SG::BaseInfoBase structure holding the converter
    /// functions for objects held by StoreGate
    const SG::BaseInfoBase* m_bib;

    /// Pointer to the @ IClassIDSvc to be able to cast objects based on
    /// the @a clid.
    static IClassIDSvc* s_clidSvc;

    /// Access (and initialize) the pointer to the @c IClassIDSvc
    static IClassIDSvc* clidSvc();
  };

  /**
   * @brief A helper class to manage accesses to PyProxies
   */
  struct PyProxyMgr
  {
    IDictLoaderSvc * m_dictSvc;
    IClassIDSvc* m_clidSvc;
    /// a dictionary of "typedef'ed typename" -> "typename"
    PyObject* m_aliases;

    /// a dictionary of 'typename' -> CLID (and reverse CLID->'typename')
    PyObject* m_clids;

    typedef SG::unordered_map<StoreGateSvc*,SG::PyProxyDict*> PyProxyMap_t;
    PyProxyMap_t m_proxyMap;
    
    /// a dictionary of CLID -> reflex typename
    typedef SG::unordered_map<CLID, std::string> ClidMap_t;
    ClidMap_t m_clidMap;

    static
    PyProxyMgr& instance()
    { static PyProxyMgr mgr; return mgr; }

    PyProxyMgr();
    ~PyProxyMgr();

    SG::PyProxyDict* pyproxy( StoreGateSvc* sg );

    /// returns a borrowed reference
    inline
    PyObject* pyclid(PyObject* tp)
    {
      PyObject* clid = PyDict_GetItem(m_clids, tp);
      if ( NULL == clid ) {
        const CLID id = this->clid(tp);
        if ( id == CLID_NULL ) {
          return NULL;
        }
        clid = PyLong_FromLong(id);
        PyDict_SetItem(m_clids, tp, clid);
        // add reverse look-up entry too
        PyDict_SetItem(m_clids, clid, tp);
        //Py_INCREF(clid);
      }
      return clid;
    }

    /// returns a borrowed reference
    inline
    PyObject* pytp(PyObject* clid)
    {
      PyObject* tp = PyDict_GetItem(m_clids, clid);
      if ( NULL == tp ) {
        std::string cpp_tp;
        if (!m_clidSvc->getTypeNameOfID(PyLong_AsUnsignedLong(clid), 
                                        cpp_tp).isSuccess()) {
          return NULL;
        }
        PyObject* alias = PyDict_GetItemString(m_aliases, cpp_tp.c_str());
        if ( alias ) {
          tp = alias;
        } else {
          tp = PyString_FromString(cpp_tp.c_str());
        }
        PyDict_SetItem(m_clids, clid, tp);
        // reverse look-up
        PyDict_SetItem(m_clids, tp, clid);
        if (!alias) {
          Py_DECREF(tp);
        }
      }
      return tp;
    }

    /// returns a borrowed reference
    inline 
    PyObject* pytp(CLID clid)
    {
      PyObject* pyclid = PyLong_FromLong(clid);
      PyObject* o = this->pytp(pyclid);
      Py_DECREF(pyclid);
      return o;
    }

    inline
    CLID clid(PyObject* tp)
    {
      CLID id = CLID_NULL;
      // FIXME: get rid of this massaging when/if ROOT finally
      // standardize on keeping the std:: namespace...
      std::string tn = TClassEdit::ShortType(PyString_AS_STRING(tp),
                                             TClassEdit::kDropAllDefault);
      m_clidSvc->getIDOfTypeName(tn, id).ignore();
      if ( id == CLID_NULL ) {
        // try an alias...
        PyObject* alias = PyDict_GetItemString(m_aliases, tn.c_str());
        if ( alias ){
          m_clidSvc->getIDOfTypeName(PyString_AS_STRING(alias), id).ignore();
        }
      }
      if (id == CLID_NULL) {
        // then try a type-id name...
        return this->clid_from_tid (tp);
      }
      return id;
    }

    inline
    CLID clid_from_tid (PyObject* tp)
    {
      CLID id = CLID_NULL;
      // FIXME: get rid of this massaging when/if ROOT finally
      // standardize on keeping the std:: namespace...
      std::string tn = TClassEdit::ShortType(PyString_AS_STRING(tp),
                                             TClassEdit::kDropAllDefault);
      m_clidSvc->getIDOfTypeInfoName(tn, id).ignore();
      if ( id == CLID_NULL ) {
        // try an alias...
        PyObject* alias = PyDict_GetItemString(m_aliases, tn.c_str());
        if ( alias ){
          m_clidSvc->getIDOfTypeInfoName(PyString_AS_STRING(alias), 
                                         id).ignore();
        }
      }
      return id;
    }

    /** ensure everything has been loaded for the clid id (classid,
     *  reflex dict, baseinfobase,...)
     *  @return the reflex typename associated with that clid
     */
    inline
    const char* load_type(CLID id)
    {
      typedef ClidMap_t::iterator Itr_t;
      Itr_t i = m_clidMap.find(id);
      if (i != m_clidMap.end()) {
        return i->second.c_str();
      }
      m_clidMap[id] = m_dictSvc->load_type(id).Name(Reflex::SCOPED);
      return m_clidMap[id].c_str();
    }

  private:
    /// import the dictionary of aliases from a well known location
    PyObject* importDictAliases()
    {
      const std::string moduleName = "AthenaPython.Bindings";
      PyObject* module = PyImport_ImportModule
        ( const_cast<char*>(moduleName.c_str()) );
      if ( !module || !PyModule_Check(module) ) {
        std::cerr << "SG::PyProxyDict WARNING: could not import module '"
                  << moduleName << "' !\n";
        Py_XDECREF(module);
        m_aliases = PyDict_New();
        return m_aliases;
      }

      m_aliases = PyDict_GetItemString(PyModule_GetDict(module),
                                       (char*)"_clid_typename_aliases");
      // borrowed ref. so we increment it
      Py_XINCREF(m_aliases);
      // don't need this one anymore
      Py_DECREF(module);
      
      if ( !m_aliases ) {
        std::cerr << "SG::PyProxyDict WARNING: could not retrieve the "
                  << "dictionary of aliases from '"
                  << moduleName << "' !\n";
        Py_XDECREF(m_aliases);
        m_aliases = PyDict_New();
      }
      return m_aliases;
    }
    
  }; //> class PyProxyMgr

  /** @brief a python front-end to the @c IProxyDict interface, with caching
   *         the type of held object by the proxy (for `class` look-up issues)
   *  A @c SG::PyProxyDict holds a dictionary of { (clid,sgkey) : pyobj }
   */
  struct PyProxyDict
  {
    StoreGateSvc* m_sgSvc;
    PyObject* m_sgProxies;
    PyObject* m_objProxies;

    PyProxyDict( StoreGateSvc* sgSvc ) : 
      m_sgSvc     ( sgSvc ),
      m_sgProxies ( PyDict_New() ),
      m_objProxies( PyDict_New() )
    {}
    ~PyProxyDict() 
    { 
      Py_DECREF(m_sgProxies ); 
      Py_DECREF(m_objProxies);
    }

    inline
    PyObject* proxy( PyObject* pyclid, PyObject* pykey )
    {
      _SGPY_MSG("PyProxyDict::proxy(...)...");

      PyObject* k = PyTuple_Pack(2, pyclid, pykey);
      PyObject* pyproxy = PyDict_GetItem(m_sgProxies, k);
      if ( NULL == pyproxy ) {
        CLID id = CLID_NULL;
        PyArg_Parse( pyclid, "l", &id );
        const std::string skey = ( pykey == Py_None )
          ? ""
          : PyString_AS_STRING(pykey);
        SG::DataProxy* proxy = skey.empty()
          ? m_sgSvc->proxy(id)
          : m_sgSvc->proxy(id, skey);
        _SGPY_MSG("PyProxyDict::proxy(" 
                  << (proxy ? proxy->clID() : id)   << ", "
                  << (proxy ? proxy->name() : skey) << ")...");
        pyproxy = TPython::ObjectProxy_FromVoidPtr((void*)proxy, 
                                                   "SG::DataProxy");
        if (skey.find ("HLTAutoKey") != 0) {
          PyDict_SetItem(m_sgProxies, k, pyproxy);
        }
      }
      Py_DECREF(k);
      _SGPY_MSG("PyProxyDict::proxy(...)... [done]");
      return pyproxy;
    }

    inline
    PyObject* dataObject( PyObject* proxy, const char* klass, void* addr=0 )
    {
      PyObject* obj = PyDict_GetItem( m_objProxies, proxy );
      if ( NULL == obj ) {
        if ( !(obj = TPython::ObjectProxy_FromVoidPtr((void*)addr, klass)) ) {
          std::cerr << "--error-- could not create a pyobject...\n";
          throw PyROOT::TPyException();
        }
        PyDict_SetItem(m_objProxies, proxy, obj);
      }
      if ( addr && obj ) {
        ((PyROOT::ObjectProxy*)obj)->fObject = addr;
      }
      return obj;
    }
  }; //> struct PyProxyDict



  // -------- inlines ----------------------
  inline
  PyProxyDict* 
  PyProxyMgr::pyproxy(StoreGateSvc* sg)
  {
    SG::PyProxyDict* p = 0;
    PyProxyMap_t::iterator i = m_proxyMap.find(sg);
    if ( i == m_proxyMap.end() ) {
      m_proxyMap[sg] = p = new SG::PyProxyDict(sg);
    } else {
      p = i->second;
    }
    return p;
  }
  

} //> end namespace SG

#endif // !STOREGATEBINDINGS_SGPYDATAMODEL_H