Source

mana-core-storegatebindings / src / StoreGatePyExt.cxx

  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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
///////////////////////// -*- C++ -*- /////////////////////////////
// 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"

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

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

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

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

// PyROOT includes
#include "TPython.h"
#include "TPyException.h"

#include <string>
#include <vector>
#include <algorithm> // for stable_partition

typedef std::vector<char*> bytes_t;

// temporaryly duplicate PyROOT's API...
// Wim will fix that up

#define ObjectProxy_ASVOIDPTR(o) (((PyROOT::ObjectProxy*)(o))->GetObject())

namespace PyROOT {

class ObjectProxy {
public:
  enum EFlags { kNone = 0x0, kIsOwner = 0x0001, kIsReference = 0x0002 };

  TClass* ObjectIsA() const
  {
    return fClass.GetClass();                        // may return null
  }

  void* GetObject() const
  {
    if ( fObject && ( fFlags & kIsReference ) )
      return *(reinterpret_cast< void** >( const_cast< void* >( fObject ) ));
    else
      return const_cast< void* >( fObject );        // may be null
  }

  void HoldOn() { fFlags |= kIsOwner; }

  PyObject_HEAD
  void*     fObject;
  TClassRef fClass;
  int       fFlags;
};

R__EXTERN PyTypeObject ObjectProxy_Type;

template< typename T >
inline Bool_t ObjectProxy_Check( T* object )
{
  return object && PyObject_TypeCheck( object, &ObjectProxy_Type );
}

PyObject* BindRootObjectNoCast( void* object, TClass* klass, Bool_t isRef = kFALSE );
PyObject* BindRootObject( void* object, TClass* klass, Bool_t isRef = kFALSE );

union TParameter;

class TConverter {
public:
  virtual ~TConverter() {}

public:
  virtual Bool_t SetArg( PyObject*, TParameter&, G__CallFunc* = 0 ) = 0;
  virtual PyObject* FromMemory( void* address );
  virtual Bool_t ToMemory( PyObject* value, void* address );
};

TConverter* CreateConverter( const std::string& fullType, Long_t user = -1 );

class PyCallable;

R__EXTERN PyTypeObject MethodProxy_Type;

struct MethodInfo_t;

class MethodProxy
{
public:
  typedef std::map< Long_t, Int_t >  DispatchMap_t;
  typedef std::vector< PyCallable* > Methods_t;

  void Set( const std::string& name, std::vector< PyCallable* >& methods );
  const std::string& GetName() const;

public:               // public, as the python C-API works with C structs
  PyObject_HEAD
  ObjectProxy*   fSelf;        // The instance it is bound to, or NULL
  MethodInfo_t*  fMethodInfo;
};

MethodProxy* MethodProxy_New(
         const std::string& name, std::vector< PyCallable* >& methods )
{
  MethodProxy* pymeth = (MethodProxy*)MethodProxy_Type.tp_new( &MethodProxy_Type, 0, 0 );
  pymeth->Set( name, methods );
  return pymeth;
}

MethodProxy* MethodProxy_New( const std::string& name, PyCallable* method )
{
  std::vector< PyCallable* > p;
  p.push_back( method );
  return MethodProxy_New( name, p );
}



struct MethodInfo_t {
  std::string                 fName;
  MethodProxy::DispatchMap_t  fDispatchMap;
  MethodProxy::Methods_t      fMethods;
  std::string                 fDoc;
  Bool_t                      fIsSorted;

  int* fRefCount;
};

const std::string& MethodProxy::GetName() const { return fMethodInfo->fName; }

class PyCallable {
public:
  virtual ~PyCallable() {}

public:
  virtual PyObject* GetSignature() = 0;
  virtual PyObject* GetPrototype() = 0;
  virtual PyObject* GetDocString();
  virtual Int_t GetPriority();

public:
  virtual PyObject* operator()( ObjectProxy* self, PyObject* args, PyObject* kwds ) = 0;
};

} //> namespace PyROOT

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( PyROOT::ObjectProxy* pyObj,
		  CLID clid );


    /**
     * @brief Destructor.
     */
    ~PyDataBucket() { Py_DECREF( m_pyObj ); }
    /**
     * @brief Return the held object.
     */
    virtual void* object() { return m_pyObj->GetObject(); }


    /**
     * @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.
     */
    virtual void* cast (CLID clid) 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.
     */
    virtual void* cast (const std::type_info& tinfo) 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;

  private:
    /// Pointer to the held pyroot object.
    PyROOT::ObjectProxy* m_pyObj;

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

    /// 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 Concrete @c IThinningHdlr to handle the thinning of an object via 
   *        its python binding and use the Root dictionary to do conversions.
   */
  struct PyThinningHdlr : ::IThinningHdlr
  {
  
    /** @brief Constructor to handle thinning of a python object
     */
    PyThinningHdlr( bytes_t& container );

    /** @brief remove an element from the proxied @c DataVector
     */
    virtual void remove( const std::size_t idx );
    /** @brief pack the proxied @c DataVector
     *         This is needed in order to keep element link indices consistent
     *         and T/P converters unchanged.
     */
    virtual void pack();
  
    /** @brief unpack the proxied @c DataVector ie: restore it as it was 
     *         *before* any thinning took place
     */
    virtual void unpack();
  private:

    /** Vector holding the pointers to the elements of @c DataVector, before
     *  any thinning took place
     */
    const bytes_t m_backup;

    /** Reference to the actual underlying std::vector backing the 
     *  @c DataVector being thinned
     */
    bytes_t& m_container;
  };

  /** @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 )
    {
      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);
	pyproxy = TPython::ObjectProxy_FromVoidPtr((void*)proxy, 
						   "SG::DataProxy");
	PyDict_SetItem(m_sgProxies, k, pyproxy);
      }
      Py_DECREF(k);
      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)) ) {
	  throw PyROOT::TPyException();
	}
	PyDict_SetItem(m_objProxies, proxy, obj);
      }
      if ( addr && obj ) {
	((PyROOT::ObjectProxy*)obj)->fObject = addr;
      }
      return obj;
    }
  };

  /**
   * @brief A helper class to manage accesses to PyProxies
   */
  struct PyProxyMgr
  {
    IClassIDSvc* m_clidSvc;
    /// a dictionary of 'typename' -> CLID
    PyObject* m_clids;

    typedef SG::unordered_map<StoreGateSvc*,SG::PyProxyDict*> PyProxyMap_t;
    PyProxyMap_t m_proxyMap;

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

    PyProxyMgr()
    {
      m_clids   = PyDict_New();
      m_clidSvc = 0;
      if ( !Gaudi::svcLocator()->getService("ClassIDSvc", 
					    (IService*&)m_clidSvc)
	   .isSuccess() ) {
	throw std::runtime_error
	  ("SG::PyProxyMgr: Could not retrieve ClassIDSvc");
      }
    }

    ~PyProxyMgr() 
    {
      Py_DECREF(m_clids);
      // delete the proxy dicts...
      for ( PyProxyMap_t::iterator 
	      i    = m_proxyMap.begin(),
	      iEnd = m_proxyMap.end();
	    i != iEnd;
	    ++i ) {
	delete i->second; i->second = 0;
      }
    }

    inline
    SG::PyProxyDict* 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;
    }

    /// 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);
	//Py_INCREF(clid);
      }
      return clid;
    }

    inline
    CLID clid(PyObject* tp)
    {
      CLID id = CLID_NULL;
      m_clidSvc->getIDOfTypeName(PyString_AS_STRING(tp), id).ignore();
      return id;
    }

  };

} //> end namespace SG

PyObject* 
AthenaInternal::retrieveObjectFromStore( PyObject* self, 
					 PyObject* tp, PyObject* pykey )
{
  void* res = 0;
  PyObject* objProxy = NULL;

  static SG::PyProxyMgr& s_mgr = SG::PyProxyMgr::instance();

  StoreGateSvc* store = (StoreGateSvc*)ObjectProxy_ASVOIDPTR(self);

// unlikely to happen, but checking is cheap
  if ( ! store ) {
    PyErr_SetString( PyExc_RuntimeError, 
		     "no store available, is Athena initialized?" );
    return 0;
  }

// expect a type or type name and an optional string key
  PyObject* pyname = 0;

  if ( ! PyType_Check( tp ) ) {
    if ( ! PyString_Check( tp ) ) {
      PyErr_SetString( PyExc_TypeError, 
		       "retrieve() argument 1 must be type or class name" );
      return 0;
    } else {
      Py_INCREF( tp );
      pyname = tp;
    }
  } else {
    pyname = PyObject_GetAttrString( tp, (char*)"__name__" );
    if ( pyname && ! PyString_Check( pyname ) ) {
      PyObject* pystr = PyObject_Str( pyname );
      if ( pystr ) {
	Py_DECREF( pyname );
	pyname = pystr;
      }
    }

    if ( PyErr_Occurred() )
      return 0;
  }

  if ( pykey != Py_None && ! PyString_Check( pykey ) ) {
    PyErr_SetString( PyExc_TypeError, 
		     "retrieve() argument 2 must be string key" );
    return 0;
  }

  SG::PyProxyDict* proxyDict = s_mgr.pyproxy(store);
// retrieve CLID corresponding to the request
  PyObject* pyclid = s_mgr.pyclid(pyname);
  if ( ! pyclid ) {
    PyErr_Format( PyExc_NameError, 
		  "ID of \"%s\" is unknown", PyString_AS_STRING( pyname ) );
    return 0;
  }

  PyObject* pyproxy = proxyDict->proxy(pyclid, pykey);
  if ( ! pyproxy ) {
    PyErr_Format( PyExc_LookupError, 
		  "no py-proxies for (clid=%lu, type=%s, key=%s)", 
		  PyLong_AsUnsignedLong(pyclid),
		  PyString_AS_STRING( pyname ),
		  (char*)( (pykey == Py_None) 
			   ? "<None>" 
			   : PyString_AS_STRING(pykey) )
		  );
    return 0;
  }

  SG::DataProxy* proxy = (SG::DataProxy*)ObjectProxy_ASVOIDPTR(pyproxy);

  if ( ! proxy ) {
    PyErr_Format( PyExc_LookupError, 
		  "no proxies for (clid=%lu, type=%s, key=%s)", 
		  PyLong_AsUnsignedLong(pyclid),
		  PyString_AS_STRING( pyname ),
		  (char*)( (pykey == Py_None) 
			   ? "<None>" 
			   : PyString_AS_STRING(pykey) )
		  );
    return 0;
  }

// cast proxy to pointer type if needed (setting on return type is evil hack)
  DataObject* dobj = proxy->accessData();
  if ( ! dobj ) {
    PyErr_Format( PyExc_LookupError, 
		  "no such object \"%s\"", PyString_AS_STRING( pyname ) );
    return 0;
  }
  
  DataBucketBase* dbb = dynamic_cast< DataBucketBase* >( dobj );
  if ( ! dbb ) {
    PyErr_SetString
      ( PyExc_TypeError,
	"unexpected kind of DataObject: can not verify final type" );
    return 0;
  }

  CLID id     = proxy->clID();
  CLID realID = dbb->clID();
  if ( id == realID ) {
    res = dbb->object();
    
    if ( ! res ) {
      PyErr_Format( PyExc_RuntimeError, "found an invalid object" );
      return 0;
    }
    
    objProxy = proxyDict->dataObject(pyproxy, PyString_AS_STRING(pyname), res);

  } else {
    // either use CLID BaseInfo<> or Reflex, try both as appropriate
    res = dbb->cast( id );
    
    if ( res ) {

      objProxy= proxyDict->dataObject(pyproxy, PyString_AS_STRING(pyname), res);
    } else {
      // -> try Reflex...
      IClassIDSvc* clidSvc = s_mgr.m_clidSvc;
      std::string realName = "";
      if ( !clidSvc->getTypeNameOfID(realID, realName).isSuccess() ) {
	PyErr_Format( PyExc_TypeError, "actual type of CLID %lu unknown",
		      (long unsigned int)realID );
	return 0;
      }
      
      const ROOT::Reflex::Type& fromType = ROOT::Reflex::Type::ByName(realName);
      
      if ( (bool)fromType ) {
	ROOT::Reflex::Object realobj( fromType, dbb->object() );
	
 	const ROOT::Reflex::Type& toType = ROOT::Reflex::Type::ByName( PyString_AS_STRING( pyname ) );
 	const ROOT::Reflex::Object& finalobj = fromType.CastObject( toType, realobj );
	
 	res = (void*)finalobj.Address();
 	if ( res ) {
 	  objProxy = proxyDict->dataObject(pyproxy, realName.c_str(), res);
 	}
      }
    }

    if ( ! res ) {
      PyErr_SetString( PyExc_TypeError, "cast to requested type failed" );
      return 0;
    }

  }

  Py_INCREF(objProxy);
  return objProxy;
}

PyObject* 
AthenaInternal::recordObjectToStore( PyObject* self,
				     PyObject* obj, PyObject* pykey )
{
  static SG::PyProxyMgr& s_mgr = SG::PyProxyMgr::instance();

  StoreGateSvc* store = (StoreGateSvc*)ObjectProxy_ASVOIDPTR(self);

// unlikely to happen, but checking is cheap
  if ( ! store ) {
    PyErr_SetString( PyExc_RuntimeError, 
		     "no store available, is Athena initialized?" );
    return 0;
  }

  // expect a type or type name
  PyObject* tp = PyObject_GetAttrString( obj, (char*)"__class__" );
  if ( ! PyType_Check( tp ) ) {
      PyErr_SetString( PyExc_RuntimeError, 
		       "could not retrieve type of object" );
      return 0;
  }
  PyObject* pyname = PyObject_GetAttrString( tp, (char*)"__name__" );
  if ( pyname && ! PyString_Check( pyname ) ) {
    PyObject* pystr = PyObject_Str( pyname );
    if ( pystr ) {
      Py_DECREF( pyname );
      pyname = pystr;
    }
  }
  if ( PyErr_Occurred() )
    return 0;
    
  if ( ! PyString_Check( pykey ) ) {
    PyErr_SetString( PyExc_TypeError, 
		     "record() argument 2 must be string key" );
    return 0;
  }
  
  // retrieve CLID corresponding to the request
  const CLID id = s_mgr.clid(pyname);
  if ( CLID_NULL == id ) {
    PyErr_Format( PyExc_NameError, 
		  "ID of \"%s\" is unknown", PyString_AS_STRING( pyname ) );
    return 0;
  }
  
  PyROOT::ObjectProxy* pyRootObj = (PyROOT::ObjectProxy*)obj;
  DataObject* dataObj = new SG::PyDataBucket( pyRootObj, id );
  static bool allowMods = true;
  int sc = store->typeless_record( dataObj, PyString_AS_STRING(pykey),
				   pyRootObj->GetObject(),
				   allowMods ).isSuccess()
    ? 1
    : 0; 
  return Py_BuildValue( const_cast<char*>("i"), sc );
}

PyObject* 
AthenaInternal::thinContainer( IThinningSvc* self,
			       PyObject* container_,
			       PyObject* filter_,
			       int op )
{
// unlikely to happen, but checking is cheap
   if ( ! self ) {
      PyErr_SetString( PyExc_RuntimeError, 
		       "no thinning svc available, is Athena initialized?" );
      return 0;
   }

   if ( ! PyROOT::ObjectProxy_Check( container_ ) ) {
     PyErr_SetString( PyExc_TypeError,
		      "filter() argument 2 must be a PyROOT object" );
     return 0;
   }
   PyROOT::ObjectProxy* container = (PyROOT::ObjectProxy*)container_;
   const int nElements = PySequence_Size( container_ );
   if ( -1 == nElements ) {
     PyErr_SetString
       ( PyExc_TypeError,
	 "filter() argument 2 must be a non zero-length sequence" );
   }

   // right now the python layer should give us an array of 'PyBools'
   // -> massage this into a std::vector<bool>
   typedef IThinningSvc::Filter_t Filter_t;
   Filter_t filter( nElements, false );
   if ( PySequence_Check( filter_ ) ) {
     for ( std::size_t i = 0, iMax = filter.size(); i != iMax; ++i ) {
       PyObject* iFilter = PySequence_GetItem( filter_, i );
       if ( iFilter == Py_True ) { filter[i] = true;
       } else                    { filter[i] = false;
       }
       Py_DECREF(iFilter);
     }
   } else {
     PyErr_SetString( PyExc_TypeError,
		      "filter() argument 3 must a sequence" );
     return 0;
   }

   // FIXME: won't work b/c of damn specialization of std::vector<bool> !!
   // -> change IThinningSvc::filter interface or,
   // -> copy the python array of booleans into a temporary vector<bool>
//    Filter_t& filter = 
//      *(Filter_t*)(((PyROOT::ObjectProxy*)filter_)->GetObject());

   SG::DataProxy* proxy = self->deep_proxy( container->GetObject() );
   if ( !proxy ) {
       PyErr_SetString( PyExc_RuntimeError,
			"could not manage to find a deep_proxy" );
     return 0;
   }

   IThinningHdlr* hdlr = self->handler(proxy);
   if ( 0 == hdlr ) {
     PyObject* stdcont_ = PyObject_CallMethod
       ( (PyObject*)container, 
	 const_cast<char*>("stdcont"), const_cast<char*>("") );
     if ( ! PyROOT::ObjectProxy_Check( stdcont_ ) ) {
       PyErr_SetString( PyExc_RuntimeError,
			"could not access stdcont() method from DataVector" );
       return 0;
     } else {
       PyROOT::ObjectProxy* pystdcont = (PyROOT::ObjectProxy*)stdcont_;
       bytes_t& stdcont = *reinterpret_cast<bytes_t*>( pystdcont->GetObject() );
       hdlr = new SG::PyThinningHdlr( stdcont );
     }
   }

   int sc = self->filter_impl( hdlr, proxy, filter, 
			       (IThinningSvc::Operator::Type)op ).isSuccess()
	      ? 1
	      : 0; 
   return Py_BuildValue( const_cast<char*>("i"), sc );
}

std::size_t 
AthenaInternal::thinIdxContainer( IThinningSvc* self,
				  PyObject* container_, 
				  std::size_t idx )
{
  // unlikely to happen, but checking is cheap
   if ( ! self ) {
      PyErr_SetString( PyExc_RuntimeError, 
		       "no thinning svc available, is Athena initialized?" );
      return 0;
   }

   if ( ! PyROOT::ObjectProxy_Check( container_ ) ) {
     PyErr_SetString( PyExc_TypeError,
		      "index() argument 2 must be a PyROOT object" );
     return 0;
   }
   PyROOT::ObjectProxy* container = (PyROOT::ObjectProxy*)container_;

   SG::DataProxy* proxy = self->deep_proxy( container->GetObject() );
   if ( 0 == proxy ) {
     PyErr_SetString( PyExc_RuntimeError,
		      "could not manage to find a deep_proxy" );
     return 0;
   }
   return self->index( proxy, idx );
}

std::size_t AthenaInternal::thinRemovedIdx() 
{ return IThinningSvc::RemovedIdx; }

namespace {
  /** @brief Predicate to spot non NULL pointers
   */
  struct IsNonNullPtr
  {
    template <typename Element>
    bool operator()( Element* f ) const
    { return f != 0; }
  };
}

//
namespace SG {
  IClassIDSvc* PyDataBucket::s_clidSvc = 0;
  IClassIDSvc* PyDataBucket::clidSvc()
  {
    if ( 0 == s_clidSvc ) {
      Gaudi::svcLocator()->getService( "ClassIDSvc", 
				       (IService*&)s_clidSvc ).ignore();
    }
    return s_clidSvc;
  }

  PyDataBucket::PyDataBucket( PyROOT::ObjectProxy* pyObj,
			      CLID clid ) :
    DataBucketBase(),
    m_pyObj( pyObj ),
    m_clid ( clid  )
  {
    // prevent Python from sweeping the rug under our feet
    Py_INCREF( pyObj );
  }

  void* PyDataBucket::cast( CLID clid ) const
  {
    // if requested type is same than myself ==> no conversion needed
    if ( clid == m_clid ) {
      return m_pyObj->GetObject();
    }

    std::string clidTypeName;
    StatusCode sc = clidSvc()->getTypeNameOfID(clid, clidTypeName);
    if ( sc.isFailure() ) {
      PyErr_Format( PyExc_TypeError, "actual type of CLID %lu unknown",
		    (long unsigned int)clid );
      return 0;
    }

    // Create a converter for that type
    PyROOT::TConverter* pcnv = PyROOT::CreateConverter( clidTypeName );
    void* address = m_pyObj->GetObject();
    PyObject* value = pcnv->FromMemory(&address);
    delete pcnv;

    if ( PyROOT::ObjectProxy_Check(value) ) {
      return ((PyROOT::ObjectProxy*)value)->GetObject();
    }
    Py_XDECREF(value);
    PyErr_Format( PyExc_TypeError, 
		  "Could not convert to %s", clidTypeName.c_str() );
    return 0;
  }

  void* PyDataBucket::cast( const std::type_info& tinfo ) const
  {
    // if requested type is same than myself ==> no conversion needed
    if ( tinfo == *(m_pyObj->fClass->GetTypeInfo()) ) {
      return m_pyObj->GetObject();
    }

    // Create a converter for that type
    PyROOT::TConverter* pcnv = PyROOT::CreateConverter( tinfo.name() );
    void* address = m_pyObj->GetObject();
    PyObject* value = pcnv->FromMemory(&address);
    delete pcnv;

    if ( PyROOT::ObjectProxy_Check(value) ) {
      return ((PyROOT::ObjectProxy*)value)->GetObject();
    }
    Py_XDECREF(value);
    PyErr_Format( PyExc_TypeError, 
		  "Could not convert to %s", tinfo.name() );
    return 0;
  }

  PyDataBucket* PyDataBucket::clone() const
  { 
    PyErr_SetString
      ( PyExc_RuntimeError, 
	"SG::PyDataBucket::clone() is not meant to be called (yet)" );
    std::abort();
    return 0;
//     new SG::PyDataBucket( m_type, copy<>(m_pyObj), m_clid );
  }

  /////////////////////////////////////////////////////////////////////////////
  // PyThinningHdlr implementation

  PyThinningHdlr::PyThinningHdlr( bytes_t& container ) :
    IThinningHdlr(      ),
    m_backup     ( container.begin(), container.end() ),
    m_container  ( container )
  {}

  /** @brief remove an element from the proxied @c DataVector
   */
  void PyThinningHdlr::remove( const std::size_t idx )
  {
    m_container[idx] = 0;
  }
  
  /** @brief pack the proxied @c DataVector
   *         This is needed in order to keep element link indices consistent
   *         and T/P converters unchanged.
   */
  void PyThinningHdlr::pack()
  {
    typedef bytes_t::iterator  Iter;
    // move non NULL pointers at the begin of the vector, 
    // preserving relative order...
    Iter itr = std::stable_partition( m_container.begin(), 
				      m_container.end(), 
				      IsNonNullPtr() );
    // nicely truncate our container: removes the NULL elements
    m_container.resize( std::distance( m_container.begin(), itr ) );
  }
  
  /** @brief unpack the proxied @c DataVector ie: restore it as it was 
   *         *before* any thinning took place
   */
  void PyThinningHdlr::unpack()
  {
    typedef bytes_t::iterator   Iter;
    typedef bytes_t::value_type Value;
    const std::size_t size = m_backup.size();
      
    m_container.resize( size );
    for ( std::size_t i = 0; i != size; ++i ) {
      m_container[i] = m_backup[i];
    }
  }

} //< end namespace SG
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.