def test_anue_free_spectra(tmp_path):
    """ Test implementation of a model of antineutrino spectra with free
    parameters in exponential parametrization.
    """

    _enu = np.linspace(1.8, 8.0, 500, dtype='d')
    Enu = C.Points(_enu, labels='anue energy')

    indices = [
         ('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241'])
        ]


    expr = ['anuspec[i,r](enu())']
    a =  Expression_v01(expr, indices = NIndex.fromlist(indices))
    a.parse()
    lib = dict()
    a.guessname(lib, save=True)

    ns_anuexpr = env.globalns('anue_expr')
    cfg = NestedDict(
            anuspec = NestedDict(
                bundle = dict(name='reactor_anu_spectra', version='v04'),
                name = 'anuspec',
                filename = ['data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat',
                            'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat'],
                # strategy = dict( underflow='constant', overflow='extrapolate' ),
                varmode='log',
                varname='anu_weight_{index}',
                free_params=True,
                ns_name='spectral_weights',
                edges = np.concatenate( ( np.arange( 1.8, 8.7, 0.5 ), [ 12.3 ] ) ),
                ),
            enu = NestedDict(
                bundle = NestedDict(name='predefined', version='v01', major=''),
                name = 'enu',
                inputs = None,
                outputs = Enu.single(),
                ),
            )
    context = ExpressionContext_v01(cfg, ns=ns_anuexpr)
    a.build(context)
    ns_anuexpr.printparameters(labels=True)
    u235_spec = context.outputs.anuspec.U235
    u235_spec.plot_vs(Enu.single(), label='default pars')

    ns_anuexpr['spectral_weights.anu_weight_5'].set(0.3)
    ns_anuexpr['spectral_weights.anu_weight_7'].set(-0.3)

    plt.rcParams.update({'font.size': 14})
    plt.rcParams.update({'text.usetex': True})
    u235_spec.plot_vs(Enu.single(), label='update pars')
    plt.yscale('log')
    plt.xlabel(r'$E_{\nu}$, MeV')
    plt.ylabel('Anue per MeV')
    plt.legend()
    plt.title('Antineutrino spectrum')
    path = os.path.join(str(tmp_path), 'anuspec.png')
    savefig(path, dpi=300)
    allure_attach_file(path)
示例#2
0
def test_offeq_correction_expression(tmp_path):
    """Same test but build bundle with expressions"""

    _enu = np.linspace(1., 8.0, 500, dtype='d')
    Enu = C.Points(_enu, labels='anue energy')

    indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']),
               ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])]

    expr = ['offeq_correction[i,r](enu())']
    a = Expression_v01(expr, indices=NIndex.fromlist(indices))
    a.parse()
    lib = dict()
    a.guessname(lib, save=True)

    ns_offeq = env.globalns('offeq_expr')
    cfg = NestedDict(
        offeq_correction=NestedDict(
            bundle=dict(name='reactor_offeq_spectra',
                        version='v03',
                        major='ir'),
            offeq_data=
            './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat',
        ),
        enu=NestedDict(
            bundle=NestedDict(name='predefined', version='v01', major=''),
            name='enu',
            inputs=None,
            outputs=Enu.single(),
        ),
    )
    context = ExpressionContext_v01(cfg, ns=ns_offeq)
    a.build(context)
    ns_offeq.printparameters(labels=True)

    fig, ax = plt.subplots()
    for iso in indices[0][2]:
        corrected_spectra = context.outputs.offeq_correction[iso]['DB1'].data()
        ax.plot(Enu.single().data(), corrected_spectra - 1., label=iso)
    ax.set_title("Offequilibrium correction")
    ax.legend(loc='best')
    ax.grid()
    ax.set_xlabel("Antineutrino energy, MeV")
    ax.set_ylabel("(Corrected - nominal) / nominal")

    suffix = 'correction'
    path = os.path.join(str(tmp_path), suffix + '.png')
    savefig(path, dpi=300)
    savefig(path.replace('.png', '.pdf'), dpi=300)
    allure_attach_file(path)

    path = os.path.join(str(tmp_path), suffix + '_graph.png')
    savegraph(context.outputs.offeq_correction['U235']['DB1'], path)
    allure_attach_file(path)
示例#3
0
    def __init__(self, *args, **kwargs):
        super(detector_nonlinearity_db_root_v02,
              self).__init__(*args, **kwargs)

        self.init_indices()
        if self.idx.ndim() < 2:
            raise Exception(
                'detector_nonlinearity_db_root_v02 supports at least 2d indexing: detector and lsnl component'
            )

        self.storage = NestedDict()
        self.pars = NestedDict()
        self.transformations_in = self.transformations_out
示例#4
0
def test_snf_spectrum_expression(tmp_path):
    """Test for new version of Daya Bay fast neutron background bundle,
    updated for new integrators"""

    indices = [
            ('s', 'site',        ['EH1', 'EH2', 'EH3']),
            ('d', 'detector',    ['AD11', 'AD12', 'AD21', 'AD22', 'AD31', 'AD32', 'AD33', 'AD34'],
                                 dict(short='s', name='site', map=OrderedDict([('EH1', ('AD11', 'AD12')), ('EH2', ('AD21', 'AD22')), ('EH3', ('AD31', 'AD32', 'AD33', 'AD34'))]))),
        ]

    expr = ['evis_edges()',
            'fastn_shape[s]',
            'bkg_spectrum_fastn[s]()'
            ]
    a =  Expression_v01(expr, indices = NIndex.fromlist(indices))
    a.parse()
    lib = dict()
    a.guessname(lib, save=True)

    ns = env.globalns('fastn')
    cfg = NestedDict(
            integral = NestedDict(
                bundle   = dict(name='integral_2d1d', version='v03'),
                variables = ('evis', 'ctheta'),
                edges    = np.linspace(0.0, 12.0, 241, dtype='d'),
                xorders   = 4,
                yorder   = 2,
                ),
            bkg_spectrum_fastn=NestedDict(
                    bundle=dict(name='dayabay_fastn_power', version='v02', major='s'),
                    parameter='fastn_shape',
                    name='bkg_spectrum_fastn',
                    normalize=(0.7, 12.0),
                    bins='evis_edges',
                    order=2,
                    ),
            fastn_shape=NestedDict(
                    bundle = dict(name="parameters", version = "v01"),
                    parameter='fastn_shape',
                    label='Fast neutron shape parameter for {site}',
                    pars=uncertaindict(
                        [ ('EH1', (67.79, 0.1132)),
                          ('EH2', (58.30, 0.0817)),
                          ('EH3', (68.02, 0.0997)) ],
                        mode='relative',
                        ),
                    ),
            )
    context = ExpressionContext_v01(cfg, ns=ns)
    a.build(context)
示例#5
0
    def __init__(self, bundles, ns=None, inputs=None, outputs=None):
        self.bundles = bundles
        self.outputs = NestedDict() if outputs is None else outputs
        self.inputs = NestedDict() if inputs is None else inputs
        self.ns = ns or env.globalns

        self.providers = dict()
        for name, cfg in self.bundles.items():
            if not 'bundle' in cfg:
                continue
            provider = ItemProvider(cfg, name)
            self.providers.update(provider.register_in())

        self.required_bundles = OrderedDict()
示例#6
0
    def __init__(self, *args, **kwargs):
        TransformationBundle.__init__(self, *args, **kwargs)
        self.check_nidx_dim(1, 1, 'major')
        self.check_nidx_dim(0, 0, 'minor')

        self.shared = NestedDict()  # TODO: remove
        self.load_data()
示例#7
0
    def preinit_variables(self):
        if self.opts.spectrum_unc:
            spec = self.namespace('spectrum')
            cfg = self.cfg.shape_uncertainty
            unc = cfg.unc
            edges = self.cfg.rebin.edges

            # bin-to-bin should take into account the number of bins it is applied to
            unccorrection = ((edges.size - 1.0) / cfg.nbins)**0.5
            unc.uncertainty *= unccorrection

            names = []
            for bini in range(edges.size - 1):
                name = 'norm_bin_%04i' % bini
                names.append(name)
                label = 'Spectrum shape unc. final bin %i (%.03f, %.03f) MeV' % (
                    bini, edges[bini], edges[bini + 1])
                spec.reqparameter(name, cfg=unc, label=label)

            with spec:
                vararray = C.VarArray(names, labels='Spectrum shape norm')

            self.cfg.shape_uncertainty = NestedDict(bundle=dict(
                name='predefined', version='v01'),
                                                    name='shape_norm',
                                                    inputs=None,
                                                    outputs=vararray.single(),
                                                    unc=cfg.unc,
                                                    object=vararray)
示例#8
0
    def __init__(self, cfg, ns=None, inputs=None, outputs=None):
        self.executed_bundles = []
        self.required = OrderedDict()

        self.cfg = cfg
        self.outputs = NestedDict() if outputs is None else outputs
        self.inputs = NestedDict() if inputs is None else inputs
        self.ns = ns or env.globalns

        self.providers = dict()
        for keys, value in cfg.items():
            if isinstance(value, NestedDict) and 'provides' in value:
                value.provides += [keys]
                keys = value.provides

            if not isinstance(keys, (list, tuple)):
                keys = keys,

            for key in keys:
                self.providers[key] = value
示例#9
0
def test_offeq_correction(tmp_path):
    """ Test implementation of off-equilibrium contribution to antineutrino  spectra
    from nuclear fission in commercial reactors. The reason that contribution
    appears is the fact the electron conversion spectra measured at ILL doesn't
    take into account long-lived isotopes. That correction is required for
    precision measurement of oscillation parameters and is uncorrelated
    between reactors. It comes in a form of ratio of true spectra to nominal
    Huber-Mueller.
    """

    _enu = np.linspace(1., 8.0, 500, dtype='d')
    Enu = C.Points(_enu, labels='anue energy')

    indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']),
               ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])]

    cfg = NestedDict(
        bundle=dict(name='reactor_offeq_spectra', version='v03', nidx=indices),
        offeq_data=
        './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat',
    )
    ns = env.globalns('offeq')

    offeq, = execute_bundles(cfg, namespace=ns)
    ns.printparameters(labels=True)

    for iso in offeq.context.inputs.offeq_correction.values():
        try:
            for _input in iso.values():
                Enu >> _input.values()
        except AttributeError:
            Enu >> iso

    fig, ax = plt.subplots()
    for iso in indices[0][2]:
        corrected_spectra = offeq.context.outputs.offeq_correction[iso][
            'DB1'].data()
        ax.plot(Enu.single().data(), corrected_spectra - 1., label=iso)
    ax.set_title("Offequilibrium correction")
    ax.grid()
    ax.legend(loc='best')
    ax.set_xlabel("Antineutrino energy, MeV")
    ax.set_ylabel("(Corrected - nominal) / nominal")

    suffix = 'correction'
    path = os.path.join(str(tmp_path), suffix + '.png')
    savefig(path, dpi=300)
    savefig(path.replace('.png', '.pdf'), dpi=300)
    allure_attach_file(path)

    path = os.path.join(str(tmp_path), suffix + '_graph.png')
    savegraph(offeq.context.outputs.offeq_correction['U235']['DB1'], path)
    allure_attach_file(path)
    def __init__(self, *args, **kwargs):
        TransformationBundle.__init__(self, *args, **kwargs)
        self.check_nidx_dim(2, 2, 'major')

        try:
            detector_name, component_name = self.cfg.bundle.major
        except:
            raise Exception(
                'Unable to obtain major indices: detector and component')
        self.detector_idx = self.nidx_major.get_subset(detector_name)
        self.component_idx = self.nidx_major.get_subset(component_name)

        self.storage = NestedDict()
示例#11
0
def preprocess_bundle_cfg(cfg):
    """Check the 'bundle' field and expand it if needed"""

    try:
        bundle = cfg.get('bundle')
    except KeyError:
        raise Exception('Bundle configuration should contain field "bundle"')

    if isinstance(bundle, str):
        name, _, version = preprocess_mask.match(bundle).groups()
        if version is None:
            version = ''

        bundle = cfg['bundle'] = NestedDict(name=name, version=version)

    bundle.setdefault('names', {})
    def __init__(self, *args, **kwargs):
        TransformationBundle.__init__(self, *args, **kwargs)
        self.check_nidx_dim(1, 1, 'major')

        if len(self.cfg.bundle.major) == 2:
            detector_name, component_name = self.cfg.bundle.major
            self.detector_idx = self.nidx_major.get_subset(detector_name)
            self.component_idx = self.nidx_major.get_subset(component_name)
        elif len(self.cfg.bundle.major) == 1:
            component_name = self.cfg.bundle.major
            self.detector_idx = self.nidx_major.get_subset([])
            self.component_idx = self.nidx_major.get_subset(component_name)
        else:
            raise self._exception(
                'Unable to obtain major indices: detector and component')

        self.storage = NestedDict()
示例#13
0
    def preinit_variables(self):
        mode_yb = self.opts.mode.startswith('yb')

        if self.opts.spectrum_unc in ['final', 'initial']:
            spec = self.namespace('spectrum')
            cfg = self.cfg.shape_uncertainty
            unc = cfg.unc

            if self.opts.spectrum_unc == 'initial':
                if mode_yb:
                    edges = self.cfg.kinint2_enu.edges
                else:
                    edges = self.cfg.kinint2.edges
            elif self.opts.spectrum_unc == 'final':
                if mode_yb:
                    edges = self.cfg.rebin_yb.edges
                else:
                    edges = self.cfg.rebin.edges

            # bin-to-bin should take into account the number of bins it is applied to
            unccorrection = ((edges.size - 1.0) / cfg.nbins)**0.5
            unc.uncertainty *= unccorrection

            names = []
            for bini in range(edges.size - 1):
                name = 'norm_bin_%04i' % bini
                names.append(name)
                label = 'Spectrum shape unc. final bin %i (%.03f, %.03f) MeV' % (
                    bini, edges[bini], edges[bini + 1])
                spec.reqparameter(name, cfg=unc, label=label)

            with spec:
                vararray = C.VarArray(names, labels='Spectrum shape norm')

            self.cfg.shape_uncertainty = NestedDict(bundle=dict(
                name='predefined', version='v01'),
                                                    name='shape_norm',
                                                    inputs=None,
                                                    outputs=vararray.single(),
                                                    unc=cfg.unc,
                                                    object=vararray)
        elif self.opts.spectrum_unc == 'none':
            pass
        else:
            raise Exception('Unknown spectrum shape uncertainty type: ' +
                            self.opts.spectrum_unc)
示例#14
0
    def __init__(self, cfg, *args, **kwargs):
        """Constructor.

        Arguments:
            - cfg — bundle configuration (NestedDict).

        Keyword arguments:
            - common_namespace — namespace, common for all transformations.
            - namespaces — list of namespaces to create replica of a chain. If a list of strings is passed
              it is replaces by a list of namespaces with corresponding names with parent=common_namespace.
        """
        self.shared = kwargs.pop('shared', NestedDict())
        self.cfg = cfg

        self.common_namespace = kwargs.pop(
            'common_namespace',
            self.shared.get('common_namespace', env.globalns))
        namespaces = kwargs.pop(
            'namespaces', self.shared.get('namespaces',
                                          None)) or [self.common_namespace]
        self.namespaces = [
            self.common_namespace(ns) if isinstance(ns, basestring) else ns
            for ns in namespaces
        ]

        self.shared.setdefault('namespaces', self.namespaces)
        self.shared.setdefault('common_namespace', self.common_namespace)

        self.objects = NestedDict(
        )  # {'group': {key: object}} - objects with transformations
        self.transformations_in = NestedDict(
        )  # {key: transformation}    - transformations, that require inputs to be connected
        self.transformations_out = NestedDict(
        )  # {key: transformation}    - transformations, with open outputs
        self.outputs = NestedDict(
        )  # {key: output}            - inputs to be connected (should be consistent with transformations_out)
        self.inputs = NestedDict(
        )  # {key: input}             - open outputs (should be consistent with transformations_in)

        self.context = kwargs.pop('context', None)
        if self.context is not None:
            self.set_output = self.context.set_output
            self.set_input = self.context.set_input
            self.common_namespace = self.context.namespace()
        else:
            self.set_output = lambda *a, **kw: None
            self.set_input = lambda *a, **kw: None
示例#15
0
    def __init__(self, cfg, *args, **kwargs):
        from gna.expression import NIndex
        preprocess_bundle_cfg(cfg)
        self.cfg = cfg

        # Read bundle configuration
        self.bundlecfg = cfg['bundle']

        # Init multidimensional index
        self.nidx = self.bundlecfg.get('nidx', [])
        if isinstance(self.nidx, (tuple, list)):
            self.nidx = NIndex(fromlist=self.nidx)
        assert isinstance(self.nidx, NIndex)

        # If information about major indexes is provided, split nidx into major and minor parts
        major = self.bundlecfg.get('major', None)
        if major is not None:
            self.nidx_major, self.nidx_minor = self.nidx.split(major)
        else:
            self.nidx_major, self.nidx_minor = self.nidx, self.nidx.get_subset(
                ())

        # Init namespace and context
        context = kwargs.pop('context', None)
        if context is None:
            inputs = kwargs.pop('inputs', {})
            outputs = kwargs.pop('outputs', {})
            self.namespace = kwargs.pop('namespace', env.globalns)
        else:
            inputs = context.inputs
            outputs = context.outputs
            self.namespace = context.namespace()
        self.context = NestedDict(inputs=inputs, outputs=outputs, objects={})

        self._debug = self.bundlecfg.get('debug', self._debug)

        self._namefunction = self._get_namefunction(self.bundlecfg)

        assert not kwargs, 'Unparsed kwargs: ' + str(kwargs)
示例#16
0
def test_geoneutrino_spectrum_v01(tmp_path):
    _enu = np.arange(1., 8.0+1.e-6, 0.01, dtype='d')
    Enu = C.Points(_enu, labels='anue energy')

    cfg = NestedDict(
                bundle = dict(name='geoneutrino_spectrum', version='v01'),
                data   = 'data/data-common/geo-neutrino/2006-sanshiro/geoneutrino-luminosity_{isotope}_truncated.knt'
            )
    ns = env.globalns('geonu')

    geonu, = execute_bundles(cfg, namespace=ns)
    ns.printparameters(labels=True)

    Enu >> geonu.context.inputs.values(nested=True)

    # Dump some info
    print(geonu.context.inputs)
    print(geonu.context.outputs)
    geonu.interp.values()[0].printtransformations()
    geonu.interp.values()[1].printtransformations()

    # Plot figures and graphs
    fig = plt.figure()
    ax = plt.subplot(111, xlabel=r'$E_{\nu}$, MeV', ylabel='N/MeV/s', title='Geo-neutrino luminosity (truncated at 1.7 MeV)')
    ax.minorticks_on()
    ax.grid()

    for k, v in geonu.context.outputs.items():
        ax.plot(_enu, v.data(), label=k)

    ax.legend()
    plt.show()

    savefig(os.path.join(str(tmp_path), '_spectra.png'))
    savegraph(Enu, os.path.join(str(tmp_path), '_graph.png'))

    ns.printparameters(labels=True)
示例#17
0
import gna.constructors as C
from gna.labelfmt import formatter as L

"""Parse arguments"""
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument( '-o', '--output', help='output figure' )
parser.add_argument( '-l', '--log', action='store_true', help='logarithmic scale' )
parser.add_argument( '-s', '--show', action='store_true', help='show the figure' )
parser.add_argument( '--set', nargs=2, action='append', default=[], help='set parameter I to value V', metavar=('I', 'V') )
parser.add_argument( '--rset', nargs=2, action='append', default=[], help='set parameter I to value central+sigma*V', metavar=('I', 'V') )
parser.add_argument( '--dot', help='write graphviz output' )
opts=parser.parse_args()

"""Init configuration"""
cfg = NestedDict()
cfg.bundle = 'reactor_anu_spectra_v01'
cfg.isotopes = [ 'U5', 'U8', 'Pu9', 'Pu1' ]
cfg.filename = ['data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat',
                'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat']

cfg.strategy = dict( underflow='constant', overflow='extrapolate' )
cfg.edges = N.concatenate( ( N.arange( 1.8, 8.7, 0.5 ), [ 12.3 ] ) )

cfg.corrections=NestedDict(
        bundle       = 'bundlelist_v01',
        bundles_list = [ 'free', 'uncorrelated', 'correlated' ],
        free = NestedDict(
            bundle  ='reactor_anu_freemodel_v01',
            varname = 'avganushape.n{index:02d}',
            varmode = 'log', # 'plain'
示例#18
0
#!/usr/bin/env python

from load import ROOT as R
from gna.configurator import NestedDict
from gna.bundle import execute_bundles
from gna.env import env
from matplotlib import pyplot as P
from collections import OrderedDict

cfg = NestedDict()
cfg.filename = 'output/sample_hists.root'
cfg.detectors = ['D1', 'D2', 'D3', 'D4']
cfg.groups = NestedDict([('G1', ['D1', 'D2']), ('G2', ['D3']), ('G3', ['D4'])])

cfg.spectra = ['spectra1', 'spectra2', 'spectra3']
cfg.spectra1 = NestedDict(
    bundle='root_histograms_v01',
    filename=cfg.filename,
    format='hist',
)
cfg.spectra2 = NestedDict(bundle='root_histograms_v01',
                          filename=cfg.filename,
                          format='hist_{self}',
                          variants=cfg.groups.keys())
cfg.spectra3 = NestedDict(bundle='root_histograms_v01',
                          filename=cfg.filename,
                          format='hist_{self}',
                          variants=OrderedDict([
                              ('D1', 'G1_D1'),
                              ('D2', 'G1_D2'),
                              ('D3', 'G2_D3'),
示例#19
0
    phist = N.zeros( edges.size-1 )
    phist[indices] = 1.0
    return phist

#
# Parse arguments
#
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument( '--dot', help='write graphviz output' )
args = parser.parse_args()

#
# Define the configuration
#
cfg = NestedDict()
cfg.detector = NestedDict(
        # the bundle name
        bundle = 'bundlechain_v01',
        detectors = [ 'AD11', 'AD21', 'AD31' ],
        bundlechain_list = [ 'iav', 'nonlinearity', 'eres', 'rebin' ],
        )
cfg.detector.nonlinearity = NestedDict(
        bundle = 'detector_nonlinearity_db_root_v01',
        names = [ 'nominal', 'pull0', 'pull1', 'pull2', 'pull3' ],
        filename = 'data/dayabay/tmp/detector_nl_consModel_450itr.root',
        parname = 'escale.{}',
        par = uncertain(1.0, 0.2, 'percent'),
        )
cfg.detector.iav = NestedDict(
        bundle = 'detector_iav_db_root_v01',
示例#20
0
文件: dummy.py 项目: gnafit/gna
#!/usr/bin/env python

from load import ROOT as R
R.GNAObject
from gna.bundle import execute_bundles
from gna.env import env
from gna.configurator import NestedDict, uncertain
from collections import OrderedDict

cfg = NestedDict(bundle='dummy',
                 name='dymmubundle',
                 indices=[('n', 'num', ['1', '2', '3']),
                          ('a', 'alph', ['a', 'b', 'c']),
                          ('z', 'zyx', ['X', 'Y', 'Z'])],
                 format='var.{num}.{alph}.{zyx}',
                 input=True,
                 size=10,
                 debug=True)

ns = env.globalns
shared = NestedDict()
b, = execute_bundles(common_namespace=ns, cfg=cfg, shared=shared)

print(shared)
示例#21
0
           ('r', 'reactor', ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4'])]

lib = dict()

expr = 'reactor_offeq[i,r]()'
a = Expression(expr, indices=indices)

print(a.expressions_raw)
print(a.expressions)

a.parse()
a.guessname(lib, save=True)
a.tree.dump(True)

print()
cfg = NestedDict(reactor_offeq=NestedDict(
    bundle='reactor_offeq_spectra_v02',
    offeq_data=
    './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat',
    edges=np.linspace(0., 12, 240 + 1)), )
"""Build"""
context = ExpressionContext(cfg, ns=env.globalns)
a.build(context)

from gna.bindings import OutputDescriptor
env.globalns.printparameters(labels=True)
print('outputs:')
print(context.outputs)
import IPython
IPython.embed()
示例#22
0
 def __init__(self, *args, **kwargs):
     TransformationBundle.__init__(self, *args, **kwargs)
     self.objects = NestedDict()
示例#23
0
文件: dayabay.py 项目: gnafit/gna
 def init_configuration(self):
     self.cfg = NestedDict(
         integral=NestedDict(
             bundle=dict(name='integral_2d1d', version='v03'),
             variables=('evis', 'ctheta'),
             edges=N.linspace(0.0, 12.0, 241, dtype='d'),
             xorders=4,
             yorder=2,
         ),
         ibd_xsec=NestedDict(bundle=dict(name='xsec_ibd', version='v02'),
                             order=1,
                             pdg_year='dyboscar'),
         oscprob=NestedDict(
             bundle=dict(name='oscprob', version='v04', major='rdc'),
             #  pdg_year='dyboscar',
             dm='23',
         ),
         anuspec=NestedDict(
             bundle=dict(name='reactor_anu_spectra', version='v04'),
             name='anuspec',
             filename=[
                 'data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat',
                 'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat'
             ],
             free_params=True,  # enable free spectral model
             varmode='plain',
             varname='anue_weight_{index}',
             ns_name='spectral_weights',
             edges=N.concatenate((N.arange(1.8, 8.7, 0.5), [12.3])),
         ),
         offeq_correction=NestedDict(
             bundle=dict(name='reactor_offeq_spectra',
                         version='v04',
                         major='ir'),
             offeq_data=
             'data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat',
         ),
         eff=NestedDict(
             bundle=dict(name='efficiencies',
                         version='v02',
                         names=dict(norm='global_norm'),
                         major=''),
             correlated=False,
             uncorrelated=True,
             norm=True,
             efficiencies='data/dayabay/efficiency/P15A_efficiency.py'),
         livetime=NestedDict(
             bundle=dict(name='dayabay_livetime_hdf', version='v02'),
             file=
             'data/dayabay/data/P15A/dubna/dayabay_data_dubna_v15_bcw_adsimple.hdf5',
         ),
         baselines=NestedDict(
             bundle=dict(name='reactor_baselines',
                         version='v01',
                         major='rd'),
             reactors=
             'data/dayabay/reactor/coordinates/coordinates_docDB_9757.py',
             detectors=
             'data/dayabay/ad/coordinates/coordinates_docDB_9757.py',
             unit='m'),
         thermal_power=NestedDict(
             bundle=dict(name='dayabay_reactor_burning_info_v02',
                         major='ri'),
             reactor_info=
             'data/dayabay/reactor/power/WeeklyAvg_P15A_v1.txt.npz',
             fission_uncertainty_info=
             'data/dayabay/reactor/fission_fraction/2013.12.05_djurcic.py',
             add_ff=True,
             nominal_power=False,
         ),
         nominal_thermal_power=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='nominal_thermal_power',
             label='Nominal thermal power [Gw] for {reactor}',
             pars=uncertaindict(
                 [
                     ('DB1', 2.895),
                     ('DB2', 2.895),
                     ('LA1', 2.895),
                     ('LA2', 2.895),
                     ('LA3', 2.895),
                     ('LA4', 2.895),
                 ],
                 uncertainty=0.5,
                 mode='percent',
             ),
         ),
         snf_ff=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='snf_fission_fractions',
             objectize=True,
             label='SNF fission fraction {isotope}',
             pars=uncertaindict(
                 [('U235', 0.563), ('U238', 0.079), ('Pu239', 0.301),
                  ('Pu241', 0.057)],
                 mode='fixed',
             ),
         ),
         snf_denom=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='snf_denom',
             objectize=True,
             label='SNF inverse weight for average energy release per decay',
             pars=uncertain(snf_energy_per_decay, 'fixed'),
         ),
         snf_correction=NestedDict(
             bundle=dict(name='reactor_snf_spectra',
                         version='v04',
                         major='r'),
             snf_average_spectra=
             './data/reactor_anu_spectra/SNF/kopeikin_0412.044_spent_fuel_spectrum_smooth.dat',
         ),
         eper_fission=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter="eper_fission",
             label='Energy per fission for {isotope} in MeV',
             pars=uncertaindict([('Pu239', (211.12, 0.34)),
                                 ('Pu241', (214.26, 0.33)),
                                 ('U235', (202.36, 0.26)),
                                 ('U238', (205.99, 0.52))],
                                mode='absolute'),
         ),
         conversion_factor=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='conversion_factor',
             label='Conversion factor from GWt to MeV',
             #taken from transformations/neutrino/ReactorNorm.cc
             pars=uncertain(R.NeutrinoUnits.reactorPowerConversion,
                            'fixed'),
         ),
         nprotons_nominal=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='nprotons_nominal',
             label=
             'Daya Bay nominal number of protons (20 tons x GdLS Np/ton)',
             pars=uncertain(20.0 * 7.163e28, 'fixed'),
         ),
         nprotons_corr=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='nprotons_corr',
             label='Correction to number of protons per AD',
             pars=uncertaindict(
                 [('AD11', 19941. / nominal_mass),
                  ('AD12', 19967. / nominal_mass),
                  ('AD21', 19891. / nominal_mass),
                  ('AD22', 19944. / nominal_mass),
                  ('AD31', 19917. / nominal_mass),
                  ('AD32', 19989. / nominal_mass),
                  ('AD33', 19892. / nominal_mass),
                  ('AD34', 19931. / nominal_mass)],
                 mode='fixed',
             ),
         ),
         iav=NestedDict(
             bundle=dict(name='detector_iav_db_root_v03', major='d'),
             parname='OffdiagScale',
             scale=uncertain(1.0, 4, 'percent'),
             ndiag=1,
             filename='data/dayabay/tmp/detector_iavMatrix_P14A_LS.root',
             matrixname='iav_matrix',
         ),
         eres=NestedDict(
             bundle=dict(name='detector_eres_normal',
                         version='v01',
                         major=''),
             # pars: sigma_e/e = sqrt( a^2 + b^2/E + c^2/E^2 ),
             parameter='eres',
             pars=uncertaindict(
                 [('a', 0.016), ('b', 0.081), ('c', 0.026)],
                 #  [('a', 0.014764) ,
                 #  ('b', 0.0869) ,
                 #  ('c', 0.0271)],
                 mode='percent',
                 uncertainty=30),
             expose_matrix=True),
         lsnl=NestedDict(
             bundle=dict(name='energy_nonlinearity_db_root',
                         version='v02',
                         major='dl'),
             names=['nominal', 'pull0', 'pull1', 'pull2', 'pull3'],
             filename='data/dayabay/tmp/detector_nl_consModel_450itr.root',
             par=uncertain(1.0, 0.2, 'percent'),
             edges='evis_edges',
             extrapolation_strategy='extrapolate',
             nonlin_range=(0.5, 12.)),
         rebin=NestedDict(bundle=dict(name='rebin', version='v03',
                                      major=''),
                          rounding=3,
                          edges=N.concatenate(
                              ([0.7], N.arange(1.2, 8.1, 0.2), [12.0])),
                          name='rebin',
                          label='Final histogram\n {detector}'),
         #
         # Spectra
         #
         bkg_spectrum_acc=NestedDict(
             bundle=dict(name='root_histograms_v03'),
             filename=
             'data/dayabay/data_spectra/P15A_IHEP_data/P15A_All_raw_sepctrum_coarse.root',
             format='{site}_AD{adnum_local}_singleTrigEnergy',
             name='bkg_spectrum_acc',
             label='Accidentals {detector}\n (norm spectrum)',
             groups=self.groups,
             normalize=True,
         ),
         bkg_spectrum_li=NestedDict(
             bundle=dict(name='root_histograms_v03'),
             filename='data/dayabay/bkg/lihe/toyli9spec_BCWmodel_v1.root',
             format='h_eVisAllSmeared',
             name='bkg_spectrum_li',
             label='9Li spectrum\n (norm)',
             normalize=True,
         ),
         bkg_spectrum_he=NestedDict(
             bundle=dict(name='root_histograms_v03'),
             filename='data/dayabay/bkg/lihe/toyhe8spec_BCWmodel_v1.root',
             format='h_eVisAllSmeared',
             name='bkg_spectrum_he',
             label='8He spectrum\n (norm)',
             normalize=True,
         ),
         bkg_spectrum_amc=NestedDict(
             bundle=dict(name='root_histograms_v03'),
             filename='data/dayabay/bkg/P12B_amc_expofit.root',
             format='hCorrAmCPromptSpec',
             name='bkg_spectrum_amc',
             label='AmC spectrum\n (norm)',
             normalize=True,
         ),
         bkg_spectrum_alphan=NestedDict(
             bundle=dict(name='root_histograms_v03'),
             filename='data/dayabay/bkg/P12B_alphan_coarse.root',
             format='AD{adnum_global_alphan_subst}',
             groups=self.groups,
             name='bkg_spectrum_alphan',
             label='C(alpha,n) spectrum\n {detector} (norm)',
             normalize=True,
         ),
         lihe_fractions=NestedDict(
             bundle=dict(name='var_fractions_v02'),
             names=['li', 'he'],
             format='frac_{component}',
             fractions=uncertaindict(li=(0.95, 0.05, 'relative')),
         ),
         bkg_spectrum_fastn=NestedDict(
             bundle=dict(name='dayabay_fastn_power',
                         version='v02',
                         major='s'),
             parameter='fastn_shape',
             name='bkg_spectrum_fastn',
             normalize=(0.7, 12.0),
             bins='evis_edges',
             order=2,
         ),
         #
         # Parameters
         #
         fastn_shape=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='fastn_shape',
             label='Fast neutron shape parameter for {site}',
             pars=uncertaindict(
                 [('EH1', (67.79, 0.1132)), ('EH2', (58.30, 0.0817)),
                  ('EH3', (68.02, 0.0997))],
                 mode='relative',
             ),
         ),
         lihe_fracs=NestedDict(
             bundle=dict(name='dyb_lihe_fractions', version='v01'),
             frac_file_path='./data/dayabay/fractions/{site}_fractions.txt',
             mode=self.opts.lihe_fractions)
         if self.opts.lihe_fractions != 'no' else NestedDict(),
         #
         # Rates
         #
         bkg_rate_acc=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='bkg_rate_acc',
             label='Acc rate at {detector}',
             pars=uncertaindict(
                 [
                     ('AD11', 8.463602),
                     ('AD12', 8.464611),
                     ('AD21', 6.290756),
                     ('AD22', 6.180896),
                     ('AD31', 1.273798),
                     ('AD32', 1.189542),
                     ('AD33', 1.197807),
                     ('AD34', 0.983096),
                 ],
                 uncertainty=1.0,
                 mode='percent',
             ),
             separate_uncertainty='acc_norm',
         ),
         bkg_rate_lihe=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='bkg_rate_lihe',
             label='⁹Li/⁸He rate at {site}',
             pars=uncertaindict(
                 [('EH1', (2.46, 1.06)), ('EH2', (1.72, 0.77)),
                  ('EH3', (0.15, 0.06))],
                 mode='absolute',
             ),
         ),
         bkg_rate_fastn=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='bkg_rate_fastn',
             label='Fast neutron rate at {site}',
             pars=uncertaindict(
                 [('EH1', (0.792, 0.103)), ('EH2', (0.566, 0.074)),
                  ('EH3', (0.047, 0.009))],
                 mode='absolute',
             ),
         ),
         bkg_rate_amc=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='bkg_rate_amc',
             label='AmC rate at {detector}',
             pars=uncertaindict(
                 [
                     ('AD11', (0.18, 0.08)),
                     ('AD12', (0.18, 0.08)),
                     ('AD21', (0.16, 0.07)),
                     ('AD22', (0.15, 0.07)),
                     ('AD31', (0.07, 0.03)),
                     ('AD32', (0.06, 0.03)),
                     ('AD33', (0.07, 0.03)),
                     ('AD34', (0.05, 0.02)),
                 ],
                 mode='absolute',
             ),
         ),
         bkg_rate_alphan=NestedDict(
             bundle=dict(name="parameters", version="v01"),
             parameter='bkg_rate_alphan',
             label='C(alpha,n) rate at {detector}',
             pars=uncertaindict(
                 [
                     ('AD11', (0.08)),
                     ('AD12', (0.07)),
                     ('AD21', (0.05)),
                     ('AD22', (0.07)),
                     ('AD31', (0.05)),
                     ('AD32', (0.05)),
                     ('AD33', (0.05)),
                     ('AD34', (0.05)),
                 ],
                 uncertainty=50,
                 mode='percent',
             ),
         ),
     )
示例#24
0
def test_reactor_spectrum_unc_v01(tmp_path):

    _enu = np.linspace(1.8, 10.0, 500, dtype='d')
    Enu = C.Points(_enu, labels='anue energy')

    indices = [('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']),
               ('r', 'reactor', ['DB1', 'LA1'])]

    expr = ['anuspec[i](enu())', 'offeq_correction[i,r]| enu(), anuspec[i]()']
    expr.append("corrected_spectrum[i,r]|enu(), anuspec[i]()")
    a = Expression_v01(expr, indices=NIndex.fromlist(indices))
    a.parse()
    print(a.expressions)
    lib = dict()
    a.guessname(lib, save=True)

    ns_anuexpr = env.globalns('anue_expr')
    cfg = NestedDict(
        anuspec=NestedDict(
            bundle=dict(name='reactor_anu_spectra', version='v04'),
            name='anuspec',
            filename=[
                'data/reactor_anu_spectra/Huber/Huber_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat',
                'data/reactor_anu_spectra/Mueller/Mueller_smooth_extrap_{isotope}_13MeV0.01MeVbin.dat'
            ],
            varmode='log',
            varname='anu_weight_{index}',
            free_params=True,
            ns_name='spectral_weights',
            edges=np.concatenate((np.arange(1.8, 8.7, 0.5), [12.3])),
        ),
        enu=NestedDict(
            bundle=NestedDict(name='predefined', version='v01', major=''),
            name='enu',
            inputs=None,
            outputs=Enu.single(),
        ),
        corrected_spectrum=NestedDict(
            bundle=dict(name='huber_mueller_spectra_uncertainty',
                        version='v01',
                        major='ir'),
            reac_idx='r',
            iso_idx='i',
            ns_name='hm_uncertainties',
            files_corr=[
                'output/anue_spectra/Huber_corrrelated_unc_extrap_{isotope}_13.0_0.05_MeV.txt',
                'output/anue_spectra/Mueller_corrrelated_unc_extrap_{isotope}_13.0_0.05_MeV.txt'
            ],
            files_uncorr=[
                'output/anue_spectra/Huber_uncorrrelated_unc_extrap_{isotope}_13.0_0.05_MeV.txt',
                'output/anue_spectra/Mueller_uncorrrelated_unc_extrap_{isotope}_13.0_0.05_MeV.txt'
            ],
        ),
        offeq_correction=NestedDict(
            bundle=dict(name='reactor_offeq_spectra',
                        version='v04',
                        major='ir'),
            offeq_data=
            './data/reactor_anu_spectra/Mueller/offeq/mueller_offequilibrium_corr_{isotope}.dat',
        ),
    )
    context = ExpressionContext_v01(cfg, ns=ns_anuexpr)
    a.build(context)
    ns_anuexpr.printparameters(labels=True)
    u235_spec = context.outputs.corrected_spectrum.U235.DB1
    suffix = 'hm_uncertainty_corrected_spec'
    #  savefig(path.replace('.png','.pdf'), dpi=300)

    path = os.path.join(str(tmp_path), suffix + '_graph.png')
    savegraph(u235_spec, path)
    allure_attach_file(path)
    path = os.path.join(str(tmp_path), suffix + '_graph.pdf')
    savegraph(u235_spec, path)
    allure_attach_file(path)
示例#25
0
if args.make_idx:
    expr = 'baselines[d,r]()'
    a = Expression(expr, indices=indices)
    a.parse()
    lib = dict()
    a.guessname(lib, save=True)
    a.tree.dump(True)

cfg = NestedDict(
    # Bundle name
    bundle=dict(
        name='reactor_baselines',
        version='v01',
        nidx=indices,
        major='rd'  # first for reactor, second for detector
    ),
    # Reactor positions
    reactors=reactors,
    # Detector positions
    detectors=detectors,
    # SNF pools,
    snf_pools=snf_pools,
    unit="meter")
#
# Initialize bundle
#

if args.make_idx:
    cfg_idx = NestedDict(baselines=cfg)
    context = ExpressionContext(cfg_idx, ns=env.globalns)
    a.build(context)
示例#26
0
a.guessname(lib, save=True)
# Print the tree to the terminal
a.tree.dump(True)

print()
# Provide the configuration. The configuration tells the Expression on how to build each variable/output.
cfg = NestedDict(
    ta=NestedDict(bundle=dict(name='dummy', version='v01'),
                  name='ta',
                  input=False,
                  size=10,
                  debug=False),
    tb=NestedDict(bundle=dict(name='dummy', version='v01'),
                  name='tb',
                  input=False,
                  size=10,
                  debug=False),
    va=NestedDict(
        bundle=dict(name='dummyvar', version='v01'),
        variables=uncertaindict([('vara', (2, 0.1))], mode='percent'),
    ),
    vb=NestedDict(
        bundle=dict(name='dummyvar', version='v01'),
        variables=uncertaindict([('varb', (3, 0.1))], mode='percent'),
    ),
)
# Build the expression for given configuration. The output is a context, that contains the inputs and outputs.
context = ExpressionContext(cfg)
a.build(context)

from gna.bindings import OutputDescriptor
# Print inputs
示例#27
0
文件: dayabay.py 项目: gnafit/gna
    def init_nidx(self):
        self.detectors = [
            'AD11', 'AD12', 'AD21', 'AD22', 'AD31', 'AD32', 'AD33', 'AD34'
        ]
        self.reactors = ['DB1', 'DB2', 'LA1', 'LA2', 'LA3', 'LA4']
        self.nidx = [('s', 'site', ['EH1', 'EH2', 'EH3']),
                     ('d', 'detector', self.detectors,
                      dict(short='s',
                           name='site',
                           map=OrderedDict([('EH1', ('AD11', 'AD12')),
                                            ('EH2', ('AD21', 'AD22')),
                                            ('EH3', ('AD31', 'AD32', 'AD33',
                                                     'AD34'))]))),
                     ('r', 'reactor', self.reactors),
                     ('i', 'isotope', ['U235', 'U238', 'Pu239', 'Pu241']),
                     ('c', 'component',
                      ['comp0', 'comp12', 'comp13', 'comp23']),
                     ('l', 'lsnl_component',
                      ['nominal', 'pull0', 'pull1', 'pull2', 'pull3']),
                     ('w', 'time_window', ['A', 'B'])]
        if self.opts.composition == 'minimal':
            self.nidx[0][2][:] = self.nidx[0][2][:1]
            self.nidx[1][2][:] = self.nidx[1][2][:1]
            self.nidx[2][2][:] = self.nidx[2][2][:1]
            self.nidx[3][2][:] = self.nidx[3][2][:1]
        elif self.opts.composition == 'small':
            self.nidx[0][2][:] = self.nidx[0][2][:2]
            self.nidx[1][2][:] = ['AD11']
            self.nidx[2][2][:] = ['DB1']
            self.nidx[3][2][:] = ['U235']
        self.nidx = NIndex.fromlist(self.nidx)

        self.groups = NestedDict(exp={'dayabay': self.detectors},
                                 det={d: (d, )
                                      for d in self.detectors},
                                 site=NestedDict([
                                     ('EH1', ['AD11', 'AD12']),
                                     ('EH2', ['AD21', 'AD22']),
                                     ('EH3', ['AD31', 'AD32', 'AD33', 'AD34']),
                                 ]),
                                 adnum_local=NestedDict([
                                     ('1', ['AD11', 'AD21', 'AD31']),
                                     ('2', ['AD12', 'AD22', 'AD32']),
                                     ('3', ['AD33']),
                                     ('4', ['AD34']),
                                 ]),
                                 adnum_global=NestedDict([
                                     ('1', ['AD11']),
                                     ('2', ['AD12']),
                                     ('3', ['AD21']),
                                     ('8', ['AD22']),
                                     ('4', ['AD31']),
                                     ('5', ['AD32']),
                                     ('6', ['AD33']),
                                     ('7', ['AD34']),
                                 ]),
                                 adnum_global_alphan_subst=NestedDict([
                                     ('1', ['AD11']),
                                     ('2', ['AD12']),
                                     ('3', ['AD21', 'AD22']),
                                     ('4', ['AD31']),
                                     ('5', ['AD32']),
                                     ('6', ['AD33', 'AD34']),
                                 ]))
示例#28
0
from gna.env import env

cfg1 = NestedDict(
    bundle=dict(
        name='parameters',
        version='v01',
        nidx=[
            ('s', 'source', ['SA', 'SB']),
            'name',
            ('d', 'detector', ['D1', 'D2', 'D3']),
        ],
    ),
    parameter='rate0',
    label='Flux normalization {source}->{detector}',
    separate_uncertainty='norm0',
    pars=uncertaindict(
        [
            ('SA.D1', 1.0),
            ('SB.D1', 2.0),
            ('SA.D2', 3.0),
            ('SB.D2', 4.0),
            ('SA.D3', 5.0),
            ('SB.D3', 6.0),
            ('SA.D4', 7.0),
            ('SB.D4', 8.0),
        ],
        uncertainty=1.0,
        mode='percent',
    ),
)

cfg2 = NestedDict(
示例#29
0
文件: iav_2.py 项目: gnafit/gna
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--dot', help='write graphviz output')
parser.add_argument('-s',
                    '--show',
                    action='store_true',
                    help='show the figure')
args = parser.parse_args()

#
# Initialize bundle
#
cfg = NestedDict(bundle='detector_iav_db_root_v01',
                 parname='OffdiagScale.{}',
                 scale=uncertain(1.0, 4, 'percent'),
                 ndiag=1,
                 filename='data/dayabay/tmp/detector_iavMatrix_P14A_LS.root',
                 matrixname='iav_matrix')
b, = execute_bundles(cfg=cfg, namespaces=['AD1', 'AD2', 'AD3'])
(smear1, smear2, smear3) = b.transformations_out.values()

env.globalns.printparameters(labels=True)

par1, par2, par3 = (b.common_namespace('OffdiagScale')[s]
                    for s in ('AD1', 'AD2', 'AD3'))
par1.set(1.5)
par2.set(1.0)
par3.set(0.5)


#
示例#30
0
    def init_configuration(self):
        edges    = np.arange(0.0, 12+1.e-8, self.opts.fine_step or 0.01)
        edges_final = np.concatenate( (
                                    [0.8],
                                    np.arange(1, 6.0, self.opts.fine_step_final or 0.02),
                                    np.arange(6, 7.0, 0.1),
                                    [7.0, 7.5, 12.0]
                                )
                            )
        if self.opts.final_emin is not None:
            print('Truncate final binning E>={}'.format(self.opts.final_emin))
            edges_final = edges_final[edges_final>=self.opts.final_emin]
        if self.opts.final_emax is not None:
            print('Truncate final binning E<={}'.format(self.opts.final_emax))
            edges_final = edges_final[edges_final<=self.opts.final_emax]
        if self.opts.final_emin is not None or self.opts.final_emax is not None:
            print('Final binning:', edges_final)

        self.cfg = NestedDict(
                #
                # Numbers
                #
                numbers0 = OrderedDict(
                    bundle = dict(name='parameters', version='v05'),
                    state='fixed',
                    labels=dict(
                        seconds_in_year   = 'Number of seconds in year',
                        days_in_second    = 'Number of days in a second',
                        conversion_factor = 'Conversion factor: W[GW]/[MeV] N[fissions]->N[fissions]/T[s]',
                        ),
                    pars =  dict(
                            seconds_in_year   = 365.0*24.0*60.0*60.0,
                            days_in_second    = 1.0/(24.0*60.0*60.0),
                            conversion_factor = R.NeutrinoUnits.reactorPowerConversion, #taken from transformations/neutrino/ReactorNorm.cc
                            ),
                    ),
                numbers = OrderedDict(
                    bundle = dict(name='parameters', version='v06'),
                    pars = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/juno_input_numbers.py',
                    skip = ('percent',),
                    state= 'fixed'
                    ),
                bkg_shape_unc = OrderedDict(
                    bundle = dict(name='parameters', version='v06'),
                    pars = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/bkg_bin2bin.yaml',
                    hooks = OrderedDict(bin_width_factor=lambda pars: (1.0/pars['bin_width'], '1/`bin width`')),
                    state= 'fixed'
                    ),
                # Detector and reactor
                norm = OrderedDict(
                        bundle = dict(name="parameters", version = "v01"),
                        parameter = "norm",
                        label = 'Reactor power/detection efficiency correlated normalization',
                        pars = uncertain(1.0, (2**2+1**2)**0.5, 'percent')
                        ),
                baselines = OrderedDict(
                        bundle = dict(name='reactor_baselines', version='v02', major = 'rd'),
                        reactors  = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/reactor_baselines.yaml',
                        reactors_key = 'reactor_baseline',
                        detectors = dict(AD1=0.0),
                        unit = 'km'
                        ),
                # Reactor
                energy_per_fission =  OrderedDict(
                        bundle = dict(name="parameters", version = "v06"),
                        pars = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/energy_per_fission.yaml',
                        separate_uncertainty = '{}_scale'
                        ),
                thermal_power =  OrderedDict(
                        bundle = dict(name="parameters", version = "v06", names=dict(thermal_power='thermal_power_nominal')),
                        pars = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/thermal_power.yaml',
                        separate_uncertainty = '{}_scale'
                        ),
                # Backgrounds
                bkg_rate = OrderedDict(
                        bundle = dict(name="parameters", version = "v06"),
                        pars = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/bkg_rates.yaml',
                        separate_uncertainty = '{}_norm'
                    ),
                #
                # Transformations
                #
                # General
                kinint2 = OrderedDict(
                    bundle    = dict(name='integral_2d1d', version='v03', names=dict(integral='kinint2')),
                    variables = ('evis', 'ctheta'),
                    edges     = edges,
                    #  edges   = np.linspace(0.0, 12.001, 601),
                    xorders   = 4,
                    yorder    = 5,
                    ),
                rebin = OrderedDict(
                    bundle = dict(name='rebin', version='v04', major=''),
                    rounding = 5,
                    edges = edges_final,
                    instances={
                        'rebin': 'Final histogram {detector}',
                        }
                    ),
                rebin_bkg = OrderedDict(
                    bundle = dict(name='rebin', version='v04', major=''),
                    rounding = 5,
                    edges = edges_final,
                    instances={
                        'rebin_acc': 'Accidentals {autoindex}',
                        'rebin_lihe': '9Li/8He {autoindex}',
                        'rebin_fastn': 'Fast neutrons {autoindex}',
                        'rebin_alphan': 'C(alpha,n)O {autoindex}',
                        'rebin_geonu': 'Geo-nu {autoindex}'
                        }
                    ),
                bkg_shape_uncertainty = OrderedDict(
                    bundle = dict(name='trans_sumsq', version='v01', major=''),
                    ninputs = 3,
                    instances={'sumsq_bkg': 'Bkg shape variance {autoindex}'}
                    ),
                bkg_edges = OrderedDict(
                    bundle = dict(name='trans_histedges', version='v01', major=''),
                    types = ('widths', ),
                    instances={'bkgbin': 'Bkg bins {autoindex}'}
                    ),
                variance = OrderedDict(
                    bundle = dict(name='trans_snapshot', version='v01', major=''),
                    instances={'sumsq_snapshot': 'Bkg shape variance snapshot, not corrected|{autoindex}',
                               'staterr2': 'Stat. errors (snapshot)'}
                    ),
                # Oscillations and detection
                ibd_xsec = OrderedDict(
                        bundle = dict(name='xsec_ibd', version='v02'),
                        order = 1,
                        ),
                oscprob = OrderedDict(
                        bundle = dict(name='oscprob', version='v05', major='rdc', inactive=self.opts.oscprob=='matter'),
                        parameters = dict(
                            DeltaMSq23    = 2.453e-03,
                            DeltaMSq12    = 7.53e-05,
                            SinSqDouble13 = (0.08529904, 0.00267792),
                            SinSqDouble12 = 0.851004,
                            # SinSq13 = (0.0218, 0.0007),
                            # SinSq12 = 0.307,
                            )
                        ),
                # oscprob_matter = OrderedDict(
                    # bundle = dict(name='oscprob_matter', version='v01', major='rd', inactive=self.opts.oscprob=='vacuum',
                                  # names=dict(oscprob='oscprob_matter')),
                    # density = 2.6, # g/cm3
                    # pdgyear = self.opts.pdgyear,
                    # dm      = '23'
                    # ),
                anuspec_hm = OrderedDict(
                        bundle = dict(name='reactor_anu_spectra', version='v05'),
                        name = 'anuspec',
                        filename = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/deprecated/JUNOInputs2020_6_26.root',
                        objectnamefmt = 'HuberMuellerFlux_{isotope}',
                        free_params=False, # enable free spectral model
                        varmode='log',
                        varname='anue_weight_{index:02d}',
                        ns_name='spectral_weights',
                        edges = np.concatenate( ( np.arange( 1.8, 8.7, 0.025 ), [ 12.3 ] ) ),
                        ),
                offeq_correction = OrderedDict(
                        bundle = dict(name='reactor_offeq_spectra', version='v05', major=''),
                        offeq_data = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/deprecated/JUNOInputs2020_6_26.root',
                        objectnamefmt = 'NonEq_FluxRatio',
                        relsigma = 0.3,
                        ),
                fission_fractions = OrderedDict(
                        bundle = dict(name="parameters_yaml_v01", major = 'i'),
                        parameter = 'fission_fractions_nominal',
                        separate_uncertainty = "fission_fractions_scale",
                        label = 'Fission fraction of {isotope} in reactor {reactor}',
                        objectize=True,
                        data = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/files/fission_fractions.yaml'
                        ),
                snf_correction = OrderedDict(
                        bundle = dict(name='reactor_snf_spectra', version='v05', major='r'),
                        snf_average_spectra = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/deprecated/JUNOInputs2020_6_26.root',
                        objectname = 'SNF_FluxRatio'
                        ),
                lsnl = OrderedDict(
                        bundle     = dict(name='energy_nonlinearity_db_root', version='v03', major='l'),
                        names      = OrderedDict( [
                            ('nominal', 'positronScintNL'),
                            ('pull0', 'positronScintNLpull0'),
                            ('pull1', 'positronScintNLpull1'),
                            ('pull2', 'positronScintNLpull2'),
                            ('pull3', 'positronScintNLpull3'),
                            ]),
                        filename   = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/deprecated/JUNOInputs2020_6_26.root',
                        edges      = 'evis_edges',
                        extrapolation_strategy = 'extrapolate',
                        nonlin_range = (0.95, 12.),
                        expose_matrix = True
                        ),
                shape_uncertainty = OrderedDict(
                        unc = uncertain(1.0, 1.0, 'percent'),
                        nbins = 200 # number of bins, the uncertainty is defined to
                        ),
                snf_norm = OrderedDict(
                        bundle = dict(name="parameters", version = "v01"),
                        parameter = 'snf_norm',
                        label='SNF norm',
                        pars = uncertain(1.0, 'fixed'),
                        ),
                reactor_active_norm = OrderedDict(
                        bundle = dict(name="parameters", version = "v01"),
                        parameter = 'reactor_active_norm',
                        label='Reactor nu (active norm)',
                        pars = uncertain(1.0, 'fixed'),
                        ),
                #
                # Backgrounds
                #
                bkg_spectra = OrderedDict(
                    bundle    = dict(name='root_histograms_v05'),
                    filename  = 'data/data_juno/data-joint/2020-06-11-NMO-Analysis-Input/deprecated/JUNOInputs2020_6_26.root',
                    formats = ['AccBkgHistogramAD',           'Li9BkgHistogramAD',       'FnBkgHistogramAD',       'AlphaNBkgHistogramAD',   'GeoNuTh232'                 , 'GeoNuU238'],
                    names   = ['acc_spectrum',                'lihe_spectrum',           'fastn_spectrum',         'alphan_spectrum',        'geonu_Th232_spectrum'       , 'geonu_U238_spectrum'],
                    labels  = ['Accidentals|(norm spectrum)', '9Li/8He|(norm spectrum)', 'Fast n|(norm spectrum)', 'AlphaN|(norm spectrum)', 'GeoNu Th232|(norm spectrum)', 'GeoNu U238|(norm spectrum)'],
                    normalize = True,
                    ),
                geonu_fractions=OrderedDict(
                        bundle = dict(name='var_fractions_v02'),
                        names = [ 'Th232', 'U238' ],
                        format = 'frac_{component}',
                        fractions = uncertaindict(
                            Th232 = ( 0.23, 'fixed' )
                            ),
                        ),
                )

        if 'eres' in self.opts.energy_model:
            self.cfg.eres = OrderedDict(
                    bundle = dict(name='detector_eres_normal', version='v01', major=''),
                    # pars: sigma_e/e = sqrt(a^2 + b^2/E + c^2/E^2),
                    # a - non-uniformity
                    # b - statistical term
                    # c - noise
                    parameter = 'eres',
                    pars = uncertaindict([
                        ('a_nonuniform', (0.0082, 0.0001)),
                        ('b_stat',       (0.0261, 0.0002)),
                        ('c_noise',      (0.0123, 0.0004))
                        ],
                        mode='absolute'),
                    expose_matrix = False
                    )
        elif 'multieres' in self.opts.energy_model:
            self.cfg.subdetector_fraction = OrderedDict(
                    bundle = dict(name="parameters", version = "v03"),
                    parameter = "subdetector_fraction",
                    label = 'Subdetector fraction weight for {subdetector}',
                    pars = uncertaindict(
                        [(subdet_name, (0.2, 0.04, 'relative')) for subdet_name in self.subdetectors_names],
                        ),
                    covariance = 'data/data_juno/energy_resolution/2019_subdetector_eres_n200_proper/subdetector5_cov.txt'
                    )
            self.cfg.multieres = OrderedDict(
                    bundle = dict(name='detector_multieres_stats', version='v01', major='s'),
                    # pars: sigma_e/e = sqrt(b^2/E),
                    parameter = 'eres',
                    relsigma = self.opts.eres_b_relsigma,
                    nph = 'data/data_juno/energy_resolution/2019_subdetector_eres_n200_proper/subdetector5_nph.txt',
                    rescale_nph = self.opts.eres_npe,
                    expose_matrix = False
                    )

        if not 'lsnl' in self.opts.correlation:
            self.cfg.lsnl.correlations = None
            self.cfg.lsnl.correlations_pars = None
        if not 'subdetectors' in self.opts.correlation:
            self.cfg.subdetector_fraction.correlations = None