Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
pyroot001_arrayInterface.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_pyroot
3## \notebook -nodraw
4## This tutorial illustrates the conversion of STL vectors and TVec to numpy
5## arrays without copying the data.
6## The memory-adoption is achieved by the dictionary __array_interface__, which
7## is added dynamically to the Python objects by PyROOT.
8##
9## \macro_code
10## \macro_output
11##
12## \date April 2018
13## \author Stefan Wunsch
14
15import ROOT
16from sys import exit
17
18try:
19 import numpy as np
20except:
21 exit()
22
23# Create a vector ROOT object and assign values
24# Note that this works as well with a TVec
25vec = ROOT.std.vector("float")(2)
26vec[0] = 1
27vec[1] = 2
28print("Content of the ROOT vector object: {}".format([x for x in vec]))
29
30# Interface ROOT vector with a numpy array
31array = np.asarray(vec)
32print("Content of the associated numpy array: {}".format([x for x in array]))
33
34# The numpy array adopts the memory of the vector without copying the content.
35# Note that the first entry of the numpy array changes when assigning a new
36# value to the first entry of the ROOT vector.
37vec[0] = 42
38print(
39 "Content of the numpy array after changing the first entry of the ROOT vector: {}".
40 format([x for x in array]))
41
42# Use numpy features on data of ROOT objects
43print("Mean of the numpy array entries: {}".format(np.mean(array)))
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format