Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
TTreePyz.cxx
Go to the documentation of this file.
1// Author: Enric Tejedor CERN 06/2018
2// Original PyROOT code by Wim Lavrijsen, LBL
3
4/*************************************************************************
5 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12// Bindings
17
18// Th API changed a bit with the new CPyCppyy, which we can detect by checking
19// if CPYCPPYY_VERSION_HEX is defined.
20#ifdef CPYCPPYY_VERSION_HEX
22#endif
23
24#include "CPyCppyy/API.h"
25
26#include "PyROOTPythonize.h"
27
28// ROOT
29#include "TClass.h"
30#include "TTree.h"
31#include "TBranch.h"
32#include "TBranchElement.h"
33#include "TBranchObject.h"
34#include "TLeaf.h"
35#include "TLeafElement.h"
36#include "TLeafObject.h"
37#include "TStreamerElement.h"
38#include "TStreamerInfo.h"
39
40namespace {
41
42// Get the TClass of the C++ object proxied by pyobj
44{
46}
47
48} // namespace
49
50using namespace CPyCppyy;
51
52static TBranch *SearchForBranch(TTree *tree, const char *name)
53{
54 TBranch *branch = tree->GetBranch(name);
55 if (!branch) {
56 // for benefit of naming of sub-branches, the actual name may have a trailing '.'
57 branch = tree->GetBranch((std::string(name) + '.').c_str());
58 }
59 return branch;
60}
61
62static TLeaf *SearchForLeaf(TTree *tree, const char *name, TBranch *branch)
63{
64 TLeaf *leaf = tree->GetLeaf(name);
65 if (branch && !leaf) {
66 leaf = branch->GetLeaf(name);
67 if (!leaf) {
68 TObjArray *leaves = branch->GetListOfLeaves();
69 if (leaves->GetSize() && (leaves->First() == leaves->Last())) {
70 // i.e., if unambiguously only this one
71 leaf = (TLeaf *)leaves->At(0);
72 }
73 }
74 }
75 return leaf;
76}
77
78static std::pair<void *, std::string> ResolveBranch(TTree *tree, const char *name, TBranch *branch)
79{
80 // for partial return of a split object
81 if (branch->InheritsFrom(TBranchElement::Class())) {
83 if (be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID())) {
84 Long_t offset = ((TStreamerElement *)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
85 return {be->GetObject() + offset, be->GetCurrentClass()->GetName()};
86 }
87 }
88
89 // for return of a full object
90 if (branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class()) {
91 TClass *klass = TClass::GetClass(branch->GetClassName());
92 if (klass && branch->GetAddress())
93 return {*(void **)branch->GetAddress(), branch->GetClassName()};
94
95 // try leaf, otherwise indicate failure by returning a typed null-object
96 TObjArray *leaves = branch->GetListOfLeaves();
97 if (klass && !tree->GetLeaf(name) && !(leaves->GetSize() && (leaves->First() == leaves->Last())))
98 return {nullptr, branch->GetClassName()};
99 }
100
101 return {nullptr, ""};
102}
103
105{
106 if (1 < leaf->GetLenStatic() || leaf->GetLeafCount()) {
107 bool isStatic = 1 < leaf->GetLenStatic();
108 // array types
109 std::string typeName = leaf->GetTypeName();
110#ifdef CPYCPPYY_VERSION_HEX
111 dim_t dimsArr[]{leaf->GetNdata()};
113#else
114 dim_t dims[]{1, leaf->GetNdata()}; // first entry is the number of dims
115#endif
116 Converter *pcnv = CreateConverter(typeName + (isStatic ? "[]" : "*"), dims);
117
118 void *address = 0;
119 if (leaf->GetBranch())
120 address = (void *)leaf->GetBranch()->GetAddress();
121 if (!address)
122 address = (void *)leaf->GetValuePointer();
123
124 PyObject *value = pcnv->FromMemory(&address);
126
127 return value;
128 } else if (leaf->GetValuePointer()) {
129 // value types
130 Converter *pcnv = CreateConverter(leaf->GetTypeName());
131 PyObject *value = 0;
132 if (leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class())
133 value = pcnv->FromMemory((void *)*(void **)leaf->GetValuePointer());
134 else
135 value = pcnv->FromMemory((void *)leaf->GetValuePointer());
137
138 return value;
139 }
140
141 return nullptr;
142}
143
144// Allow access to branches/leaves as if they were data members Returns a
145// Python tuple where the first element is either the desired CPyCppyy proxy,
146// or an address that still needs to be wrapped by the caller in a proxy using
147// cppyy.ll.cast. In the latter case, the second tuple element is the target
148// type name. Otherwise, the second element is an empty string.
150{
151 PyObject *self = nullptr;
152 PyObject *pyname = nullptr;
153
154 PyArg_ParseTuple(args, "OU:GetBranchAttr", &self, &pyname);
155
158 return 0;
159
160 // get hold of actual tree
161 auto tree = (TTree *)GetTClass(self)->DynamicCast(TTree::Class(), CPyCppyy::Instance_AsVoidPtr(self));
162
163 if (!tree) {
164 PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
165 return 0;
166 }
167
168 // deal with possible aliasing
169 const char *name = tree->GetAlias(name_possibly_alias);
170 if (!name)
172
173 // search for branch first (typical for objects)
175
176 if (branch) {
177 // found a branched object, wrap its address for the object it represents
179 if (!finalTypeName.empty()) {
183 return outTuple;
184 }
185 }
186
187 // if not, try leaf
188 if (TLeaf *leaf = SearchForLeaf(tree, name, branch)) {
189 // found a leaf, extract value and wrap with a Python object according to its type
190 auto wrapper = WrapLeaf(leaf);
191 if (wrapper != nullptr) {
195 return outTuple;
196 }
197 }
198
199 // confused
200 PyErr_Format(PyExc_AttributeError, "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name);
201 return 0;
202}
203
204////////////////////////////////////////////////////////////////////////////
205/// Try to match the arguments of TTree::Branch to the following overload:
206/// - ( const char*, void*, const char*, Int_t = 32000 )
207/// If the match succeeds, invoke Branch on the C++ tree with the right
208/// arguments.
210{
211 PyObject *treeObj = nullptr;
212 PyObject *name = nullptr, *address = nullptr, *leaflist = nullptr, *bufsize = nullptr;
213
214 if (PyArg_ParseTuple(args, "OO!OO!|O!:Branch", &treeObj, &PyUnicode_Type, &name, &address, &PyUnicode_Type,
216
218 if (!tree) {
219 PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
220 return nullptr;
221 }
222
223 void *buf = nullptr;
224 if (CPPInstance_Check(address))
225 buf = CPyCppyy::Instance_AsVoidPtr(address);
226 else
227 Utility::GetBuffer(address, '*', 1, buf, false);
228
229 if (buf) {
230 TBranch *branch = nullptr;
231 if (argc == 5) {
233 } else {
234 branch = tree->Branch(PyUnicode_AsUTF8(name), buf, PyUnicode_AsUTF8(leaflist));
235 }
236
237 return BindCppObject(branch, Cppyy::GetScope("TBranch"));
238 }
239 }
240 PyErr_Clear();
241
243}
244
245////////////////////////////////////////////////////////////////////////////
246/// Try to match the arguments of TTree::Branch to one of the following
247/// overloads:
248/// - ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
249/// - ( const char*, T**, Int_t = 32000, Int_t = 99 )
250/// If the match succeeds, invoke Branch on the C++ tree with the right
251/// arguments.
253{
254 PyObject *treeObj = nullptr;
255 PyObject *name = nullptr, *clName = nullptr, *address = nullptr, *bufsize = nullptr, *splitlevel = nullptr;
256
257 auto bIsMatch = false;
258 if (PyArg_ParseTuple(args, "OO!O!O|O!O!:Branch", &treeObj, &PyUnicode_Type, &name, &PyUnicode_Type, &clName,
259 &address, &PyInt_Type, &bufsize, &PyInt_Type, &splitlevel)) {
260 bIsMatch = true;
261 } else {
262 PyErr_Clear();
263 if (PyArg_ParseTuple(args, "OO!O|O!O!", &treeObj, &PyUnicode_Type, &name, &address, &PyInt_Type, &bufsize,
265 bIsMatch = true;
266 } else {
267 PyErr_Clear();
268 }
269 }
270
271 if (bIsMatch) {
273 if (!tree) {
274 PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
275 return nullptr;
276 }
277
278 std::string klName = clName ? PyUnicode_AsUTF8(clName) : "";
279 void *buf = nullptr;
280
281 if (CPPInstance_Check(address)) {
282 if (((CPPInstance *)address)->fFlags & CPPInstance::kIsReference)
283 buf = (void *)((CPPInstance *)address)->fObject;
284 else
285 buf = (void *)&((CPPInstance *)address)->fObject;
286
287 if (!clName) {
288 klName = GetTClass(address)->GetName();
289 argc += 1;
290 }
291 } else {
292 Utility::GetBuffer(address, '*', 1, buf, false);
293 }
294
295 if (buf && !klName.empty()) {
296 TBranch *branch = nullptr;
297 if (argc == 4) {
298 branch = tree->Branch(PyUnicode_AsUTF8(name), klName.c_str(), buf);
299 } else if (argc == 5) {
300 branch = tree->Branch(PyUnicode_AsUTF8(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize));
301 } else if (argc == 6) {
302 branch = tree->Branch(PyUnicode_AsUTF8(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize),
304 }
305
306 return BindCppObject(branch, Cppyy::GetScope("TBranch"));
307 }
308 }
309
311}
312
313////////////////////////////////////////////////////////////////////////////
314/// \brief Add pythonization for TTree::Branch.
315/// \param[in] self Always null, since this is a module function.
316/// \param[in] args Pointer to a Python tuple object containing the arguments
317/// received from Python.
318///
319/// Modify the behaviour of Branch so that proxy references can be passed
320/// as arguments from the Python side, more precisely in cases where the C++
321/// implementation of the method expects the address of a pointer.
322///
323/// For example:
324/// ~~~{.py}
325/// v = ROOT.std.vector('int')()
326/// t.Branch('my_vector_branch', v)
327/// ~~~
328///
329/// The following signatures are treated in this pythonization:
330/// - ( const char*, void*, const char*, Int_t = 32000 )
331/// - ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
332/// - ( const char*, T**, Int_t = 32000, Int_t = 99 )
334{
335 int argc = PyTuple_GET_SIZE(args);
336
337 if (argc >= 3) { // We count the TTree proxy object too
339 if (branch != Py_None)
340 return branch;
341
343 if (branch != Py_None)
344 return branch;
345 }
346
347 // Not the overload we wanted to pythonize, return None
349}
#define Py_RETURN_NONE
Definition CPyCppyy.h:268
#define CPyCppyy_PyText_FromString
Definition CPyCppyy.h:81
_object PyObject
std::ios_base::fmtflags fFlags
long Long_t
Definition RtypesCore.h:54
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:110
static TBranch * SearchForBranch(TTree *tree, const char *name)
Definition TTreePyz.cxx:52
PyObject * TryBranchLeafListOverload(int argc, PyObject *args)
Try to match the arguments of TTree::Branch to the following overload:
Definition TTreePyz.cxx:209
PyObject * TryBranchPtrToPtrOverloads(int argc, PyObject *args)
Try to match the arguments of TTree::Branch to one of the following overloads:
Definition TTreePyz.cxx:252
static std::pair< void *, std::string > ResolveBranch(TTree *tree, const char *name, TBranch *branch)
Definition TTreePyz.cxx:78
static TLeaf * SearchForLeaf(TTree *tree, const char *name, TBranch *branch)
Definition TTreePyz.cxx:62
static PyObject * WrapLeaf(TLeaf *leaf)
Definition TTreePyz.cxx:104
A Branch for the case of an object.
static TClass * Class()
static TClass * Class()
A TTree is a list of TBranches.
Definition TBranch.h:93
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:81
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2968
static TClass * Class()
static TClass * Class()
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition TLeaf.h:57
An array of TObjects.
Definition TObjArray.h:31
A TTree represents a columnar dataset.
Definition TTree.h:79
static TClass * Class()
Py_ssize_t GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, bool check=true)
Definition Utility.cxx:808
bool CPPInstance_Check(T *object)
CPYCPPYY_EXTERN Converter * CreateConverter(const std::string &name, cdims_t=0)
PyObject * BindCppObject(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
CPYCPPYY_EXTERN void * Instance_AsVoidPtr(PyObject *pyobject)
Definition API.cxx:106
CPYCPPYY_EXTERN void DestroyConverter(Converter *p)
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
PyObject * BranchPyz(PyObject *self, PyObject *args)
Add pythonization for TTree::Branch.
Definition TTreePyz.cxx:333
PyObject * GetBranchAttr(PyObject *self, PyObject *args)
Definition TTreePyz.cxx:149