Ejemplo n.º 1
0
def test_directory():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x, y, N, base_dir='new_dir/')

    with pytest.raises(Exception):
        chi_plotter(N)

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x, y, N, base_dir='new_dir/', data_save=True)

    if os.path.isdir('new_dir/Output_Signs/'):
        shutil.rmtree('new_dir/Output_Signs/')

    with pytest.raises(Exception):
        chi_plotter(N, base_dir='new_dir/')
Ejemplo n.º 2
0
def test_ifp():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 10

    sol = smooth(x,
                 y,
                 N,
                 zero_crossings=[4, 5, 6],
                 constraints=1,
                 all_output=True)

    assert (len(sol.optimum_zc_dict) == 4)
    assert (type(sol.optimum_zc_dict) is dict)

    sol = smooth(x,
                 y,
                 N,
                 zero_crossings=[4, 5, 6],
                 constraints=1,
                 all_output=True,
                 fit_type='qp')

    assert (len(sol.optimum_zc_dict) == 4)
    assert (type(sol.optimum_zc_dict) is dict)
Ejemplo n.º 3
0
def test_data_save():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    sol = smooth(x, y, N, data_save=True, base_dir='new_dir/')

    assert (os.path.exists('new_dir/') is True)
    assert (os.path.exists('new_dir/Output_Parameters/') is True)
    assert (os.path.exists('new_dir/Output_Signs/') is True)
    assert (os.path.exists('new_dir/Output_Evaluation/') is True)
    assert (os.path.isfile('new_dir/Optimal_Results_qp-sign_flipping_4.txt') is
            True)
    assert (os.path.isfile('new_dir/Output_Parameters/4_qp-sign_flipping.txt')
            is True)
    assert (os.path.isfile('new_dir/Output_Signs/4_qp-sign_flipping.txt') is
            True)
    assert (os.path.isfile('new_dir/Output_Evaluation/4_qp-sign_flipping.txt')
            is True)

    sol = smooth(x, y, N, data_save=True, base_dir='new_dir/')
Ejemplo n.º 4
0
def test_files():

    Ndat = 100
    x = np.linspace(50, 150, Ndat)
    y = 5e7 * x**(-2.5)

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x,
           y,
           N,
           base_dir='new_dir/',
           data_save=True,
           model_type='log_polynomial')

    plot = chi_plotter(N, base_dir='new_dir/')

    assert (plot.chi is None)
    assert (plot.cap == ((2**(N - 2)) // N) + N)
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x, y, N, base_dir='new_dir/', data_save=True, fit_type='qp')

    plot = chi_plotter(N, base_dir='new_dir/', fit_type='qp')

    assert (plot.chi is None)
    assert (plot.cap == ((2**(N - 2)) // N) + N)
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)
Ejemplo n.º 5
0
def test_keywords():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x, y, N, base_dir='new_dir/', data_save=True)

    with pytest.raises(Exception):
        chi_plotter(N='Banana', base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N=3.3, base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, base_dir='new_dir')
    with pytest.raises(Exception):
        chi_plotter(N, base_dir=5)
    with pytest.raises(Exception):
        chi_plotter(N, color='pink', base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, constraints=4.3, base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, constraints=7, base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, zero_crossings=[3.3], base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, zero_crossings=[1], base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, zero_crossings='string', base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, fit_type='pink', base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, chi_squared_limit='banana', base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, cap=5.5, base_dir='new_dir/')
    with pytest.raises(Exception):
        chi_plotter(N, plot_limits='pink', base_dir='new_dir/')

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    with pytest.raises(Exception):
        chi_plotter(N, base_dir='new_dir/')
Ejemplo n.º 6
0
def test_loglog():

    Ndat = 100
    x = np.linspace(50, 150, Ndat)
    y = 5e7 * x**(-2.5)

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    sol = smooth(x, y, N, model_type='loglog_polynomial')

    param_plotter(sol.optimum_params,
                  sol.optimum_signs,
                  x,
                  y,
                  N,
                  samples=10,
                  base_dir='new_dir/',
                  model_type='loglog_polynomial',
                  data_plot=True,
                  center_plot=True)

    assert (os.path.exists('new_dir/Parameter_plot.pdf') is True)
Ejemplo n.º 7
0
def test_ifp():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 10

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    sol = smooth(x,
                 y,
                 N,
                 zero_crossings=[4, 5, 6],
                 constraints=1,
                 base_dir='new_dir/',
                 data_save=True)

    chi_plotter(N,
                base_dir='new_dir/',
                zero_crossings=[4, 5, 6],
                constraints=1)
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)
Ejemplo n.º 8
0
def test_files():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 6

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    res = smooth(x, y, N, zero_crossings=[4])

    param_plotter(res.optimum_params,
                  res.optimum_signs,
                  x,
                  y,
                  N,
                  base_dir='new_dir/',
                  samples=10,
                  zero_crossings=[4])

    assert (os.path.exists('new_dir/') is True)
    assert (os.path.exists('new_dir/Parameter_plot.pdf') is True)

    N = 10

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    res = smooth(x, y, N)

    param_plotter(res.optimum_params,
                  res.optimum_signs,
                  x,
                  y,
                  N,
                  base_dir='new_dir/',
                  samples=10,
                  gridlines=True)

    assert (os.path.exists('new_dir/') is True)
    assert (os.path.exists('new_dir/Parameter_plot.pdf') is True)
Ejemplo n.º 9
0
def test_smooth_fit():
    # Check parameters of smooth function are correct
    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 4
    sol = smooth(x, y, N, model_type='polynomial', all_output=True)

    assert_almost_equal(sol.optimum_params.T[0], [1, 1, 1, 1], decimal=3)

    for i in range(len(sol.derivatives)):
        assert (np.all(sol.derivatives[i] <= 1e-6)
                or np.all(sol.derivatives[i] >= -1e-6))

    sol = smooth(x,
                 y,
                 N,
                 model_type='polynomial',
                 fit_type='qp',
                 all_output=True)

    assert (sol.cap is None)
    assert_almost_equal(sol.optimum_params.T[0], [1, 1, 1, 1], decimal=3)

    for i in range(len(sol.derivatives)):
        assert (np.all(sol.derivatives[i] <= 1e-6)
                or np.all(sol.derivatives[i] >= -1e-6))

    with pytest.raises(Exception):
        sol = smooth(x, y, N, model_type='polynomial', cvxopt_maxiter=1)

    sol = smooth(x,
                 y,
                 N,
                 model_type='polynomial',
                 initial_params=[1] * N,
                 cap=100,
                 chi_squared_limit=1e4)

    assert (sol.cap == 100)
    assert_almost_equal(sol.optimum_params.T[0], [1, 1, 1, 1], decimal=3)
Ejemplo n.º 10
0
def test_output_directional_exp():

    Ndat = 100
    x = np.linspace(50, 150, Ndat)
    y = 5e7 * x**(-2.5)

    N = 10
    sol = smooth(x, y, N, model_type='legendre', all_output=True)

    assert_almost_equal(sol.optimum_chi, ((y - sol.y_fit)**2).sum())
Ejemplo n.º 11
0
        def fit(model_type):

            chi = []
            N_passed = []
            for i in range(len(self.N)):
                try:

                    result = smooth(self.x,
                                    self.y,
                                    self.N[i],
                                    model_type=model_type,
                                    fit_type=self.fit_type,
                                    pivot_point=self.pivot_point,
                                    constraints=self.constraints,
                                    cvxopt_maxiter=self.cvxopt_maxiter,
                                    zero_crossings=self.zero_crossings,
                                    cap=self.cap,
                                    chi_squared_limit=self.chi_squared_limit)

                    if model_type == 'loglog_polynomial':
                        chi.append(np.sum((self.y - result.y_fit)**2))
                    else:
                        chi.append(result.optimum_chi)
                    N_passed.append(self.N[i])
                except Exception:
                    print('Unable to fit with N = ' + str(self.N[i]) +
                          ' and ' + str(model_type) + '.')

            if chi != []:
                chi = np.array(chi)
                min_chi = chi.min()
                for i in range(len(chi)):
                    if chi[i] == chi.min():
                        best_N = self.N[i]
            else:
                chi = np.nan
                min_chi = np.nan
                N_passed = np.nan
                best_N = np.nan

            return chi, min_chi, N_passed, best_N
Ejemplo n.º 12
0
def test_limits():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 10

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    sol = smooth(x, y, N, base_dir='new_dir/', data_save=True)

    chi_plotter(N,
                base_dir='new_dir/',
                cap=10,
                chi_squared_limit=1e4,
                plot_limits=True)
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)
Ejemplo n.º 13
0
def test_api():
    # Check api
    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 4
    sol = smooth(x, y, N)
    # Check RMS/Chi/y_fit calculated/returned correctly
    assert_almost_equal(sol.rms, np.sqrt(np.sum((y - sol.y_fit)**2) / len(y)))
    assert_almost_equal(sol.optimum_chi, ((y - sol.y_fit)**2).sum())

    def model(x, N, params):
        y_sum = np.sum([params[i] * (x - x[len(x) // 2])**i for i in range(N)],
                       axis=0)
        return y_sum

    y_fit = model(x, N, sol.optimum_params)
    assert_almost_equal(sol.optimum_chi, ((y - y_fit)**2).sum())
    assert (len(sol.optimum_signs) == N - 2)
    assert (sol.derivatives.shape == (N - 2, len(y)))
Ejemplo n.º 14
0
        mth_order_derivative.append(mth_order_derivative_term)

    return mth_order_derivative


"""
With our functions and additional arguments defined we can pass these
to the ``maxsmooth`` smooth() function as is shown below. This overwrites the
built in DCF model but you are still able to modify the fit type i.e. testing all
available sign combinations or sampling them.
"""

result = smooth(x,
                y,
                N,
                basis_functions=basis_functions,
                model=model,
                derivatives=derivative,
                der_pres=derivative_pre,
                args=arguments)
"""
The output of the fit can be accessed as before,
"""

print('Objective Funtion Evaluations:\n', result.optimum_chi)
print('RMS:\n', result.rms)
print('Parameters:\n', result.optimum_params[2])
print('Fitted y:\n', result.y_fit)
print('Sign Combinations:\n', result.optimum_signs)
print('Derivatives:\n', result.derivatives)
Ejemplo n.º 15
0
def test_new_basis_without_args():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 4

    def basis_functions(x, y, pivot_point, N, *args):

        phi = np.empty([len(x), N])
        for h in range(len(x)):
            for i in range(N):
                phi[h, i] = (x[h])**i

        return phi

    def model(x, y, pivot_point, N, params, *args):

        y_sum = np.sum([params[i] * (x)**i for i in range(N)], axis=0)

        return y_sum

    def derivative(m, x, y, N, pivot_point, params, *args):
        mth_order_derivative = []
        for i in range(N):
            if i <= m - 1:
                mth_order_derivative.append([0] * len(x))
        for i in range(N - m):
            mth_order_derivative_term = np.math.factorial(m+i) / \
                np.math.factorial(i) * \
                params[int(m)+i]*(x)**i
            mth_order_derivative.append(mth_order_derivative_term)

        return mth_order_derivative

    def derivative_pre(m, x, y, N, pivot_point, *args):

        mth_order_derivative = []
        for i in range(N):
            if i <= m - 1:
                mth_order_derivative.append([0] * len(x))
        for i in range(N - m):
            mth_order_derivative_term = np.math.factorial(m+i) / \
                np.math.factorial(i) * \
                (x)**i
            mth_order_derivative.append(mth_order_derivative_term)

        return mth_order_derivative

    sol = smooth(x,
                 y,
                 N,
                 basis_functions=basis_functions,
                 model=model,
                 derivatives=derivative,
                 der_pres=derivative_pre)

    assert (sol.model_type == 'user_defined')
    assert_almost_equal(sol.rms, np.sqrt(np.sum((y - sol.y_fit)**2) / len(y)))
    assert_almost_equal(sol.optimum_chi, ((y - sol.y_fit)**2).sum())

    with pytest.raises(Exception):
        sol = smooth(x,
                     y,
                     N,
                     basis_functions=basis_functions,
                     model=None,
                     derivatives=derivative,
                     der_pres=derivative_pre)
Ejemplo n.º 16
0
def test_keywords():
    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 4

    with pytest.raises(Exception):
        sol = smooth(x, y, N, color='pink')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, base_dir='file')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, base_dir=5)
    with pytest.raises(Exception):
        sol = smooth(x, y, 5.5)
    with pytest.raises(Exception):
        sol = smooth(x, y, 'string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, fit_type='banana')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, model_type='pink')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, pivot_point='string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, pivot_point=5.5)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, pivot_point=len(x) + 10)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, cvxopt_maxiter='string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, cvxopt_maxiter=41.2)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, all_output=9)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, data_save='string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, constraints='string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, constraints=20)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, zero_crossings=[3.3])
    with pytest.raises(Exception):
        sol = smooth(x, y, N, zero_crossings=[1])
    with pytest.raises(Exception):
        sol = smooth(x, y, N, chi_squared_limit='string')
    with pytest.raises(Exception):
        sol = smooth(x, y, N, chi_squared_limit=[1, 2])
    with pytest.raises(Exception):
        sol = smooth(x, y, N, cap=5.5)
    with pytest.raises(Exception):
        sol = smooth(x, y, N, initial_params=[1] * (N + 10))
    with pytest.raises(Exception):
        sol = smooth(x, y, N, initial_params=['string'] * (N))
Ejemplo n.º 17
0
derivatives.

First you will need to import your data and fit this using ``maxsmooth`` as
was done in the simple example code.

"""

import numpy as np

x = np.load('Data/x.npy')
y = np.load('Data/y.npy')

from maxsmooth.DCF import smooth

N = 10
result = smooth(x, y, N, base_dir='examples/', data_save=True, fit_type='qp')
"""
Here we have used some additional keyword arguments for the 'smooth' fitting
function. 'data_save' ensures that the files containing the tested sign combinations
and the corresponding objective function evaluations exist in the base directory
which we have changed to 'base_dir='examples/''. These files are essential for
the plotting the :math:`{\chi^2}` distribution and are not saved by ``maxsmooth``
without 'data_save=True'. We have also set the 'fit_type' to 'qp' rather than the
default 'qp-sign_flipping'. This ensures that all of the available sign
combinations are tested rather than a sampled set giving us a full picture of the
distribution when we plot it. We have used the default DCF model to fit this data.

We can import the 'chi_plotter' like so,
"""

from maxsmooth.chidist_plotter import chi_plotter
Ejemplo n.º 18
0
    print('Objective Funtion Evaluations:\n', result.Optimum_chi)
    print('RMS:\n', result.rms)
    print('Parameters:\n', result.Optimum_params)
    print('Fitted y:\n', result.y_fit)
    print('Sign Combinations:\n', result.Optimum_signs)
    print('Derivatives:\n', result.derivatives)

    plt.plot(x, y - result.y_fit)
    plt.xlabel('x', fontsize=12)
    plt.ylabel(r'$\delta y$', fontsize=12)
    plt.tight_layout()
    plt.show()

"""

result = smooth(x, y, N)

print('Accessing Fit Attributes:')
print('Objective Funtion Evaluations:\n', result.optimum_chi)
print('RMS:\n', result.rms)
#print('Parameters:\n', result.Optimum_params)
#print('Fitted y:\n', result.y_fit)
print('Sign Combinations:\n', result.optimum_signs)
#print('Derivatives:\n', result.derivatives)

plt.plot(x, y - result.y_fit)
plt.xlabel('x', fontsize=12)
plt.ylabel(r'$\delta y$', fontsize=12)
plt.tight_layout()
plt.show()
"""
Ejemplo n.º 19
0
be used to identify correlations between the foreground parameters.
For more details on this see the ``maxsmooth`` paper.

We begin by importing and fitting the data as with the chi_plotter()
function illustrated above.
"""

import numpy as np

x = np.load('Data/x.npy')
y = np.load('Data/y.npy')

from maxsmooth.DCF import smooth

N = 5
result = smooth(x, y, N, base_dir='examples/', fit_type='qp')
"""
We have changed the order of the fit to 5 to illustrate that for
order :math:`{N \leq 5}` and fits with derivatives :math:`{m \geq 2}` constrained
the function will plot each region of the graph corresponding to
different sign functions in a different colourmap. If the constraints are
different or the order is greater than 5 then the viable regions will have
a single colourmap. Invalid regions are plotted as black shaded colourmaps
and the contour lines are contours of :math:`{\chi^2}`.

Specifically, invalid regions violate the condition

.. math::

  \pm_m \frac{\delta^m y}{\delta x^m} \leq 0
Ejemplo n.º 20
0
noise = np.random.normal(0,0.5,len(x))
y = 0.6+2*x+4*x**(3)+9*x**(4)+noise"""

x = np.loadtxt('x_data_for_comp.txt')
y = np.loadtxt('y_data_for_comp.txt')

N = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

# Testing all signs
times_qp = []
chi_qp = []
for i in range(len(N)):
    s = time.time()
    result = smooth(x,
                    y,
                    N[i],
                    model_type='normalised_polynomial',
                    fit_type='qp')
    e = time.time()
    times_qp.append(e - s)
    chi_qp.append(result.optimum_chi)

# Using the maxsmooth sign navigating algorithm
times_qpsf = []
chi_qpsf = []
for i in range(len(N)):
    s = time.time()
    result = smooth(x, y, N[i], model_type='normalised_polynomial')
    e = time.time()
    times_qpsf.append(e - s)
    chi_qpsf.append(result.optimum_chi)
Ejemplo n.º 21
0
def test_new_basis_without_args():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(-1, 1, Ndat)
    y = 1 + x + x**2 + x**3 + np.random.normal(0, 0.05, 100)

    N = 4

    def basis_functions(x, y, pivot_point, N, *args):

        phi = np.empty([len(x), N])
        for h in range(len(x)):
            for i in range(N):
                phi[h, i] = (x[h])**i

        return phi

    def model(x, y, pivot_point, N, params, *args):

        y_sum = np.sum([params[i] * (x)**i for i in range(N)], axis=0)

        return y_sum

    def derivative(m, x, y, N, pivot_point, params, *args):
        mth_order_derivative = []
        for i in range(N):
            if i <= m - 1:
                mth_order_derivative.append([0] * len(x))
        for i in range(N - m):
            mth_order_derivative_term = np.math.factorial(m+i) / \
                np.math.factorial(i) * \
                params[int(m)+i]*(x)**i
            mth_order_derivative.append(mth_order_derivative_term)

        return mth_order_derivative

    def derivative_pre(m, x, y, N, pivot_point, *args):

        mth_order_derivative = []
        for i in range(N):
            if i <= m - 1:
                mth_order_derivative.append([0] * len(x))
        for i in range(N - m):
            mth_order_derivative_term = np.math.factorial(m+i) / \
                np.math.factorial(i) * \
                (x)**i
            mth_order_derivative.append(mth_order_derivative_term)

        return mth_order_derivative

    sol = smooth(x,
                 y,
                 N,
                 basis_functions=basis_functions,
                 model=model,
                 derivatives=derivative,
                 der_pres=derivative_pre)

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    param_plotter(sol.optimum_params,
                  sol.optimum_signs,
                  x,
                  y,
                  N,
                  samples=10,
                  base_dir='new_dir/',
                  basis_functions=basis_functions,
                  model=model,
                  derivatives=derivative,
                  der_pres=derivative_pre)

    assert (os.path.exists('new_dir/') is True)
    assert (os.path.exists('new_dir/Parameter_plot.pdf') is True)

    with pytest.raises(Exception):
        param_plotter(sol.optimum_params,
                      sol.optimum_signs,
                      x,
                      y,
                      N,
                      samples=10,
                      base_dir='new_dir/',
                      basis_functions=basis_functions,
                      model=None,
                      derivatives=derivative,
                      der_pres=None)
Ejemplo n.º 22
0
def test_chi():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(50, 150, Ndat)
    y = 5e7 * x**(-2.5)

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x,
           y,
           N,
           base_dir='new_dir/',
           data_save=True,
           model_type='loglog_polynomial',
           fit_type='qp')

    def model(x, N, params):
        y_sum = 10**(np.sum([params[i] * np.log10(x)**i for i in range(N)],
                            axis=0))
        return y_sum

    parameters = np.loadtxt('new_dir/Output_Parameters/4_qp.txt')

    chi_out = []
    for i in range(len(parameters)):
        chi_out.append(np.sum((y - model(x, N, parameters[i]))**2))
    chi_out = np.array(chi_out)

    plot = chi_plotter(N, base_dir='new_dir/', chi=chi_out, fit_type='qp')

    assert (np.all(plot.chi == chi_out))
    assert (plot.chi_squared_limit == 2 * min(chi_out))
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    smooth(x,
           y,
           N,
           base_dir='new_dir/',
           data_save=True,
           model_type='loglog_polynomial')

    parameters = np.loadtxt('new_dir/Output_Parameters/4_qp-sign_flipping.txt')

    chi_out = []
    for i in range(len(parameters)):
        chi_out.append(np.sum((y - model(x, N, parameters[i]))**2))
    chi_out = np.array(chi_out)

    plot = chi_plotter(N, base_dir='new_dir/', chi=chi_out)

    assert (np.all(plot.chi == chi_out))
    assert (plot.chi_squared_limit == 2 * min(chi_out))
    assert (os.path.exists('new_dir/chi_distribution.pdf') is True)
Ejemplo n.º 23
0
def test_keywords():

    np.random.seed(0)

    Ndat = 100
    x = np.linspace(0, 1, Ndat)
    y = 1 + x + x**2 + x**3

    N = 4

    if os.path.isdir('new_dir/'):
        shutil.rmtree('new_dir/')

    res = smooth(x, y, N, base_dir='new_dir/', data_save=True)

    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      color='pink')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params, res.optimum_signs, x, y, 5.5)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      model_type='banana')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      pivot_point='string')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      pivot_point=len(x) + 10)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      base_dir=5)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      base_dir='string')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      constraints=3.3)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      constraints=20)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      zero_crossings=[3.3])
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      zero_crossings=[1])
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      samples=50.2)
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      width='string')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      warnings='string')
    with pytest.raises(Exception):
        param_plotter(res.optimum_params,
                      res.optimum_signs,
                      x,
                      y,
                      N,
                      gridlines=9)
Ejemplo n.º 24
0
plt.show()
"""
As already stated ``maxsmooth`` does not constrain the first derivative of the
DCF by default so we can go ahead and fit the data.

.. code:: bash

    from maxsmooth.DCF import smooth

    res = smooth(x, y, N)

"""

from maxsmooth.DCF import smooth

res = smooth(x, y, N)
"""
If we than plot the resultant residuals we will see that despite the data
having a turning point present we have recovered the Gaussian noise.

.. code:: bash

    plt.plot(x, y- res.y_fit, label='Recovered Noise')
    plt.plot(x, noise, label='Actual Noise')
    plt.ylabel(r'$\delta y$', fontsize=12)
    plt.xlabel('x', fontsize=12)
    plt.legend()
    plt.show()

"""