Archive for the ‘python’ Category

Articles

Solve weighted least squares with NumPy

In python on Aug 3, 2016 by theoryl Tagged: , , , ,

As posted on StackOverflow: http://stackoverflow.com/questions/27128688/how-to-use-least-squares-with-weight-matrix-in-python

import numpy as np

# Solve for X in AX = B
A = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,0,0]])
B = np.array([1,1,1,1,1])
W = np.array([1,2,3,4,5])
Aw = A * np.sqrt(W[:,np.newaxis])
Bw = B * np.sqrt(W)
X = np.linalg.lstsq(Aw, Bw)[0]

Articles

Loop over histograms in ROOT file

In python on Jul 29, 2016 by theoryl Tagged: , ,

Looping over all histograms in a ROOT file using pyROOT

from ROOT import TFile
tfile = TFile.Open("histos.root")
tfile.cd()
for h in tfile.GetListOfKeys():
    h = h.ReadObj()
    print h.ClassName(), h.GetName()

Articles

Solve system of linear equations

In python on Jul 27, 2016 by theoryl Tagged: , , ,

Solving system of linear equations m x = y with NumPy

import numpy as np
from numpy import linalg as LA

m = np.array([
[  0.68,  0.597,  -0.33,],
[-0.211,  0.823,  0.536,],
[ 0.566, -0.605, -0.444,],
])

y = np.array([
[  0.108,   -0.27,   0.832,],
[-0.0452,  0.0268,   0.271,],
[  0.258,   0.904,   0.435,],
])

# Using QR decomposition
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.qr.html
q, r = LA.qr(m)
soln = np.dot(LA.inv(r), np.dot(q.T, y))

# Using least squares
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html
soln2 = LA.solve(m, y)

>>> print m
[[ 0.68   0.597 -0.33 ]
 [-0.211  0.823  0.536]
 [ 0.566 -0.605 -0.444]]
>>> print y
[[ 0.108  -0.27    0.832 ]
 [-0.0452  0.0268  0.271 ]
 [ 0.258   0.904   0.435 ]]
>>> print q
[[-0.74762435 -0.58417508 -0.31590713]
 [ 0.23198344 -0.67542676  0.69998741]
 [-0.62228733  0.45004241  0.64048444]]
>>> print r
[[-0.90954769  0.12107447  0.64735473]
 [-0.         -1.1769044  -0.3690698 ]
 [ 0.         -0.          0.19506751]]
>>> print soln
[[ 0.60907309  2.67396101  1.67163769]
 [-0.2309286  -1.56240961  0.07184063]
 [ 0.51001615  3.50162105  1.05334088]]
>>> print np.dot(m, soln)
[[ 0.108  -0.27    0.832 ]
 [-0.0452  0.0268  0.271 ]
 [ 0.258   0.904   0.435 ]]
>>> print soln2
[[ 0.60907309  2.67396101  1.67163769]
 [-0.2309286  -1.56240961  0.07184063]
 [ 0.51001615  3.50162105  1.05334088]]
>>> print np.dot(m, soln2)
[[ 0.108  -0.27    0.832 ]
 [-0.0452  0.0268  0.271 ]
 [ 0.258   0.904   0.435 ]]