Example #1
0
    def define_variables(self):
        from gna.parameters.oscillation import reqparameters
        pmnspars_kwargs = dict()
        pdgyear = self.cfg.get('pdg_year', None)
        if pdgyear:
            pmnspars_kwargs['pdg_year'] = pdgyear

        for it in self.nidx_minor:
            name = it.current_values(name='pmns')
            ns_pmns = self.namespace(name)
            reqparameters(ns_pmns, **pmnspars_kwargs)

            names = C.stdvector(['comp0', 'comp12', 'comp13', 'comp23'])
            with ns_pmns:
                R.OscProbPMNSExpressions(R.Neutrino.ae(),
                                         R.Neutrino.ae(),
                                         names,
                                         ns=ns_pmns)
                ns_pmns['Delta'].setFixed()
                ns_pmns['SigmaDecohRel'].setFixed()
                ns_pmns['SinSq23'].setFixed()
                ns_pmns.materializeexpressions()

            for i, vname in enumerate(names):
                ns_pmns[vname].setLabel('Psur(ee) weight %i: %s ' % (i, vname))
Example #2
0
def test_tree_manager(function_name):
    from gna.env import env
    gns = env.globalns(function_name)
    ndata = 200

    with context.manager(ndata) as manager:
        ns = gns('namespace1')
        ns.defparameter('float1',   central=1, fixed=True, label='Float variable 1')
        ns.defparameter('float2',   central=2, fixed=True, label='Float variable 2')

        ns = gns('namespace2')
        ns.defparameter('angle',    central=3, label='Angle parameter', type='uniformangle')
        ns.defparameter('discrete', default='a', label='Discrete parameter', type='discrete', variants=OrderedDict([('a', 10.0), ('b', 20.0), ('c', 30.0)]))

        ns = gns('namespace3')
        from gna.parameters.oscillation import reqparameters
        reqparameters(ns)
        with ns:
            ns.materializeexpressions()
        ns['Delta'].set(N.pi*0.25)

        pars = tuple(par.getVariable() for (name,par) in ns.walknames())
        manager.setVariables(C.stdvector(pars))

    gns.printparameters(labels=True)

    allocator = manager.getAllocator()
    varray = manager.getVarArray()
    data_v = varray.vararray.points.data()
    data_a = allocator.view()
    print('Data (filled):', data_a.size, data_a.dtype, data_a)
    print('Data (vararray):', data_v.size, data_v.dtype, data_v)
    mask = data_v==data_a
    assert mask is not False and mask.all()
Example #3
0
    def define_variables(self):
        from gna.parameters.oscillation import reqparameters_reactor as reqparameters
        pmnspars_kwargs = dict()
        pdgyear = self.cfg.get('pdg_year', None)
        if pdgyear:
            pmnspars_kwargs['pdg_year'] = pdgyear

        pmns_name = self.get_globalname('pmns')
        ns_pmns = self.namespace(pmns_name)
        reqparameters(ns_pmns, self.cfg.dm, **pmnspars_kwargs)

        names = C.stdvector(['comp0', 'comp12', 'comp13', 'comp23'])
        with ns_pmns:
            R.OscProbPMNSExpressions(R.Neutrino.ae(),
                                     R.Neutrino.ae(),
                                     names,
                                     ns=ns_pmns)
            ns_pmns['Delta'].setFixed()
            ns_pmns['SigmaDecohRel'].setFixed()
            ns_pmns['SinSq23'].setFixed()
            ns_pmns.materializeexpressions()

        ns_pmns.reqparameter('rho',
                             central=self.cfg.density,
                             fixed=True,
                             label='Matter density g/cm3')

        for i, vname in enumerate(names):
            ns_pmns[vname].setLabel('Psur(ee) weight %i: %s ' % (i, vname))
Example #4
0
def test_variable_allocation_complex():
    from gna.env import env
    gns = env.globalns('test_variable_allocation_complex')
    ndata = 200
    allocator = R.arrayviewAllocatorSimple('double')(ndata)

    with context.allocator(allocator):
        ns = gns('namespace1')
        ns.defparameter('float1',
                        central=1,
                        fixed=True,
                        label='Float variable 1')
        ns.defparameter('float2',
                        central=2,
                        fixed=True,
                        label='Float variable 2')

        ns = gns('namespace2')
        ns.defparameter('angle',
                        central=3,
                        label='Angle parameter',
                        type='uniformangle')
        ns.defparameter('discrete',
                        default='a',
                        label='Discrete parameter',
                        type='discrete',
                        variants=OrderedDict([('a', 10.0), ('b', 20.0),
                                              ('c', 30.0)]))

        ns = gns('namespace3')
        from gna.parameters.oscillation import reqparameters
        reqparameters(ns)
        with ns:
            ns.materializeexpressions()
        ns['Delta'].set(N.pi * 1.5)

    gns.printparameters(labels=True)

    allocdata = allocator.view()
    print('Data (filled):', allocdata)
    print('Data (all):', allocator.viewall())

    for name, par in gns.walknames():
        av = par.getVariable().values()
        offset = av.offset()
        size = av.size()

        avview = av.view()
        assert (allocdata[offset:offset + size] == avview).all()
Example #5
0
    def define_variables(self):
        from gna.parameters.oscillation import reqparameters
        ns_pmns=self.namespace('pmns')
        reqparameters(ns_pmns)

        names = C.stdvector(['comp0', 'comp12', 'comp13', 'comp23'])
        with ns_pmns:
            R.OscProbPMNSExpressions(R.Neutrino.ae(), R.Neutrino.ae(), names, ns=ns_pmns)
            ns_pmns['Delta'].setFixed()
            ns_pmns['SigmaDecohRel'].setFixed()
            ns_pmns['SinSq23'].setFixed()
            ns_pmns.materializeexpressions()

        for i, vname in enumerate(names):
            ns_pmns[vname].setLabel('Psur(ee) weight %i: %s '%(i, vname))
Example #6
0
def example():
    parser = argparse.ArgumentParser()
    parser.add_argument("-e",
                        "--energy",
                        metavar=('Start', 'Final', 'Step'),
                        default=[700., 2000., 10],
                        nargs=3,
                        type=float,
                        help='Set neutrino energy range and step in MeV')
    parser.add_argument(
        '-f',
        '--flavors',
        metavar=('Initial_flavor', 'Final_flavor'),
        default=['mu', 'mu'],
        nargs=2,
        help='Set initital and final flavors for oscillation probability')
    parser.add_argument('-r',
                        '--density',
                        default=2.75,
                        type=float,
                        help='Set density of matter in g/cm^3')
    parser.add_argument('-L',
                        '--distance',
                        default=810.,
                        type=float,
                        help='Set distance of propagation in kilometers')
    parser.add_argument('--mass-ordering',
                        default='normal',
                        choices=['normal', 'inverted'],
                        help='Set neutrino mass ordering (hierarchy)')
    parser.add_argument('--print-pars',
                        action='store_true',
                        help='Print all parameters in namespace')
    parser.add_argument('--savefig', help='Path to save figure')
    parser.add_argument('--graph',
                        help='Path to save computational graph scheme')
    opts = parser.parse_args()

    # For fast usage printing load GNA specific modules only after argument
    # parsing
    import ROOT
    ROOT.PyConfig.IgnoreCommandLineOptions = True  #prevents ROOT from hijacking sys.argv

    from gna.env import env
    from gna.parameters.oscillation import reqparameters
    from gna.bindings import common
    import gna.constructors as C
    _flavors = {
        "e": ROOT.Neutrino.e(),
        "mu": ROOT.Neutrino.mu(),
        "tau": ROOT.Neutrino.tau(),
        "ae": ROOT.Neutrino.ae(),
        "amu": ROOT.Neutrino.amu(),
        "atau": ROOT.Neutrino.atau()
    }

    # Parsed arguments are put into opts object (of type argparse.Namespace) as attributes and can be accessed with a '.'
    # like in examples below.
    # Note that argparse translate dashes '-' into underscores '_' for attribute names.

    #initialize energy range
    Enu = np.arange(opts.energy[0], opts.energy[1], step=opts.energy[2])
    E_MeV = C.Points(Enu, labels='Neutrino energy')

    # initialize initial and final flavors for neutrino after propagating in media
    try:
        initial_flavor, final_flavor = tuple(_flavors[flav]
                                             for flav in opts.flavors)
    except KeyError:
        raise KeyError(
            "Invalid flavor is requested: try something from e, mu, tau")

    ns = env.ns("matter_osc")
    reqparameters(
        ns)  # initialize oscillation parameters in namespace 'matter_osc'

    ns['Delta'].set(0)  # set CP-violating phase to zero
    ns['SinSq23'].set(
        0.6
    )  # change value of sin²θ₂₃, it will cause recomputation of PMNS matrix elements that depend of it
    ns['Alpha'].set(opts.mass_ordering)  # Choose mass ordering
    ns.defparameter("L", central=opts.distance, fixed=True)  # kilometres
    ns.defparameter("rho", central=opts.density, fixed=True)  # g/cm^3

    # Print values of all parameters in namespace if asked
    if opts.print_pars:
        ns.printparameters()

    #initialize neutrino oscillation probability in matter and in vacuum for comparison.
    # All neccessary parameters such as values of mixing angles, mass splittings,
    # propagation distance and density of matter are looked up in namespace ns
    # upon creation of ROOT.OscProbMatter.
    with ns:
        oscprob_matter = ROOT.OscProbMatter(
            initial_flavor,
            final_flavor,
            labels='Oscillation probability in matter')
        oscprob_vacuum = ROOT.OscProbPMNS(
            initial_flavor,
            final_flavor,
            labels='Oscillation probability in vacuum')

        # Add output of plain array of energies as input "Enu" to oscillation
        # probabilities. It means that oscillation probabilities would be computed
        # for each energy in array and array of it would be
        # provided as output
        E_MeV.points >> oscprob_matter.oscprob.Enu
        E_MeV.points >> oscprob_vacuum.full_osc_prob
        oscprob_vacuum.full_osc_prob.setLabel(
            'Oscillation probability in vacuum')

    # Accessing the outputs of oscillation probability for plotting

    matter = oscprob_matter.oscprob.oscprob.data()
    vacuum = oscprob_vacuum.full_osc_prob.oscprob.data()

    # Make a pair of plots for both probabilities and their ratio
    # Plot probabilities
    fig, (ax, ax_ratio) = plt.subplots(nrows=2, ncols=1, sharex=True)
    ax.plot(Enu,
            matter,
            label='Matter, density={} gm/cm^3'.format(opts.density))
    ax.plot(Enu, vacuum, label='Vacuum')

    ax.set_title("Oscillation probabilities, {0} -> {1}".format(
        opts.flavors[0], opts.flavors[1]),
                 fontsize=16)
    ax.set_ylabel("Oscprob", fontsize=14)
    ax.legend(loc='best')
    ax.grid(alpha=0.5)

    # Plot ratio
    ax_ratio.plot(Enu, matter / vacuum, label='matter / vacuum')
    ax_ratio.set_xlabel("Neutrino energy, MeV", fontsize=14)
    ax_ratio.set_ylabel("Ratio", fontsize=14)
    ax_ratio.legend(loc='best')
    ax_ratio.grid(alpha=0.5)

    # Convert path to absolute path and save figure or show
    if opts.savefig:
        plt.savefig(os.path.abspath(opts.savefig))
    else:
        plt.show()

    # Save a plot of computational graph scheme
    if opts.graph:
        from gna.graphviz import savegraph
        savegraph(oscprob_matter.oscprob.oscprob, opts.graph, namespace=ns)
from gna.env import env, ExpressionsEntry
import numpy as N

from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-c', '--pmnsc', action='store_true')
opts = parser.parse_args()

nsosc = env.globalns('osc')
nsreac = env.globalns('reac')

from gna.parameters.oscillation import reqparameters, reqparameters_reactor
print('Initialize variables')
pdg_year = 2018
reqparameters_reactor(nsreac, '23', pdg_year=pdg_year)
reqparameters(nsosc, pdg_year=pdg_year)
nsreac['Delta'].set(N.pi * 1.5)
nsosc['Delta'].set(N.pi * 1.5)

print('Init OP ae-ae')
with nsreac:
    pmnsreac = R.OscProbPMNSExpressions(R.Neutrino.ae(),
                                        R.Neutrino.ae(),
                                        ns=nsreac)
    print('Materialize expresions')
    nsreac.materializeexpressions()

with nsosc:
    pmnsosc = R.OscProbPMNSExpressions(R.Neutrino.ae(),
                                       R.Neutrino.ae(),
                                       ns=nsosc)
Example #8
0
from load import ROOT as R
from gna.env import env, ExpressionsEntry
import numpy as N

from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-c', '--pmnsc', action='store_true')
opts = parser.parse_args()

ns = env.globalns
ns.defparameter('L', central=1, sigma=0.1)

from gna.parameters.oscillation import reqparameters
print('Initialize variables')
reqparameters(ns)
ns['Delta'].set(N.pi * 1.5)
print('Materialize expressions')
ns.materializeexpressions()

print('Status:')
env.globalns.printparameters(labels=True)
print()

if opts.pmnsc:
    print('Initialize variables (C)')

    checkpmns = ns('checkpmns')
    exprs = R.PMNSExpressionsC(ns=checkpmns)
    print('Materialize expressions')
    checkpmns.materializeexpressions()