Ejemplo n.º 1
0
# Connect inputs
#
for inp, hist in zip(b.inputs.values(), hists_list):
    inp( hist.hist )

print('\nObservables:')
env.globalns.printobservables()

#
# Dump graph
#
if args.dot:
    try:
        from gna.graphviz import GNADot

        graph = GNADot( b.transformations_out[0][0] )
        graph.write(args.dot)
        print( 'Write output to:', args.dot )
    except Exception as e:
        print( '\033[31mFailed to plot dot\033[0m' )

#
# Make plots
#
from mpl_tools.helpers import plot_hist
from gna.labelfmt import formatter as L
axes=()
for i, hist in enumerate(hists_list):
    P.figure(),
    ax = P.subplot( 111 )
    axes+=ax,
Ejemplo n.º 2
0
# plot function versus sample points
ax.plot(gl_int.points.x.data(), fcn.rate.rate.data(), label='function')
# plot histogram using GNA to matplotlib interface
hist_output.plot_bar(label='histogram (sum=%g)' % hist.sum(), alpha=0.5)
# plot histogram manually
plot_bar(edges, hist / widths, label='histogram/binwidth', alpha=0.5)

# add legend
ax.legend(loc=opts.legend)

# Our function of interest is a guassian and should give 1 when integrated
# Test it by summing the histogram bins
diff = hist.sum() - 1
print('Integral-1:', diff)
print(
    N.fabs(diff) < 1.e-8 and '\033[32mIntegration is OK!'
    or '\033[31mIntegration FAILED!', '\033[0m')

if opts.dot:
    try:
        from gna.graphviz import GNADot
        graph = GNADot(gl_hist.hist)
        graph.write(opts.dot)
        print('Write output to:', opts.dot)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')
        raise

P.show()
Ejemplo n.º 3
0
                                args=(1.0, 10, 1)), )
# Build the expression for given configuration. The output is a context, that contains the inputs and outputs.
context = ExpressionContext(cfg)
a.build(context)

print('Variables')
context.ns.printparameters(labels=True)

from gna.bindings import OutputDescriptor
# Print inputs
print('Inputs')
print(context.inputs)

# Print outputs
print()
print('Outputs')
print(context.outputs)

print('The sum should be:', context.outputs['arr.a'].data().sum())
print('The sum is:', context.outputs['testsum.a'].data())

if args.dot:
    # try:
    from gna.graphviz import GNADot

    graph = GNADot(context.outputs.ta)
    graph.write(args.dot)
    print('Write output to:', args.dot)
    # except Exception as e:
    # print( '\033[31mFailed to plot dot\033[0m' )
Ejemplo n.º 4
0
                       ],
                                               mode='percent')),
    enu=NestedDict(bundle='dummy',
                   name='enu',
                   input=False,
                   size=10,
                   debug=False),
    spec=NestedDict(bundle='dummy',
                    name='spec',
                    input=True,
                    size=10,
                    debug=False),
)
context = ExpressionContext(cfg, ns=env.globalns)
a.build(context)

from gna.bindings import OutputDescriptor
env.globalns.printparameters()
print('outputs:')
print(context.outputs)

if args.dot:
    # try:
    from gna.graphviz import GNADot

    graph = GNADot(context.outputs.totalprod)
    graph.write(args.dot)
    print('Write output to:', args.dot)
    # except Exception as e:
    # print( '\033[31mFailed to plot dot\033[0m' )
Ejemplo n.º 5
0
            name = 'epos',
            input = False,
            size = 10,
            debug = False
            ),
        spec = NestedDict(
            bundle = 'dummy',
            name = 'spec',
            input = 2,
            size = 10,
            debug = False
            ),
        )
context = ExpressionContext(cfg, ns=env.globalns)
a.build(context)

from gna.bindings import OutputDescriptor
env.globalns.printparameters()
print( 'outputs:' )
print( context.outputs )

if args.dot:
    # try:
    from gna.graphviz import GNADot

    graph = GNADot( context.outputs.spec['1'], joints=False )
    graph.write(args.dot)
    print( 'Write output to:', args.dot )
    # except Exception as e:
        # print( '\033[31mFailed to plot dot\033[0m' )
Ejemplo n.º 6
0
    print('Parameters after modification')
    env.globalns.printparameters()

    for name, output in b.outputs.items():
        data=output.data().copy()
        ax.plot( points, N.ma.array(data, mask=data==0.0), '--', label=L.s(name) )

if opts.log:
    ax.set_yscale('log')

ax.legend( loc='upper right' )

if opts.dot:
    try:
        from gna.graphviz import GNADot

        kwargs=dict(
                # splines='ortho'
                joints=False,
                )
        graph = GNADot( b.transformations_out.values()[0], **kwargs )
        graph.write(opts.dot)
        print( 'Write output to:', opts.dot )
    except Exception as e:
        print( '\033[31mFailed to plot dot\033[0m' )

savefig(opts.output)

if opts.show:
    P.show()
Ejemplo n.º 7
0
            debug = False
            )
expr = 'sum[n]| '+expr

a = Expression(expr, indices=indices)

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

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

print()
context = ExpressionContext( cfg )
a.build(context)

from gna.bindings import OutputDescriptor
print( 'outputs:' )
print( context.outputs )

if args.dot:
    # try:
    from gna.graphviz import GNADot

    graph = GNADot( context.outputs.finalsum )
    graph.write(args.dot)
    print( 'Write output to:', args.dot )
    # except Exception as e:
        # print( '\033[31mFailed to plot dot\033[0m' )
Ejemplo n.º 8
0
            name = 'enu',
            input = False,
            size = 10,
            debug = False
            ),
        oscprob = NestedDict(
            bundle = 'oscprob_v01',
            name = 'oscprob',
            input = True,
            size = 10,
            debug = False
            ),
        )
context = ExpressionContext(cfg, ns=env.globalns)
a.build(context)

from gna.bindings import OutputDescriptor
env.globalns.printparameters( labels=True )
print( 'outputs:' )
print( context.outputs )

if args.dot:
    try:
        from gna.graphviz import GNADot

        graph = GNADot( context.outputs.enu, joints=False )
        graph.write(args.dot)
        print( 'Write output to:', args.dot )
    except Exception as e:
        print( '\033[31mFailed to plot dot\033[0m' )
Ejemplo n.º 9
0
        # par.setNormalValue(float(value))

    # print()
    # print('Parameters after modification')
    # env.globalns.printparameters()

    # for name, output in b.outputs.items():
        # ax.plot( points, output.data().copy(), '--', label=L.s(name) )

# if opts.log:
    # ax.set_yscale('log')

# ax.legend( loc='upper right' )

if opts.dot:
    if True:
        from gna.graphviz import GNADot

        kwargs=dict(
                # splines='ortho'
                )
        ts = [ snf.transformations_out.values()[0] ]+list(offeq.transformations_out.values()[0].values())
        graph = GNADot( ts, **kwargs )
        graph.write(opts.dot)
        print( 'Write output to:', opts.dot )
    # except Exception as e:
        # print( '\033[31mFailed to plot dot\033[0m' )

if opts.show:
    P.show()
Ejemplo n.º 10
0
# hist_output.plot_bar(label='histogram (sum=%g)'%hist.sum(), **baropts)
# # plot histogram manually
# plot_bar( edges, hist/widths, label='histogram/binwidth', **baropts)

# add legend
# ax.legend(loc=opts.legend)

# # Our function of interest is a guassian and should give 1 when integrated
# # Test it by summing the histogram bins
# diff = hist.sum()-integral
# print('Integral (analytic)', integral)
# print('Integral (analytic, sum)', integrals.sum())
# print('Diff (Integral - %g):'%integral, diff)
# # print('Integrals (analytic)', integrals)
# # print('Integrals (calc)', hist)
# adiff = N.fabs(integrals-hist).sum()
# print('Diffs (abssum):', adiff)
# print( N.fabs(diff)<1.e-8 and adiff<1.e-8 and '\033[32mIntegration is OK!' or '\033[31mIntegration FAILED!', '\033[0m' )

if opts.dot:
    try:
        from gna.graphviz import GNADot
        graph = GNADot(integrator.hist)
        graph.write(opts.dot)
        print( 'Write output to:', opts.dot )
    except Exception as e:
        print( '\033[31mFailed to plot dot\033[0m' )
        raise

P.show()
Ejemplo n.º 11
0
def build_and_plot(expr, obj, suffix):
    # Initialize the expression and indices
    a = Expression(expr, indices)

    # Dump the information
    print(a.expressions_raw)
    print(a.expressions)

    # Parse the expression
    a.parse()
    # The next step is needed to name all the intermediate variables.
    a.guessname(lib, save=True)
    # Dump the tree.
    a.tree.dump(True)

    cfg = NestedDict(
        kinint2=NestedDict(
            bundle='integral_2d1d_v01',
            variables=('evis', 'ctheta'),
            edges=N.linspace(0.0, 12.0, 241, dtype='d'),
            xorders=3,
            yorder=5,
            provides=['evis', 'ctheta', 'evis_edges'],
        ),
        ibd_xsec=NestedDict(bundle='xsec_ibd_v01',
                            order=1,
                            provides=['ibd_xsec', 'ee', 'enu', 'jacobian']),
        oscprob=NestedDict(bundle='oscprob_v01',
                           name='oscprob',
                           provides=['oscprob', 'pmns']),
        anuspec=NestedDict(
            bundle='reactor_anu_spectra_v02',
            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' ),
            edges=N.concatenate((N.arange(1.8, 8.7, 0.5), [12.3])),
        ),
        eff=NestedDict(
            bundle='efficiencies_v01',
            correlated=False,
            uncorrelated=True,
            norm=True,
            names=dict(norm='global_norm'),
            provides=['eff', 'effunc_corr', 'effunc_uncorr', 'global_norm'],
            efficiencies='data/dayabay/efficiency/P15A_efficiency.py'),
        livetime=NestedDict(
            bundle='dayabay_livetime_hdf_v01',
            file=
            'data/dayabay/data/P15A/dubna/dayabay_data_dubna_v15_bcw_adsimple.hdf5',
            provides=['livetime_daily', 'efflivetime_daily']),
        baselines=NestedDict(
            bundle='baselines_v01',
            reactors=
            'data/dayabay/reactor/coordinates/coordinates_docDB_9757.py',
            detectors='data/dayabay/ad/coordinates/coordinates_docDB_9757.py',
            provides=['baseline', 'baselineweight'],
            units="meters"),
        thermal_power=NestedDict(
            bundle='dayabay_reactor_burning_info_v01',
            reactor_info='data/dayabay/reactor/power/WeeklyAvg_P15A_v1.txt.npz',
            provides=['thermal_power', 'fission_fractions']),
        iav=NestedDict(
            bundle='detector_iav_db_root_v02',
            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='detector_eres_common3_v02',
            # pars: sigma_e/e = sqrt( a^2 + b^2/E + c^2/E^2 ),
            pars=uncertaindict([('Eres_a', 0.014764), ('Eres_b', 0.0869),
                                ('Eres_c', 0.0271)],
                               mode='percent',
                               uncertainty=30),
            provides=['eres', 'eres_matrix'],
            expose_matrix=True),
        lsnl=NestedDict(
            bundle='detector_nonlinearity_db_root_v02',
            names=['nominal', 'pull0', 'pull1', 'pull2', 'pull3'],
            filename='data/dayabay/tmp/detector_nl_consModel_450itr.root',
            parnames=dict(lsnl='lsnl_weight', escale='escale'),
            par=uncertain(1.0, 0.2, 'percent'),
            edges='evis_edges',
            provides=[
                'lsnl', 'lsnl_component', 'escale', 'lsnl_weight', 'lsnl_edges'
            ]),
        rebin=NestedDict(bundle='rebin_v02',
                         rounding=3,
                         edges=N.concatenate(([0.7], N.arange(1.2, 8.1,
                                                              0.2), [12.0]))))
    #
    # Put the expression into context
    context = ExpressionContext(cfg, ns=env.globalns)
    a.build(context)

    # # Print the list of outputs, stored for the expression
    # from gna.bindings import OutputDescriptor
    # env.globalns.materializeexpressions(True)
    # env.globalns.printparameters( labels=True )
    # print( 'outputs:' )
    # print( context.outputs )

    try:
        from gna.graphviz import GNADot

        obj = context.outputs[obj]
        if isinstance(obj, NestedDict):
            obj = obj.values()
        if len(expr) < 4:
            label = expr[0]
            if label == 'evis()':
                label = expr[1]
        else:
            label = ''
        graph = GNADot(obj, joints=False, label=label)
        name = args.dot.replace('.dot', '_' + suffix + '.dot')
        graph.write(name)
        print('Write output to:', name)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')
        raise
Ejemplo n.º 12
0
    # step('_03_lsnl')
    # outputs.eres.AD11.plot_hist(label='+eres')
    if args.mode == 'dyboscar':
        out = outputs.sum_sum_sum_eres_cw
    else:
        out = outputs.eres
    out.AD11.plot_hist(label='EH1 AD1')
    step('_04_eres')

if args.show:
    P.show()

#
# Dump the histogram to a dot graph
#
if args.dot:
    try:
        from gna.graphviz import GNADot

        graph = GNADot(context.outputs.ee, joints=False)
        graph.write(args.dot)
        print('Write output to:', args.dot)

        graph = GNADot(context.outputs.thermal_power.values(), joints=False)
        name = args.dot.replace('.dot', '_lt.dot')
        graph.write(name)
        print('Write output to:', name)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')
        raise
Ejemplo n.º 13
0
    def init(self):
        head = self.opts.plot[0]

        kwargs = dict(self.opts.options, joints=self.opts.joints)
        kwargs.setdefault('rankdir', 'LR')
        kwargs['subgraph']=self.opts.subgraph
        kwargs['include_only']=self.opts.include_only
        if self.opts.splines:
            kwargs['splines']=self.opts.splines

        if self.opts.namespace is not self.undefined:
            kwargs['namespace']=env.globalns(self.opts.namespace)

        graph = GNADot( head, **kwargs )


        for output in self.opts.outputs:
            print( 'Write graph to:', output )

            if output.endswith('.dot'):
                graph.write(output)
            else:
                graph.layout(prog='dot')
                graph.draw(output)

        if self.opts.stdout:
            graph.write()

        if self.opts.stderr:
            import sys
            graph.write( sys.stderr )
Ejemplo n.º 14
0
# fig = P.figure()
# ax = P.subplot( 111 )
# ax.minorticks_on()
# ax.grid()
# ax.set_xlabel(L.u('enu'))
# ax.set_ylabel(L('{enu} step'))
# ax.set_title(L('Check {enu} step'))

# idx = N.arange(enu.shape[0])
# for i, e in enumerate(enu.T):
# ax.plot(idx, e, '-', label='Slice %i'%i)

# ax.legend(loc='upper left')

if args.show:
    P.show()

#
# Dump the histogram to a dot graph
#
if args.dot:
    try:
        from gna.graphviz import GNADot

        graph = GNADot(context.outputs.ee, joints=True)
        graph.write(args.dot)
        print('Write output to:', args.dot)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')
        raise
Ejemplo n.º 15
0
# ax.vlines(cfg.edges, 0.0, 2.5, linestyles='--', alpha=0.5, colors='blue')

# for name, output in context.outputs.anuspec.items():
# data=output.data().copy()
# ax.plot( context.outputs.enu.data(), N.ma.array(data, mask=data==0.0), label=L.s(name) )

if opts.log:
    ax.set_yscale('log')

ax.legend(loc='upper right')

if opts.dot:
    try:
        from gna.graphviz import GNADot

        kwargs = dict(
            # splines='ortho'
            joints=False, )
        graph = GNADot(context.outputs.anuspec.U235, **kwargs)
        graph.write(opts.dot)
        print('Write output to:', opts.dot)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')
        raise

savefig(opts.output)

if opts.show:
    P.show()
Ejemplo n.º 16
0
Archivo: iav_2.py Proyecto: gnafit/gna
ax.set_title('IAV effect')

smeared1 = smear1.Nrec.data()
smeared2 = smear2.Nrec.data()
smeared3 = smear3.Nrec.data()
print('Sum check for {} (diff): {}'.format(1.0, phist.sum() - smeared1.sum()))
print('Sum check for {} (diff): {}'.format(2.0, phist.sum() - smeared2.sum()))
print('Sum check for {} (diff): {}'.format(2.0, phist.sum() - smeared3.sum()))

lines = plot_hist(edges, smeared1, linewidth=1.0, label='IAV 1')
lines = plot_hist(edges, smeared2, linewidth=1.0, label='IAV 2')
lines = plot_hist(edges, smeared3, linewidth=1.0, label='IAV 3')

ax.legend(loc='upper right')

#
# Dump graph
#
if args.dot:
    try:
        from gna.graphviz import GNADot

        graph = GNADot(b.transformations_out.values()[0])
        graph.write(args.dot)
        print('Write output to:', args.dot)
    except Exception as e:
        print('\033[31mFailed to plot dot\033[0m')

if args.show:
    P.show()
Ejemplo n.º 17
0
)

a = Expression(expr, indices=indices)

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

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

print()
context = ExpressionContext(cfg)
a.build(context)

from gna.bindings import OutputDescriptor
print('outputs:')
print(context.outputs)

print('Ratio (should be 0.5):', context.outputs['ratio.1.A'].data())

if args.dot:
    # try:
    from gna.graphviz import GNADot

    graph = GNADot(context.outputs.ratio['1.A'])
    graph.write(args.dot)
    print('Write output to:', args.dot)
    # except Exception as e:
    # print( '\033[31mFailed to plot dot\033[0m' )