Ejemplo n.º 1
0
def runMonitorsAtSample(E, m2sout, out):
    from mcni.utils.conversion import e2v
    v = e2v(E)
    from pyre.units.time import second
    L = 13.6
    t = L/v

    neutronfile = os.path.join(m2sout, 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import count
    n = count(neutronfile)

    cmd = ['arcs_analyze_beam']
    cmd += ['--output-dir=%s' % out]
    cmd += ['--ncount=%s' % n]
    cmd += ['--buffer_size=%s' % min(n, 1e6)]
    cmd += ['--source.path=%s' % neutronfile]
    # fix monitor params that depend on incident energy
    cmd += ['--monitor.mtof.tofmin=%s' % (t*0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t*1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (E*0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (E*1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    cmd = ' '.join(cmd)
    print 'Running beam monitors...'
    _exec(cmd)
    print 'done.'
    time.sleep(1)
    return
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def runMonitorsAtSample(E, m2sout, out, L=LSAMPLE, instrument='arcs'):
    from mcni.utils.conversion import e2v
    v = e2v(E)
    from pyre.units.time import second
    t = L/v

    neutronfile = os.path.join(m2sout, 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import count
    n = count(neutronfile)

    cmd = ['mcvine instruments %s analyze_beam' % instrument]
    cmd += ['--output-dir=%s' % out]
    cmd += ['--ncount=%s' % n]
    cmd += ['--buffer_size=%s' % min(n, int(1e6))]
    cmd += ['--source.path=%s' % neutronfile]
    # fix monitor params that depend on incident energy
    cmd += ['--monitor.mtof.tofmin=%s' % (t*0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t*1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (E*0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (E*1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    cmd = ' '.join(cmd)
    print('Running beam monitors...')
    _exec(cmd)
    print('done.')
    time.sleep(1)
    return
Ejemplo n.º 5
0
def runMonitorsAtSample(E, LMS, m2sout, out):
    from mcni.utils.conversion import e2v
    v = e2v(E)
    from pyre.units.time import second
    L = LMM + LMS
    t = L/v
    
    neutronfile = os.path.join(m2sout, 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import count
    n = count(neutronfile)
    
    cmd = ['mcvine_analyze_beam']
    cmd += ['--output-dir=%s' % out]
    cmd += ['--ncount=%s' % n]
    cmd += ['--buffer_size=%s' % min(n, 1e6)]
    # XXX: -0.15 comes from the fact that the in hyspec_moderator2sample
    # XXX: the neutron storage is 0.15 before the sample position
    cmd += ['--geometer.source="((0,0,-0.15),(0,0,0))"']
    cmd += ['--source.path=%s' % neutronfile]
    # fix monitor params that depend on incident energy
    cmd += ['--monitor.mtof.tofmin=%s' % (t*0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t*1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (E*0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (E*1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    cmd = ' '.join(cmd)
    print('Running beam monitors...')
    _exec(cmd)
    print('done.')
    time.sleep(1)
    return
Ejemplo n.º 6
0
def sendneutronstodetsys(
    neutronfile=None, scattering_rundir=None, nodes=None, ncount=None,
    workdir = None, tofbinsize = None, tofmax=None, detsys = None,
    z_rotation = None,
    ):
    """
    run a simulation to send neutrons to det system
    
    workdir: directory where the simulation is run
    tofmax: unit: second
    tofbinsize: unit: microsecond
    
    z_rotation: angle of rotation applied to the detector system around z axis (vertical). unit: degree
    """
    # create workdir if it does not exist
    if not os.path.exists(workdir):
        os.makedirs(workdir)
        
    # number of neutrons scattered
    if not neutronfile:
        neutronfile = os.path.join(scattering_rundir, 'out', 'scattered-neutrons')
    if not ncount:
        from mcni.neutron_storage.idf_usenumpy import count
        ncount = count(neutronfile)
        
    # create simulation command
    cmd_name = 'sd'
    sim_cmd = os.path.join(workdir, cmd_name)
    open(sim_cmd, 'wt').write(sd_txt)
    
    
    # build command
    cmd = ['python '+cmd_name]
    args = {
        'source': 'NeutronFromStorage',
        'detsys': 'DetectorSystemFromXml',
        'output-dir': 'out',
        'detsys.tofparams': '0,%s,%s' % (tofmax, 1e-6*tofbinsize,), 
        'detsys.instrumentxml': detsys,
        'detsys.eventsdat': 'events.dat',
        'geometer.detsys': '(0,0,0),(0,%s,0)' % (z_rotation or 0,),
        'ncount': ncount,
        'source.path': neutronfile,
        }
    if nodes:
        from mcni.pyre_support.MpiApplication \
            import mpi_launcher_choice as launcher
        args['%s.nodes' % launcher] = nodes
    cmd += ['--%s=%s' % (k,v) for k,v in args.iteritems()]
    cmd = ' '.join(cmd)
    run_sh = os.path.join(workdir, 'run.sh')
    open(run_sh, 'w').write(cmd+'\n')
    execute(cmd, workdir)
    
    # events.dat
    outfile = os.path.join(workdir, 'out', 'events.dat')
    return outfile
Ejemplo n.º 7
0
def sendneutronstodetsys(
    neutronfile=None,
    scattering_rundir=None,
    nodes=None,
    ncount=None,
    workdir=None,
):
    """
    run a simulation to send neutrons to det system
    
    workdir: directory where the simulation is run
    """
    # create workdir if it does not exist
    if not os.path.exists(workdir):
        os.makedirs(workdir)

    # number of neutrons scattered
    if not neutronfile:
        neutronfile = os.path.join(scattering_rundir, 'out',
                                   'scattered-neutrons')
    if not ncount:
        from mcni.neutron_storage.idf_usenumpy import count
        ncount = count(neutronfile)

    # create simulation command
    cmd_name = 'sd'
    sim_cmd = os.path.join(workdir, cmd_name)
    open(sim_cmd, 'wt').write(sd_txt)

    # build command
    cmd = ['python ' + cmd_name]
    args = {
        'source': 'NeutronFromStorage',
        'detsys': 'DetectorSystemFromXml',
        'output-dir': 'out',
        'detsys.tofparams': '0,1.,%s' % (1e-6 * tofbinsize, ),
        'detsys.instrumentxml': cncsxml,
        'detsys.eventsdat': 'events.dat',
        'ncount': ncount,
        'source.path': neutronfile,
    }
    if nodes:
        from mcni.pyre_support.MpiApplication \
            import mpi_launcher_choice as launcher
        args['%s.nodes' % launcher] = nodes
    cmd += ['--%s=%s' % (k, v) for k, v in args.items()]
    cmd = ' '.join(cmd)
    run_sh = os.path.join(workdir, 'run.sh')
    open(run_sh, 'w').write(cmd + '\n')
    from .utils import execute
    execute(cmd, workdir)

    # events.dat
    outfile = os.path.join(workdir, 'out', 'events.dat')
    return outfile
Ejemplo n.º 8
0
def sendneutronstodetsys(
    neutronfile=None, scattering_rundir=None, nodes=None, ncount=None,
    workdir = None,
    ):
    """
    run a simulation to send neutrons to det system
    
    workdir: directory where the simulation is run
    """
    # create workdir if it does not exist
    if not os.path.exists(workdir):
        os.makedirs(workdir)
        
    # number of neutrons scattered
    if not neutronfile:
        neutronfile = os.path.join(scattering_rundir, 'out', 'scattered-neutrons')
    if not ncount:
        from mcni.neutron_storage.idf_usenumpy import count
        ncount = count(neutronfile)
        
    # create simulation command
    cmd_name = 'sd'
    sim_cmd = os.path.join(workdir, cmd_name)
    open(sim_cmd, 'wt').write(sd_txt)
    
    
    # build command
    cmd = ['python '+cmd_name]
    args = {
        'source': 'NeutronFromStorage',
        'detsys': 'DetectorSystemFromXml',
        'output-dir': 'out',
        'detsys.tofparams': '0,0.02,%s' % (1e-6*tofbinsize,), 
        'detsys.instrumentxml': arcsxml,
        'detsys.eventsdat': 'events.dat',
        'ncount': ncount,
        'source.path': neutronfile,
        }
    if nodes:
        from mcni.pyre_support.MpiApplication \
            import mpi_launcher_choice as launcher
        args['%s.nodes' % launcher] = nodes
    cmd += ['--%s=%s' % (k,v) for k,v in args.iteritems()]
    cmd = ' '.join(cmd)
    run_sh = os.path.join(workdir, 'run.sh')
    open(run_sh, 'w').write(cmd+'\n')
    from .utils import execute
    execute(cmd, workdir)

    # events.dat
    outfile = os.path.join(workdir, 'out', 'events.dat')
    return outfile
Ejemplo n.º 9
0
def computeFlux(m2sout):
    f = os.path.join(m2sout, 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import totalintensity, count
    I = totalintensity(f)
    if I == 0:
        raise RuntimeError, "There is no neutrons at sample position. Please increase ncount"
    # one MC run corresponds to 34kJ/pulse
    # this is the flux if the power is at 34kJ/pulse
    # unit: 1/34kJ pulse
    # every neutron in the storage represents one 34kJ pulse. so 
    # we need to normalize by number of events in the storage
    nevts = count(f)
    flux = I/nevts
    return flux
Ejemplo n.º 10
0
def computeFlux(m2sout):
    f = os.path.join(m2sout, 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import totalintensity, count
    I = totalintensity(f)
    if I == 0:
        raise RuntimeError("There is no neutrons at sample position. Please increase ncount")
    # one MC run corresponds to 34kJ/pulse
    # this is the flux if the power is at 34kJ/pulse
    # unit: 1/34kJ pulse
    # every neutron in the storage represents one 34kJ pulse. so 
    # we need to normalize by number of events in the storage
    nevts = count(f)
    flux = I/nevts
    return flux
Ejemplo n.º 11
0
def runMonitorsAtSample(E, m2sout, out, L):
    from mcni.utils.conversion import e2v
    v = e2v(E)
    from pyre.units.time import second
    t = L / v

    neutronfile = os.path.abspath(os.path.join(m2sout, 'neutrons'))
    from mcni.neutron_storage.idf_usenumpy import count
    n = count(neutronfile)

    # cmd = ['mcvine instruments %s analyze_beam' % instrument]
    app = os.path.join(here, 'dgs_bpp_analyze_beam.py')
    # create a temp dir to run the simulation
    import tempfile
    tmpd = tempfile.mkdtemp()

    def copy2tmpd(fn):
        src = os.path.join(here, fn)
        dest = os.path.join(tmpd, fn)
        shutil.copyfile(src, dest)

    copy2tmpd('dgs_bpp_analyze_beam.pml')
    copy2tmpd('beam_analyzer.odb')
    cmd = ['python {}'.format(app)]
    cmd += ['--output-dir=%s' % os.path.abspath(out)]
    cmd += ['--ncount=%s' % n]
    cmd += ['--buffer_size=%s' % min(n, int(1e6))]
    cmd += ['--source.path=%s' % neutronfile]
    # fix monitor params that depend on incident energy
    cmd += ['--monitor.mtof.tofmin=%s' % (t * 0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t * 1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (E * 0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (E * 1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    cmd = ' '.join(cmd)
    print('Running beam monitors...')
    from mcvine.run_script import _exec
    print(cmd, tmpd)
    _exec(cmd, cwd=tmpd)
    print('done.')
    time.sleep(1)
    # shutil.rmtree(tmpd)
    return
Ejemplo n.º 12
0
def merge_and_normalize(filename, outputs_dir, overwrite_datafiles=True):
    """merge_and_normalize('scattered-neutrons', 'out')
    """
    # find all output files
    from mcni.components.outputs import n_mcsamples_files, mcs_sum
    import glob, os

    pattern = os.path.join(outputs_dir, "*", filename)
    nsfiles = glob.glob(pattern)
    n_mcsamples = n_mcsamples_files(outputs_dir)
    assert len(nsfiles) == n_mcsamples, "neutron storage files %s does not match #mcsample files %s" % (
        len(nsfiles),
        n_mcsamples,
    )
    if not nsfiles:
        return None, None

    # output
    out = os.path.join(outputs_dir, filename)
    if overwrite_datafiles:
        if os.path.exists(out):
            os.remove(out)
    # merge
    from mcni.neutron_storage import merge

    merge(nsfiles, out)

    # number of neutron events totaly in the neutron file
    from mcni.neutron_storage.idf_usenumpy import count

    nevts = count(out)

    # load number_of_mc_samples
    mcs = mcs_sum(outputs_dir)

    # normalization factor. this is a bit tricky!!!
    nfactor = mcs / nevts

    # normalize
    from mcni.neutron_storage import normalize

    normalize(out, nfactor)
    return
Ejemplo n.º 13
0
def runMonitorsAtSample(E, LMS, m2sout, out):
    from mcni.utils.conversion import e2v

    v = e2v(E)
    from pyre.units.time import second

    # this is copied from hyspec_moderator2sample.instr
    # XXX: duplicate code. will need to change this
    # XXX: if the instrument changes.
    L1 = 9.93
    L2 = 48.0 * 0.501
    L3 = 5.0
    LMM = L1 + L2 + L3
    L = LMM + LMS
    t = L / v

    neutronfile = os.path.join(m2sout, "neutrons")
    from mcni.neutron_storage.idf_usenumpy import count

    n = count(neutronfile)

    cmd = ["mcvine_analyze_beam"]
    cmd += ["--output-dir=%s" % out]
    cmd += ["--ncount=%s" % n]
    cmd += ["--buffer_size=%s" % min(n, 1e6)]
    # XXX: -0.15 comes from the fact that the in hyspec_moderator2sample
    # XXX: the neutron storage is 0.15 before the sample position
    cmd += ['--geometer.source="((0,0,-0.15),(0,0,0))"']
    cmd += ["--source.path=%s" % neutronfile]
    # fix monitor params that depend on incident energy
    cmd += ["--monitor.mtof.tofmin=%s" % (t * 0.9)]
    cmd += ["--monitor.mtof.tofmax=%s" % (t * 1.1)]
    cmd += ["--monitor.mtof.ntof=%s" % (1000)]
    cmd += ["--monitor.menergy.energymin=%s" % (E * 0.9)]
    cmd += ["--monitor.menergy.energymax=%s" % (E * 1.1)]
    cmd += ["--monitor.menergy.nenergy=%s" % (1000)]
    cmd = " ".join(cmd)
    print "Running beam monitors..."
    _exec(cmd)
    print "done."
    time.sleep(1)
    return
Ejemplo n.º 14
0
def sendneutronstodetsys(scattering_rundir, nodes, ncount=None):
    import os
    if os.path.exists('out'):
        raise IOError, "output directory 'out' already exists. Rename or remove it"
    # number of neutrons scattered
    neutronfile = os.path.join(scattering_rundir, 'out', 'scattered-neutrons')
    if not ncount:
        from mcni.neutron_storage.idf_usenumpy import count
        ncount = count(neutronfile)

    # build command
    cmd = ['./sd']
    args = {
        'ncount': ncount,
        'mpirun.nodes': nodes,
        'source.path': neutronfile,
        }
    cmd += ['--%s=%s' % (k,v) for k,v in args.iteritems()]
    cmd = ' '.join(cmd)
    execute(cmd)
    return
Ejemplo n.º 15
0
    def _merge_and_normalize(self):
        # XXX: should rewrite using mcni.neutron_storage.merge_and_normalize
        outdir = self.simulation_context.outputdir

        # find all output files
        from mcni.components.outputs import n_mcsamples_files, mcs_sum
        import glob, os
        filename = self.path
        pattern = os.path.join(outdir, '*', filename)
        nsfiles = glob.glob(pattern)
        n_mcsamples = n_mcsamples_files(outdir)
        assert len(nsfiles) == n_mcsamples, \
            "neutron storage files %s does not match #mcsample files %s" %(
            len(nsfiles), n_mcsamples)
        if not nsfiles:
            return None, None

        # output
        out = os.path.join(outdir, self.path)
        if self.overwrite_datafiles:
            if os.path.exists(out):
                os.remove(out)
        # merge
        from mcni.neutron_storage import merge
        merge(nsfiles, out)

        # number of neutron events totaly in the neutron file
        from mcni.neutron_storage.idf_usenumpy import count
        nevts = count(out)

        # load number_of_mc_samples
        mcs = mcs_sum(outdir)

        # normalization factor. this is a bit tricky!!!
        nfactor = mcs / nevts

        # normalize
        from mcni.neutron_storage import normalize
        normalize(out, nfactor)
        return
Ejemplo n.º 16
0
    def _merge_and_normalize(self):
        # XXX: should rewrite using mcni.neutron_storage.merge_and_normalize
        outdir = self.simulation_context.outputdir

        # find all output files
        from mcni.components.outputs import n_mcsamples_files, mcs_sum
        import glob, os
        filename = self.path
        pattern = os.path.join(outdir, '*', filename)
        nsfiles = glob.glob(pattern)
        n_mcsamples = n_mcsamples_files(outdir)
        assert len(nsfiles) == n_mcsamples, \
            "neutron storage files %s does not match #mcsample files %s" %(
            len(nsfiles), n_mcsamples)
        if not nsfiles:
            return None, None
        
        # output
        out = os.path.join(outdir, self.path)
        if self.overwrite_datafiles:
            if os.path.exists(out):
                os.remove(out)
        # merge
        from mcni.neutron_storage import merge
        merge(nsfiles, out)
        
        # number of neutron events totaly in the neutron file
        from mcni.neutron_storage.idf_usenumpy import count
        nevts = count(out)

        # load number_of_mc_samples
        mcs = mcs_sum(outdir)

        # normalization factor. this is a bit tricky!!!
        nfactor = mcs/nevts
        
        # normalize
        from mcni.neutron_storage import normalize
        normalize(out, nfactor)
        return
Ejemplo n.º 17
0
def merge_and_normalize(filename, outputs_dir, overwrite_datafiles=True):
    """merge_and_normalize('scattered-neutrons', 'out')
    """
    # find all output files
    from mcni.components.outputs import n_mcsamples_files, mcs_sum
    import glob, os
    pattern = os.path.join(outputs_dir, '*', filename)
    nsfiles = glob.glob(pattern)
    n_mcsamples = n_mcsamples_files(outputs_dir)
    assert len(nsfiles) == n_mcsamples, \
        "neutron storage files %s does not match #mcsample files %s" %(
        len(nsfiles), n_mcsamples)
    if not nsfiles:
        return None, None

    # output
    out = os.path.join(outputs_dir, filename)
    if overwrite_datafiles:
        if os.path.exists(out):
            os.remove(out)
    # merge
    from mcni.neutron_storage import merge
    merge(nsfiles, out)

    # number of neutron events totaly in the neutron file
    from mcni.neutron_storage.idf_usenumpy import count
    nevts = count(out)

    # load number_of_mc_samples
    mcs = mcs_sum(outputs_dir)

    # normalization factor. this is a bit tricky!!!
    nfactor = mcs / nevts

    # normalize
    from mcni.neutron_storage import normalize
    normalize(out, nfactor)
    return
Ejemplo n.º 18
0
    def collimator_inefficiency(self, params):

        dcs, I_d, error = self.diffraction_pattern_calculation(params)

        scattered = os.path.join(beam_path, 'clampcellSi_neutron')

        ncount = 1e9

        sample_peaks = self.peaks['sample']

        cell_peaks = self.peaks['cell']

        scattered_beam_intensity = totalintensity(scattered) * ncount / count(
            scattered)

        sample_peak_int = 0.0
        cell_peak_int = 0.0

        for sample_peak in sample_peaks:
            sample_peak_int += I_d[(dcs < sample_peak.dmax)
                                   & (dcs > sample_peak.dmin)].sum(
                                   )  #I_d[ (dcs<3.5) & (dcs>3)].sum()

        for cell_peak in cell_peaks:
            cell_peak_int += I_d[(dcs < cell_peak.dmax)
                                 & (dcs > cell_peak.dmin)].sum(
                                 )  #I_d[np.logical_and(dcs<2.2, dcs>2)].sum()

        # collimator_ineff=(cell_peak_int/sample_peak_int)+(1-sample_peak_int/scattered_beam_intensity)

        collimator_ineff = (cell_peak_int / sample_peak_int
                            )  # new objective function suggested by Garrett

        print('coll_len,:', params[0], 'focal_distance,:', params[1],
              'collimator_performance: ', (sample_peak_int / cell_peak_int))

        return (collimator_ineff)
Ejemplo n.º 19
0
from collimator_geometry import create as create_collimator_geometry, Parameter_error
import reduction, conf

scattered = os.path.join(
    beam_path, 'clampcellSi_neutron'
)  # path to scattered neutrons from clamp cell and sample
sample = 'collimator'
ncount = 1e5
nodes = 20
sourceTosample = 0
detector_size = 0.5

instr = os.path.join(libpath, 'myinstrument.py')

scattered_beam_intensity = totalintensity(scattered) * ncount / count(
    scattered)

samplepath = os.path.join(thisdir, '../sample')
filename = 'coll_geometry.xml'
outputfile = os.path.join(samplepath, filename)


def objective_func(params):
    try:
        diffraction_pattern = diffraction_pattern_calculation(params)

        return (collimator_inefficiency(diffraction_pattern))

    except Parameter_error as e:
        return (1e10)
Ejemplo n.º 20
0
def run(beam_neutrons_path, instrument, samplexmlpath, psi, hkl2Q, pixel, t_m2p,
        Q, E, hkl_projection, Nbuffer=100000, Nrounds_beam=1):
    """Run mcvine simulation with using the resolution sample and the resolution pixel,
    and save the results as numpy arrays

    - beam_neutrons_path: path to the "neutrons" file of a beam simulation
    - instrument: instrument object with geometry data such as L1 and L2
    - samplexmlpath: path to the sampleassembly xml file
    - psi: sample rotation angle
    - hkl2Q: matrix to convert hkl to Q: Q = hkl dot hkl2Q
    - pixel: pixel object with pixe, height, pressure. and position
    - t_m2p: exepcted tof from moderator to pixel
    - Q: expected Q
    - E: expected E
    - hkl_projection: the simulated data is projected to this axis and E axis for easy inspection
    - Nbuffer: neutron buffer size
    - Nrounds_beam: number of rounds replaying neutrons in the beam
    """
    from mcni.components.NeutronFromStorage import NeutronFromStorage
    source = NeutronFromStorage('source', path=beam_neutrons_path)
    from mccomponents.sample import samplecomponent
    sample = samplecomponent( 'sample', samplexmlpath)
    # dummy component to save the state of scattered neutrons
    from mcni.components.Dummy import Dummy
    sample_location = Dummy('sample_location')
    # det pixel
    from mccomponents.components.DGSSXResPixel import DGSSXResPixel
    pressure = mcvine.units.parse(pixel.pressure)/mcvine.units.parse("kg/m/s/s")
    r = mcvine.units.parse(pixel.radius)/mcvine.units.meter
    h = mcvine.units.parse(pixel.height)/mcvine.units.meter
    pixel_comp = DGSSXResPixel(
        "pixel",
        pressure=pressure, tof=t_m2p,
        radius=r, height=h)
    # build instrument simulation chain
    import mcni
    sim_chain = mcni.instrument( [source, sample, sample_location, pixel_comp] )
    # put components into place
    geometer = mcni.geometer()
    z_beam = mcvine.units.parse(instrument.offset_sample2beam)/mcvine.units.meter
    # z along beam
    geometer.register( source, (0,0,z_beam), (0,0,0) )
    geometer.register( sample, (0,0,0), (0,psi*180/np.pi,0) )
    geometer.register( sample_location, (0,0,0), (0,0,0) )
    geometer.register( pixel_comp, pixel.position, pixel.orientation )
    #
    Q2hkl = np.linalg.inv(hkl2Q)
    # lengh of hkl_projection squared
    hkl_proj_len2 = np.dot(hkl_projection, hkl_projection)
    # neutron buffer
    from mcni.neutron_storage.idf_usenumpy import count
    N0 = count(beam_neutrons_path) * Nrounds_beam
    dxs_all = None; dEs_all = None; probs_all=None; dhkls_all=None
    start = 0
    for i in range(int(np.ceil(N0/Nbuffer))+1):
    # for i in range(10):
        end = start + Nbuffer
        end = min(end, N0)
        if end<=start:
            continue
        sys.stdout.write("%s-%s: " % (start, end-1)); sys.stdout.flush()
        neutrons = mcni.neutron_buffer(end-start)
        # simulate
        tracer = NeutronTracer()
        mcni.simulate( sim_chain, geometer, neutrons, tracer=tracer)
        #
        before_dummy_start, after_dummy_start, \
            before_incident, after_incident, \
            before_scattered, after_scattered, \
            at_sample_location, at_sample_location2, \
            before_detected, after_detected, \
            before_dummy_end, after_dummy_end = tracer._store
        incident = after_incident
        # has to be `at_sample_location` because both sample_location and
        # beam have no relative rotation. 
        # should not used after_scattered.
        # it is in the sample's coordinate system, which is rotated by angle psi.
        # should not use before_detected. It could be rotated in spherical case
        scattered = at_sample_location
        detected = after_detected
        del (before_dummy_start, after_dummy_start,
             before_incident, after_incident,
             before_scattered, after_scattered,
             before_detected, after_detected,
             before_dummy_end, after_dummy_end)
        is_scattered = incident.v != scattered.v
        is_scattered = np.logical_or(
            is_scattered[:,0],
            np.logical_or(is_scattered[:,1], is_scattered[:,2])
            )
        good = np.logical_and(is_scattered, detected.p>np.finfo(float).eps)

        vi = incident.v[good]
        vf = scattered.v[good]
        probs = p = detected.p[good]

        from mcni.utils import conversion
        Ei = conversion.VS2E * (vi*vi).sum(axis=-1)
        Ef = conversion.VS2E * (vf*vf).sum(axis=-1)
        Es = Ei - Ef

        vQ = vi-vf
        Qs = vQ * conversion.V2K
        Qs = np.array([Qs[:, 2], Qs[:, 0], Qs[:, 1]]).T
        # print Qs
        # print Es
        dQs = Qs - Q
        dEs = Es - E
        dhkls = np.dot(dQs, Q2hkl)
        # print dhkls
        # print dEs
        # print p
        dxs = np.dot( dhkls, np.array(hkl_projection) )/hkl_proj_len2
        if dxs_all is None:
            dxs_all = dxs
            dEs_all = dEs
            probs_all = probs
            dhkls_all = dhkls
        else:
            dxs_all = np.concatenate((dxs_all, dxs))
            dEs_all = np.concatenate((dEs_all, dEs))
            probs_all = np.concatenate((probs_all, probs))
            dhkls_all = np.concatenate((dhkls_all, dhkls))
        print()
        start = end
        continue
    # reverse x and E
    # the negative sign here makes the result the PSF
    dxs_all *= -1
    dEs_all *= -1
    dhkls_all *= -1
    # save results
    np.save("dhkls.npy", dhkls_all)
    np.save("dxs.npy", dxs_all)
    np.save("dEs.npy", dEs_all)
    np.save("probs.npy", probs_all)
    h, xedges, yedges = np.histogram2d(
        dxs_all, dEs_all, bins=100, weights=probs_all)
    import histogram as H, histogram.hdf as hh
    xaxis = H.axis('x', boundaries=xedges)
    Eaxis = H.axis('E', boundaries=yedges)
    res = H.histogram('res', (xaxis, Eaxis), data=h)
    hh.dump(res, 'res.h5')
    sys.stdout.write("Done.\n"); sys.stdout.flush()
    return
Ejemplo n.º 21
0
def sendneutronstodetsys(
    neutronfile=None,
    scattering_rundir=None,
    nodes=None,
    ncount=None,
    workdir=None,
    tofbinsize=None,
    tofmax=None,
    detsys=None,
    z_rotation=None,
):
    """
    run a simulation to send neutrons to det system
    
    workdir: directory where the simulation is run
    tofmax: unit: second
    tofbinsize: unit: microsecond
    
    z_rotation: angle of rotation applied to the detector system around z axis (vertical). unit: degree
    """
    # create workdir if it does not exist
    if not os.path.exists(workdir):
        os.makedirs(workdir)

    # number of neutrons scattered
    if not neutronfile:
        neutronfile = os.path.join(scattering_rundir, 'out',
                                   'scattered-neutrons')
    if not ncount:
        from mcni.neutron_storage.idf_usenumpy import count
        ncount = count(neutronfile)

    # create simulation command
    cmd_name = 'sd'
    sim_cmd = os.path.join(workdir, cmd_name)
    open(sim_cmd, 'wt').write(sd_txt)

    # build command
    cmd = ['python ' + cmd_name]
    args = {
        'source': 'NeutronFromStorage',
        'detsys': 'DetectorSystemFromXml',
        'output-dir': 'out',
        'detsys.tofparams': '0,%s,%s' % (
            tofmax,
            1e-6 * tofbinsize,
        ),
        'detsys.instrumentxml': detsys,
        'detsys.eventsdat': 'events.dat',
        'geometer.detsys': '(0,0,0),(0,%s,0)' % (z_rotation or 0, ),
        'ncount': ncount,
        'source.path': neutronfile,
    }
    if nodes:
        args['mpirun.nodes'] = nodes
    cmd += ['--%s=%s' % (k, v) for k, v in args.iteritems()]
    cmd = ' '.join(cmd)
    run_sh = os.path.join(workdir, 'run.sh')
    open(run_sh, 'w').write(cmd + '\n')
    execute(cmd, workdir)

    # events.dat
    outfile = os.path.join(workdir, 'out', 'events.dat')
    return outfile
Ejemplo n.º 22
0
def run(Ei,
        ncount,
        nodes,
        moderator_erange=None,
        fermichopper=None,
        fermi_nu=None,
        T0_nu=None,
        emission_time=None,
        dry_run=False):
    fermichopper = fermichopper or "100-1.5-SMI"
    emission_time = emission_time or -1
    fermi_nu = fermi_nu or 600
    T0_nu = T0_nu or 120
    # generate configration
    cmd = """
    arcs-m2s \
        --fermi_nu=%(fermi_nu)s \
        --T0_nu=%(T0_nu)s \
        --E=%(Ei)s \
        --emission_time=%(emission_time)s \
        --fermi_chopper=%(fermichopper)s \
        --- \
        -dump-pml
    """ % locals()
    execute(cmd)

    # fine tune configuraiton
    cmd = ["arcs_moderator2sample --overwrite-datafiles"]
    Emin, Emax = moderator_erange
    cmd.append('--moderator.Emin=%s' % Emin)
    cmd.append('--moderator.Emax=%s' % Emax)
    cmd.append("--dump-pml")
    cmd = ' '.join(cmd)
    execute(cmd)

    # run simulation
    import os, shutil
    if os.path.exists('out'):
        shutil.rmtree('out')
    cmd = "arcs_moderator2sample -ncount=%(ncount)s " % locals()
    # ... moderator data file
    moddat = os.path.join(
        os.environ['MCVINE_DIR'],
        'share',
        'mcvine',
        'instruments',
        'ARCS',
        'source_sct521_bu_17_1.dat',
    )
    cmd += ' -moderator.S_filename=%s ' % moddat
    cmd += ' -mpirun.nodes=%s' % nodes
    cmd += '> m2s.log 2> m2s.err'
    if dry_run:
        print cmd
    else:
        execute(cmd)

    # analyze output
    # ... number of neutrons left
    neutronfile = os.path.join('out', 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import count
    if dry_run:
        ncountatsample = 1000
    else:
        ncountatsample = count(neutronfile)

    if ncountatsample == 0:
        raise RuntimeError, "no neutrons at sample. need to increase mc samples at mod2sample simulation"

    cmd = [
        'arcs_analyze_beam',
        '-source.path=%(neutronfile)s' % locals(),
        '-ncount=%(ncountatsample)s' % locals(),
        '--output-dir=out-analyzer',
    ]
    # ... compute enegy range
    from mcni.utils.conversion import e2v
    v = e2v(Ei)
    from pyre.units.time import second
    L = 13.6
    t = L / v
    # ... build command line with monitor parameters
    cmd += ['--monitor.mtof.tofmin=%s' % (t * 0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t * 1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (Ei * 0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (Ei * 1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    # ... run
    cmd = ' '.join(cmd)
    if dry_run:
        print cmd
    else:
        execute(cmd)
    return
Ejemplo n.º 23
0
#!/usr/bin/env python

import os
here = os.path.dirname(__file__) or '.'
here = os.path.abspath(here)

scattered = os.path.join(here, '../sample/out/scattered.mcvine')

from mcni.neutron_storage.idf_usenumpy import count
N = count(scattered)

from mcvine import run_script
run_script.run_mpi('./sd.py', 'out', ncount=N, nodes=8, overwrite_datafiles=True)
Ejemplo n.º 24
0
def run(Ei, ncount, nodes,
        moderator_erange = None,
        fermichopper=None, fermi_nu=None, 
        T0_nu = None,
        emission_time = None,
        dry_run=False):
    fermichopper = fermichopper or "100-1.5-SMI"
    emission_time = emission_time or -1
    fermi_nu = fermi_nu or 600
    T0_nu = T0_nu or 120
    # generate configration
    cmd = """
    arcs-m2s \
        --fermi_nu=%(fermi_nu)s \
        --T0_nu=%(T0_nu)s \
        --E=%(Ei)s \
        --emission_time=%(emission_time)s \
        --fermi_chopper=%(fermichopper)s \
        --- \
        -dump-pml
    """ % locals()
    execute(cmd)


    # fine tune configuraiton
    cmd = ["arcs_moderator2sample --overwrite-datafiles"]
    Emin, Emax = moderator_erange
    cmd.append('--moderator.Emin=%s' % Emin)
    cmd.append('--moderator.Emax=%s' % Emax)
    cmd.append("--dump-pml")
    cmd = ' '.join(cmd)
    execute(cmd)

    # run simulation
    import os, shutil
    if os.path.exists('out'):
        shutil.rmtree('out')
    cmd = "arcs_moderator2sample -ncount=%(ncount)s " % locals()
    # ... moderator data file
    moddat = os.path.join(
        os.environ['MCVINE_DIR'], 'share', 'mcvine',
        'instruments', 'ARCS', 'source_sct521_bu_17_1.dat',
        )
    cmd += ' -moderator.S_filename=%s ' % moddat
    cmd += ' -mpirun.nodes=%s' % nodes
    cmd += '> m2s.log 2> m2s.err'
    if dry_run:
        print cmd
    else:
        execute(cmd)


    # analyze output
    # ... number of neutrons left
    neutronfile = os.path.join('out', 'neutrons')
    from mcni.neutron_storage.idf_usenumpy import count
    if dry_run:
        ncountatsample = 1000
    else:
        ncountatsample = count(neutronfile)

    if ncountatsample == 0:
        raise RuntimeError, "no neutrons at sample. need to increase mc samples at mod2sample simulation"
    
    cmd = [
        'arcs_analyze_beam',
        '-source.path=%(neutronfile)s' % locals(),
        '-ncount=%(ncountatsample)s' % locals(),
        '--output-dir=out-analyzer',
        ]
    # ... compute enegy range
    from mcni.utils.conversion import e2v
    v = e2v(Ei)
    from pyre.units.time import second
    L = 13.6
    t = L/v
    # ... build command line with monitor parameters
    cmd += ['--monitor.mtof.tofmin=%s' % (t*0.9)]
    cmd += ['--monitor.mtof.tofmax=%s' % (t*1.1)]
    cmd += ['--monitor.mtof.ntof=%s' % (1000)]
    cmd += ['--monitor.menergy.energymin=%s' % (Ei*0.9)]
    cmd += ['--monitor.menergy.energymax=%s' % (Ei*1.1)]
    cmd += ['--monitor.menergy.nenergy=%s' % (1000)]
    # ... run
    cmd = ' '.join(cmd)
    if dry_run:
        print cmd
    else:
        execute(cmd)
    return