def makeDispersion(): nAtoms = 2 nBranches = 3 * nAtoms nQx = 10; nQy = 12; nQz = 14 Qaxes = [ ([1,0,0], nQx), ([0,1,0], nQy), ([0,0,1], nQz), ] import histogram as H qx = H.axis('qx', H.arange(0, 1+1e-10, 1./(nQx-1))) qy = H.axis('qy', H.arange(0, 1+1e-10, 1./(nQy-1))) qz = H.axis('qz', H.arange(0, 1+1e-10, 1./(nQz-1))) br = H.axis('branchId', range(nBranches)) atoms = H.axis('atomId', range(nAtoms)) pols = H.axis('polId', range(3)) realimags = H.axis('realimagId', range(2)) eps = H.histogram('eps', [qx,qy,qz,br,atoms,pols,realimags]) eps.I[:] = 1 e = H.histogram('e', [qx,qy,qz,br], fromfunction = lambda qx,qy,qz,br: (qx*qx+qy*qy+qz*qz)/3.*50, ) disp = b.linearlyinterpolateddispersion_3d(nAtoms, Qaxes, eps.I, e.I) disp = b.periodicdispersion(disp, ((1,0,0), (0,1,0), (0,0,1))) return disp
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nx = core.nx ny = core.ny n = nx * ny shape = nx, ny # xmin = core.x_min; xmax = core.x_max # ymin = core.y_min; ymax = core.y_max xmin = attr(core, "xmin", "x_min") xmax = attr(core, "xmax", "x_max") ymin = attr(core, "ymin", "y_min") ymax = attr(core, "ymax", "y_max") dx = (xmax - xmin) / nx dy = (ymax - ymin) / ny Iarr = bpptr2npyarr(core.getPSD_p_00(), 'double', n).copy() E2arr = bpptr2npyarr(core.getPSD_p2_00(), 'double', n).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis('x', arange(xmin, xmax, dx)) yaxis = axis('y', arange(ymin, ymax, dy)) h = histogram('I(x,y)', [xaxis, yaxis], data=Iarr, errors=E2arr) return h
def get_histogram( monitor ): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() xmin = 0; xmax = 1 ymin = 0; ymax = 1 dx = 0.1 dy = 0.1 # xmin = core.xmin; xmax = core.xmax # ymin = core.ymin; ymax = core.ymax # dx = xmax - xmin # dy = ymax - ymin # OUTPUT PARAMETERS (DEFS, Vars) #Iarr = bpptr2npyarr( core.getDEFS( ), 'double', n ).copy() #? #E2arr = bpptr2npyarr( core.getPSD_p2_00( ), 'double', n ).copy() #Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis( 'x', arange( xmin, xmax, dx ) ) yaxis = axis( 'y', arange( ymin, ymax, dy ) ) h = histogram( 'I(x,y)', [xaxis,yaxis], data = [2,yaxis], errors=[2,yaxis]) #Iarr) #, errors = E2arr ) return h
def testdump2(self): 'dump two histograms to one hdf' filename = 'testdump1.h5' import os if os.path.exists( filename): os.remove( filename ) from h5py import File fs = File( filename, 'w' ) from histogram import histogram, arange h = histogram('h', [('x', arange(0,100, 1.) ), ('y', arange(100, 180, 1.) ),], unit = 'meter', ) dump( h, None, '/', fs = fs ) h2 = histogram('h2', [('x', arange(0,100, 1.) ), ('y', arange(100, 180, 1.) ),], unit = 'meter', ) dump( h2, None, '/', fs = fs ) #load histogram h2c = load( filename, '/h2', fs = fs ) print h2c self.assert_( os.path.exists( filename ))
def get_histogram( monitor ): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nx = core.nxchan; ny =core.nychan; nb = core.nbchan n = nx * ny * nb shape = nx, ny, nb xmin = -core.xwidth/2; xmax = core.xwidth/2 ymin = -core.yheight/2; ymax = core.yheight/2 dx = (xmax - xmin)/nx dy = (ymax - ymin)/ny if core.bmax!=0: bmax=core.bmax bmin=core.bmin db=(bmax-bmin)/nb else : db = core.deltab bmin=0; bmax=nb*db+bmin Iarr = bpptr2npyarr( core.getTOF_p_00( ), 'double', n ).copy() E2arr = bpptr2npyarr( core.getTOF_p2_00( ), 'double', n ).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis( 'x', boundaries=arange( xmin, xmax+dx/10, dx ) ) yaxis = axis( 'y', boundaries=arange( ymin, ymax+dy/10, dy ) ) baxis = axis( 'b', boundaries=arange( bmin, bmax+db/10, db ) ) h = histogram( 'I(x,y,b)', [xaxis,yaxis,baxis], data = Iarr, errors = E2arr ) return h
def testdump2(self): 'dump two histograms to one hdf' filename = 'testdump1.h5' import os if os.path.exists(filename): os.remove(filename) from h5py import File fs = File(filename, 'w') from histogram import histogram, arange h = histogram( 'h', [ ('x', arange(0, 100, 1.)), ('y', arange(100, 180, 1.)), ], unit='meter', ) dump(h, None, '/', fs=fs) h2 = histogram( 'h2', [ ('x', arange(0, 100, 1.)), ('y', arange(100, 180, 1.)), ], unit='meter', ) dump(h2, None, '/', fs=fs) #load histogram h2c = load(filename, '/h2', fs=fs) print(h2c) self.assertTrue(os.path.exists(filename))
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nx = core.nx ny = core.ny assert nx == int(nx) nx = int(nx) assert ny == int(ny) ny = int(ny) n = nx * ny shape = nx, ny Iarr = bpptr2npyarr(core.getPSD_p_00(), 'double', n).copy() E2arr = bpptr2npyarr(core.getPSD_p2_00(), 'double', n).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange dx = 360. / nx xaxis = axis('x', arange(0, 360, dx), unit='deg') dy = 180. / ny yaxis = axis('y', arange(-90, 90, dy), unit='deg') h = histogram('I(x,y)', [xaxis, yaxis], data=Iarr, errors=E2arr) return h
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() xmin = 0 xmax = 1 ymin = 0 ymax = 1 dx = 0.1 dy = 0.1 # xmin = core.xmin; xmax = core.xmax # ymin = core.ymin; ymax = core.ymax # dx = xmax - xmin # dy = ymax - ymin # OUTPUT PARAMETERS (DEFS, Vars) #Iarr = bpptr2npyarr( core.getDEFS( ), 'double', n ).copy() #? #E2arr = bpptr2npyarr( core.getPSD_p2_00( ), 'double', n ).copy() #Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis('x', arange(xmin, xmax, dx)) yaxis = axis('y', arange(ymin, ymax, dy)) h = histogram('I(x,y)', [xaxis, yaxis], data=[2, yaxis], errors=[2, yaxis]) #Iarr) #, errors = E2arr ) return h
def makeDispersion(): nAtoms = 2 nBranches = 3 * nAtoms nQx = 10 nQy = 12 nQz = 14 Qaxes = [ ([1, 0, 0], nQx), ([0, 1, 0], nQy), ([0, 0, 1], nQz), ] import histogram as H qx = H.axis('qx', H.arange(0, 1 + 1e-10, 1. / (nQx - 1))) qy = H.axis('qy', H.arange(0, 1 + 1e-10, 1. / (nQy - 1))) qz = H.axis('qz', H.arange(0, 1 + 1e-10, 1. / (nQz - 1))) br = H.axis('branchId', range(nBranches)) atoms = H.axis('atomId', range(nAtoms)) pols = H.axis('polId', range(3)) realimags = H.axis('realimagId', range(2)) eps = H.histogram('eps', [qx, qy, qz, br, atoms, pols, realimags]) eps.I[:] = 1 e = H.histogram( 'e', [qx, qy, qz, br], fromfunction=lambda qx, qy, qz, br: (qx * qx + qy * qy + qz * qz) / 3. * 50, ) disp = b.linearlyinterpolateddispersion_3d(nAtoms, Qaxes, eps.I, e.I) disp = b.periodicdispersion(disp, ((1, 0, 0), (0, 1, 0), (0, 0, 1))) return disp
def get_histogram( monitor ): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nx = core.nx; ny =core.ny n = nx * ny shape = nx, ny # xmin = core.x_min; xmax = core.x_max # ymin = core.y_min; ymax = core.y_max xmin = attr(core, "xmin", "x_min"); xmax = attr(core, "xmax", "x_max"); ymin = attr(core, "ymin", "y_min"); ymax = attr(core, "ymax", "y_max"); dx = (xmax - xmin)/nx dy = (ymax - ymin)/ny Iarr = bpptr2npyarr( core.getPSD_p_00( ), 'double', n ).copy() E2arr = bpptr2npyarr( core.getPSD_p2_00( ), 'double', n ).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis( 'x', arange( xmin, xmax, dx ) ) yaxis = axis( 'y', arange( ymin, ymax, dy ) ) h = histogram( 'I(x,y)', [xaxis,yaxis], data = Iarr, errors = E2arr ) return h
def test_values2indexes(self): "Histogram: values2indexes" from histogram import histogram, axis, arange x = axis( 'x', arange(1., 10., 1.) ) y = axis( 'y', arange(-1., 1., 0.1) ) h = histogram('h', (x,y) ) self.assertVectorEqual( h.values2indexes( (2, 0.2) ), (1,12) ) return
def test__idiv__2(self): "histogram: h/=h1" h = self._histogram.copy() h2 = self._histogram2 h /= h2 self.assertVectorAlmostEqual( h[1.5,1], (1,2.0/3) ) h = self._histogram.copy() h2 = createHistogram( noerror = True ) h /= h2 self.assertVectorAlmostEqual( h[1.5,1], (1,1./3) ) from histogram import histogram, axis, arange, datasetFromFunction x = axis('x', arange(1, 2, .2 ) ) y = axis('y', arange(0, 3, .5 ) ) def fa(x,y): return x*y + x ha = histogram('a', [x,y], datasetFromFunction( fa, (x,y) ) ) for xi in x.binCenters(): for yi in y.binCenters(): self.assertAlmostEqual( fa(xi,yi), ha[xi,yi][0] ) def fb(x,y): return x hb = histogram('b', [x,y], datasetFromFunction( fb, (x,y) ) ) hc = ha/hb for xi in x.binCenters(): for yi in y.binCenters(): self.assertAlmostEqual( yi+1, hc[xi,yi][0] ) def fberr(x,y): return 0*x hb = histogram('b', [x,y], datasetFromFunction( fb, (x,y) ), datasetFromFunction( fberr, (x,y) ) ) hc = ha/hb for xi in x.binCenters(): for yi in y.binCenters(): self.assertAlmostEqual( yi+1, hc[xi,yi][0] ) #involve units h1 = histogram( 'h1', [ ('x', [1,2,3]), ], unit = 'meter', data = [1,2,3], errors = [1,2,3], ) h2 = histogram( 'h2', [ ('x', [1,2,3]), ], data = [1,1,1], errors = [1,1,1], unit = 'second', ) h3 = h1/h2 self.assertVectorAlmostEqual( h3.I, (1,2,3) ) self.assertVectorAlmostEqual( h3.E2, (2,6,12) ) return
def test_axisFromId(self): "Histogram: axisFromId" from histogram import histogram, axis, arange x = axis( 'x', arange(1., 10., 1.) ) y = axis( 'y', arange(-1., 1., 0.1) ) h = histogram('h', (x,y) ) self.assertEqual( h.axisFromId(1), x ) self.assertEqual( h.axisFromId(2), y ) return
def test0(self): import histogram as H qaxis = H.axis('Q', boundaries=H.arange(0, 13.0, 0.1)) eaxis = H.axis('energy', boundaries=H.arange(-50, 50, 1.0)) sqe = H.histogram('sqe', [qaxis, eaxis], fromfunction=lambda q, e: q * q + e * e) from mccomponents.sample.idf import writeSQE writeSQE(sqe, datapath) return
def setParameters( self, Q_params, E_params, ARCSxml, Ei, emission_time): keys = [ 'detector-system-dimensions', 'moderator-sample distance', 'pixelID-position mapping binary file', 'detector axes', 'solidangles', ] infos = self._readInstrumentInfo(ARCSxml, keys=keys) npacks, ndetsperpack, npixelsperdet = infos[ 'detector-system-dimensions'] mod2sample = infos['moderator-sample distance'] pixelPositionsFilename = infos[ 'pixelID-position mapping binary file'] self._debug.log( "pixel-positions-filename=%s" % pixelPositionsFilename) self._debug.log( 'E_params (unit: meV) = %s' % (E_params, ) ) self._debug.log( 'Q_params (unit: angstrom^-1) = %s' % (Q_params, ) ) self._debug.log( 'mod2sample distance = %s' % mod2sample ) self._debug.log( 'Incident energy (unit: meV) = %s' % (Ei, ) ) self._debug.log( 'emission_time (unit: microsecond) = %s' % (emission_time, ) ) E_begin, E_end, E_step = E_params # meV Q_begin, Q_end, Q_step = Q_params # angstrom^-1 Q_axis = histogram.axis('Q', boundaries = histogram.arange( Q_begin, Q_end, Q_step) ) E_axis = histogram.axis('energy', boundaries = histogram.arange( E_begin, E_end, E_step) ) h = histogram.histogram( 'I(Q,E)', [ Q_axis, E_axis, ], data_type = 'int', ) pixelPositions = arcseventdata.readpixelpositions( pixelPositionsFilename, npacks, ndetsperpack, npixelsperdet ) # remember a few things so that we can do normalization mpiRank = self.mpiRank if mpiRank == 0: pixelSolidAngles = infos['solidangles'].I self._remember( Ei, pixelPositions, pixelSolidAngles ) self.out_histogram = h self.pixelPositions = pixelPositions self.Ei = Ei self.mod2sample = mod2sample self.emission_time = emission_time return
def createSqe(): import histogram as H qaxis = H.axis( 'Q', boundaries = H.arange(0, 13.0, 0.1) ) eaxis = H.axis( 'energy', boundaries = H.arange(-50, 50, 1.0) ) sqe = H.histogram( 'sqe', [ qaxis, eaxis ], fromfunction = sqe_f ) return sqe
def testReplaceAxis(self): 'Hisogram: replaceAxis' from histogram import histogram, axis, arange a = axis('a', arange(1,10,1.0)) b = axis('b', arange(1,100,10.)) h = histogram( 'h', [a] ) self.assertTrue(a is h.axisFromName('a')) h.replaceAxis(name='a', axis=b) self.assertTrue(b is h.axisFromName('a')) return
def test(): from histogram import histogram, axis, arange, plot xaxis = axis('x', arange(5), unit='meter') yaxis = axis('y', arange(7), unit='cm') axes = [xaxis, yaxis] h = histogram( "intensity", axes, fromfunction=lambda x,y: x**2+y**2) print h plot(h) help(h) slice = h[3, ()]
def test(): from histogram import histogram, axis, arange, plot xaxis = axis('x', arange(5), unit='meter') yaxis = axis('y', arange(7), unit='cm') axes = [xaxis, yaxis] h = histogram("intensity", axes, fromfunction=lambda x, y: x**2 + y**2) print(h) plot(h) help(h) slice = h[3, ()]
def testReplaceAxis(self): 'Hisogram: replaceAxis' from histogram import histogram, axis, arange a = axis('a', arange(1,10,1.0)) b = axis('b', arange(1,100,10.)) h = histogram( 'h', [a] ) self.assert_(a is h.axisFromName('a')) h.replaceAxis(name='a', axis=b) self.assert_(b is h.axisFromName('a')) return
def test2Db(self): "pylab plotter: 2D. z>0" import histogram as H, pylab h = H.histogram("h", [("x", H.arange(10)), ("y", H.arange(5))], fromfunction=lambda x, y: x * x + y * y) self.plotter.plot(h) if interactive: raw_input("Press ENTER to continue") pylab.clf() pylab.close() return
def test0(self): import histogram as H qaxis = H.axis( 'Q', boundaries = H.arange(0, 13.0, 0.1) ) eaxis = H.axis( 'energy', boundaries = H.arange(-50, 50, 1.0) ) sqe = H.histogram( 'sqe', [ qaxis, eaxis ], fromfunction = lambda q,e: q*q+e*e ) from mccomponents.sample.idf import writeSQE writeSQE( sqe, datapath ) return
def test2(self): 'create a SQE histogram from data and plot it' from histogram import histogram, arange sqe = histogram( name = 'S(Q,E)', axes = [('Q', arange(0,12,0.1), 'angstrom**-1'), ('E', arange(-50,50, 1.), 'meV')], ) sqe.I[:] = 1 if interactive: from histogram.plotter import defaultPlotter defaultPlotter.plot(sqe) return
def test1(self): 'create a SQE histogram from function and plot it' from histogram import histogram, arange sqe = histogram( name = 'S(Q,E)', axes = [('Q', arange(0,12,0.1), 'angstrom**-1'), ('E', arange(-50,50, 1.), 'meV')], fromfunction = lambda q,e: q**2+e**2, ) if interactive: from histogram.plotter import defaultPlotter defaultPlotter.plot(sqe) return
def test3(self): 'LinearlyInterpolatedDispersion_3D' import mccomponents.sample.phonon.bindings as bindings b = bindings.get('BoostPython') nAtoms = 2 nBranches = 3 * nAtoms nQx = 10 nQy = 12 nQz = 14 Qaxes = [ ([1, 1, 0], nQx), ([1, 0, 1], nQy), ([0, 1, 1], nQz), ] import histogram as H qx = H.axis('qx', H.arange(0, 1 + 1e-10, 1. / (nQx - 1))) qy = H.axis('qy', H.arange(0, 1 + 1e-10, 1. / (nQy - 1))) qz = H.axis('qz', H.arange(0, 1 + 1e-10, 1. / (nQz - 1))) br = H.axis('branchId', range(nBranches)) atoms = H.axis('atomId', range(nAtoms)) pols = H.axis('polId', range(3)) realimags = H.axis('realimagId', range(2)) eps = H.histogram('eps', [qx, qy, qz, br, atoms, pols, realimags], fromfunction=lambda qx, qy, qz, br, atom, pol, realimag: qx + qy + qz + br + atom + pol + realimag) e = H.histogram('e', [qx, qy, qz, br], fromfunction=lambda qx, qy, qz, br: qx + qy + qz + br) disp = b.linearlyinterpolateddispersion_3d(nAtoms, Qaxes, eps.I, e.I) Q = b.vector3 # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # these tests failed because we are not doing interpolation # right now since we don't have a good way to do # it for the polarization vectors. # right now we just take the value of the closest vertex. checkDiff = self.assertAlmostEqual def checkDiff(a, b): print a, b checkDiff(disp.energy(0, Q(0, 0, 0)), 0) checkDiff(disp.energy(0, Q(1 - 1e-5, 1 - 1e-5, 0)), 1 - 1e-5) checkDiff(disp.energy(0, Q(0.5, 0.5, 0)), 0.5) checkDiff(disp.energy(0, Q(0.5, 0, 0.5)), 0.5) checkDiff(disp.energy(0, Q(0, 0.5, 0.5)), 0.5) checkDiff(disp.energy(0, Q(0.5, 0.5, 1 - 1e-10)), 1) return
def testdump0a(self): """ histogram.hdf: dump with compression""" from histogram import histogram, arange h = histogram('h', [('x', arange(0,100, 1.) ), ('y', arange(100, 180, 1.) ),], unit = 'meter', ) filename = 'test0-compressed.h5' import os if os.path.exists( filename): os.remove( filename ) dump( h, filename, '/', mode = 'c', compression=6 ) return
def testload3(self): 'load a slice of a histogram ' tmpfile = "tmp.h5" if os.path.exists( tmpfile): os.remove(tmpfile) cmd = "from histogram.hdf import dump; from histogram import histogram, arange; h = histogram( 'h', [ ('xID', range(10)), ('y', arange(0, 1,0.1)) ] ); from numpy import array; d = array(range(100)); d.shape = 10,10; h[{}] = d, 0; dump(h, %r, '/', 'c') " % tmpfile os.system( 'python -c %r' % cmd ) if not os.path.exists( tmpfile ): raise "failed to create tmp h5 file of historam" h1 = load( tmpfile, 'h', xID=(3,6) ) assert h1.shape() == (4,10) d = h1.data().storage().asNumarray().copy() d.shape = 40, print d self.assertVectorAlmostEqual( d, range(30,70) ) self.assertVectorEqual( h1.axisFromId(1).binCenters(), (3,4,5,6) ) from numpy import arange self.assertVectorAlmostEqual( h1.axisFromId(2).binCenters(), arange(0,1,0.1) ) h2 = load( tmpfile, 'h', xID=(3,6), y=(0.4,0.5) ) assert h2.shape() == (4,2) d = h2.data().storage().asNumarray().copy() d.shape = 8, self.assertVectorAlmostEqual( d, (34,35,44,45,54,55,64,65) ) self.assertVectorEqual( h2.axisFromId(1).binCenters(), (3,4,5,6) ) from numpy import arange self.assertVectorAlmostEqual( h2.axisFromId(2).binCenters(), (0.4,0.5) )
def events2Idpt( events, instrument, tofparams ): from mccomponents.detector.utils import \ getDetectorHierarchyDimensions dims = getDetectorHierarchyDimensions( instrument ) # 1st attempt to create axes from histogram import histogram, axis, arange axes = [ axis('%sID' % name.lower(), range(n)) for name, n in dims ] # the first level of detectors (tubes, packs, or others) need # special attention. ids of that level could be not continuous. detectorSystem = instrument.getDetectorSystem() assert len(detectorSystem.elements()) == dims[0][1] ids = [ element.id() for element in detectorSystem.elements() ] axes[0] = axis( axes[0].name(), ids ) detaxes = axes #tof axis tmin, tmax, tstep = tofparams tofaxis = axis( 'tof', boundaries = arange( tmin, tmax+tstep/10., tstep ), unit = 'second' ) #all axes axes = detaxes + [tofaxis] #histogram hist = histogram( 'Idpt', axes ) #get the numpy array which will accept events npixels = hist.size()/tofaxis.size() Ipixtof = hist.data().storage().asNumarray() Ipixtof.shape = npixels, -1 events2Ipixtof( events, Ipixtof ) return hist
def resample( hist1, size ): import histogram as H assert hist1.dimension() == 1 assert hist1.shape()[0] > display_size*10 xaxis = hist1.axes()[0] xbb = xaxis.binBoundaries().asNumarray() front, back = xbb[0], xbb[-1] step = (back-front)/size newxbb = H.arange( front, back+step/2, step) newxaxis = H.axis( xaxis.name(), boundaries = newxbb, unit = xaxis.unit() ) newhist = H.histogram( hist1.name(), [ newxaxis ] ) newxc = newxaxis.binCenters() for x in newxc[1:-1] : newhist[ x ] = hist1[ (x-step/2, x+step/2) ].sum() continue newhist[ newxc[0] ]= hist1[ (newxbb[0], newxc[0] + step/2) ].sum() newhist[ newxc[-1] ]= hist1[ (newxc[-1]-step/2, newxbb[-1]-step*1.e-10) ].sum() return newhist
def test_as_floattype(self): from histogram import histogram, arange h = histogram( 'h', [ ('x',arange(10)) ], data_type = 'int') h1 = h.as_floattype() self.assertEqual( h1.typeCode(), 6 ) self.assert_( h1.axisFromName( 'x' ) is not h.axisFromName( 'x' ) ) return
def create(noerror=False): from histogram import createContinuousAxis, createDiscreteAxis, arange #create axis E axisE = createContinuousAxis('E', 'meter', arange(0.5, 3.5, 1.0)) #create axis "tubeId" axisTubeId = createDiscreteAxis("tubeId", [1, 3, 99], 'int') #create histogram from histogram import createDataset from ndarray.StdVectorNdArray import NdArray dataStorage = NdArray('double', range(9)) dataStorage.setShape((3, 3)) errorsStorage = NdArray('double', range(9)) errorsStorage.setShape((3, 3)) data = createDataset('data', '', storage=dataStorage) if noerror: errors = None else: errors = createDataset('errors', '', storage=errorsStorage) from histogram.Histogram import Histogram histogram = Histogram(name='I(E, TubeId)', data=data, errors=errors, axes=[axisE, axisTubeId]) return histogram
def testload3(self): 'load a slice of a histogram ' tmpfile = "tmp.h5" if os.path.exists(tmpfile): os.remove(tmpfile) cmd = "from histogram.hdf import dump; from histogram import histogram, arange; h = histogram( 'h', [ ('xID', range(10)), ('y', arange(0, 1,0.1)) ] ); from numpy import array; d = array(range(100)); d.shape = 10,10; h[{}] = d, 0;" cmd += "dump(h, {!r}, '/', 'c') ".format(tmpfile) os.system('python -c {0!r}'.format(cmd)) if not os.path.exists(tmpfile): raise "failed to create tmp h5 file of historam" h1 = load(tmpfile, 'h', xID=(3, 6)) assert h1.shape() == (4, 10) d = h1.data().storage().asNumarray().copy() d.shape = 40, print(d) self.assertVectorAlmostEqual(d, list(range(30, 70))) self.assertVectorEqual(h1.axisFromId(1).binCenters(), (3, 4, 5, 6)) from numpy import arange self.assertVectorAlmostEqual( h1.axisFromId(2).binCenters(), arange(0, 1, 0.1)) h2 = load(tmpfile, 'h', xID=(3, 6), y=(0.4, 0.5)) assert h2.shape() == (4, 2) d = h2.data().storage().asNumarray().copy() d.shape = 8, self.assertVectorAlmostEqual(d, (34, 35, 44, 45, 54, 55, 64, 65)) self.assertVectorEqual(h2.axisFromId(1).binCenters(), (3, 4, 5, 6)) from numpy import arange self.assertVectorAlmostEqual(h2.axisFromId(2).binCenters(), (0.4, 0.5))
def resample(hist1, size): import histogram as H assert hist1.dimension() == 1 assert hist1.shape()[0] > display_size * 10 xaxis = hist1.axes()[0] xbb = xaxis.binBoundaries().asNumarray() front, back = xbb[0], xbb[-1] step = 1. * (back - front) / size newxbb = H.arange(front, back + step / 2., step) newxaxis = H.axis(xaxis.name(), boundaries=newxbb, unit=xaxis.unit()) newhist = H.histogram(hist1.name(), [newxaxis]) newxc = newxaxis.binCenters() for x in newxc[1:-1]: newhist[x] = hist1[(x - step / 2., x + step / 2.)].sum() continue newhist[newxc[0]] = hist1[(newxbb[0], newxc[0] + step / 2.)].sum() newhist[newxc[-1]] = hist1[(newxc[-1] - step / 2., newxbb[-1] - step * 1.e-10)].sum() return newhist
def test_as_floattype(self): from histogram import histogram, arange h = histogram( 'h', [ ('x',arange(10)) ], data_type = 'int') h1 = h.as_floattype() self.assertEqual( h1.typeCode(), 6 ) self.assertTrue( h1.axisFromName( 'x' ) is not h.axisFromName( 'x' ) ) return
def testSlicing(self): "Axis[3:5]" from histogram import createContinuousAxis, arange axis = createContinuousAxis("distance", "meter", arange(1.0, 2.0, 0.1)) from histogram.SlicingInfo import SlicingInfo new = axis[SlicingInfo((1.1, 1.5))] self.assertVectorAlmostEqual(new.storage().asList(), [1.05, 1.15, 1.25, 1.35, 1.45, 1.55]) new = axis[SlicingInfo((1.0, 1.9))] self.assertVectorAlmostEqual(new.storage().asList(), axis.storage().asList()) self.assertRaises(IndexError, axis.__getitem__, SlicingInfo( (1.0, 2.0))) # dimensional sliciing from histogram._units import length meter = length.meter new = axis[SlicingInfo((1.0 * meter, 1.9 * meter))] self.assertVectorAlmostEqual(new.storage().asList(), axis.storage().asList()) return
def testSlicing(self): "Axis[3:5]" from histogram import createContinuousAxis, arange axis = createContinuousAxis( "distance", "meter", arange( 1.0, 2.0, 0.1 ) ) from histogram.SlicingInfo import SlicingInfo new = axis[ SlicingInfo( (1.1, 1.5) ) ] self.assertVectorAlmostEqual( new.storage().asList(), [1.05, 1.15, 1.25, 1.35, 1.45, 1.55] ) new = axis[ SlicingInfo( (1.0, 1.9) ) ] self.assertVectorAlmostEqual( new.storage().asList(), axis.storage().asList() ) self.assertRaises( IndexError, axis.__getitem__, SlicingInfo( (1.0, 2.0) ) ) # dimensional sliciing from histogram._units import length meter = length.meter new = axis[ SlicingInfo( (1.0*meter, 1.9*meter) ) ] self.assertVectorAlmostEqual( new.storage().asList(), axis.storage().asList() ) return
def setParameters( self, ARCSxml, d_params, emission_time): info.log( 'd_params (unit: AA) = %s' % (d_params, ) ) info.log( 'emission_time (unit: microsecond) = %s' % (emission_time, ) ) infos = self._readInstrumentInfo(ARCSxml) npacks, ndetsperpack, npixelsperdet = infos[ 'detector-system-dimensions'] mod2sample = infos['moderator-sample distance'] pixelPositionsFilename = infos[ 'pixelID-position mapping binary file'] d_begin, d_end, d_step = d_params # angstrom d_axis = histogram.axis('d spacing', boundaries = histogram.arange( d_begin, d_end, d_step) ) detaxes = infos['detector axes'] h = histogram.histogram( 'I(pdpd)', detaxes + [d_axis], data_type = 'int', ) info.log( "reading pixelID->position map..." ) pixelPositions = arcseventdata.readpixelpositions( pixelPositionsFilename, npacks, ndetsperpack, npixelsperdet) self.out_histogram = h self.pixelPositions = pixelPositions self.mod2sample = mod2sample self.emission_time = emission_time return
def test3(self): 'LinearlyInterpolatedDispersion_3D' import mccomponents.sample.phonon.bindings as bindings b = bindings.get('BoostPython') nAtoms = 2 nBranches = 3 * nAtoms nQx = 10; nQy = 12; nQz = 14 Qaxes = [ ([1,1,0], nQx), ([1,0,1], nQy), ([0,1,1], nQz), ] import histogram as H qx = H.axis('qx', H.arange(0, 1+1e-10, 1./(nQx-1))) qy = H.axis('qy', H.arange(0, 1+1e-10, 1./(nQy-1))) qz = H.axis('qz', H.arange(0, 1+1e-10, 1./(nQz-1))) br = H.axis('branchId', range(nBranches)) atoms = H.axis('atomId', range(nAtoms)) pols = H.axis('polId', range(3)) realimags = H.axis('realimagId', range(2)) eps = H.histogram( 'eps', [qx,qy,qz,br,atoms,pols,realimags], fromfunction = lambda qx,qy,qz,br,atom,pol,realimag: qx+qy+qz+br+atom+pol+realimag) e = H.histogram( 'e', [qx,qy,qz,br], fromfunction = lambda qx,qy,qz,br: qx+qy+qz+br) disp = b.linearlyinterpolateddispersion_3d(nAtoms, Qaxes, eps.I, e.I) Q = b.vector3 # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # these tests failed because we are not doing interpolation # right now since we don't have a good way to do # it for the polarization vectors. # right now we just take the value of the closest vertex. checkDiff = self.assertAlmostEqual def checkDiff(a, b): print a,b checkDiff(disp.energy(0, Q(0,0,0)), 0) checkDiff(disp.energy(0, Q(1-1e-5,1-1e-5,0)), 1-1e-5) checkDiff(disp.energy(0, Q(0.5,0.5,0)), 0.5) checkDiff(disp.energy(0, Q(0.5,0,0.5)), 0.5) checkDiff(disp.energy(0, Q(0,0.5,0.5)), 0.5) checkDiff(disp.energy(0, Q(0.5,0.5,1-1e-10)), 1) return
def e2Id( events, n, pixelpositions, dspacing_params = None, Idspacing = None, preNeXus_tofUnit = 1.e-7, mod2sample = 13.5): '''e2Id(events, n, pixelpositions, Idspacing = None, dspacing_params = None, npacks = 115, ndetsperpack = 8, npixelsperdet = 128, preNeXus_tofUnit = 1.e-7, mod2sample = 13.5) --> integrate events to I(d spacing) histogram Either Idspacing or dspacing_params must be given Idspacing: histogram I(d spacing). If this is None, a histogram will be created using dspacing_params. dspacing_params: begin, end, and step of dspacing. unit: angstrom If Idspacing is given, this is ignored. events: neutron events n: number of neutron events to process pixelpositions: array of pixel positions preNeXus_tofUnit: unit of event.tof in the pre-Nexus data format. unit: second mod2sample: moderator-sample distance. unit: meter return: the I(d spacing) histogram ''' if Idspacing is None: if dspacing_params is None: raise ValueError, "Must provide either the (min, max, step) of d axis or the I(d) histogram" dspacing_begin, dspacing_end, dspacing_step = dspacing_params # angstrom import histogram daxis = histogram.axis( 'd', boundaries = histogram.arange(dspacing_begin, dspacing_end, dspacing_step), unit = 'angstrom', ) Idspacing = histogram.histogram( 'I(d spacing)', [daxis], data_type = 'int', ) pass events2Idspacing( events, n, Idspacing, pixelpositions, tofUnit = preNeXus_tofUnit, mod2sample = mod2sample) return Idspacing
def t2(): from histogram import histogram, arange from numpy import exp h = histogram("h", [("tof", arange(1000.0, 3000.0, 1.0), "microsecond")], fromfunction=lambda x: exp(-x / 1000.0)) print h plot(h) return
def t2(): from histogram import histogram, arange from numpy import exp h = histogram("h", [('tof', arange(1000., 3000., 1.0), "microsecond")], fromfunction=lambda x: exp(-x / 1000.)) print(h) plot(h) return
def testdump0a(self): """ histogram.hdf: dump with compression""" from histogram import histogram, arange h = histogram( 'h', [ ('x', arange(0, 100, 1.)), ('y', arange(100, 180, 1.)), ], unit='meter', ) filename = 'test0-compressed.h5' import os if os.path.exists(filename): os.remove(filename) dump(h, filename, '/', mode='c', compression=6) return
def testdump1(self): """ histogram.hdf: dump with fs specified""" filename = 'test1.h5' if os.path.exists( filename): os.remove( filename ) from h5py import File fs = File( filename, 'w' ) from histogram import histogram, arange h = histogram('h', [('x', arange(0, 100, 1.) ), ('y', arange(100, 180, 1.) ),], unit = 'meter', ) #fs will take over dump( h, 'abc', '/', mode = 'w', fs = fs ) self.assert_( os.path.exists( filename )) return
def test_getattribute(self): 'Histogram: __getattribute__' from histogram import histogram, axis, arange x = axis( 'x', arange(1., 10., 1.) ) y = axis( 'y', arange(-1., 1., 0.1) ) h = histogram('h', (x,y) ) self.assertVectorEqual( h.x, x.binCenters() ) self.assertVectorEqual( h.y, y.binCenters() ) t1 = h.I; t2 = h.data().storage().asNumarray() t1.shape = t2.shape = -1, self.assertVectorEqual( t1, t2 ) t1 = h.E2; t2 = h.errors().storage().asNumarray() t1.shape = t2.shape = -1, self.assertVectorEqual( t1, t2 ) return
def read(directory, omega2_idf_file='Omega2', qgridinfo_file='Qgridinfo', weightedq_file='WeightedQ', nD=3): ''' read omega2 data file in idf format nD is the dimension of the qgrid. it is assumed that the qgrid is regular, and is defined in qgridinfo_file The qgridinfo_file is a python file that defines vars bi, {i=1..nD} and ni, {i=1..nD} ''' import os from idf.Omega2 import read info, omega2 = read(os.path.join(directory, omega2_idf_file)) qgridinfo = _retrieveQgridinfo(directory, qgridinfo_file, weightedq_file, nD=nD) # nQ, nbXnD = omega2.shape # import operator nis = [qgridinfo['n' + str(i)] for i in range(1, nD + 1)] assert nQ == reduce(operator.__mul__, nis),\ "Q points mismatch: nQ=%s, {ni}=%s" % (nQ, nis) # number of basis nb = nbXnD / nD # import histogram as H # Q axes Qaxes = [] for i in range(nD): ni = qgridinfo['n' + str(i + 1)] bi = qgridinfo['b' + str(i + 1)] Qiaxis = H.axis('Q' + str(i + 1), H.arange(0, 1 + 1e-10, 1. / (ni - 1)), '1./angstrom', attributes={'b': bi}) Qaxes.append(Qiaxis) continue # basis basisaxis = H.axis('basisID', range(nb)) # dimension Daxis = H.axis('dimensionID', range(nD)) # axes = Qaxes + [basisaxis, Daxis] # omega2.shape = [axis.size() for axis in axes] h = H.histogram('Omega2', axes, data=omega2) return h
def test2Db(self): "pylab plotter: 2D. z>0" import histogram as H, pylab h = H.histogram( 'h', [ ('x', H.arange(10)), ('y', H.arange(5)), ], fromfunction=lambda x, y: x * x + y * y, ) self.plotter.plot(h) if interactive: if sys.version_info < (3, ): input('Press ENTER to continue') else: eval(input('Press ENTER to continue')) pylab.clf() pylab.close() return
def get_histogram( monitor ): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() n = core.nchan Iarr = bpptr2npyarr( core.getTOF_p( ), 'double', n ).copy() E2arr = bpptr2npyarr( core.getTOF_p2( ), 'double', n ).copy() from histogram import histogram, axis, arange dt = (core.tmax-core.tmin)/core.nchan taxis = axis( 'tof', arange( core.tmin+dt/2., core.tmax+dt/2-0.1*dt, dt ), unit = 's' ) h = histogram( 'I(tof)', [taxis], data = Iarr, errors = E2arr ) return h
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() n = core.nchan Iarr = bpptr2npyarr( core.getL_p( ), 'double', n ).copy() E2arr = bpptr2npyarr( core.getL_p2( ), 'double', n ).copy() from histogram import histogram, axis, arange dL = (core.Lmax-core.Lmin)/core.nchan Laxis = axis( 'wavelength', arange( core.Lmin+dL/2, core.Lmax+dL/2, dL ), unit = 'angstrom' ) h = histogram( 'I(L)', [Laxis], data = Iarr, errors = E2arr ) return h
def testdump1(self): """ histogram.hdf: dump with fs specified""" filename = 'test1.h5' if os.path.exists(filename): os.remove(filename) from h5py import File fs = File(filename, 'w') from histogram import histogram, arange h = histogram( 'h', [ ('x', arange(0, 100, 1.)), ('y', arange(100, 180, 1.)), ], unit='meter', ) #fs will take over dump(h, 'abc', '/', mode='w', fs=fs) self.assertTrue(os.path.exists(filename)) return
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() n = core.nchan Iarr = bpptr2npyarr(core.getE_p(), 'double', n).copy() E2arr = bpptr2npyarr(core.getE_p2(), 'double', n).copy() from histogram import histogram, axis, arange dE = (core.Emax - core.Emin) / core.nchan Eaxis = axis('energy', arange(core.Emin + dE / 2, core.Emax, dE), unit='meV') h = histogram('I(E)', [Eaxis], data=Iarr, errors=E2arr) return h
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nQ = core.nQ nE = core.nE n = nQ * nE shape = nQ, nE Iarr = bpptr2npyarr(core.getIQE_p(), 'double', n).copy() E2arr = bpptr2npyarr(core.getIQE_p2(), 'double', n).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange dE = (core.Emax - core.Emin) / nE Eaxis = axis('energy', arange(core.Emin, core.Emax, dE), unit='meV') dQ = (core.Qmax - core.Qmin) / nQ Qaxis = axis('Q', arange(core.Qmin, core.Qmax, dQ), unit='angstrom**-1') h = histogram('I(Q,E)', [Qaxis, Eaxis], data=Iarr, errors=E2arr) return h
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() n = core.nchan Iarr = bpptr2npyarr(core.getL_p(), 'double', n).copy() E2arr = bpptr2npyarr(core.getL_p2(), 'double', n).copy() from histogram import histogram, axis, arange dL = (core.Lmax - core.Lmin) / core.nchan Laxis = axis('wavelength', arange(core.Lmin + dL / 2, core.Lmax + dL / 2, dL), unit='angstrom') h = histogram('I(L)', [Laxis], data=Iarr, errors=E2arr) return h
def test1D_largearray(self): "pylab plotter: 1D large array" import histogram as H, pylab h = H.histogram('h', [('x', H.arange(100000))], fromfunction=lambda x: x * x) self.plotter.plot(h) if interactive: if sys.version_info < (3, ): input('Press ENTER to continue') else: eval(input('Press ENTER to continue')) pylab.clf() pylab.close() return
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() n = core.nchan Iarr = bpptr2npyarr(core.getTOF_p(), 'double', n).copy() E2arr = bpptr2npyarr(core.getTOF_p2(), 'double', n).copy() from histogram import histogram, axis, arange dt = (core.tmax - core.tmin) / core.nchan taxis = axis('tof', arange(core.tmin + dt / 2., core.tmax + dt / 2 - 0.1 * dt, dt), unit='s') h = histogram('I(tof)', [taxis], data=Iarr, errors=E2arr) return h
def get_histogram(monitor): from mcstas2.utils.carray import bpptr2npyarr core = monitor.core() nx = core.nxchan ny = core.nychan nb = core.nbchan n = nx * ny * nb shape = nx, ny, nb xmin = -core.xwidth / 2 xmax = core.xwidth / 2 ymin = -core.yheight / 2 ymax = core.yheight / 2 dx = (xmax - xmin) / nx dy = (ymax - ymin) / ny if core.bmax != 0: bmax = core.bmax bmin = core.bmin db = (bmax - bmin) / nb else: db = core.deltab bmin = 0 bmax = nb * db + bmin Iarr = bpptr2npyarr(core.getTOF_p_00(), 'double', n).copy() E2arr = bpptr2npyarr(core.getTOF_p2_00(), 'double', n).copy() Iarr.shape = E2arr.shape = shape from histogram import histogram, axis, arange xaxis = axis('x', boundaries=arange(xmin, xmax + dx / 10, dx)) yaxis = axis('y', boundaries=arange(ymin, ymax + dy / 10, dy)) baxis = axis('b', boundaries=arange(bmin, bmax + db / 10, db)) h = histogram('I(x,y,b)', [xaxis, yaxis, baxis], data=Iarr, errors=E2arr) return h