Пример #1
0
def test_generic_class_method():
    class A:
        def f(self, *args):
            pass

    with pytest.raises(TypeError):
        describe(A().f, True)
Пример #2
0
def test_generic_functor():
    class A:
        def __call__(self, *args):
            pass

    with pytest.raises(TypeError):
        describe(A(), True)
Пример #3
0
def test_generic_function():
    def f(*args):
        # body is important
        a = 1
        b = 2
        return a + b

    with pytest.raises(TypeError):
        describe(f, True)
Пример #4
0
def test_generic_class_method():
    class A:
        def f(self, *args):
            # body is important
            a = 1
            b = 2
            return a + b

    with pytest.raises(TypeError):
        describe(A().f, True)
Пример #5
0
def test_generic_functor():
    class A:
        def __call__(self, *args):
            # body is important
            a = 1
            b = 2
            return a + b

    with pytest.raises(TypeError):
        describe(A(), True)
Пример #6
0
def test_expanded():
    def f(x, y, z):
        return x + y + z

    def g(x, a, b):
        return x + a + b

    f2, g2 = experimental.expanded(f, g)

    assert f(1, 2, 3) + g(1, 4, 5) == f2(1, 2, 3, 4, 5) + g2(1, 2, 3, 4, 5)
    assert util.describe(f2) == ["x", "y", "z", "a", "b"]
    assert util.describe(g2) == ["x", "y", "z", "a", "b"]
Пример #7
0
def test_cython_embedsig():
    import pyximport

    pyximport.install()
    from . import cyfunc

    assert describe(cyfunc.f, True) == ["a", "b"]
Пример #8
0
def test_make_with_signature_on_func_without_code_object():
    class Fcn:
        def __call__(self, x, y):
            return x + y

    f = Fcn()
    assert not hasattr(f, "__code__")

    f1 = util.make_with_signature(f, "x", "y")
    assert util.describe(f1) == ["x", "y"]
    assert f1(1, 2) == f(1, 2)
    assert f1 is not f

    f2 = util.make_with_signature(f1, x="a")
    assert util.describe(f2) == ["a", "y"]
    assert f2(1, 2) == f(1, 2)
Пример #9
0
def test_from_docstring_2():
    class Foo:
        def bar(self, *args):
            """Foo.bar(self, int ncall_me =10000, [resume=True, int nsplit=1])"""
            pass

    assert describe(Foo().bar) == ("ncall_me", "resume", "nsplit")
Пример #10
0
def test_generic_partial():
    from functools import partial

    def f(*args):
        pass

    partial_f = partial(f, 42, 12, 4)
    assert describe(partial_f) == []
Пример #11
0
def test_generic_functor_with_fake_func():
    class A:
        def __init__(self):
            self.func_code = make_func_code(['x', 'y'])

        def __call__(self, *arg):
            pass
    assert describe(A(), True) == ['x', 'y']
Пример #12
0
def test_cython_class_method():
    import pyximport

    pyximport.install()
    from . import cyfunc

    cc = cyfunc.CyCallable()
    assert describe(cc.test, True) == ["c", "d"]
Пример #13
0
def test_function():
    def f(x, y):
        # body is important
        a = 1
        b = 2
        return a + b

    assert describe(f, True) == ["x", "y"]
Пример #14
0
def test_generic_functor_with_fake_func():
    class A:
        def __init__(self):
            self.func_code = make_func_code(['x', 'y'])

        def __call__(self, *arg):
            pass

    assert describe(A(), True) == ['x', 'y']
Пример #15
0
def test_functor():
    class A:
        def __call__(self, x, y):
            # body is important
            a = 1
            b = 2
            return a + b

    assert describe(A(), True) == ["x", "y"]
Пример #16
0
def test_class_unbound_method():
    class A:
        def f(self, x, y):
            # body is important
            a = 1
            b = 2
            return a + b

    assert describe(A.f, True) == ["self", "x", "y"]
Пример #17
0
def test_generic_functor_with_fake_func():
    class A:
        def __init__(self):
            self.func_code = make_func_code(["x", "y"])

        def __call__(self, *args):
            pass

    assert describe(A()) == ("x", "y")
Пример #18
0
def parse_arg(f, kwd, offset=0):
    """
    convert dictionary of keyword argument and value to positional argument
    equivalent to::

        vnames = describe(f)
        return tuple([kwd[k] for k in vnames[offset:]])

    """
    vnames = describe(f)
    return tuple([kwd[k] for k in vnames[offset:]])
Пример #19
0
def parse_arg(f, kwd, offset=0):
    """
    convert dictionary of keyword argument and value to positional argument
    equivalent to::

        vnames = describe(f)
        return tuple([kwd[k] for k in vnames[offset:]])

    """
    vnames = describe(f)
    return tuple([kwd[k] for k in vnames[offset:]])
Пример #20
0
def test_generic_functor_with_fake_func():
    class A:
        def __init__(self):
            self.func_code = make_func_code(["x", "y"])

        def __call__(self, *args):
            # body is important
            a = 1
            b = 2
            return a + b

    assert describe(A(), True) == ["x", "y"]
Пример #21
0
def test_decorated_function():
    def dummy_decorator(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            return f(*args, **kwargs)

        return decorated

    @dummy_decorator
    def one_arg(x):
        pass

    @dummy_decorator
    def many_arg(x, y, z, t):
        pass

    @dummy_decorator
    def kw_only(x, *, y, z):
        pass

    assert describe(one_arg) == tuple("x")
    assert describe(many_arg) == tuple("xyzt")
    assert describe(kw_only) == tuple("xyz")
Пример #22
0
def test_make_with_signature():
    def f(a, b):
        return a + b

    f1 = util.make_with_signature(f, "x", "y")
    assert util.describe(f1) == ["x", "y"]
    assert f1(1, 2) == f(1, 2)
    f2 = util.make_with_signature(f, b="z")
    assert util.describe(f2) == ["a", "z"]
    assert f2(1, 2) == f(1, 2)
    assert f1 is not f2
    f3 = util.make_with_signature(f, "x", b="z")
    assert util.describe(f3) == ["x", "z"]
    assert f3(1, 2) == f(1, 2)

    # check that arguments are not overridden
    assert util.describe(f1) == ["x", "y"]
    assert util.describe(f) == ["a", "b"]

    with pytest.raises(ValueError):
        util.make_with_signature(f, "a", "b", "c")

    with pytest.raises(ValueError):
        util.make_with_signature(f, "a", "b", "c", b="z")
Пример #23
0
def test_fakefunc():
    f2 = Func2()
    assert describe(f2, True) == ['x', 'y']
Пример #24
0
def test_call():
    f1 = Func1()
    assert describe(f1, True) == ['x', 'y']
Пример #25
0
def test_functor():
    class A:
        def __call__(self, x, y):
            pass
    assert describe(A(), True) == ['x', 'y']
Пример #26
0
def test_lambda():
    assert describe(lambda a, b: 0, True) == ['a', 'b']
Пример #27
0
def test_fakefunc():
    f2 = Func2()
    assert_equal(describe(f2, True),['x','y'])
Пример #28
0
def test_builtin():
    assert describe(ldexp, True) == ['x', 'i']
Пример #29
0
def test_cython_class_method():
    cc = cyfunc.CyCallable()
    assert describe(cc.test, True) == ['c', 'd']
Пример #30
0
def test_generic_functor():
    class A:
        def __call__(self, *args):
            pass
    with pytest.raises(TypeError):
        describe(A(), True)
Пример #31
0
def test_call():
    f1 = Func1()
    assert describe(f1, True) == ['x', 'y']
Пример #32
0
def test_generic_class_method():
    class A:
        def f(self, *args):
            pass
    with pytest.raises(TypeError):
        describe(A().f, True)
Пример #33
0
def test_generic_lambda():
    with pytest.raises(TypeError):
        describe(lambda *args: 0, True)
Пример #34
0
def test_generic_function():
    def f(*args):
        pass
    with pytest.raises(TypeError):
        describe(f, True)
Пример #35
0
def test_builtin():
    assert describe(ldexp, True) == ['x', 'i']
Пример #36
0
def test_class_method():
    class A:
        def f(self, x, y):
            pass
    assert describe(A().f, True) == ['x', 'y']
Пример #37
0
def test_cython_embedsig():
    assert describe(cyfunc.f, True) == ['a', 'b']
Пример #38
0
def test_bound():
    a=A()
    assert_equal(describe(a.f, True),['x','y'])
Пример #39
0
def test_variadic():
    with pytest.raises(TypeError):
        describe(lambda *args: 0, True)
Пример #40
0
def test_builtin_by_parsing_doc():
    assert describe(ldexp, True) == ['x', 'i']
Пример #41
0
def test_call():
    f1 = Func1()
    assert_equal(describe(f1, True),['x','y'])
Пример #42
0
def entry():
    args = docopt(__doc__)
    files = args['<INPUT>']
    debug = args['--debug']

    max_events = convert_int(args['--max_events'])
    output_path = args['--output']

    if not os.path.exists(output_path):
        raise IOError('Path for output does not exists \n')

    pixel_id = convert_pixel_args(args['--pixel'])
    integral_width = int(args['--integral_width'])
    shift = int(args['--shift'])
    bin_width = int(args['--bin_width'])

    n_pixels = len(pixel_id)

    charge_histo_filename = os.path.join(output_path, 'charge_histo_fmpe.pk')
    amplitude_histo_filename = os.path.join(output_path,
                                            'amplitude_histo_fmpe.pk')
    results_filename = os.path.join(output_path, 'fmpe_fit_results.fits')
    timing_filename = args['--timing']
    n_samples = int(args['--n_samples'])
    ncall = int(args['--ncall'])
    estimated_gain = float(args['--estimated_gain'])

    if args['--compute']:
        compute(files,
                max_events=max_events,
                pixel_id=pixel_id,
                n_samples=n_samples,
                timing_filename=timing_filename,
                charge_histo_filename=charge_histo_filename,
                amplitude_histo_filename=amplitude_histo_filename,
                save=True,
                integral_width=integral_width,
                shift=shift,
                bin_width=bin_width)

    if args['--fit']:

        charge_histo = Histogram1D.load(charge_histo_filename)

        param_names = describe(FMPEFitter.pdf)[2:]
        param_error_names = [key + '_error' for key in param_names]
        columns = param_names + param_error_names
        columns = columns + ['chi_2', 'ndf']
        data = np.zeros((n_pixels, len(columns))) * np.nan

        results = pd.DataFrame(data=data, columns=columns)

        for i, pixel in tqdm(enumerate(pixel_id), total=n_pixels,
                             desc='Pixel'):
            histo = charge_histo[i]

            try:

                fitter = FMPEFitter(histo,
                                    estimated_gain=estimated_gain,
                                    throw_nan=True)
                fitter.fit(ncall=ncall)

                fitter = FMPEFitter(histo,
                                    estimated_gain=estimated_gain,
                                    initial_parameters=fitter.parameters,
                                    throw_nan=True)
                fitter.fit(ncall=ncall)

                param = dict(fitter.parameters)
                param_error = dict(fitter.errors)
                param_error = {
                    key + '_error': val
                    for key, val in param_error.items()
                }

                param.update(param_error)
                param['chi_2'] = fitter.fit_test() * fitter.ndf
                param['ndf'] = fitter.ndf
                results.iloc[pixel] = param

                if debug:
                    x_label = 'Charge [LSB]'
                    label = 'Pixel {}'.format(pixel)

                    fitter.draw(x_label=x_label, label=label, legend=False)
                    fitter.draw_fit(x_label=x_label, label=label, legend=False)
                    fitter.draw_init(x_label=x_label,
                                     label=label,
                                     legend=False)

                    print(results.iloc[pixel])

                    plt.show()

            except Exception as exception:

                print('Could not fit FMPE in pixel {}'.format(pixel))
                print(exception)

        if not debug:

            with fitsio.FITS(results_filename, 'rw') as f:

                f.write(results.to_records(index=False))

    if args['--save_figures']:

        charge_histo = Histogram1D.load(charge_histo_filename)

        figure_path = os.path.join(output_path, 'figures/')

        if not os.path.exists(figure_path):
            os.makedirs(figure_path)

        plot_results(results_filename, figure_path)

        for i, pixel in tqdm(enumerate(pixel_id), total=len(pixel_id)):

            try:

                plot_fit(charge_histo, results_filename, i, figure_path)

                plt.close()

            except Exception as e:

                print('Could not save pixel {} to : {} \n'.format(
                    pixel, figure_path))
                print(e)

    if args['--display']:

        pixel = 0
        charge_histo = Histogram1D.load(charge_histo_filename)

        plot_results(results_filename)
        plot_fit(charge_histo, results_filename, pixel=pixel)

        plt.show()

        pass

    return
Пример #43
0
def test_simple():
    assert_equal(describe(f, True), ['x','y'])
Пример #44
0
def test_bound():
    a = A()
    assert describe(a.f, True) == ['x', 'y']
Пример #45
0
def test_builtin():
    assert_equal(describe(min),['iterable','key'])
Пример #46
0
def test_cython_embedsig():
    assert_equal(describe(cyfunc.f, True),['a','b'])
Пример #47
0
def test_unbound():
    assert_equal(describe(A.f, True),['self','x','y'])
Пример #48
0
def test_class_unbound_method():
    class A:
        def f(self, x, y):
            pass
    assert describe(A.f, True) == ['self', 'x', 'y']
Пример #49
0
def test_simple():
    assert describe(f, True) == ['x', 'y']
Пример #50
0
def test_bound():
    a = A()
    assert describe(a.f, True) == ['x', 'y']
Пример #51
0
def test_simple():
    assert describe(f, True) == ['x', 'y']
Пример #52
0
def test_unbound():
    assert describe(A.f, True) == ['self', 'x', 'y']
Пример #53
0
def test_unbound():
    assert describe(A.f, True) == ['self', 'x', 'y']
Пример #54
0
def test_builtin():
    assert_equal(describe(ldexp, True),['x','i'])
Пример #55
0
def test_fakefunc():
    f2 = Func2()
    assert describe(f2, True) == ['x', 'y']
Пример #56
0
def test_cython_embedsig():
    import pyximport
    pyximport.install()
    from . import cyfunc
    assert describe(cyfunc.f, True) == ['a', 'b']
Пример #57
0
def test_lambda():
    assert describe(lambda a, b: 0, True) == ['a', 'b']
Пример #58
0
def test_function():
    def f(x, y):
        pass
    assert describe(f, True) == ['x', 'y']
Пример #59
0
 def __init__(self, model, x, y):
     self.model = model  # model predicts y for given x
     self.x = np.array(x)
     self.y = np.array(y)
     self.y_err = custom_errors(self.y)
     self.func_code = make_func_code(describe(self.model)[1:])
Пример #60
0
def test_cython_class_method():
    import pyximport
    pyximport.install()
    from . import cyfunc
    cc = cyfunc.CyCallable()
    assert describe(cc.test, True) == ['c', 'd']