13.2.2. Macro “howtoConvertTMatrixDArray.py”
13.2.2.1. Objective
The goal of this macro is only to show how to convert a TMatrixD object into a numpy.array and
vice-versa.
13.2.2.2. Macro Uranie
"""
Example of TMatrix into numpy array conversion
"""
import numpy as np
import ROOT
# define the number of rows and columns
nrow = 3
ncol = 5
# Initialise and fill a TMatrixD
InMat = ROOT.TMatrixD(nrow, ncol)
for i in range(nrow):
for j in range(ncol):
InMat[i][j] = ROOT.gRandom.Gaus(0, 1)
print("Original TMatrixD")
InMat.Print()
# Create the ndarray with the good shape
mat_version = np.frombuffer(InMat.GetMatrixArray(), dtype=np.float64,
count=nrow*ncol).reshape(nrow, ncol)
print("Numpy array transformation")
print(mat_version)
# Back to another TMatrixD
OutMat = ROOT.TMatrixD(nrow, ncol)
OutMat.SetMatrixArray(mat_version)
print("\nRecreated TMatrixD")
OutMat.Print()
The first block simply defines the size of the matrix to be created and creates along, from scratch,
a TMatrixD with a random gaussian content. Once done, the conversion into a np.array is done in
a single line manner below that would be breakdown to get the full picture:
mat_version = np.frombuffer(InMat.GetMatrixArray(), dtype=np.float64,
count=nrow*ncol).reshape(nrow, ncol)
The content of the original TMatrixD can be accessed by calling GetMatrixArray(). This returns a
pointer to the first element’s address, so it can be used by the lowest level array object of numpy,
the np.frombuffer which also needs the type of data and the number of elements. This is important
as the memory will be scanned given these two information. The last step is to call, on this newly
created object the reshape method to create a properly organised np.array.
The second part consists in creating a brand new TMatrixD from the newly created np.array. The
idea is simply to create the object empty and use the SetMatrixArray method to dump the array
content into the matrix, as done below.
OutMat = ROOT.TMatrixD(nrow, ncol)
OutMat.SetMatrixArray(mat_version)
The output of this macro is shown in Console.
13.2.2.3. Console
Original TMatrixD
3x5 matrix is as follows
| 0 | 1 | 2 | 3 | 4 |
----------------------------------------------------------------------
0 | 0.9989 -0.4348 0.7818 -0.03005 0.8243
1 | -0.05672 -0.9009 -0.0747 0.007912 -0.4108
2 | 1.391 -0.9851 -0.04894 -1.443 -1.061
Numpy array transformation
[[ 0.99893272 -0.43476439 0.78179626 -0.03005277 0.82426369]
[-0.05671733 -0.90087599 -0.07470447 0.00791221 -0.41076317]
[ 1.39119397 -0.98506611 -0.04894054 -1.44333537 -1.06067041]]
Recreated TMatrixD
3x5 matrix is as follows
| 0 | 1 | 2 | 3 | 4 |
----------------------------------------------------------------------
0 | 0.9989 -0.4348 0.7818 -0.03005 0.8243
1 | -0.05672 -0.9009 -0.0747 0.007912 -0.4108
2 | 1.391 -0.9851 -0.04894 -1.443 -1.061