ROOT
6.18/05
Reference Guide
tutorials
pyroot
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
##
11
## \date April 2018
12
## \author Stefan Wunsch
13
14
import
ROOT
15
from
sys
import
exit
16
17
try
:
18
import
numpy
as
np
19
except
:
20
exit()
21
22
# Create a vector ROOT object and assign values
23
# Note that this works as well with a TVec
24
vec = ROOT.std.vector(
"float"
)(2)
25
vec[0] = 1
26
vec[1] = 2
27
print(
"Content of the ROOT vector object: {}"
.format([x
for
x
in
vec]))
28
29
# Interface ROOT vector with a numpy array
30
array = np.asarray(vec)
31
print(
"Content of the associated numpy array: {}"
.format([x
for
x
in
array]))
32
33
# The numpy array adopts the memory of the vector without copying the content.
34
# Note that the first entry of the numpy array changes when assigning a new
35
# value to the first entry of the ROOT vector.
36
vec[0] = 42
37
print(
38
"Content of the numpy array after changing the first entry of the ROOT vector: {}"
.
39
format([x
for
x
in
array]))
40
41
# Use numpy features on data of ROOT objects
42
print(
"Mean of the numpy array entries: {}"
.format(np.mean(array)))