コード例 #1
0
def sample_energy(edist, depth, ct, m, nsamples=10000):

    # bins that will have roughly equal contents
    rbins = numpy.array([0, 1, 2, 3, 4, 6, 10, 15, 250])
    powerlaw = MuonGun.OffsetPowerLaw(4, 1e3, edist.min, edist.max)
    ebins = powerlaw.isf(numpy.linspace(0, 1, 21)[::-1])

    start = resource.getrusage(resource.RUSAGE_SELF)
    samples = edist.generate(rng, depth, ct, m, nsamples)
    end = resource.getrusage(resource.RUSAGE_SELF)
    dt = end.ru_utime - start.ru_utime
    icetray.logging.log_info("%.1f microsec/sample" % (1e6 * dt / nsamples))
    samples = numpy.array([(i.first, i.second) for i in samples])

    bins, edges = numpy.histogramdd(samples, bins=(rbins, ebins))
    assert bins.sum() == nsamples

    empties = (bins < 10).sum() / float(bins.size)
    if empties > 0.25:
        warnings.warn('%d%% of bins have fewer than 10 entries' %
                      (100 * empties))

    norm = nsamples / edist.integrate(depth, ct, m, 0, 250, edist.min,
                                      edist.max)

    @numpy.vectorize
    def integrate_model(rbin, ebin):
        return edist.integrate(depth, ct, m, edges[0][rbin],
                               edges[0][rbin + 1], edges[1][ebin],
                               edges[1][ebin + 1])

    i, j = numpy.meshgrid(range(len(rbins) - 1),
                          range(len(ebins) - 1),
                          indexing='ij')
    mu = norm * integrate_model(i.T, j.T)
    chi2 = (bins.T - mu)**2 / mu
    return samples, chi2.sum(), bins.size
コード例 #2
0
# 1 file of E^-2.6 5-component 3e4-1e9 GeV (3:2:1:1:1)
soft = 4e5 * MuonGun.corsika_genprob('CascadeOptimized5Comp')
# 1 file of E^-2 5-component 6e2-1e11 GeV (10:5:3:2:1)
hard = 2.5e6 * MuonGun.corsika_genprob('Standard5Comp')
# In order to compare to "unweighted" CORSIKA, turn the Hoerandel flux
# into a probability (since we happen to know the integral)
areanorm = 0.131475115 * area
# 1 file of natural-spectrum ("unweighted") CORSIKA
unweighted = (2.5e7 / areanorm) * MuonGun.corsika_genprob('Hoerandel5')

model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')
model.flux.min_multiplicity = 1
model.flux.max_multiplicity = 1
# spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 8e2, 10**4.5)
spectrum = MuonGun.OffsetPowerLaw(5, 8e2, 2e3, 1e5)

# spectrum = MuonGun.OffsetPowerLaw(1.1, 650, 800, 1e8)
gun = 1e5 * MuonGun.EnergyDependentSurfaceInjector(surface, model.flux,
                                                   spectrum, model.radius)
# gun = 1e5*MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius)

# gun.target_surface = lambda e: surface


def get_weight(weighter, energy, zenith=numpy.pi / 8, scale=True):
    shape = energy.shape
    if scale:
        x = numpy.array([gun.target_surface(e).radius - 1 for e in energy])
    else:
        # x = numpy.ones(shape[0])*surface.radius - 1
コード例 #3
0
parser.add_argument("outfile", help="save plot to file")
args = parser.parse_args()

from icecube import icetray, dataclasses, dataio
from icecube import phys_services, simclasses, MuonGun
from I3Tray import I3Tray
from os.path import expandvars

tray = I3Tray()

tray.context['I3RandomService'] = phys_services.I3GSLRandomService(1337)

from icecube.MuonGun.segments import GenerateBundles
outer = MuonGun.Cylinder(1600, 800)
inner = MuonGun.Cylinder(300, 150, dataclasses.I3Position(0, 0, -350))
spectrum = MuonGun.OffsetPowerLaw(5, 1e3, 1e1, 1e4)
model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')
generator = MuonGun.EnergyDependentSurfaceInjector(
    outer, model.flux, spectrum, model.radius,
    MuonGun.ConstantSurfaceScalingFunction(inner))
tray.AddSegment(
    GenerateBundles,
    'BundleGen',
    NEvents=1000,
    Generator=generator,
    GCDFile=expandvars(
        '$I3_TESTDATA/GCD/GeoCalibDetectorStatus_IC86.55697_corrected_V2.i3.gz'
    ))


class Harvest(icetray.I3ConditionalModule):
コード例 #4
0
Use muon flux weights to calculate an effective livetime for combined
CORSIKA samples as a function of energy.
"""

import pylab, numpy
from icecube import MuonGun, icetray, dataclasses
from icecube.icetray import I3Units

outer = MuonGun.Cylinder(1600, 800)
#inner = MuonGun.Cylinder(1600, 800)
inner = MuonGun.Cylinder(500, 150, dataclasses.I3Position(46.3, -34.9, -300))
#inner = MuonGun.Cylinder(700, 125, dataclasses.I3Position(29.3,52.6,-150))
#inner = outer
#Most tested spectrum
#spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 0, 1e5)
spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 500, 1e5)

#Limited spectrum range
#spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 150, 1e4)
#spectrum = MuonGun.OffsetPowerLaw(2, 1*I3Units.TeV, 1*I3Units.TeV, 1*I3Units.PeV)
#Good spectrum producing ~1 day with 10k evts above 200 GeV
#spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 200, 1e6)
#Jackob's spectrum
#spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 200, 1e6)
#Good spectrum producing ~1 day with 5000 evts above 400 GeV
#spectrum = MuonGun.OffsetPowerLaw(5.25, 1000, 1, 1e6)
model = MuonGun.load_model(
    '/home/mamday/icesim/build/MuonGun/resources/tables/GaisserH4a_atmod12_SIBYLL'
)
#gun = .365e4*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius,
コード例 #5
0
from icecube import icetray, dataclasses, dataio
from icecube import phys_services, sim_services, simclasses, MuonGun
from I3Tray import I3Tray

tray = I3Tray()

tray.AddModule('I3InfiniteSource', 'driver')
tray.AddService('I3GSLRandomServiceFactory', 'rng', Seed=1337)

surface  = MuonGun.Cylinder(1600, 800)
flux     = MuonGun.BMSSFlux()
flux.min_multiplicity = 1
flux.max_multiplicity = 1
energies = MuonGun.BMSSEnergyDistribution()
radii    = MuonGun.BMSSRadialDistribution()
generator = 10*MuonGun.StaticSurfaceInjector(surface, flux, MuonGun.OffsetPowerLaw(2, 500., 50, 1e6), radii)

tray.AddModule('I3MuonGun::GeneratorModule', 'generator', Generator=generator)
tray.AddModule('I3MuonGun::WeightCalculatorModule', 'weight',
    Model=MuonGun.BundleModel(flux, radii, energies),
    Generator=generator)

def check_weight(frame):
    weight = frame['weight'].value
    assert weight > 0
tray.Add(check_weight, Streams=[icetray.I3Frame.DAQ])

tray.AddModule('TrashCan', 'YesWeCan')
tray.Execute()
tray.Finish()
コード例 #6
0
model.flux.max_multiplicity = 1

# Check the spectral index is negative
# This is for consistency with CORSIKA scripts
# Will convert to a positve number (as MuonGun expects it) later
assert args.power_law_index <= 0., "Spectral index must be negative"
power_law_index = args.power_law_index
positive_power_law_index = -1. * power_law_index

# Muon spectrum (spectral index, break in power law, and energy range)
power_law_offset = args.power_law_offset * icecube.icetray.I3Units.GeV
min_energy = args.min_energy * icecube.icetray.I3Units.GeV
max_energy = args.max_energy * icecube.icetray.I3Units.GeV
spectrum = MuonGun.OffsetPowerLaw(
    gamma=positive_power_law_index,
    offset=power_law_offset,
    min=min_energy,
    max=max_energy,
)

#TODO Are these stored in the I frame?


#########################
# DETECTOR 
#########################

# Create an outer surface
# This will be the generation volume
outer_surface_center = icecube.dataclasses.I3Position(
    args.outer_cylinder_x,
    args.outer_cylinder_y,
コード例 #7
0
from icecube.sim_services.propagation import get_propagators
from icecube.MuonGun.segments import GenerateBundles
from icecube.MuonGun import load_model, EnergyDependentSurfaceInjector, ConstantSurfaceScalingFunction, StaticSurfaceInjector, Cylinder, OffsetPowerLaw
# base = expandvars('$I3_SRC/MuonGun/resources/scripts/fitting/')
#Flux model
model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')
model.flux.min_multiplicity = 1
model.flux.max_multiplicity = 1
#Inner and outher target surfaces
outSurface = Cylinder(1600 * I3Units.m, 800 * I3Units.m)
inSurface = Cylinder(500 * I3Units.m, 150 * I3Units.m,
                     I3Position(46.3, -34.9, -300))
#Sets energy and spectral index of muons
#Jackob's spectrum
#spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 200, 1e6)
spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, int(sys.argv[2]), int(sys.argv[3]))
#spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 150, 1e5)
#spectrum = MuonGun.OffsetPowerLaw(2, 1e3, 1e3, 1e5)

#This version only aims at inSurface, but muons originate at outSurface
scaling = MuonGun.ConstantSurfaceScalingFunction(inSurface)
#generator = MuonGun.EnergyDependentSurfaceInjector(outSurface, model.flux, spectrum, model.radius, scaling,0,1)
generator = MuonGun.EnergyDependentSurfaceInjector(outSurface, model.flux,
                                                   spectrum, model.radius,
                                                   scaling)
#This version aims at whatever surface you give it, but originates all the muons inside the surface, not at the top layer of ice
#generator = MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius)
#Not sure yet what this does?
# generator = MuonGun.Floodlight()

# set up a random number generator
def main(cfg, run_number, scratch):
    with open(cfg, 'r') as stream:
        if int(yaml.__version__[0]) < 5:
            # backwards compatibility for yaml versions before version 5
            cfg = yaml.load(stream)
        else:
            cfg = yaml.full_load(stream)
    cfg['run_number'] = run_number
    cfg['run_folder'] = get_run_folder(run_number)

    tray = I3Tray()

    random_services, _ = create_random_services(
        dataset_number=cfg['dataset_number'],
        run_number=cfg['run_number'],
        seed=cfg['seed'],
        n_services=2)

    random_service, random_service_prop = random_services

    tray.context['I3RandomService'] = random_service

    model = MuonGun.load_model(cfg['muongun_model'])
    model.flux.min_multiplicity = cfg['muongun_min_multiplicity']
    model.flux.max_multiplicity = cfg['muongun_max_multiplicity']
    spectrum = MuonGun.OffsetPowerLaw(cfg['gamma'],
                                      cfg['e_min'] * icetray.I3Units.GeV,
                                      cfg['e_min'] * icetray.I3Units.GeV,
                                      cfg['e_max'] * icetray.I3Units.GeV)
    surface = MuonGun.Cylinder(1600, 800,
                               dataclasses.I3Position(31.25, 19.64, 0))

    if cfg['muongun_generator'] == 'energy':
        scale = MuonGun.BasicSurfaceScalingFunction()
        scale.SetSideScaling(4., 17266, 3.41, 1.74)
        scale.SetCapScaling(4., 23710, 3.40, 1.88)
        generator = MuonGun.EnergyDependentSurfaceInjector(
            surface, model.flux, spectrum, model.radius, scale)
    elif cfg['muongun_generator'] == 'static':
        generator = MuonGun.StaticSurfaceInjector(surface, model.flux,
                                                  spectrum, model.radius)
    elif cfg['muongun_generator'] == 'floodlight':
        generator = MuonGun.Floodlight(
            surface=surface,
            energyGenerator=spectrum,
            cosMin=cfg['muongun_floodlight_min_cos'],
            cosMax=cfg['muongun_floodlight_max_cos'],
        )
    else:
        err_msg = 'MuonGun generator {} is not known.'
        err_msg += " Must be 'energy','static' or 'floodlight"
        raise ValueError(err_msg.format(cfg['muongun_generator']))

    tray.Add(MuonGun.segments.GenerateBundles,
             'MuonGenerator',
             Generator=generator,
             NEvents=cfg['n_events_per_run'],
             GCDFile=cfg['gcd'])

    tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"])

    tray.AddSegment(segments.PropagateMuons,
                    "PropagateMuons",
                    RandomService=random_service_prop,
                    **cfg['muon_propagation_config'])
    if scratch:
        outfile = cfg['scratchfile_pattern'].format(**cfg)
    else:
        outfile = cfg['outfile_pattern'].format(**cfg)
    outfile = outfile.replace(' ', '0')
    if cfg['distance_splits'] is not None:
        click.echo('SplittingDistance: {}'.format(cfg['distance_splits']))
        distance_splits = np.atleast_1d(cfg['distance_splits'])
        dom_limits = np.atleast_1d(cfg['threshold_doms'])
        if len(dom_limits) == 1:
            dom_limits = np.ones_like(distance_splits) * cfg['threshold_doms']
        oversize_factors = np.atleast_1d(cfg['oversize_factors'])
        order = np.argsort(distance_splits)

        distance_splits = distance_splits[order]
        dom_limits = dom_limits[order]
        oversize_factors = oversize_factors[order]

        stream_objects = generate_stream_object(distance_splits, dom_limits,
                                                oversize_factors)
        tray.AddModule(OversizeSplitterNSplits,
                       "OversizeSplitterNSplits",
                       thresholds=distance_splits,
                       thresholds_doms=dom_limits,
                       oversize_factors=oversize_factors)
        for stream_i in stream_objects:
            outfile_i = stream_i.transform_filepath(outfile)
            tray.AddModule("I3Writer",
                           "writer_{}".format(stream_i.stream_name),
                           Filename=outfile_i,
                           Streams=[
                               icetray.I3Frame.DAQ, icetray.I3Frame.Physics,
                               icetray.I3Frame.Stream('S'),
                               icetray.I3Frame.Stream('M')
                           ],
                           If=stream_i)
            click.echo('Output ({}): {}'.format(stream_i.stream_name,
                                                outfile_i))
    else:
        click.echo('Output: {}'.format(outfile))
        tray.AddModule("I3Writer",
                       "writer",
                       Filename=outfile,
                       Streams=[
                           icetray.I3Frame.DAQ, icetray.I3Frame.Physics,
                           icetray.I3Frame.Stream('S'),
                           icetray.I3Frame.Stream('M')
                       ])
    click.echo('Scratch: {}'.format(scratch))
    tray.AddModule("TrashCan", "the can")
    tray.Execute()
    tray.Finish()
コード例 #9
0
def main(cfg, run_number, scratch):
    with open(cfg, 'r') as stream:
        cfg = yaml.load(stream)
    cfg['run_number'] = run_number
    cfg['run_folder'] = get_run_folder(run_number)

    tray = I3Tray()

    random_service, random_service_prop, _ = create_random_services(
        dataset_number=cfg['dataset_number'],
        run_number=cfg['run_number'],
        seed=cfg['seed'])

    tray.context['I3RandomService'] = random_service

    model = MuonGun.load_model(cfg['muongun_model'])
    model.flux.min_multiplicity = cfg['muongun_min_multiplicity']
    model.flux.max_multiplicity = cfg['muongun_max_multiplicity']
    spectrum = MuonGun.OffsetPowerLaw(  cfg['gamma'],
                                        cfg['e_min']*icetray.I3Units.TeV,
                                        cfg['e_min']*icetray.I3Units.TeV,
                                        cfg['e_max']*icetray.I3Units.TeV)
    surface = MuonGun.Cylinder(1600, 800,
                            dataclasses.I3Position(31.25, 19.64, 0))

    if cfg['muongun_generator'] == 'energy':
        scale = MuonGun.BasicSurfaceScalingFunction()
        scale.SetSideScaling(4., 17266, 3.41, 1.74)
        scale.SetCapScaling(4., 23710, 3.40, 1.88)
        generator = MuonGun.EnergyDependentSurfaceInjector(surface,
                                                            model.flux,
                                                            spectrum,
                                                            model.radius,
                                                            scale)
    elif cfg['muongun_generator'] == 'static':
        generator = MuonGun.StaticSurfaceInjector(surface,
                                                    model.flux,
                                                    spectrum,
                                                    model.radius)
    elif cfg['muongun_generator'] =='floodlight':
        generator = MuonGun.Floodlight(surface = surface,
                                       energyGenerator=spectrum,
                                       cosMin=cfg['muongun_floodlight_min_cos'],
                                       cosMax=cfg['muongun_floodlight_max_cos'],
                                       )
    else:
        err_msg = 'MuonGun generator {} is not known.'
        err_msg += " Must be 'energy','static' or 'floodlight"
        raise ValueError(err_msg.format(cfg['muongun_generator']))

    tray.Add(MuonGun.segments.GenerateBundles, 'MuonGenerator',
                            Generator=generator,
                            NEvents=cfg['n_events_per_run'],
                            GCDFile=cfg['gcd'])

    tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"])

    tray.AddSegment(
        segments.PropagateMuons,
        "PropagateMuons",
        RandomService=random_service_prop)
    if scratch:
        outfile = cfg['scratchfile_pattern'].format(**cfg)
    else:
        outfile = cfg['outfile_pattern'].format(**cfg)
    outfile = outfile.replace(' ', '0')
    outfile = outfile.replace('.bz2', '')
    tray.AddModule("I3Writer", "writer",
                   Filename=outfile,
                   Streams=[icetray.I3Frame.DAQ,
                            icetray.I3Frame.Physics,
                            icetray.I3Frame.Stream('S'),
                            icetray.I3Frame.Stream('M')])

    tray.AddModule("TrashCan", "the can")
    tray.Execute()
    tray.Finish()
コード例 #10
0
def main(cfg, run_number, scratch):
    with open(cfg, 'r') as stream:
        cfg = yaml.load(stream, Loader=yaml.Loader)
    cfg['run_number'] = run_number
    cfg['run_folder'] = get_run_folder(run_number)

    if scratch:
        outfile = cfg['scratchfile_pattern'].format(**cfg)
    else:
        outfile = cfg['outfile_pattern'].format(**cfg)
    outfile = outfile.replace(' ', '0')

    if cfg['distance_splits'] is not None:
        click.echo('SplittingDistances: {}'.format(cfg['distance_splits']))
        click.echo('Oversizefactors: {}'.format(cfg['oversize_factors']))
    click.echo('NEvents: {}'.format(cfg['n_events_per_run']))
    click.echo('EMin: {}'.format(cfg['e_min']))
    click.echo('EMax: {}'.format(cfg['e_max']))
    click.echo('EBreak: {}'.format(cfg['muongun_e_break']))
    click.echo('Gamma: {}'.format(cfg['gamma']))
    click.echo('ZenithMin: {}'.format(cfg['zenith_min']))
    click.echo('ZenithMax: {}'.format(cfg['zenith_max']))

    # create convex hull
    if 'use_convex_hull' in cfg and cfg['use_convex_hull']:

        # hardcode icecube corner points
        # ToDo: read from geometry file
        points = [
            [-570.90002441, -125.13999939, 501],  # string 31
            [-256.14001465, -521.08001709, 501],  # string 1
            [361., -422.82998657, 501],  # string 6
            [576.36999512, 170.91999817, 501],  # string 50
            [338.44000244, 463.72000122, 501],  # string 74
            [101.04000092, 412.79000854, 501],  # string 72
            [22.11000061, 509.5, 501],  # string 78
            [-347.88000488, 451.51998901, 501],  # string 75
            [-570.90002441, -125.13999939, -502],  # string 31
            [-256.14001465, -521.08001709, -502],  # string 1
            [361., -422.82998657, -502],  # string 6
            [576.36999512, 170.91999817, -502],  # string 50
            [338.44000244, 463.72000122, -502],  # string 74
            [101.04000092, 412.79000854, -502],  # string 72
            [22.11000061, 509.5, -502],  # string 78
            [-347.88000488, 451.51998901, -502],  # string 75
        ]
        convex_hull = ConvexHull(points)
    else:
        convex_hull = None

    if 'extend_past_hull' not in cfg:
        cfg['extend_past_hull'] = 0.0

    random_services, _ = create_random_services(
        dataset_number=cfg['dataset_number'],
        run_number=cfg['run_number'],
        seed=cfg['seed'],
        n_services=2)

    random_service, random_service_prop = random_services

    # create muon
    muon = create_muon(
        azimuth_range=[cfg['azimuth_min'], cfg['azimuth_max']],
        zenith_range=[cfg['zenith_min'], cfg['zenith_max']],
        energy_range=[cfg['e_min'], cfg['e_max']],
        anchor_time_range=cfg['anchor_time_range'],
        anchor_x_range=cfg['anchor_x_range'],
        anchor_y_range=cfg['anchor_y_range'],
        anchor_z_range=cfg['anchor_z_range'],
        length_to_go_back=cfg['length_to_go_back'],
        convex_hull=convex_hull,
        extend_past_hull=cfg['extend_past_hull'],
        random_service=random_services[0],
    )

    tray = I3Tray()

    tray.context['I3RandomService'] = random_service

    tray.AddModule("I3InfiniteSource",
                   "TheSource",
                   Prefix=cfg['gcd'],
                   Stream=icetray.I3Frame.DAQ)

    if cfg['MuonGenerator'] == 'MuonGunSinglemuons':
        tray.AddSegment(segments.GenerateSingleMuons,
                        "GenerateCosmicRayMuons",
                        NumEvents=cfg['n_events_per_run'],
                        FromEnergy=cfg['e_min'] * icetray.I3Units.GeV,
                        ToEnergy=cfg['e_max'] * icetray.I3Units.GeV,
                        BreakEnergy=cfg['muongun_e_break'] *
                        icetray.I3Units.GeV,
                        GammaIndex=cfg['gamma'],
                        ZenithRange=[
                            cfg['zenith_min'] * icetray.I3Units.deg,
                            cfg['zenith_max'] * icetray.I3Units.deg
                        ])

    elif cfg['MuonGenerator'] == 'MuonGunGeneral':
        model = MuonGun.load_model(cfg['muongun_model'])
        model.flux.min_multiplicity = cfg['muongun_min_multiplicity']
        model.flux.max_multiplicity = cfg['muongun_max_multiplicity']
        spectrum = MuonGun.OffsetPowerLaw(cfg['gamma'],
                                          cfg['e_min'] * icetray.I3Units.GeV,
                                          cfg['e_min'] * icetray.I3Units.GeV,
                                          cfg['e_max'] * icetray.I3Units.GeV)
        surface = MuonGun.Cylinder(1600, 800,
                                   dataclasses.I3Position(31.25, 19.64, 0))

        if cfg['muongun_generator'] == 'energy':
            scale = MuonGun.BasicSurfaceScalingFunction()
            scale.SetSideScaling(4., 17266, 3.41, 1.74)
            scale.SetCapScaling(4., 23710, 3.40, 1.88)
            generator = MuonGun.EnergyDependentSurfaceInjector(
                surface, model.flux, spectrum, model.radius, scale)
        elif cfg['muongun_generator'] == 'static':
            generator = MuonGun.StaticSurfaceInjector(surface, model.flux,
                                                      spectrum, model.radius)
        elif cfg['muongun_generator'] == 'floodlight':
            generator = MuonGun.Floodlight(
                surface=surface,
                energyGenerator=spectrum,
                cosMin=cfg['muongun_floodlight_min_cos'],
                cosMax=cfg['muongun_floodlight_max_cos'],
            )
        else:
            err_msg = 'MuonGun generator {} is not known.'
            err_msg += " Must be 'energy','static' or 'floodlight"
            raise ValueError(err_msg.format(cfg['muongun_generator']))

        tray.Add(MuonGun.segments.GenerateBundles,
                 'MuonGenerator',
                 Generator=generator,
                 NEvents=cfg['n_events_per_run'],
                 GCDFile=cfg['gcd'])

        tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"])

    elif cfg['MuonGenerator'] == 'MuonResimulation':
        tray.AddModule(ParticleMultiplier,
                       'make_particles',
                       num_events=cfg['n_events_per_run'],
                       primary=muon)
    else:
        err_msg = 'MuonGenerator {} is not known.'
        err_msg += " Must be 'MuonGunSinglemuons','MuonGunGeneral' or 'MuonResimulation"
        raise ValueError(err_msg.format(cfg['MuonGenerator']))

    # --------------------------------------
    # Propagate Muons
    # --------------------------------------
    tray.AddSegment(segments.PropagateMuons,
                    "PropagateMuons",
                    RandomService=random_service_prop,
                    **cfg['muon_propagation_config'])

    # --------------------------------------
    # Distance Splits
    # --------------------------------------
    if cfg['distance_splits'] is not None:
        click.echo('SplittingDistance: {}'.format(cfg['distance_splits']))
        distance_splits = np.atleast_1d(cfg['distance_splits'])
        dom_limits = np.atleast_1d(cfg['threshold_doms'])
        if len(dom_limits) == 1:
            dom_limits = np.ones_like(distance_splits) * cfg['threshold_doms']
        oversize_factors = np.atleast_1d(cfg['oversize_factors'])
        order = np.argsort(distance_splits)

        distance_splits = distance_splits[order]
        dom_limits = dom_limits[order]
        oversize_factors = oversize_factors[order]

        stream_objects = generate_stream_object(distance_splits, dom_limits,
                                                oversize_factors)
        tray.AddModule(OversizeSplitterNSplits,
                       "OversizeSplitterNSplits",
                       thresholds=distance_splits,
                       thresholds_doms=dom_limits,
                       oversize_factors=oversize_factors)
        for stream_i in stream_objects:
            outfile_i = stream_i.transform_filepath(outfile)
            tray.AddModule("I3Writer",
                           "writer_{}".format(stream_i.stream_name),
                           Filename=outfile_i,
                           Streams=[
                               icetray.I3Frame.DAQ, icetray.I3Frame.Physics,
                               icetray.I3Frame.Stream('S'),
                               icetray.I3Frame.Stream('M')
                           ],
                           If=stream_i)
            click.echo('Output ({}): {}'.format(stream_i.stream_name,
                                                outfile_i))
    else:
        click.echo('Output: {}'.format(outfile))
        tray.AddModule("I3Writer",
                       "writer",
                       Filename=outfile,
                       Streams=[
                           icetray.I3Frame.DAQ, icetray.I3Frame.Physics,
                           icetray.I3Frame.Stream('S'),
                           icetray.I3Frame.Stream('M')
                       ])

    click.echo('Scratch: {}'.format(scratch))

    tray.Execute()

    del tray
コード例 #11
0
surface = MuonGun.Cylinder(1600, 800)
flux = MuonGun.BMSSFlux()
flux.min_multiplicity = 1
flux.max_multiplicity = 1
energies = MuonGun.BMSSEnergyDistribution()
radii = MuonGun.BMSSRadialDistribution()

model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')
flux = model.flux
flux.min_multiplicity = 1
flux.max_multiplicity = 1
radii = model.radius
energies = model.energy

generator = 10000 * MuonGun.StaticSurfaceInjector(
    surface, flux, MuonGun.OffsetPowerLaw(2, 500., energies.min, energies.max),
    radii)

tray.AddModule('I3MuonGun::GeneratorModule',
               'GenerateCosmicRayMuons',
               Generator=generator)
tray.AddModule('I3MuonGun::WeightCalculatorModule',
               'weight',
               Model=MuonGun.BundleModel(flux, radii, energies),
               Generator=generator)

weights = []


def check_weight(frame):
    frame['MCMuon'] = frame['I3MCTree'].primaries[0]
コード例 #12
0
def PolyplopiaSegment(
        tray,
        name,
        mctype='CORSIKA',
        RandomService=None,
        mctree_name="I3MCTree_preMuonProp",
        separate_coincident_mctree_name="",  # leave empty to combine
        bgfile=None,
        timewindow=40. * I3Units.microsecond,
        rate=5.0 * I3Units.kilohertz,
        If=lambda f: True):
    """
         There are three scenarios for diplopia:
            1. bgfile: We are reading background MC from a separate file and
            injecting events to signal (or weighted background) based on 
            a Poisson distribution within the given time window.

            2. we are generating MuonGun bundles and
            injecting events to signal (or weighted background) based on 
            a Poisson distribution within the given time window.
      """

    from icecube import diplopia, MuonGun

    #tray.AddModule("ParticleMapper","mapprimary")
    if bgfile:  # merge bg into signal
        background = diplopia.CoincidentI3ReaderService()
        background.open(bgfile)

    else:
        # Use MuonGun
        # Default: use Hoerandel as a template for generating muons.
        model = MuonGun.load_model("Hoerandel5_atmod12_SIBYLL")

        # Generate bundles (even if not 100 percent accurate).
        model.flux.max_multiplicity = 100

        gamma_index = 2.6
        energy_offset = 700.
        energy_min = 1e4
        energy_max = 1e7
        cylinder_length = 1600.
        cylinder_radius = 800.
        cylinder_x = 0.
        cylinder_y = 0.
        cylinder_z = 0.

        # Default: cylinder aligned with z-axis at detector center as injection
        # surface.
        outsurface_center = dataclasses.I3Position(cylinder_x * I3Units.m,
                                                   cylinder_y * I3Units.m,
                                                   cylinder_z * I3Units.m)

        outsurface = MuonGun.Cylinder(length=cylinder_length * I3Units.m,
                                      radius=cylinder_radius * I3Units.m,
                                      center=outsurface_center)

        # Draw energies from a power law with offset.
        spectrum = MuonGun.OffsetPowerLaw(gamma=gamma_index,
                                          offset=energy_offset * I3Units.GeV,
                                          min=energy_min * I3Units.GeV,
                                          max=energy_max * I3Units.GeV)

        generator = MuonGun.StaticSurfaceInjector(outsurface, model.flux,
                                                  spectrum, model.radius)

        background = diplopia.MuonGunBackgroundService()
        background.set_generator(generator)
        background.set_rng(RandomService)
        background.set_rate(rate)
        background.set_mctree_name(mctree_name)

    tray.AddModule("PoissonMerger",
                   "merge",
                   CoincidentEventService=background,
                   PrimaryType=mctype,
                   MCTreeName=mctree_name,
                   SeparateMCTree=separate_coincident_mctree_name,
                   TimeWindow=timewindow)

    return tray
コード例 #13
0
from icecube import MuonGun, sim_services
from icecube.icetray import I3Units
from icecube.dataclasses import *
from icecube.sim_services.propagation import get_propagators
from icecube.MuonGun.segments import GenerateBundles
from icecube.MuonGun import load_model, EnergyDependentSurfaceInjector, ConstantSurfaceScalingFunction, StaticSurfaceInjector, Cylinder, OffsetPowerLaw
#Flux model
model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')
model.flux.min_multiplicity = 1
model.flux.max_multiplicity = 1
#Inner and outher target surfaces
outSurface = Cylinder(1600 * I3Units.m, 800 * I3Units.m)
inSurface = Cylinder(700 * I3Units.m, 125 * I3Units.m,
                     I3Position(29.3, 52.6, -150))
#Sets energy and spectral index of muons
spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 200, 1e6)
#This version only aims at inSurface, but muons originate at outSurface
scaling = MuonGun.ConstantSurfaceScalingFunction(inSurface)
generator = MuonGun.EnergyDependentSurfaceInjector(outSurface, model.flux,
                                                   spectrum, model.radius,
                                                   scaling, 0, 1)

tray.AddModule(
    'I3MuonGun::WeightCalculatorModule',
    'MuonWeight',
    Model=model,
    Generator=generator,
)

tray.AddModule("Delete",
               "delete_triggerHierarchy",