Ejemplo n.º 1
0
 def test2(self):
     "neutron"
     # creating instances
     from mcni import neutron
     n = neutron(r=(0,0,0), v=(0,0,3000))
     n = neutron(r=(0,0,0), v=(0,0,3000), time=1000.)
     n = neutron(r=(0,0,0), v=(0,0,3000), time=1000., prob=10.)
     n = neutron(r=(0,0,0), v=(0,0,3000), s=(0,1), time=1000., prob=10.)
     # printing
     print n
     print n.state
     print n.state.velocity
     # setting values
     n.state.position = mcni.position(1,2,3)
     self.assertEqual(tuple(n.state.position), (1,2,3))
     n.state.velocity = mcni.velocity(1,2,3)
     self.assertEqual(tuple(n.state.velocity), (1,2,3))
     n.state.spin = mcni.spin(1,0)
     self.assertEqual(n.state.spin.s1, 1)
     self.assertEqual(n.state.spin.s2, 0)
     n.time = 999
     self.assertEqual(n.time, 999)
     n.probability = 888
     self.assertEqual(n.probability, 888)
     return
Ejemplo n.º 2
0
 def test2(self):
     "neutron"
     # creating instances
     from mcni import neutron
     n = neutron(r=(0, 0, 0), v=(0, 0, 3000))
     n = neutron(r=(0, 0, 0), v=(0, 0, 3000), time=1000.)
     n = neutron(r=(0, 0, 0), v=(0, 0, 3000), time=1000., prob=10.)
     n = neutron(r=(0, 0, 0),
                 v=(0, 0, 3000),
                 s=(0, 1),
                 time=1000.,
                 prob=10.)
     # printing
     print n
     print n.state
     print n.state.velocity
     # setting values
     n.state.position = mcni.position(1, 2, 3)
     self.assertEqual(tuple(n.state.position), (1, 2, 3))
     n.state.velocity = mcni.velocity(1, 2, 3)
     self.assertEqual(tuple(n.state.velocity), (1, 2, 3))
     n.state.spin = mcni.spin(1, 0)
     self.assertEqual(n.state.spin.s1, 1)
     self.assertEqual(n.state.spin.s2, 0)
     n.time = 999
     self.assertEqual(n.time, 999)
     n.probability = 888
     self.assertEqual(n.probability, 888)
     return
Ejemplo n.º 3
0
def test_pass_through_guide():
    """
    Test several cases where neutrons pass through the guide
    """
    guide_length = 16
    guide_exit_height = 2.0
    guide = Guide('test guide', 3, 3, 2, guide_exit_height, guide_length)

    # neutron straight through at origin
    result = do_process(guide, neutron(r=(0., 0., 0.), v=(0.0, 0.0, 0.5)))
    # the neutron should be at the same place propagated along the +Z axis
    np.testing.assert_equal([0., 0., guide_length], result[0:3])
    # make sure the velocity does not change
    np.testing.assert_equal([0., 0., 0.5], result[3:6])
    # the time should be the same as t = d/v
    np.testing.assert_equal(guide_length / 0.5, result[8])
    # probability shouldn't change since there are no reflections
    np.testing.assert_equal(1.0, result[9])

    # neutron angled at the upper back guide exit from the origin
    vmag = 0.5
    angle = np.arctan((0.5 * guide_exit_height) / guide_length)
    result = do_process(
        guide,
        neutron(r=(0., 0., 0.),
                v=(0.0, vmag * np.sin(angle), vmag * np.cos(angle))))
    np.testing.assert_equal([0.0, 0.5 * guide_exit_height, guide_length],
                            result[0:3])
    np.testing.assert_equal(1.0, result[9])
Ejemplo n.º 4
0
Archivo: slit.py Proyecto: mcvine/acc
    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)
Ejemplo n.º 5
0
def help_test_slit_beamstop(component, passes):
    # Where the neutron is when it reaches the component.
    xs_arrived = np.arange(-9, 10)  # 19
    ys_arrived = np.arange(-9, 10)  # 19
    # How the neutron position is different before it reaches the component.
    dxs = np.arange(-3, 4)  # 7
    dys = np.arange(-3, 4)  # 7
    # Try various neutron weights.
    ws = deque(np.arange(0.2, 1.1, 0.2))
    # Pattern of weights should be irregular against geometry of test data.
    assert gcd(len(ws), prod(map(len, [xs_arrived, ys_arrived, dxs, dys]))) == 1
    # Fill a neutron buffer with a range of neutrons that approach the plane of
    # the component.
    neutrons_start = []
    neutrons_end_expected = []
    (any_pass, any_fail) = (False, False)
    for x_arrived in xs_arrived:
        for y_arrived in ys_arrived:
            for dx in dxs:
                for dy in dys:
                    # Construct an incoming neutron 2m before.
                    distance = sqrt(sum([2, pow(dx, 2), pow(dy, 2)]))
                    position_start = [x_arrived + dx, y_arrived + dy, -2]
                    velocity = [n / distance for n in [-dx, -dy, 2]]  # 1 m/s
                    w = ws[0]
                    ws.rotate()  # A different weight for the next neutron.
                    neutrons_start.append(neutron(
                        r=position_start, v=velocity, prob=w))
                    if passes(x_arrived, y_arrived, w):
                        # Construct a neutron expected from the component.
                        position_arrived = [x_arrived, y_arrived, 0]
                        neutrons_end_expected.append(neutron(
                            r=position_arrived, v=velocity, prob=w,
                            time=distance))
                        any_pass = True
                    else:
                        any_fail = True
    assert any_pass and any_fail
    neutrons_end_expected = neutron_buffer_from_array(neutrons_end_expected)

    # Propagate the neutrons.
    neutrons_buffer = neutron_buffer_from_array(neutrons_start)
    component.process(neutrons_buffer)

    # Compare the actual neutrons with the expectation.
    tolerance = 1e-6 if get_numpy_floattype() == np.float32 else 1e-15
    assert np.allclose(neutrons_as_npyarr(neutrons_buffer),
                       neutrons_as_npyarr(neutrons_end_expected),
                       atol=tolerance)
    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
    def test3(self):
        '''create pure python representation of a homogeneous scatterer with
        composite kernel. render the c++ computation engine of that kernel.
        '''
        #shape
        from mccomposite.geometry import primitives
        shape = primitives.block( (1,1,1) )

        #kernel
        nprinter = NeutronPrinter( )
        
        #composite kernel
        composite_kernel = hs.compositeKernel()
        composite_kernel.addElement( nprinter )

        #scatterer
        scatterer = hs.homogeneousScatterer(
            shape, composite_kernel)

        #render the c++ representation
        cscatterer = hs.scattererEngine( scatterer )

        for i in range(10):
            ev = mcni.neutron( r = (0,0,-5), v = (0,0,1) )
            cscatterer.scatter(ev)
            continue
        return
Ejemplo n.º 8
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
    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
    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
Ejemplo n.º 11
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
    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
Ejemplo n.º 13
0
    def test1(self):
        'detector hierarchy from xml'
        from instrument.nixml import parse_file
        instrument = parse_file('ARCS.xml')

        import instrument.geometers as ig
        instrument.geometer.changeRequestCoordinateSystem(
            ig.coordinateSystem(coordinate_system))

        assignLocalGeometers(instrument, coordinate_system=coordinate_system)

        detectorSystem = instrument.getDetectorSystem()

        tofparams = 0, 10e-3, 1e-4
        detectorSystem.tofparams = tofparams
        dims = getDetectorHierarchyDimensions(instrument)
        dims = [dim for name, dim in dims]
        mca = md.eventModeMCA(outfilename, dims)
        detectorSystem.mca = mca

        cds = mh.scattererEngine(detectorSystem,
                                 coordinate_system=coordinate_system)

        for i in range(nevents):
            if i % 1000 == 0: print i
            ev = mcni.neutron(r=(0, 0, 0), v=(2000, 1500, 0))
            cds.scatter(ev)
            continue

        instrument.geometer = instrument.global_geometer
        return
Ejemplo n.º 14
0
 def process(self, neutrons):
     import mcni
     for i in range(len(neutrons)):
         info.log("loop #%d" % i)
         neutrons[i] = mcni.neutron( r = ( 0,0,0 ), v = (0,0,random.random()) )
         continue
     return neutrons
Ejemplo n.º 15
0
    def test3(self):
        '''create pure python representation of a homogeneous scatterer with
        composite kernel. render the c++ computation engine of that kernel.
        '''
        #shape
        from mccomposite.geometry import primitives
        shape = primitives.block((1, 1, 1))

        #kernel
        nprinter = NeutronPrinter()

        #composite kernel
        composite_kernel = hs.compositeKernel()
        composite_kernel.addElement(nprinter)

        #scatterer
        scatterer = hs.homogeneousScatterer(shape, composite_kernel)

        #render the c++ representation
        cscatterer = hs.scattererEngine(scatterer)

        for i in range(10):
            ev = mcni.neutron(r=(0, 0, -5), v=(0, 0, 1))
            cscatterer.scatter(ev)
            continue
        return
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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
Ejemplo n.º 19
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
Ejemplo n.º 20
0
    def test1(self):
        'detector hierarchy from xml'
        from instrument.nixml import parse_file
        instrument = parse_file( 'ARCS.xml' )

        import instrument.geometers as ig
        instrument.geometer.changeRequestCoordinateSystem(
            ig.coordinateSystem( coordinate_system ) )
        
        assignLocalGeometers( instrument, coordinate_system = coordinate_system )
        
        detectorSystem = instrument.getDetectorSystem()

        tofparams = 0, 10e-3, 1e-4
        detectorSystem.tofparams = tofparams
        dims = getDetectorHierarchyDimensions( instrument )
        dims = [ dim for name, dim in dims ]
        mca = md.eventModeMCA(  outfilename, dims )
        detectorSystem.mca = mca
        
        cds = mh.scattererEngine( detectorSystem, coordinate_system = coordinate_system )

        for i in range(nevents):
            if i%1000 == 0: print i
            ev = mcni.neutron( r = (0,0,0), v = (1500,0,2000) )
            cds.scatter(ev)
            continue

        instrument.geometer = instrument.global_geometer
        return
Ejemplo n.º 21
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)
    def test1(self):
        'complex. pack, detector, pixel hierarchy'
        
        mca = md.eventModeMCA(
            outfilename,
            (npacks, ndetsperpack, npixelsperdet,) )
        cylinder = operations.subtract( primitives.cylinder( sample2det * 1.1, detlength ),
                                        primitives.cylinder( sample2det * 0.9, detlength ) )
        ds = md.detectorSystem( cylinder, tofparams, mca )

        pack0 = makepack()
        packs = [pack0]
        for i in range(1, npacks):
            packs.append( mccomposite.scatterercopy( pack0, id = i ) )
            continue

        for i in range( npacks ):
            z = 0 * meter
            angle = (i-packindexat0)* 5./180 * N.pi
            x = sample2det * math.cos(angle)
            y = sample2det * math.sin(angle)
            ds.addElement( packs[i], (x,y,z) )
            continue

        cds = mh.scattererEngine( ds, coordinate_system = "InstrumentScientist" )

        for i in range(nevents):
            if i%1000 == 0: print i
            ev = mcni.neutron( r = (-L1,0,0), v = (vi,0,0) )
            cds.scatter(ev)
            continue

        return
Ejemplo n.º 23
0
    def process(self, neutrons):
        import mcni

        for i in range(len(neutrons)):
            neutrons[i] = mcni.neutron(r=(1, 2, 3), v=(1, 2, 3))
            continue
        return neutrons
Ejemplo n.º 24
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)
Ejemplo n.º 25
0
    def test(self):
        E_Q = "Q*Q/3."
        S_Q = "1"
        Qmin = 0; Qmax = 10
        absorption_coefficient = scattering_coefficient = 1.
        kernel = mccomponentsbp.create_E_Q_Kernel(
            E_Q, S_Q,
            Qmin, Qmax,
            absorption_coefficient,
            scattering_coefficient,
            )

        ei = 500 # meV
        from mcni.utils import conversion
        vil = conversion.e2v(ei)
        vi = (0,0,vil)

        import numpy.linalg as nl
        import numpy as np
        for i in range(10):
            event = mcni.neutron( 
                r = (0,0,0), v = vi, 
                prob = 1, time = 0 )
            kernel.scatter( event );
            vf = np.array(event.state.velocity)
            diffv = vi - vf
            Q = conversion.v2k(nl.norm(diffv))
            ef = conversion.v2e(nl.norm(vf))
            E = ei - ef
            # print E, Q, event
            E1 = eval(E_Q)
            self.assertAlmostEqual(E, E1)
            continue

        return
Ejemplo n.º 26
0
    def test_copy(self):
        '''copy'''
        print "This test creates two identical blocks, each of which "\
              "does not interact with neutrons. They print the info "\
              "about the neutrons passing thru them, however. "\
              "This test then send one neutron through these two "\
              "blocks, so we should see two printings of neutron info, "\
              "differing only on time-of-flight."
        # create a shape
        from mccomposite.geometry import primitives
        smallblock = primitives.block((1, 1, 1))

        #create pure python representation of scatterer composite
        composite1 = mccomposite.composite(smallblock)
        import UseNeutronPrinter2
        nprinter = UseNeutronPrinter2.NeutronPrinter(smallblock)
        composite1.addElement(nprinter)
        #create a copy
        copy = Copy.Copy(composite1)

        #create a larget composite
        largeblock = primitives.block((1, 1, 2))
        composite = mccomposite.composite(largeblock)
        composite.addElement(composite1, (0, 0, -0.5))
        #composite.addElement( nprinter, (0,0,-0.5) )
        composite.addElement(copy, (0, 0, +0.5))

        #render the c++ representation
        ccomposite = mccomposite.scattererEngine(composite)

        ev = mcni.neutron(r=(0, 0, -5), v=(0, 0, 1))

        ccomposite.scatter(ev)
        return
Ejemplo n.º 27
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
Ejemplo n.º 28
0
    def test_scatterercopy(self):
        '''scatterercopy'''
        # create a weird shape
        from mccomposite.geometry import primitives
        shape = primitives.block( (1,1,1) )

        #create pure python representation of scatterer composite
        composite1 = mccomposite.composite( shape )
        nprinter = NeutronPrinter( shape )
        composite1.addElement( nprinter )
        #create a copy
        copy = mccomposite.scatterercopy( composite1 )
        
        #create a larget composite
        shape = primitives.block( (1,1,2) )
        composite = mccomposite.composite( shape )
        composite.addElement( composite1, (0,0,-0.5) )
        composite.addElement( copy, (0,0,+0.5) )

        #render the c++ representation
        ccomposite = mccomposite.scattererEngine( composite )

        ev = mcni.neutron( r = (0,0,-5), v = (0,0,1) )
        ccomposite.scatter(ev)
        
        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
Ejemplo n.º 30
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
Ejemplo n.º 31
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
Ejemplo n.º 32
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
Ejemplo n.º 33
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
Ejemplo n.º 34
0
    def testCompositeScatteringKernel(self):
        'CompositeScatteringKernel'
        shape = mccompositebp.Block(1,1,1)

        from neutron_printer3 import cKernel as Printer
        printer = Printer( )

        kernels = mccomponentsbp.pointer_vector_Kernel(0)
        kernels.append( printer )
        
        weights = mccomponentsbp.vector_double(0)
        weights.append(1.)

        rotmats = mccomponentsbp.vector_rotmat(0)
        rotmat = mcnibp.RotationMatrix_double(1,0,0, 0,1,0, 0,0,1)
        rotmats.append(rotmat)
        
        average=False
        kernelcomposite = mccomponentsbp.CompositeScatteringKernel( 
            kernels, weights, rotmats, average)

        mcweights = mccomponentsbp.MCWeights_AbsorptionScatteringTransmission()
        scatterer = mccomponentsbp.HomogeneousNeutronScatterer(
            shape, kernelcomposite, mcweights )

        for i in range(10):
            ev = mcni.neutron( r = (0,0,-5), v = (0,0,1) )
            scatterer.scatter(ev)
            continue
        return
    def testCompositeScatteringKernel(self):
        'CompositeScatteringKernel'
        shape = mccompositebp.Block(1, 1, 1)

        from neutron_printer3 import cKernel as Printer
        printer = Printer()

        kernels = mccomponentsbp.pointer_vector_Kernel(0)
        kernels.append(printer)

        weights = mccomponentsbp.vector_double(0)
        weights.append(1.)

        average = False
        kernelcomposite = mccomponentsbp.CompositeScatteringKernel(
            kernels, weights, average)

        mcweights = mccomponentsbp.MCWeights_AbsorptionScatteringTransmission()
        scatterer = mccomponentsbp.HomogeneousNeutronScatterer(
            shape, kernelcomposite, mcweights)

        for i in range(10):
            ev = mcni.neutron(r=(0, 0, -5), v=(0, 0, 1))
            scatterer.scatter(ev)
            continue
        return
Ejemplo n.º 36
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)
Ejemplo n.º 37
0
    def test_copy(self):
        '''copy'''
        print "This test creates two identical blocks, each of which "\
              "does not interact with neutrons. They print the info "\
              "about the neutrons passing thru them, however. "\
              "This test then send one neutron through these two "\
              "blocks, so we should see two printings of neutron info, "\
              "differing only on time-of-flight."
        # create a shape
        from mccomposite.geometry import primitives
        smallblock = primitives.block( (1,1,1) )

        #create pure python representation of scatterer composite
        composite1 = mccomposite.composite( smallblock )
        import UseNeutronPrinter2
        nprinter = UseNeutronPrinter2.NeutronPrinter( smallblock )
        composite1.addElement( nprinter )
        #create a copy
        copy = Copy.Copy( composite1 )
        
        #create a larget composite
        largeblock = primitives.block( (1,1,2) )
        composite = mccomposite.composite( largeblock )
        composite.addElement( composite1, (0,0,-0.5) )
        #composite.addElement( nprinter, (0,0,-0.5) )
        composite.addElement( copy, (0,0,+0.5) )

        #render the c++ representation
        ccomposite = mccomposite.scattererEngine( composite )

        ev = mcni.neutron( r = (0,0,-5), v = (0,0,1) )

        ccomposite.scatter(ev)
        return
    def test1a(self):
        from sampleassembly.saxml import parse_file
        import os
        dir, filename = os.path.split(sampleassembly_xml)
        save = os.path.abspath(os.curdir)
        os.chdir(dir)
        sa = parse_file( filename )

        from mccomponents.sample.sampleassembly_support \
             import sampleassembly2compositescatterer, \
             findkernelsfromxmls
        
        scatterercomposite = findkernelsfromxmls(
            sampleassembly2compositescatterer( sa ) )
        
        import mccomponents.homogeneous_scatterer as hs
        engine = hs.scattererEngine( scatterercomposite )

        os.chdir(save)
        for i in range(1000):
            ev = mcni.neutron( r = (0,0,-5), v = (0,0,3000) )
            engine.scatter( ev )
            # print ev
            continue
        
        return
Ejemplo n.º 39
0
    def test1a(self):
        from sampleassembly.saxml import parse_file
        import os
        dir, filename = os.path.split(sampleassembly_xml)
        save = os.path.abspath(os.curdir)
        os.chdir(dir)
        sa = parse_file(filename)

        from mccomponents.sample.sampleassembly_support \
             import sampleassembly2compositescatterer, \
             findkernelsfromxmls

        scatterercomposite = findkernelsfromxmls(
            sampleassembly2compositescatterer(sa))

        import mccomponents.homogeneous_scatterer as hs
        engine = hs.scattererEngine(scatterercomposite)

        os.chdir(save)
        for i in range(10):
            ev = mcni.neutron(r=(0, 0, -5), v=(0, 0, 3000))
            engine.scatter(ev)
            print ev
            continue

        return
Ejemplo n.º 40
0
    def test_scatterercopy(self):
        '''scatterercopy'''
        # create a weird shape
        from mccomposite.geometry import primitives
        shape = primitives.block((1, 1, 1))

        #create pure python representation of scatterer composite
        composite1 = mccomposite.composite(shape)
        nprinter = NeutronPrinter(shape)
        composite1.addElement(nprinter)
        #create a copy
        copy = mccomposite.scatterercopy(composite1)

        #create a larget composite
        shape = primitives.block((1, 1, 2))
        composite = mccomposite.composite(shape)
        composite.addElement(composite1, (0, 0, -0.5))
        composite.addElement(copy, (0, 0, +0.5))

        #render the c++ representation
        ccomposite = mccomposite.scattererEngine(composite)

        ev = mcni.neutron(r=(0, 0, -5), v=(0, 0, 1))
        ccomposite.scatter(ev)

        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
Ejemplo n.º 42
0
def test_expected_exits(position_x, velocity_z):
    """
    Check that neutrons exit the guide at the expected angle, etc.
    """
    import math

    # set up simple guide
    guide_length = 16
    guide = Guide('test guide', 3, 3, 2, 2, guide_length)
    guide_angle = math.atan(((3 - 2) / 2) / guide_length)

    # set up particle
    position = np.array([position_x, -1, 0], dtype=float)
    velocity = np.array([0, 1, velocity_z], dtype=float)

    # determine expected angle from z-axis of exit assuming two reflections
    angle_expected = math.atan(velocity[1] / velocity[2])
    for i in range(0, 2):
        offset_from_normal = math.pi / 2 - angle_expected - guide_angle
        angle_expected = math.pi - angle_expected - 2 * offset_from_normal

    # propagate particle through guide
    result = do_process(guide, [neutron(position, velocity)])
    (position, velocity, duration) = (result[0:3], result[3:6], result[8])
    angle_actual = math.atan(velocity[1] / velocity[2])
    path_length = duration * np.linalg.norm(velocity)

    # check outcome
    assert np.isclose(position_x, position[0])
    assert np.isclose(guide_length, position[2])
    assert np.isclose(angle_expected, angle_actual)

    assert guide_length < path_length < guide_length * 1.1
Ejemplo n.º 43
0
    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
    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
Ejemplo n.º 45
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)
Ejemplo n.º 46
0
    def test1(self):
        from mccomponents.sample.sansmodel import sansspheremodel_kernel
        scale=1.0e-6
        radius=60.0 #A
        contrast=1.0 #A-2
        background=0 #cm-1

        absorption_cross_section = 0
        scattering_cross_section = 1
        Qmin = 0
        Qmax = 10
        k = sansspheremodel_kernel(
            scale, radius, contrast, background,
            absorption_cross_section, scattering_cross_section,
            Qmin, Qmax)

        from mccomponents.sample import scattererEngine
        kengine = scattererEngine( k )

        print dir(kengine)

        n = mcni.neutron( r = (0,0,0), v = (0,0,3000) )
        kengine.scatter( n )
        print n
        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 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
Ejemplo n.º 49
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
Ejemplo n.º 50
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
Ejemplo n.º 51
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 test3(self):
        'MonochromaticSource - energy spread'

        # source component
        from mcni.components.MonochromaticSource import MonochromaticSource
        from mcni import neutron_buffer, neutron
        neutron0 = neutron(v=(0, 0, 3000), r=(0.3, 0.4, 1.5))
        dx = 0.1
        dy = 0.8
        dE = 5
        s = MonochromaticSource("name", neutron0, dx=0, dy=0, dE=dE)

        # neutron buffer
        N = 100000
        b = neutron_buffer(N)

        # process
        s.process(b)

        #
        E0 = neutron0.energy()
        #
        n_in_onesigma = 0
        n_in_twosigma = 1
        for n in b:

            E = n.energy()
            # print n
            # print E, E0
            # not always true but usually true
            self.assertNotEqual(E, E0)

            #
            if abs(E - E0) < dE:
                n_in_onesigma += 1
            if abs(E - E0) < 2 * dE:
                n_in_twosigma += 1

            self.assertEqual(
                tuple(n.state.position),
                tuple(neutron0.state.position),
            )
            self.assertEqual(
                n.time,
                neutron0.time,
            )
            self.assertEqual(
                n.probability,
                neutron0.probability,
            )

            continue

        self.assert_(abs(n_in_onesigma * 1. / N - 0.68) < 0.01)
        self.assert_(abs(n_in_twosigma * 1. / N - 0.95) < 0.01)
        return
Ejemplo n.º 53
0
    def test(self):
        "wrap IQE_monitor"

        from mcstas2 import componentfactory
        category = 'monitors'
        componentname = 'IQE_monitor'
        factory = componentfactory(category, componentname)

        Qmin = 0
        Qmax = 13.
        nQ = 130
        Emin = -50
        Emax = 50.
        nE = 100

        component = factory(
            'component',
            Ei=Ei,
            Qmin=Qmin,
            Qmax=Qmax,
            nQ=nQ,
            Emin=Emin,
            Emax=Emax,
            nE=nE,
            max_angle_out_of_plane=30,
            min_angle_out_of_plane=-30,
            max_angle_in_plane=120,
            min_angle_in_plane=-30,
        )

        scatterer = makeScatterer()

        import mcni
        N = 10000
        neutrons = mcni.neutron_buffer(N)
        for i in range(N):
            neutron = mcni.neutron(r=(0, 0, 0), v=(0, 0, vi), time=0, prob=1)
            scatterer.scatter(neutron)
            neutrons[i] = neutron
            #print neutrons[i]
            continue

        component.process(neutrons)

        hist = get_histogram(component)
        import os
        f = os.path.basename(__file__)
        filename = 'IQE-%s.h5' % f
        if os.path.exists(filename): os.remove(filename)
        import histogram.hdf as hh
        hh.dump(hist, filename, '/', 'c')

        if self.interactive:
            from histogram.plotter import defaultPlotter
            defaultPlotter.plot(hist)
        return
Ejemplo n.º 54
0
 def process(self, neutrons):
     n0 = neutrons[0]
     from mcni import neutron
     self.neutron = neutron(
         r=n0.state.position, v=n0.state.velocity, 
         s=(n0.state.spin.s1,n0.state.spin.s2),
         time=n0.time,
         prob=n0.probability,
         )
     return
Ejemplo n.º 55
0
 def testHomogeneousNeutronScatterer(self):
     'HomogeneousNeutronScatterer'
     shape = mccompositebp.Cylinder(0.025/2., 0.01)
     tof=0.001; pressure=10*101325
     pixel = mccomponentsbp.DGSSXResPixel(tof, pressure, shape)
     
     ev = mcni.neutron( r = (0,0,-3), v = (0,0,3000) )
     pixel.scatter(ev)
     print ev.probability
     return
    def test(self):
        kernel = mccomponentsbp.IsotropicKernel(1,1)

        for i in range(10):
            event = mcni.neutron( r = (0,0,0), v = (0,0,3000), prob = 1, time = 0 )
            kernel.scatter( event );
            print event
            continue

        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