Example #1
0
def test_arrayview_comparison():
    size = 5
    a1 = N.arange(size, dtype=context.current_precision_short())
    a2 = N.ascontiguousarray(a1[::-1])
    a3 = N.arange(size + 1, dtype=context.current_precision_short())
    view1a = R.arrayview(context.current_precision())(a1, a1.size)
    view1b = R.arrayview(context.current_precision())(a1, a1.size)
    view2 = R.arrayview(context.current_precision())(a2, a2.size)
    view3 = R.arrayview(context.current_precision())(a3, a3.size)

    assert view1a == view1b
    assert not view1a != view1b
    assert view1a != view2
    assert not view1a == view2
    assert view1a != view3
    assert not view1a == view3

    view4 = R.arrayview(context.current_precision())(view3.size())
    view4 = view3
    assert view3 == view4
    assert not view3 != view4

    view5 = R.arrayview(context.current_precision())(view3)
    assert view3 == view5
    assert not view3 != view5
Example #2
0
def test_viewrear_hist_02_auto():
    """Test ViewRear on Histogram (determine start and length)"""
    edges = N.arange(13, dtype='d')
    arr = N.zeros(edges.size-1, dtype=context.current_precision_short())

    ranges = [ (0, 3), (0, 12), (1, 3), (6, 6), (6, 1)]
    for rng in ranges:
        print('Range', rng)
        hist_main = C.Histogram(edges, arr)
        start, len = rng
        pedges = edges[start:start+len+1]
        arr_sub = N.arange(start, start+len, dtype=arr.dtype)
        hist_sub=C.Histogram(pedges, arr_sub, True)

        view = C.ViewRear(hist_main);
        hist_sub >> view.view.rear

        res = view.view.result.data()
        expect_edges = N.array(view.view.result.datatype().edges)
        expect = arr.copy()
        expect[start:start+len]=arr_sub
        print('Result', res)
        print('Expect', expect)
        print('Result (edges)', edges)
        print('Expect (edges)', expect_edges)
        print()
        assert (res==expect).all()
        assert (edges==expect_edges).all()
        assert (hist_main.single().data()==arr).all()
Example #3
0
def test_histedges_offset_01():
    size = 13
    edges = N.arange(size, dtype='d')
    hist_in = C.Histogram(edges)
    arr = N.zeros(edges.size - 1, dtype=context.current_precision_short())

    for offset in range(size - 1):
        print('Offset', offset)
        view = C.HistEdgesOffset(hist_in, offset)
        edges_truncated = edges[offset:]

        trans = view.histedges

        points = trans.points.data()
        points_truncated = trans.points_truncated.data()

        hist_truncated_d = trans.hist_truncated.data()
        hist_truncated = N.array(trans.hist_truncated.datatype().edges)

        print('    Edges (expected)', edges)
        print('    Edges truncated (expected)', edges_truncated)

        print('    Points', points)
        print('    Points truncated', points_truncated)
        print('    Hist truncated', hist_truncated)
        print('    Hist truncated data', hist_truncated_d)

        assert (edges == points).all()
        assert (edges_truncated == points_truncated).all()
        assert (edges_truncated == hist_truncated).all()
        assert (0.0 == hist_truncated_d).all()
Example #4
0
def test_viewrear_points_04_auto_fromhist_edges():
    """Test ViewRear on Histogram (determine start and length)"""
    edges = N.arange(13, dtype='d')
    arr = N.zeros(edges.size, dtype=context.current_precision_short())
    points_main = C.Points(arr)

    ranges = [ (0, 3), (0, 12), (1, 3), (6, 6), (6, 1)]
    for rng in ranges:
        print('Range', rng)
        hist_main = C.Histogram(edges, arr[:-1])
        start, len = rng
        pedges = edges[start:start+len+1]
        arr_sub = N.arange(start, start+len+1, dtype=arr.dtype)
        hist_sub=C.Histogram(pedges, arr_sub[:-1], True)

        points_sub=C.Points(arr_sub, True)

        view = C.ViewRear()
        view.determineOffset(hist_main, hist_sub, True)
        points_main >> view.view.original
        points_sub >> view.view.rear

        res = view.view.result.data()
        expect = arr.copy()
        expect[start:start+len+1]=arr_sub
        print('Result', res)
        print('Expect', expect)
        print()
        assert (res==expect).all()
Example #5
0
def test_viewrear_hist_04_auto_threshold():
    """Test ViewRear on Histogram (auto start and len), enable threshold"""
    edges = N.arange(13, dtype='d')
    arr = N.zeros(edges.size-1, dtype=context.current_precision_short())

    ranges = [ (0, 3), (0, 12), (1, 3), (6, 6)]
    for rng in ranges:
        hist_main = C.Histogram(edges, arr)
        start, len = rng

        pedges = edges[start:start+len+1].copy()
        print('Original edges', pedges)
        pedges[0]  = 0.5*(pedges[:2].sum())
        pedges[-1] = 0.5*(pedges[-2:].sum())
        print('Modified edges', pedges)
        arr_sub = N.arange(start, start+len, dtype=arr.dtype)
        hist_sub=C.Histogram(pedges, arr_sub, True)

        view = C.ViewRear(hist_main);
        view.allowThreshold()
        hist_sub >> view.view.rear

        res = view.view.result.data()
        expect_edges = N.array(view.view.result.datatype().edges)
        expect = arr.copy()
        expect[start:start+len]=arr_sub
        print('Range', rng)
        print('Result', res)
        print('Expect', expect)
        print('Result (edges)', edges)
        print('Expect (edges)', expect_edges)
        print()
        assert (res==expect).all()
        assert (edges==expect_edges).all()
        assert (hist_main.single().data()==arr).all()
Example #6
0
def test_jacobian_v01():
    ns = env.globalns("test_jacobian_v01")

    names = ['zero', 'one', 'two', 'three', 'four', 'five']
    values = N.arange(len(names), dtype=context.current_precision_short())
    jac = C.Jacobian()
    for name, value in zip(names, values):
        if value:
            par = ns.defparameter(name, central=value, relsigma=0.1)
        else:
            par = ns.defparameter(name, central=value, sigma=0.1)

        if name == 'five':
            break

        jac.append(par)
    five = par

    with ns:
        va = C.VarArray(names)

    va.vararray.points >> jac.jacobian.func

    vars = va.vararray.points.data()

    print('Python array:', values.shape, values)
    print('Array:', vars.shape, vars)

    res = jac.jacobian.jacobian.data()
    print('Jacobian:', res.shape, res)

    req = N.eye(len(names), len(names) - 1)
    assert N.allclose(res, req, atol=1.e-12)

    t = jac.jacobian
    tf1 = t.getTaintflag()
    tf0 = va.vararray.getTaintflag()

    assert not tf0.tainted()
    assert not tf1.tainted()
    assert tf1.frozen()

    five.set(12.0)
    assert tf0.tainted()
    assert not tf1.tainted()
    assert tf1.frozen()

    t.unfreeze()
    assert tf0.tainted()
    assert tf1.tainted()
    assert not tf1.frozen()

    res = jac.jacobian.jacobian.data()
    assert N.allclose(res, req, atol=1.e-12)
    assert not tf0.tainted()
    assert not tf1.tainted()
    assert tf1.frozen()
Example #7
0
def test_arrayview_vector():
    size = 5
    from gna.constructors import stdvector
    a1 = N.arange(size, dtype=context.current_precision_short())
    v1 = stdvector(a1)
    view1 = R.arrayview(context.current_precision())(a1, size)

    assert view1 == v1
    assert not view1 != v1
Example #8
0
def test_points_v02():
    arr = N.arange(12, dtype=context.current_precision_short())

    points = C.Points(arr)
    identity = C.Identity()
    points >> identity

    out = identity.single()

    for i in range(arr.size):
        points.set(arr, i)
        assert (out.data() == arr[:i]).all()
Example #9
0
def test_viewrear_points_01_start_len(function_name):
    """Test ViewRear on Points (start, len)"""
    arr = N.zeros(12, dtype=context.current_precision_short())
    ns = env.env.globalns(function_name)
    names=[]
    for i in range(arr.size):
        name='val_%02i'%i
        names.append(name)
        ns.defparameter( name, central=i, fixed=True, label='Value %i'%i )

    ranges = [ (0, 3), (0, 12), (1, 3), (6, 6), (6, 1)]
    for rng in ranges:
        start, len = rng

        pview = arr[start:start+len]
        points = C.Points(arr)
        view = C.ViewRear(points, start, len);

        cnames = names[start:start+len]
        with ns:
            vararray = C.VarArray(cnames)

        vararray >> view.view.rear

        print('Range', rng)
        for ichange, iname in enumerate(['']+cnames, -1):
            if iname:
                print('  Change', ichange)
                par=ns[iname]
                par.set(par.value()+1.0)

            res0 = vararray.single().data()
            res = view.view.result.data()
            expect = arr.copy()
            for i in range(start, start+len):
                expect[i] = ns[names[i]].value()

            expect0 = []
            for i in range(start, start+len):
                expect0.append(ns[names[i]].value())

            print('    Result 0', res0)
            print('    Expect 0', expect0)
            print('    Result', res)
            print('    Expect', expect)
            print('    Original data', points.single().data())
            print('    Original data (expect)', arr)

            assert (res==expect).all()
            assert (res0==expect0).all()
            assert (res[start:start+len]==res0).all()
            assert (points.single().data()==arr).all()
            print()
Example #10
0
def test_vararray_preallocated_v01(function_name):
    ns = env.globalns(function_name)

    names = ['zero', 'one', 'two', 'three', 'four', 'five']
    values = N.arange(len(names), dtype=context.current_precision_short())
    variables = R.vector('variable<%s>' % context.current_precision())()

    with context.allocator(100) as allocator:
        for name, value in zip(names, values):
            par = ns.defparameter(name, central=value, relsigma=0.1)
            variables.push_back(par.getVariable())

        with ns:
            vsum = C.VarSum(names, 'sum', ns=ns)
            vsum_var = ns['sum'].get()
            variables.push_back(vsum_var.getVariable())
            vprod = C.VarProduct(names, 'product', ns=ns)
            vprod_var = ns['product'].get()
            variables.push_back(vprod_var.getVariable())

        va = C.VarArrayPreallocated(variables)

    pool = allocator.view()
    res = va.vararray.points.data()

    values_all = N.zeros(shape=values.size + 2, dtype=values.dtype)
    values_all[:-2] = values
    values_all[-2] = values_all[:-2].sum()
    values_all[-1] = values_all[:-2].prod()

    print('Python array:', values_all)
    print('VarArray (preallocated):', res)
    print('Pool:', pool)

    assert (values_all == res).all()
    assert (values_all == pool).all()
    assert (res == pool).all()

    for i, (val, name) in enumerate(enumerate(names, 2)):
        ns[name].set(val)
        values_all[i] = val
        values_all[-2] = values_all[:-2].sum()
        values_all[-1] = values_all[:-2].prod()
        res = va.vararray.points.data()

        print('Iteration', i)
        print('    Python array:', values_all)
        print('    VarArray (preallocated):', res)

        assert (values_all == res).all()
        assert (values_all == pool).all()
        assert (res == pool).all()
Example #11
0
def test_arrayview_constructor_view():
    a = N.arange(5, dtype=context.current_precision_short())
    view = R.arrayview(context.current_precision())(a, a.size)

    assert view.size() == a.size
    assert not view.isOwner()

    vview = view.view()
    print('Python/C++', a, vview)

    assert (a == vview).all()
    assert view == view
    assert not view != view
Example #12
0
def normalizedconvolution_prepare(fcn, weights, scale=1.0, nsname=None):
    fcn = N.ascontiguousarray(fcn, dtype=context.current_precision_short())
    weights = N.ascontiguousarray(weights,
                                  dtype=context.current_precision_short())

    fcn_p, weights_p = C.Points(fcn), C.Points(weights)

    if nsname is not None:
        ns = env.globalns(nsname)
        ns.defparameter('scale', central=scale, fixed=True)
        with ns:
            nc = C.NormalizedConvolution('scale')
    else:
        scale = 1.0
        nc = C.NormalizedConvolution()

    fcn_p >> nc.normconvolution.fcn
    weights_p >> nc.normconvolution.weights

    res = nc.normconvolution.result.data()
    prod = nc.normconvolution.product.data()

    product_e = fcn * weights
    res_e = scale * product_e.sum() / weights.sum()

    print('Scale', scale)
    print('Function', fcn)
    print('Weights', weights)
    print('Product', prod)
    print('Product expected', product_e)
    print('Result', res)
    print('Result expected', res_e)

    assert (prod == product_e).all()
    assert (res == res_e).all()
    print()
Example #13
0
def test_arrayview_constructor():
    size = 5
    import ctypes
    san_size = ctypes.c_int(5)
    a = N.arange(size, dtype=context.current_precision_short())
    print("in failing test! Precision is {}".format(
        context.current_precision()))
    view = R.arrayview[context.current_precision()](size)

    assert view.size() == size
    assert view.isOwner()

    for i, v in enumerate(a):
        view[i] = v

    vview = view.view()
    print('C++', vview)

    assert (a == vview).all()
Example #14
0
def Points(array, *args, **kwargs):
    """Convert array/TH1/TH2 to Points"""

    if isinstance(array, R.TObject):
        if not hasattr(array, 'get_buffer'):
            raise Exception(
                'Only TH1D/TH2D/TH1F/TH2F/TMatrixD/TMatrixF may be converted to Points'
            )

        if isinstance(array, R.TH2):
            array = array.get_buffer().T
        else:
            array = array.get_buffer()

    array = np.ascontiguousarray(array,
                                 dtype=context.current_precision_short())
    if len(array.shape) > 2:
        raise Exception('Can convert only 1- and 2- dimensional arrays')
    s = array_to_stdvector_size_t(array.shape)
    return R.GNA.GNAObjectTemplates.PointsT(context.current_precision())(
        array.ravel(order='F'), s, *args, **kwargs)
Example #15
0
def test_object_variables(function_name):
    ns = env.globalns(function_name)

    names  = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]
    values = N.arange(len(names), dtype=context.current_precision_short())
    for name, value in zip(names, values):
        ns.defparameter(name, central=value, relsigma=0.1)

    with ns:
        va = C.VarArray(names)

    for i, (name, val_true) in enumerate(zip(names, values)):
        var = va.variables[i].getVariable()
        assert name==var.name()

        val = var.cast().value()
        assert val==val_true

    for i, (name, val_true) in enumerate(zip(names, values)):
        ns[name].set(val_true)
        var=va.variables[i].getVariable()
        val=var.cast().value()
        assert val==val_true
Example #16
0
def test_vararray_v01(function_name):
    ns = env.globalns(function_name)

    names = ['zero', 'one', 'two', 'three', 'four', 'five']
    values = N.arange(len(names), dtype=context.current_precision_short())
    for name, value in zip(names, values):
        ns.defparameter(name, central=value, relsigma=0.1)

    with ns:
        va = C.VarArray(names)

    res = va.vararray.points.data()

    print('Python array:', values)
    print('Array:', res)

    assert N.allclose(values, res)

    for i, (val, name) in enumerate(enumerate(names, 2)):
        ns[name].set(val)
        values[i] = val
        res = va.vararray.points.data()
        assert N.allclose(values, res)
Example #17
0
def test_histedges_offset_02():
    size = 13
    for edges_offset in (0, 1.5):
        edges = N.arange(size, dtype='d') + edges_offset
        hist_in = C.Histogram(edges)
        arr = N.zeros(edges.size - 1, dtype=context.current_precision_short())

        for offset in range(size - 1):
            threshold = edges[offset] + 0.6
            print('Offset', offset)
            print('Threshold', threshold)
            view = C.HistEdgesOffset(hist_in, threshold)
            edges_truncated = edges[offset:]
            edges_threshold = edges_truncated.copy()
            edges_threshold[0] = threshold

            edges_offset = edges_threshold.copy()
            edges_offset -= threshold

            trans = view.histedges

            points = trans.points.data()
            points_truncated = trans.points_truncated.data()
            points_threshold = trans.points_threshold.data()
            points_offset = trans.points_offset.data()

            hist_truncated_d = trans.hist_truncated.data()
            hist_truncated = N.array(trans.hist_truncated.datatype().edges)

            hist_threshold_d = trans.hist_threshold.data()
            hist_threshold = N.array(trans.hist_threshold.datatype().edges)

            hist_offset_d = trans.hist_offset.data()
            hist_offset = N.array(trans.hist_offset.datatype().edges)

            print('    Edges (expected)', edges)
            print('    Edges truncated (expected)', edges_truncated)
            print('    Edges threshold (expected)', edges_threshold)
            print('    Edges offset (expected)', edges_offset)

            print('    Points', points)
            print('    Points truncated', points_truncated)
            print('    Points threshold', points_threshold)
            print('    Points offset', points_offset)
            print('    Hist truncated', hist_truncated)
            print('    Hist truncated data', hist_truncated_d)
            print('    Hist threshold', hist_threshold)
            print('    Hist threshold data', hist_threshold_d)
            print('    Hist offset', hist_offset)
            print('    Hist offset data', hist_offset_d)

            assert (edges == points).all()
            assert (edges_truncated == points_truncated).all()
            assert (edges_threshold == points_threshold).all()
            assert (edges_offset == points_offset).all()
            assert (edges_truncated == hist_truncated).all()
            assert (0.0 == hist_truncated_d).all()
            assert (edges_threshold == hist_threshold).all()
            assert (0.0 == hist_threshold_d).all()
            assert (edges_offset == hist_offset).all()
            assert (0.0 == hist_offset_d).all()