Exemple #1
0
    def main(self, *args, **kwds):
        if self.inventory.dumpregistry:
            self._dumpRegsitry()
            return
        
        import mcni
        instrument = self._createInstrument()
        
        geometer = self.geometer

        context = self._makeSimContext()
        
        if self.ncount < self.buffer_size:
            self.buffer_size = int(self.ncount)
        n = int(self.ncount / self.buffer_size)
        
        from mcni import journal
        logger = journal.logger(
            'info', 'instrument', header='', footer='', format='-> %s')
        for i in range(n):
            logger("mpi node %s at loop %s" % (self.mpi.rank, i))
            neutrons = mcni.neutron_buffer( self.buffer_size )
            context.iteration_no = i
            mcni.simulate( instrument, geometer, neutrons, context=context)
            continue
        
        remain = int(self.ncount % self.buffer_size)
        if remain:
            logger("mpi node %s at last loop" % (self.mpi.rank,))
            neutrons = mcni.neutron_buffer(remain)
            context.iteration_no = n
            mcni.simulate( instrument, geometer, neutrons, context=context)
            
        print os.times()
        return
 def test4(self):
     "neutron buffer: swap"
     from mcni import neutron_buffer
     b1 = neutron_buffer(1)
     b2 = neutron_buffer(2)
     b1.swap(b2)
     self.assertEqual(len(b1), 2)
     self.assertEqual(len(b2), 1)
     return
Exemple #3
0
 def test4(self):
     "neutron buffer: swap"
     from mcni import neutron_buffer
     b1 = neutron_buffer(1)
     b2 = neutron_buffer(2)
     b1.swap(b2)
     self.assertEqual(len(b1), 2)
     self.assertEqual(len(b2), 1)
     return
Exemple #4
0
 def test5(self):
     "neutron buffer: appendNeutrons"
     from mcni import neutron_buffer
     b1 = neutron_buffer(1)
     b2 = neutron_buffer(2)
     
     b1.appendNeutrons(b2, 0, len(b2))
     self.assertEqual(len(b1), 3)
     
     b1.appendNeutrons(b2)
     self.assertEqual(len(b1), 5)
     return
    def test5(self):
        "neutron buffer: appendNeutrons"
        from mcni import neutron_buffer
        b1 = neutron_buffer(1)
        b2 = neutron_buffer(2)

        b1.appendNeutrons(b2, 0, len(b2))
        self.assertEqual(len(b1), 3)

        b1.appendNeutrons(b2)
        self.assertEqual(len(b1), 5)
        return
 def test2a(self):
     'normalize: large buffer'
     import mcni
     # create a dummy input
     neutrons = mcni.neutron_buffer( int(3e6) )
     narr = neutrons.to_npyarr()
     narr[:, -1] = 1
     neutrons.from_npyarr(narr)
     out = 'tmp-nst-test2a.ns'
     mns.dump(neutrons, out)
     del neutrons
     
     # try normalize out-of-place
     out2 = 'tmp-nst-test2a-normalized.ns'
     if os.path.exists(out2): os.remove(out2)
     mns.normalize(out, 10., out2)
     neutrons2 = mns.load(out2)
     # and see if it is done correctly
     narr = neutrons2.to_npyarr()
     self.assertTrue((narr[:, -1] == .1).all())
     del neutrons2, narr
     
     # try normalize in-place
     mns.normalize(out, 10.)
     neutrons2 = mns.load(out)
     # and see if it is done correctly
     narr = neutrons2.to_npyarr()
     self.assertTrue((narr[:, -1] == .1).all())
     return
    def test2(self):
        'normalize'
        import mcni
        # create a dummy input
        neutrons = mcni.neutron_buffer( 10 )
        for n in neutrons:
            n.probability = 1
            continue
        out = 'tmp-nst-test2.ns'
        mns.dump(neutrons, out)

        # try normalize out-of-place
        out2 = 'tmp-nst-test2-normalized.ns'
        if os.path.exists(out2): os.remove(out2)
        mns.normalize(out, 10., out2)
        neutrons2 = mns.load(out2)
        # and see if it is done correctly
        for n in neutrons2:
            self.assertAlmostEqual(n.probability, .1)
            continue

        # try normalize in-place
        mns.normalize(out, 10.)
        neutrons2 = mns.load(out)
        # and see if it is done correctly
        for n in neutrons2:
            self.assertAlmostEqual(n.probability, .1)
            continue
        return
    def test1(self):
        'mccomponents.sample.samplecomponent isotropic kernel, multiple-scattering'
        import mcni
        neutron = mcni.neutron(r=(0, 0, 0), v=(0, 0, 3000), time=0, prob=1)
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent(
            'Al', 'sampleassemblies/Al-isotropickernel/sampleassembly.xml')
        instrument = mcni.instrument([component1, component2])

        geometer = mcni.geometer()
        geometer.register(component1, (0, 0, 0), (0, 0, 0))
        geometer.register(component2, (0, 0, 1), (0, 0, 0))

        N0 = 1
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate(instrument, geometer, neutrons, multiple_scattering=True)

        N = len(neutrons)

        for i in range(N):
            neutron = neutrons[i]
            print neutron
            continue

        return
Exemple #9
0
 def make_neutrons(N):
     neutrons = mcni.neutron_buffer(N)
     #
     # randomly select E, the energy transfer
     E = core.Emin + np.random.random(N) * (core.Emax-core.Emin)
     # the final energy
     Ef = core.Ei - E
     # the final velocity
     vf = conversion.e2v(Ef)
     # choose cos(theta) between -1 and 1
     cos_t = np.random.random(N) * 2 - 1
     # theta
     theta = np.arccos(cos_t)
     # sin(theta)
     sin_t = np.sin(theta)
     # phi: 0 - 2pi
     phi = np.random.random(N) * 2 * np.pi
     # compute final velocity vector
     vx,vy,vz = vf*sin_t*np.cos(phi), vf*sin_t*np.sin(phi), vf*cos_t
     # neutron position, spin, tof are set to zero
     x = y = z = sx = sy = t = np.zeros(N, dtype="float64")
     # probability
     prob = np.ones(N, dtype="float64") * (vf/vi)
     # XXX: this assumes a specific data layout of neutron struct
     n_arr = np.array([x,y,z,vx,vy,vz, sx,sy, t, prob]).T.copy()
     neutrons.from_npyarr(n_arr)
     return neutrons
    def test(self):
        'mcni.pyre_components.NeutronsOnCone_FixedQE'
        from mcni.pyre_components.NeutronsOnCone_FixedQE import NeutronsOnCone_FixedQE as factory
        component = factory( 'source' )
        component.inventory.Q = Q
        component.inventory.E = E
        component.inventory.Ei = Ei
        component.inventory.L1 = L1
        component._configure()
        component._init()

        import mcni
        neutrons = mcni.neutron_buffer( 10 )
        component.process( neutrons )
        from numpy.linalg import norm
        from mcni.utils import v2e, e2v, v2k
        vi = e2v( Ei )
        t = L1/vi
        for n in neutrons:
            vv = n.state.velocity
            vQv = -vv[0], -vv[1], vi-vv[2]
            vQ = norm(vQv)
            Q1 = v2k(vQ)
            v = norm( vv )
            self.assertAlmostEqual( v2e(v), Ei-E, 4)
            self.assertAlmostEqual( n.time, t, 4 )
            self.assertAlmostEqual( Q, Q1, 4 )
            continue

        component._fini()
        return
    def test(self):
        "wrap SNS_source_r1"
        from mcstas2 import componentfactory

        factory = componentfactory(category, componentname)
        component = factory(
            "component",
            S_filename="source_sct521_bu_17_1.dat",
            width=0.1,
            height=0.12,
            dist=2.5,
            xw=0.1,
            yh=0.12,
            Emin=50,
            Emax=70,
        )

        import mcni

        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1), v=(0, 0, 3000), time=0, prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
Exemple #12
0
    def test3(self):
        'neutron_storage.Storage: wrap-reading (nread>ntotal)'

        path = 'test-storage-3'
        if os.path.exists(path):
            os.remove( path )
        
        from mcni.neutron_storage.Storage import Storage

        #open storage for writing
        s = Storage( path, 'w' )

        #create neutrons
        import mcni
        neutrons = mcni.neutron_buffer( 7 )
        for i in range(7):
            neutrons[i] = mcni.neutron( v = (i,0,0) )

        #write 
        s.write( neutrons )

        # flush
        del s
        
        #open the storage for reading
        sr = Storage( path, 'r', packetsize=10)

        neutrons = sr.read()
        self.assertEqual( len(neutrons), 10 )
        self.assertAlmostEqual( neutrons[5].state.velocity[0] , 5 )
        self.assertAlmostEqual( neutrons[9].state.velocity[0] , 2 )

        neutrons = sr.read()
        self.assertAlmostEqual( neutrons[0].state.velocity[0] , 3 )
        return
Exemple #13
0
    def test2(self):
        'normalize'
        import mcni
        # create a dummy input
        neutrons = mcni.neutron_buffer(10)
        for n in neutrons:
            n.probability = 1
            continue
        out = 'tmp-nst-test2.ns'
        mns.dump(neutrons, out)

        # try normalize out-of-place
        out2 = 'tmp-nst-test2-normalized.ns'
        if os.path.exists(out2): os.remove(out2)
        mns.normalize(out, 10., out2)
        neutrons2 = mns.load(out2)
        # and see if it is done correctly
        for n in neutrons2:
            self.assertAlmostEqual(n.probability, .1)
            continue

        # try normalize in-place
        mns.normalize(out, 10.)
        neutrons2 = mns.load(out)
        # and see if it is done correctly
        for n in neutrons2:
            self.assertAlmostEqual(n.probability, .1)
            continue
        return
Exemple #14
0
def _init():
    neutrons = mcni.neutron_buffer(ntotneutrons)
    for i in range(ntotneutrons):
        neutrons[i] = mcni.neutron(
            r = (0,0,i),
            )
        continue

    from mcni.utils import mpiutil
    global mpirank
    mpirank = mpiutil.rank
    mpisize = mpiutil.world.size
    if mpisize != 3:
        raise RuntimeError, __doc__

    import os
    channel = 1000
    if mpirank == 0:
        if os.path.exists(neutron_storage_path):
            os.remove(neutron_storage_path)
        from mcni.neutron_storage.Storage import Storage
        storage = Storage(neutron_storage_path, 'w')
        storage.write(neutrons)
        del storage
        for i in range(1, mpisize):
            mpiutil.send(0, i, channel)
            continue
    else:
        mpiutil.receive(0, channel)
Exemple #15
0
    def test5(self):
        'neutron_storage.Storage: wrap-reading (nread>>ntotal)'

        path = 'test-storage-4'
        if os.path.exists(path):
            os.remove( path )
        
        from mcni.neutron_storage.Storage import Storage

        #open storage for writing
        s = Storage( path, 'w' )

        #create neutrons
        import mcni
        neutrons = mcni.neutron_buffer( 5 )
        for i in range(5):
            neutrons[i] = mcni.neutron( v = (i,0,0) )

        #write 
        s.write( neutrons )

        # flush
        del s
        
        #open the storage for reading
        sr = Storage( path, 'r')

        neutrons = sr.read(100)
        self.assertEqual( len(neutrons), 100 )
        self.assertAlmostEqual( neutrons[3].state.velocity[0] , 3 )
        self.assertAlmostEqual( neutrons[4].state.velocity[0] , 4 )
        self.assertAlmostEqual( neutrons[6].state.velocity[0] , 1 )
        self.assertAlmostEqual( neutrons[7].state.velocity[0] , 2 )

        return
Exemple #16
0
 def test2(self):
     'shape positioning: cylinder with axis along beam'
     # source
     from mcni.components.MonochromaticSource import MonochromaticSource
     import mcni
     neutron = mcni.neutron(r=(0,0,-1), v=(0,0,1000), prob=1)
     source = MonochromaticSource('s', neutron, dx=0.09, dy=0.09, dE=0)
     # sample
     from mccomponents.sample import samplecomponent
     scatterer = samplecomponent('sa', 'cyl-along-beam/sampleassembly.xml' )
     # neutrons
     N = 1000
     neutrons = mcni.neutron_buffer(N)
     neutrons = source.process(neutrons)
     # find neutrons out of target
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     missing = x*x+y*y > 0.04**2
     # print neutrons
     scatterer.process(neutrons)
     # print neutrons
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     assert (z[missing] < -.9).all()
     hit = arr[np.logical_not(missing), :3]
     x,y,z = hit.T
     assert (z > -.1).all()
     assert (np.isclose((x*x + y*y)**.5, 0.04) | np.isclose(np.abs(z), 0.005)).all()
     return
Exemple #17
0
def neutrons_from_npyarr(arr, neutrons=None):
    """copy data from a numpy array to a boost python instance of
    Neutron::Events.

    arr: the numpy array
    neutrons: the Neutron::Events instance where data will be copied.
      if None, a new instance will be created.
    """
    shape = arr.shape
    assert shape[1] == ndblsperneutron
    n = len(arr)

    if neutrons is None:
        import mcni

        neutrons = mcni.neutron_buffer(n)
        pass

    n = min(n, len(neutrons))

    cevents = binding.cevents_from_npyarr(arr)

    neutrons.fromCevents(cevents, n)

    return neutrons
    def test(self):
        "Source_simple --> E_monitor"
        from mcstas2 import componentfactory
        ssimplefac = componentfactory( 'sources', 'Source_simple' )
        ssimple = ssimplefac(
            'ssimple',
            radius=0.1, dist=2, xw=0.1, yh=0.1, E0=55, dE=2)
        
        from mcstas2.wrappers import wrap
        wrap( 'E_monitor.comp', 'monitors' ) 
        emonfac = componentfactory( 'monitors', 'E_monitor' )
        emon = emonfac(
            'emon',
            nchan=20, filename="e.dat",
            xmin=-0.2, xmax=0.2,
            ymin=-0.2, ymax=0.2,
            Emin=50, Emax=60)

        import mcni
        instrument = mcni.instrument( [ssimple, emon] )

        geometer = mcni.geometer()
        geometer.register( ssimple, (0,0,0), (0,0,0) )
        geometer.register( emon, (0,0,1), (0,0,0) )

        neutrons = mcni.neutron_buffer( 100 )

        mcni.simulate( instrument, geometer, neutrons )

        return
    def test1(self):
        'mccomponents.sample.samplecomponent: IsotropicKernel'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,3000), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'Al', 'sampleassemblies/Al-isotropickernel/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,1), (0,0,0) )

        N0 = 1000
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate( instrument, geometer, neutrons )

        N = len(neutrons)

        for i in range(10):
            neutron = neutrons[i]
            print neutron
            continue

        # N should be about 2/3 of N0. this is determined by
        # the mc weights in Al-isotropic-kernel-plate-scatterer.xml
        self.assert_( N < 0.72*N0 and N > 0.6*N0)

        return
Exemple #20
0
 def make_neutrons(N):
     neutrons = mcni.neutron_buffer(N)
     #
     # randomly select E, the energy transfer
     E = core.Emin + np.random.random(N) * (core.Emax - core.Emin)
     # the final energy
     Ef = core.Ei - E
     # the final velocity
     vf = conversion.e2v(Ef)
     # choose cos(theta) between -1 and 1
     cos_t = np.random.random(N) * 2 - 1
     # theta
     theta = np.arccos(cos_t)
     # sin(theta)
     sin_t = np.sin(theta)
     # phi: 0 - 2pi
     phi = np.random.random(N) * 2 * np.pi
     # compute final velocity vector
     vx, vy, vz = vf * sin_t * np.cos(phi), vf * sin_t * np.sin(
         phi), vf * cos_t
     # neutron position, spin, tof are set to zero
     x = y = z = sx = sy = t = np.zeros(N, dtype="float64")
     # probability
     prob = np.ones(N, dtype="float64") * (vf / vi)
     # XXX: this assumes a specific data layout of neutron struct
     n_arr = np.array([x, y, z, vx, vy, vz, sx, sy, t, prob]).T.copy()
     neutrons.from_npyarr(n_arr)
     return neutrons
Exemple #21
0
 def test1(self):
     'shape positioning: plate perp to beam'
     # source
     from mcni.components.MonochromaticSource import MonochromaticSource
     import mcni
     neutron = mcni.neutron(r=(0,0,-1), v=(0,0,1000), prob=1)
     source = MonochromaticSource('s', neutron, dx=0.07, dy=0.09, dE=0)
     # sample
     from mccomponents.sample import samplecomponent
     scatterer = samplecomponent('sa', 'plate/sampleassembly.xml' )
     # neutrons
     N = 1000
     neutrons = mcni.neutron_buffer(N)
     neutrons = source.process(neutrons)
     # find neutrons out of target
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     missing = (x>0.03) | (x<-0.03) | (y>0.04) | (y<-0.04)
     # print neutrons
     scatterer.process(neutrons)
     # print neutrons
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     assert (z[missing] < -.9).all()
     hit = arr[np.logical_not(missing), :3]
     x,y,z = hit.T
     assert (z > -.1).all()
     assert (np.isclose(np.abs(x), 0.03) | np.isclose(np.abs(y), 0.04) | np.isclose(np.abs(z), 0.005)).all()
     return
Exemple #22
0
    def test(self):
        'neutron_storage.Storage: write and then read'

        path = 'test-storage'
        if os.path.exists(path):
            os.remove( path )
        
        from mcni.neutron_storage.Storage import Storage

        #open storage for writing
        s = Storage( path, 'w' )

        #create neutrons
        import mcni
        neutrons = mcni.neutron_buffer( 7 )
        neutrons[5] = mcni.neutron( v = (8,9,10) )

        #write neutrons
        s.write( neutrons )

        #delete the storage to make sure it flushes all neutrons
        del s

        #open the storage for reading
        sr = Storage( path, 'r')
        neutrons = sr.read()
        self.assertEqual( len(neutrons), 7 )

        self.assertAlmostEqual( neutrons[5].state.velocity[0] , 8 )
        return
    def test(self):
        "wrap Single_crystal"
        from mcstas2 import componentfactory
        factory = componentfactory(category, componentname)
        component = factory('component',
                            xwidth=0.01,
                            yheight=0.01,
                            zthick=0.01,
                            delta_d_d=1e-4,
                            mosaic=5,
                            ax=3.8186,
                            ay=0,
                            az=0,
                            bx=0,
                            by=3.8843,
                            bz=0,
                            cx=0,
                            cy=0,
                            cz=11.6777,
                            reflections="YBaCuO.lau")

        import mcni
        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1),
                                       v=(0, 0, 3000),
                                       time=0,
                                       prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
Exemple #24
0
    def test1(self):
        'Neutrons_from above'

        rq = lambda Q: np.exp(-Q * Q / 25)

        s = Sample('sample', 5, 5, rq)

        from mcni import neutron_buffer, neutron
        N = 8
        nb = neutron_buffer(N)
        t = 1.
        for i in range(N):
            vi = np.array((0, -(i + 1) * 100, (i + 1) * 100))
            ri = -vi * t
            nb[i] = neutron(r=ri, v=vi, s=(0, 0), time=0., prob=1.)
            continue

        nb2 = s.process(nb)
        for i, (n, n2) in enumerate(zip(nb, nb2)):
            # print "input:", n
            # print "output:", n2
            vf = np.array((0, (i + 1) * 100, (i + 1) * 100))
            np.allclose(vf, n2.state.velocity)
            np.allclose([0, 0, 0], n2.state.position)
            np.isclose(n2.time, 1.)
            vy = vf[1]
            Q = np.abs(vy * 2) * conv.V2K
            np.isclose(rq(Q), n2.probability)
        return
Exemple #25
0
    def test2a(self):
        'normalize: large buffer'
        import mcni
        # create a dummy input
        neutrons = mcni.neutron_buffer(int(3e6))
        narr = neutrons.to_npyarr()
        narr[:, -1] = 1
        neutrons.from_npyarr(narr)
        out = 'tmp-nst-test2a.ns'
        mns.dump(neutrons, out)
        del neutrons

        # try normalize out-of-place
        out2 = 'tmp-nst-test2a-normalized.ns'
        if os.path.exists(out2): os.remove(out2)
        mns.normalize(out, 10., out2)
        neutrons2 = mns.load(out2)
        # and see if it is done correctly
        narr = neutrons2.to_npyarr()
        self.assertTrue((narr[:, -1] == .1).all())
        del neutrons2, narr

        # try normalize in-place
        mns.normalize(out, 10.)
        neutrons2 = mns.load(out)
        # and see if it is done correctly
        narr = neutrons2.to_npyarr()
        self.assertTrue((narr[:, -1] == .1).all())
        return
Exemple #26
0
    def test1(self):
        'NDMonitor'

        from mcni.components.NDMonitor import NDMonitor, Axis
        xaxis = Axis(
            name='x',
            expression='x',
            bins=100,
            range=(0, 1000.),
            unit='meter',
        )
        m = NDMonitor('abc', [xaxis])

        N = 100
        from mcni import neutron_buffer, neutron
        b = neutron_buffer(N)
        for i in range(N):
            b[i] = neutron()
            continue

        m.process(b)

        self.assertEqual(m.histogram.I[0], N)
        self.assertEqual(m.histogram.E2[0], N)
        self.assertEqual(m.histogram.I[1], 0.)
        self.assertEqual(m.histogram.E2[1], 0.)

        if interactive:
            from histogram.plotter import defaultPlotter as plotter
            plotter.plot(m.histogram)
        return
Exemple #27
0
    def test1(self):
        'NDMonitor'
        
        from mcni.components.NDMonitor import NDMonitor, Axis
        xaxis = Axis(
            name = 'x', expression='x',
            bins = 100, range=(0, 1000.),
            unit = 'meter',
            )
        m = NDMonitor('abc', [xaxis])
        
        N = 100
        from mcni import neutron_buffer, neutron
        b = neutron_buffer(N)
        for i in range(N):
            b[i] = neutron()
            continue

        m.process(b)

        self.assertEqual(m.histogram.I[0], N)
        self.assertEqual(m.histogram.E2[0], N)
        self.assertEqual(m.histogram.I[1], 0.)
        self.assertEqual(m.histogram.E2[1], 0.)

        if interactive:
            from histogram.plotter import defaultPlotter as plotter
            plotter.plot(m.histogram)
        return
Exemple #28
0
    def __init__(
        self,
        name,
        xwidth,
        yheight,
        zthickness,
        mu,
        sigma,
    ):
        """
        Initialize the isotropicbox component.

        Parameters:
        name (str): the name of this component
        xwidth (m): width
        yheight (m): height
        zthickness (m): thickness
        mu (1/m): inverse absorption length
        sigma (1/m): inverse scattering length
        """
        self.name = name
        self.propagate_params = (np.array(
            [xwidth, yheight, zthickness, mu, sigma]), )

        # Aim neutrons toward the sample to cause JIT compilation.
        import mcni
        neutrons = mcni.neutron_buffer(1)
        neutrons[0] = mcni.neutron(r=(0, 0, -1), v=(0, 0, 1), prob=1, time=0)
        self.process(neutrons)
Exemple #29
0
    def test(self):
        "wrap SNS_source_r1"
        from mcstas2 import componentfactory
        factory = componentfactory(category, componentname)
        component = factory(
            'component',
            S_filename="source_sct521_bu_17_1.dat",
            width=0.1,
            height=0.12,
            dist=2.5,
            xw=0.1,
            yh=0.12,
            Emin=50,
            Emax=70,
        )

        import mcni
        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1),
                                       v=(0, 0, 3000),
                                       time=0,
                                       prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
Exemple #30
0
def _normalize(input, N, output):
    """normalize the neutrons in the given file by the factor N
    and save it in the output
    """
    import os
    input = os.path.abspath(input)
    output = os.path.abspath(output)
    # guards
    assert input != output
    if os.path.exists(output):
        raise IOError('%s already exists' % output)
    # total # of neutrons
    remain = count(input)
    # output storage
    out = storage(output, mode='w')
    # input storage
    input = storage(input)
    #
    chunk = int(1e6)
    # 
    from mcni import neutron_buffer
    nb = neutron_buffer(0)
    while remain:
        n = min(remain, chunk)
        # read
        neutrons = input.read(n, asnpyarr=True)
        # normalize
        neutrons[:, -1] /= N
        # write
        nb.from_npyarr(neutrons)
        out.write(nb)
        #
        remain -= n
        continue
    return
Exemple #31
0
    def test(self):
        'mcni.pyre_components.NeutronsOnCone_FixedQE'
        from mcni.pyre_components.NeutronsOnCone_FixedQE import NeutronsOnCone_FixedQE as factory
        component = factory('source')
        component.inventory.Q = Q
        component.inventory.E = E
        component.inventory.Ei = Ei
        component.inventory.L1 = L1
        component._configure()
        component._init()

        import mcni
        neutrons = mcni.neutron_buffer(10)
        component.process(neutrons)
        from numpy.linalg import norm
        from mcni.utils import v2e, e2v, v2k
        vi = e2v(Ei)
        t = L1 / vi
        for n in neutrons:
            vv = n.state.velocity
            vQv = -vv[0], -vv[1], vi - vv[2]
            vQ = norm(vQv)
            Q1 = v2k(vQ)
            v = norm(vv)
            self.assertAlmostEqual(v2e(v), Ei - E, 4)
            self.assertAlmostEqual(n.time, t, 4)
            self.assertAlmostEqual(Q, Q1, 4)
            continue

        component._fini()
        return
    def test1(self):
        'mccomponents.sample.samplecomponent isotropic kernel, multiple-scattering'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,3000), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'Al', 'sampleassemblies/Al-isotropickernel/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,1), (0,0,0) )

        N0 = 1
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate( instrument, geometer, neutrons, multiple_scattering=True)

        N = len(neutrons)

        for i in range(N):
            neutron = neutrons[i]
            print neutron
            continue

        return
Exemple #33
0
def _normalize(input, N, output):
    """normalize the neutrons in the given file by the factor N
    and save it in the output
    """
    import os
    input = os.path.abspath(input)
    output = os.path.abspath(output)
    # guards
    assert input != output
    if os.path.exists(output):
        raise IOError('%s already exists' % output)
    # total # of neutrons
    remain = count(input)
    # output storage
    out = storage(output, mode='w')
    # input storage
    input = storage(input)
    #
    chunk = int(1e6)
    #
    from mcni import neutron_buffer
    nb = neutron_buffer(0)
    while remain:
        n = min(remain, chunk)
        # read
        neutrons = input.read(n, asnpyarr=True)
        # normalize
        neutrons[:, -1] /= N
        # write
        nb.from_npyarr(neutrons)
        out.write(nb)
        #
        remain -= n
        continue
    return
Exemple #34
0
 def test2(self):
     'shape positioning: rotated sphere'
     # source
     from mcni.components.MonochromaticSource import MonochromaticSource
     import mcni
     neutron = mcni.neutron(r=(0,0,-1), v=(0,0,1000), prob=1)
     source = MonochromaticSource('s', neutron, dx=0.10, dy=0.09, dE=0)
     # sample
     from mccomponents.sample import samplecomponent
     scatterer = samplecomponent('sa', 'sphere-rotated-arbitrarily/sampleassembly.xml' )
     # neutrons
     N = 1000
     neutrons = mcni.neutron_buffer(N)
     neutrons = source.process(neutrons)
     # find neutrons out of target
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     missing = x*x+y*y>0.05*0.05
     # print "missed:", missing.sum()
     # print neutrons
     scatterer.process(neutrons)
     # print neutrons
     arr = neutrons.to_npyarr()
     x,y,z = arr[:, :3].T
     assert (z[missing] < -.9).all()
     hit = arr[np.logical_not(missing), :3]
     x,y,z = hit.T
     assert (z > -.1).all()
     assert np.isclose(np.abs(x*x+y*y+z*z), 0.05*0.05).all()
     return
Exemple #35
0
    def __init__(
            self, name,
            w1, h1, w2, h2, l,
            R0=0.99, Qc=0.0219, alpha=6.07, m=2, W=0.003):
        """
        Initialize this Guide component.
        The guide is centered on the z-axis with the entrance at z=0.

        Parameters:
        name (str): the name of this component
        w1 (m): width at the guide entry
        h1 (m): height at the guide entry
        w2 (m): width at the guide exit
        h2 (m): height at the guide exit
        l (m): length of guide
        R0: low-angle reflectivity
        Qc: critical scattering vector
        alpha: slope of reflectivity
        m: m-value of material (0 is complete absorption)
        W: width of supermirror cutoff
        """
        self.name = name
        ww = .5*(w2-w1); hh = .5*(h2 - h1)
        hw1 = 0.5*w1; hh1 = 0.5*h1
        self._params = (
            float(ww), float(hh), float(hw1), float(hh1), float(l),
            float(R0), float(Qc), float(alpha), float(m), float(W),
        )
        import mcni
        neutrons = mcni.neutron_buffer(1)
        neutrons[0] = mcni.neutron(r=(0,0,0), v=(0,0,1000), prob=1, time=0)
        self.process(neutrons)
    def test1(self):
        'mccomponents.sample.samplecomponent: DGSSXResKernel'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,3000), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'Al', 'sampleassemblies/Al-DGSSXResKernel/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,6), (0,0,0) )

        N0 = 10
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate( instrument, geometer, neutrons )

        N = len(neutrons)

        for i in range(10):
            neutron = neutrons[i]
            # print neutron
            self.assert_(np.allclose(neutron.state.velocity, [3000, 0, 0], atol=20))
            continue

        return
    def test1(self):
        'mccomponents.sample.samplecomponent'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,3000), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'Ni', 'sampleassemblies/Ni/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,1), (0,0,0) )

        neutrons = mcni.neutron_buffer( 1 )

        from mcni.pyre_support.ConsoleNeutronTracer import ConsoleNeutronTracer
        tracer = ConsoleNeutronTracer()
        mcni.simulate( 
            instrument, geometer, neutrons, 
            multiple_scattering=True,
            tracer = tracer
            )

        return
Exemple #38
0
    def test(self):
        "wrap TOF_monitor2"

        from mcstas2 import componentfactory
        factory = componentfactory(category, componentname)

        component = factory(
            'component',
            nchan=100,
            xmin=-0.1,
            xmax=0.1,
            ymin=-0.1,
            ymax=0.1,
            tmin=0.0,
            tmax=0.00005,
            filename="tof.dat",
        )

        import mcni
        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1),
                                       v=(0, 0, 3000),
                                       time=0,
                                       prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
Exemple #39
0
 def test6(self):
     "neutron buffer: get element"
     from mcni import neutron_buffer
     b1 = neutron_buffer(1)
     n = b1[0]
     # print n
     return
Exemple #40
0
def _init():
    neutrons = mcni.neutron_buffer(ntotneutrons)
    for i in range(ntotneutrons):
        neutrons[i] = mcni.neutron(r=(0, 0, i), )
        continue

    from mcni.utils import mpiutil
    global mpirank
    mpirank = mpiutil.rank
    mpisize = mpiutil.world.size
    if mpisize != 3:
        raise RuntimeError, __doc__

    import os
    channel = 1000
    if mpirank == 0:
        if os.path.exists(neutron_storage_path):
            os.remove(neutron_storage_path)
        from mcni.neutron_storage.Storage import Storage
        storage = Storage(neutron_storage_path, 'w')
        storage.write(neutrons)
        del storage
        for i in range(1, mpisize):
            mpiutil.send(0, i, channel)
            continue
    else:
        mpiutil.receive(0, channel)
    def test1(self):
        'mccomponents.sample.samplecomponent'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,4149.48), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'V-constantE', 'sampleassemblies/V-constantE/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,1), (0,0,0) )
        
        neutrons = mcni.neutron_buffer( 1 )
        
        from mcni.pyre_support.ConsoleNeutronTracer import ConsoleNeutronTracer
        tracer = ConsoleNeutronTracer()
        mcni.simulate( 
            instrument, geometer, neutrons, 
            multiple_scattering=True,
            tracer = tracer
            )

        return
Exemple #42
0
def test_component_n1e6():
    src = SNS_source(
        'src', dat, 5, 20, 0.03, 0.03,
        5, .03, .03,
    )
    neutrons = src.process(neutron_buffer(int(1e6)))
    return
    def test(self):
        "wrap Channeled_guide"

        from mcstas2 import componentfactory
        factory = componentfactory(category, componentname)

        component = factory('component',
                            w1=-0.1,
                            h1=0.12,
                            w2=0.02,
                            h2=0.02,
                            l=2.0,
                            R0=0.99,
                            Qcx=0.021,
                            Qcy=0.021,
                            alphax=6.07,
                            alphay=6.07,
                            W=0.003,
                            k=1,
                            d=0.0005,
                            mx=1,
                            my=1)

        import mcni
        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1),
                                       v=(0, 0, 3000),
                                       time=0,
                                       prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
 def test6(self):
     "neutron buffer: get element"
     from mcni import neutron_buffer
     b1 = neutron_buffer(1)
     n = b1[0]
     # print n
     return
    def test1(self):
        'mccomponents.sample.samplecomponent: IsotropicKernel'
        import mcni
        neutron = mcni.neutron( r = (0,0,0), v = (0,0,3000), time = 0, prob = 1 )
        from mcni.components.MonochromaticSource import MonochromaticSource
        component1 = MonochromaticSource('source', neutron)
        from mccomponents.sample import samplecomponent
        component2 = samplecomponent( 'Al', 'sampleassemblies/Al-isotropickernel/sampleassembly.xml' )
        instrument = mcni.instrument( [component1, component2] )
        
        geometer = mcni.geometer()
        geometer.register( component1, (0,0,0), (0,0,0) )
        geometer.register( component2, (0,0,1), (0,0,0) )

        N0 = 1000
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate( instrument, geometer, neutrons )

        N = len(neutrons)

        for i in range(10):
            neutron = neutrons[i]
            print neutron
            continue

        # N should be about 2/3 of N0. this is determined by
        # the mc weights in Al-isotropic-kernel-plate-scatterer.xml
        self.assert_( N < 0.72*N0 and N > 0.6*N0)

        return
    def test(self):
        "wrap Fermi_chop2"

        from mcstas2 import componentfactory
        factory = componentfactory(category, componentname)

        component = factory('component',
                            len=0.10,
                            w=0.06,
                            nu=600,
                            delta=0.0,
                            tc=0.0,
                            ymin=-0.03,
                            ymax=0.03,
                            nchan=32,
                            bw=0.00035,
                            blader=0.5801)

        import mcni
        neutrons = mcni.neutron_buffer(5)
        for i in range(5):
            neutrons[i] = mcni.neutron(r=(0, 0, -1),
                                       v=(0, 0, 3000),
                                       time=0,
                                       prob=1)
            continue
        component.process(neutrons)
        print neutrons
        return
Exemple #47
0
    def __init__(self, path, mode="r", packetsize=None, buffersize=10000):
        """
        path: path of the storage
        mode: mode of operation
          r: read
          w: write
          a: append
        packetsize: used in "r" mode. The size of the neutron packet being read
        buffersize: used in "w"/"a" mode. The size of writing buffer (unit: neutron)
        """

        path = self.path = os.path.abspath(path)
        debug.log("storage path: %s" % path)

        # checking inputs
        if mode in ["w"] and os.path.exists(path):
            msg = (
                "path %r already exists. if you want to append neutron event files to "
                'that directory, please use mode "a" to append' % path
            )
            raise RuntimeError, msg

        # if not os.path.exists( path ) and mode in ['w']: os.makedirs( path )

        if not os.path.exists(path) and mode in ["r", "a"]:
            raise RuntimeError, "Neutron storage at %r has not been established" % path

        if os.path.isdir(path):
            raise IOError, "path %r is a directory" % path

        # init
        self.mode = mode
        self._readonly = mode in ["r"]

        # file stream
        self.stream = open(path, mode)
        self._closed = False

        #
        self._buffersize = buffersize
        debug.log("buffer size: %s" % buffersize)

        import mcni

        self._buffer = mcni.neutron_buffer(0)

        # in write mode, let us initialize the file by writing
        # an empty neutron buffer
        if self.mode == "w":
            self._write_header(self.stream)

        # read mode:
        if self._readonly:
            self._packetsize = packetsize
            self._position = 0  # initial position to start reading
            self._ntotal = idfio.count(stream=self.stream)
            debug.log("packet size: %s" % packetsize)
            debug.log("total size: %s" % self._ntotal)
        return
Exemple #48
0
    def __init__(self,
                 name,
                 xmin=0,
                 xmax=0,
                 ymin=0,
                 ymax=0,
                 radius=0,
                 cut=0,
                 width=0,
                 height=0,
                 **kwargs):
        """
        Initialize this Slit component.
        The slit is at z==0.
        Setting radius to non-zero switches this slit from being rectangular to
        a circle centered on x,y==0,0.

        Parameters:
        name (str): the name of this component
        xmin (m): the smallest value of x that still passes a rectangular slit
        xmax (m): the largest value of x that still passes a rectangular slit
        ymin (m): the smallest value of y that still passes a rectangular slit
        ymax (m): the largest value of y that still passes a rectangular slit
        radius (m): the largest distance on x-y from 0,0 that still passes a
            circular slit
        cut: the smallest neutron weight that can penetrate the slit
        width (m): sets xmin and xmax to a width centered on x==0
        height (m): sets ymin and ymax to a width centered on y==0
        """
        super().__init__(__class__, **kwargs)

        self.name = name

        # Check and process the arguments.
        if width > 0:
            xmax = width / 2
            xmin = -xmax
        if height > 0:
            ymax = height / 2
            ymin = -ymax
        if not (xmin or xmax or ymin or ymax or radius):
            raise ValueError("a slit must have some extent")

        # Note the configuration of the slit.
        self.propagate_params = (np.array(
            [xmin, xmax, ymin, ymax, radius * radius, cut]), )

        # Aim neutrons toward the slit to cause JIT compilation.
        import mcni
        neutrons = mcni.neutron_buffer(2)
        # first neutron passes through
        neutrons[0] = mcni.neutron(r=(0, 0, -1), v=(0, 0, 1), prob=1, time=0)
        # second neutron is absorbed
        x_edge = radius if radius > 0 else xmax
        neutrons[1] = mcni.neutron(r=(x_edge * 2, 0, -1),
                                   v=(0, 0, 1),
                                   prob=1,
                                   time=0)
        self.process(neutrons)
Exemple #49
0
 def test7(self):
     "neutron buffer: set element"
     from mcni import neutron_buffer, neutron
     b1 = neutron_buffer(1)
     n = neutron(r=(0,10,0))
     b1[0] = n
     self.assertEqual(b1[0].state.position[1], 10)
     return
 def test7(self):
     "neutron buffer: set element"
     from mcni import neutron_buffer, neutron
     b1 = neutron_buffer(1)
     n = neutron(r=(0, 10, 0))
     b1[0] = n
     self.assertEqual(b1[0].state.position[1], 10)
     return
Exemple #51
0
def neutron_buffer_from_array(neutrons):
    buffer = neutron_buffer(len(neutrons))
    index = 0
    for neutron in neutrons:
        buffer[index] = neutron
        index += 1
    assert index
    return buffer
Exemple #52
0
    def main(self, *args, **kwds):
        if self.inventory.dumpregistry:
            self._dumpRegsitry()
            return

        import mcni
        instrument = self._createInstrument()

        geometer = self.geometer

        from mcni.SimulationContext import SimulationContext
        context = SimulationContext()
        context.multiple_scattering = self.inventory.multiple_scattering
        context.tracer = self.tracer
        context.mpiRank = self.mpiRank
        context.mpiSize = self.mpiSize
        context.outputdir = self.outputdir
        context.overwrite_datafiles = self.overwrite_datafiles

        n = int(self.ncount / self.buffer_size)
        assert n > 0, 'ncount should be larger than buffer_size: ncount=%s, buffer_size=%s' % (
            self.ncount, self.buffer_size)

        from mcni import journal
        logger = journal.logger('info',
                                'instrument',
                                header='',
                                footer='',
                                format='-> %s')
        for i in range(n):
            logger("mpi node %s at loop %s" % (self.mpiRank, i))
            neutrons = mcni.neutron_buffer(self.buffer_size)
            context.iteration_no = i
            mcni.simulate(instrument, geometer, neutrons, context=context)
            continue

        remain = int(self.ncount % self.buffer_size)
        if remain:
            logger("mpi node %s at last loop" % (self.mpiRank, ))
            neutrons = mcni.neutron_buffer(remain)
            context.iteration_no = n
            mcni.simulate(instrument, geometer, neutrons, context=context)

        import os
        print os.times()
        return
Exemple #53
0
def test_component():
    src = SNS_source(
        'src', dat, 5, 20, 0.03, 0.03,
        5, .03, .03,
    )
    neutrons = src.process(neutron_buffer(10))
    for n in neutrons:
        print(n)
    return
    def test1(self):
        'NeutronsOnCone_FixedQE'
        from mcni.components.NeutronsOnCone_FixedQE import NeutronsOnCone_FixedQE as factory
        component = factory( 'source', 8, 30, 70, 10.3 )

        import mcni
        neutrons = mcni.neutron_buffer( 10 )
        component.process( neutrons )
        # print neutrons
        return
Exemple #55
0
    def test8(self):
        "neutron buffer: clear"
        from mcni import neutron_buffer, neutron
        
        b1 = neutron_buffer(10)
        self.assertEqual(len(b1), 10)

        b1.clear()
        self.assertEqual(len(b1), 0)
        return
 def test1(self):
     'neutron_storage: mix npy implementation and non-npy one'
     import mcni
     neutrons = mcni.neutron_buffer( 7 )
     out = 'tmp-nst-test1.ns'
     if os.path.exists(out): os.remove(out)
     storage = mns.storage(out, mode='w')
     storage.write(neutrons)
     neutrons1 = mns.load( 'neutrons.dat' )
     return
    def test2(self):
        "mccomponents.sample.samplecomponent: E_vQ_Kernel - discontinued dispersion surface"
        import mcni
        from mcni.utils import conversion

        ei = 60
        vil = conversion.e2v(ei)
        vi = (0, 0, vil)
        neutron = mcni.neutron(r=(0, 0, 0), v=vi, time=0, prob=1)

        from mcni.components.MonochromaticSource import MonochromaticSource

        component1 = MonochromaticSource("source", neutron)

        from mccomponents.sample import samplecomponent

        component2 = samplecomponent("Al", "sampleassemblies/Al-E_vQ_withdiscontinuity-kernel/sampleassembly.xml")
        E_Q = "np.where(Qx*Qx+Qy*Qy+Qz*Qz>30, 25, 15)"  # in sampleassemblies/Al-E_vQ-kernel/Al-scatterer.xml

        instrument = mcni.instrument([component1, component2])

        geometer = mcni.geometer()
        geometer.register(component1, (0, 0, 0), (0, 0, 0))
        geometer.register(component2, (0, 0, 1), (0, 0, 0))

        N0 = 10000
        neutrons = mcni.neutron_buffer(N0)

        mcni.simulate(instrument, geometer, neutrons)

        N = len(neutrons)

        import numpy.linalg as nl
        import numpy as np
        from math import sin

        N_noscatt = 0
        for i in range(N):
            neutron = neutrons[i]
            vf = np.array(neutron.state.velocity)
            diffv = vi - vf
            # no scattering is fine
            if np.linalg.norm(diffv) < 1e-12:
                N_noscatt += 1
                continue
            Q = conversion.V2K * diffv
            Qx, Qy, Qz = Q
            ef = conversion.v2e(nl.norm(vf))
            E = ei - ef
            # print E, Q, neutron
            E1 = eval(E_Q)
            self.assertAlmostEqual(E, E1)
            continue
        print "\n* percentage of no scattering (Q happen to be at a singular point):", N_noscatt * 100.0 / N, "%"
        return