Beispiel #1
0
def setup():
    # load the data.
    DATASET_NAME = os.path.join(refnx.__path__[0],
                                'analysis',
                                'test',
                                'c_PLP0011859_q.txt')

    # load the data
    data = ReflectDataset(DATASET_NAME)

    # the materials we're using
    si = SLD(2.07, name='Si')
    sio2 = SLD(3.47, name='SiO2')
    film = SLD(2, name='film')
    d2o = SLD(6.36, name='d2o')

    structure = si | sio2(30, 3) | film(250, 3) | d2o(0, 3)
    structure[1].thick.setp(vary=True, bounds=(15., 50.))
    structure[1].rough.setp(vary=True, bounds=(1., 6.))
    structure[2].thick.setp(vary=True, bounds=(200, 300))
    structure[2].sld.real.setp(vary=True, bounds=(0.1, 3))
    structure[2].rough.setp(vary=True, bounds=(1, 6))

    model = ReflectModel(structure, bkg=9e-6, scale=1.)
    model.bkg.setp(vary=True, bounds=(1e-8, 1e-5))
    model.scale.setp(vary=True, bounds=(0.9, 1.1))
    model.threads = 1
    # fit on a logR scale, but use weighting
    objective = Objective(model, data, transform=Transform('logY'),
                          use_weights=True)

    return objective
Beispiel #2
0
    def test_parallel_objective(self):
        # check that a parallel objective works without issue
        # (it could be possible that parallel evaluation fails at a higher
        #  level in e.g. emcee or in scipy.optimize.differential_evolution)
        model = self.model361
        model.threads = 2

        objective = Objective(
            model,
            (self.qvals361, self.rvals361, self.evals361),
            transform=Transform("logY"),
        )
        p0 = np.array(objective.varying_parameters())
        cov = objective.covar()
        walkers = np.random.multivariate_normal(np.atleast_1d(p0),
                                                np.atleast_2d(cov),
                                                size=(100))
        map_logl = np.array(list(map(objective.logl, walkers)))
        map_chi2 = np.array(list(map(objective.chisqr, walkers)))

        wf = Wrapper_fn2(model.model, p0)
        map_mod = np.array(list(map(wf, walkers)))

        with MapWrapper(2) as g:
            mapw_mod = g(wf, walkers)
            mapw_logl = g(objective.logl, walkers)
            mapw_chi2 = g(objective.chisqr, walkers)
        assert_allclose(mapw_logl, map_logl)
        assert_allclose(mapw_chi2, map_chi2)
        assert_allclose(mapw_mod, map_mod)
Beispiel #3
0
 def _update_analysis_objects(self):
     use_weights = self.use_weights.value == 'Yes'
     self.objective = Objective(self.model,
                                self.dataset,
                                transform=self.transform,
                                use_weights=use_weights)
     self._curvefitter = None
Beispiel #4
0
    def setup(self):
        # Reproducible results!
        np.random.seed(123)

        m_true = -0.9594
        b_true = 4.294
        f_true = 0.534
        m_ls = -1.1040757010910947
        b_ls = 5.4405552502319505

        # Generate some synthetic data from the model.
        N = 50
        x = np.sort(10 * np.random.rand(N))
        y_err = 0.1 + 0.5 * np.random.rand(N)
        y = m_true * x + b_true
        y += np.abs(f_true * y) * np.random.randn(N)
        y += y_err * np.random.randn(N)

        data = Data1D(data=(x, y, y_err))

        p = Parameter(b_ls, 'b', vary=True, bounds=(-100, 100))
        p |= Parameter(m_ls, 'm', vary=True, bounds=(-100, 100))

        model = Model(p, fitfunc=line)
        self.objective = Objective(model, data)
        self.mcfitter = CurveFitter(self.objective)
        self.mcfitter_t = CurveFitter(self.objective, ntemps=20)

        self.mcfitter.initialise('prior')
        self.mcfitter_t.initialise('prior')
Beispiel #5
0
def NIST_runner(dataset, method='least_squares', chi_atol=1e-5,
                val_rtol=1e-2, err_rtol=5e-3):
    NIST_dataset = ReadNistData(dataset)
    x, y = (NIST_dataset['x'], NIST_dataset['y'])

    if dataset == 'Nelson':
        y = np.log(y)

    params = NIST_dataset['start']

    fitfunc = NIST_Models[dataset][0]
    model = Model(params, fitfunc)
    objective = Objective(model, (x, y))
    fitter = CurveFitter(objective)
    result = fitter.fit(method=method)

    assert_allclose(objective.chisqr(),
                    NIST_dataset['sum_squares'],
                    atol=chi_atol)

    certval = NIST_dataset['cert_values']
    assert_allclose(result.x, certval, rtol=val_rtol)

    if 'stderr' in result:
        certerr = NIST_dataset['cert_stderr']
        assert_allclose(result.stderr, certerr, rtol=err_rtol)
Beispiel #6
0
def NIST_runner(
    dataset,
    method="least_squares",
    chi_atol=1e-5,
    val_rtol=1e-2,
    err_rtol=6e-3,
):
    NIST_dataset = ReadNistData(dataset)
    x, y = (NIST_dataset["x"], NIST_dataset["y"])

    if dataset == "Nelson":
        y = np.log(y)

    params = NIST_dataset["start"]

    fitfunc = NIST_Models[dataset][0]
    model = Model(params, fitfunc)
    objective = Objective(model, (x, y))
    fitter = CurveFitter(objective)
    result = fitter.fit(method=method)

    assert_allclose(objective.chisqr(),
                    NIST_dataset["sum_squares"],
                    atol=chi_atol)

    certval = NIST_dataset["cert_values"]
    assert_allclose(result.x, certval, rtol=val_rtol)

    if "stderr" in result:
        certerr = NIST_dataset["cert_stderr"]
        assert_allclose(result.stderr, certerr, rtol=err_rtol)
    def setup_method(self):
        self.pth = os.path.dirname(os.path.abspath(__file__))

        self.si = SLD(2.07, name='Si')
        self.sio2 = SLD(3.47, name='SiO2')
        self.d2o = SLD(6.36, name='d2o')
        self.h2o = SLD(-0.56, name='h2o')
        self.cm3 = SLD(3.5, name='cm3')
        self.polymer = SLD(2, name='polymer')

        self.sio2_l = self.sio2(40, 3)
        self.polymer_l = self.polymer(200, 3)

        self.structure = (self.si | self.sio2_l | self.polymer_l
                          | self.d2o(0, 3))

        fname = os.path.join(self.pth, 'c_PLP0011859_q.txt')

        self.dataset = ReflectDataset(fname)
        self.model = ReflectModel(self.structure, bkg=2e-7)
        self.objective = Objective(self.model,
                                   self.dataset,
                                   use_weights=False,
                                   transform=Transform('logY'))
        self.global_objective = GlobalObjective([self.objective])
Beispiel #8
0
    def setup(self):
        pth = os.path.dirname(os.path.abspath(refnx.reflect.__file__))
        e361 = RD(os.path.join(pth, 'test', 'e361r.txt'))

        sio2 = SLD(3.47, name='SiO2')
        si = SLD(2.07, name='Si')
        d2o = SLD(6.36, name='D2O')
        polymer = SLD(1, name='polymer')

        # e361 is an older dataset, but well characterised
        structure361 = si | sio2(10, 4) | polymer(200, 3) | d2o(0, 3)
        model361 = ReflectModel(structure361, bkg=2e-5)

        model361.scale.vary = True
        model361.bkg.vary = True
        model361.scale.range(0.1, 2)
        model361.bkg.range(0, 5e-5)
        model361.dq = 5.

        # d2o
        structure361[-1].sld.real.vary = True
        structure361[-1].sld.real.range(6, 6.36)

        structure361[1].thick.vary = True
        structure361[1].thick.range(5, 20)
        structure361[2].thick.vary = True
        structure361[2].thick.range(100, 220)

        structure361[2].sld.real.vary = True
        structure361[2].sld.real.range(0.2, 1.5)

        e361.x_err = None
        objective = Objective(model361, e361)
        self.fitter = CurveFitter(objective, nwalkers=200)
        self.fitter.initialise('jitter')
Beispiel #9
0
 def test_reflectivity_fit(self):
     # a smoke test to make sure the reflectivity fit proceeds
     model = self.model361
     objective = Objective(model,
                           (self.qvals361, self.rvals361, self.evals361),
                           transform=Transform('logY'))
     fitter = CurveFitter(objective)
     with np.errstate(invalid='raise'):
         fitter.fit('differential_evolution')
Beispiel #10
0
    def test_residuals(self):
        # weighted, with and without transform
        assert_almost_equal(self.objective.residuals(),
                            (self.data.y - self.mod) / self.data.y_err)

        objective = Objective(self.model, self.data,
                              transform=Transform('lin'))
        assert_almost_equal(objective.residuals(),
                            (self.data.y - self.mod) / self.data.y_err)

        # unweighted, with and without transform
        objective = Objective(self.model, self.data, use_weights=False)
        assert_almost_equal(objective.residuals(),
                            self.data.y - self.mod)

        objective = Objective(self.model, self.data, use_weights=False,
                              transform=Transform('lin'))
        assert_almost_equal(objective.residuals(),
                            self.data.y - self.mod)
Beispiel #11
0
    def setup_method(self, tmpdir):
        self.path = os.path.dirname(os.path.abspath(__file__))
        self.tmpdir = tmpdir.strpath

        theoretical = np.loadtxt(os.path.join(self.path, "gauss_data.txt"))
        xvals, yvals, evals = np.hsplit(theoretical, 3)
        xvals = xvals.flatten()
        yvals = yvals.flatten()
        evals = evals.flatten()

        # these best weighted values and uncertainties obtained with Igor
        self.best_weighted = [-0.00246095, 19.5299, -8.28446e-2, 1.24692]

        self.best_weighted_errors = [
            0.0220313708486,
            1.12879436221,
            0.0447659158681,
            0.0412022938883,
        ]

        self.best_weighted_chisqr = 77.6040960351

        self.best_unweighted = [
            -0.10584111872702096,
            19.240347049328989,
            0.0092623066070940396,
            1.501362314145845,
        ]

        self.best_unweighted_errors = [
            0.34246565477,
            0.689820935208,
            0.0411243173041,
            0.0693429375282,
        ]

        self.best_unweighted_chisqr = 497.102084956

        self.p0 = np.array([0.1, 20.0, 0.1, 0.1])
        self.names = ["bkg", "A", "x0", "width"]
        self.bounds = [(-1, 1), (0, 30), (-5.0, 5.0), (0.001, 2)]

        self.params = Parameters(name="gauss_params")
        for p, name, bound in zip(self.p0, self.names, self.bounds):
            param = Parameter(p, name=name)
            param.range(*bound)
            param.vary = True
            self.params.append(param)

        self.model = Model(self.params, fitfunc=gauss)
        self.data = Data1D((xvals, yvals, evals))
        self.objective = Objective(self.model, self.data)
        return 0
Beispiel #12
0
def test_run():
    print("\n\n\n")
    from refnx.dataset import Data1D
    from refnx.dataset import ReflectDataset
    import refnx
    import data_in
    data = data_in.data_in('d2o/29553_54.dat')
    # dataset = data # ...
    data = Data1D(data)
    from make_egg import bsla_thesis
    #     air = SLD(0)
    #     air = air(0,0)
    bt = bsla_thesis()
    bt.interface_protein_solvent.setp(vary=True, bounds=(11, 40))
    bt.protein_length.setp(vary=True, bounds=(25, 55))
    bt.number_of_water_molecules.setp(vary=True, bounds=(1, 10000))
    bt.interface_width_air_solvent.setp(vary=True, bounds=(0.001, 30))
    #bt.interface_width_protein_solvent.setp(vary=True, bounds=(0, 5))
    bt.sld_of_protein.setp(vary=True, bounds=(1.92, 6.21))  # *(10**(-6))
    bt.d2o_to_h2o_ratio.setp(vary=True, bounds=(0, 1))
    #     if isinstance(bt, Component):
    #         print("it is comp")
    #     if isinstance(bt, Structure):
    #         print("it is")
    #print(bt.parameters)
    #     d2o = 1.9185/0.3
    #     h2o = -0.1635/0.3
    #     solvent = SLD((bt.d2o_to_h2o_ratio.value*d2o + (1-bt.d2o_to_h2o_ratio.value)*h2o))
    #     solvent = solvent(0,0)
    #     from refnx.reflect import Structure
    #     structure = air|bt|solvent
    #     structure.name = "bsla"
    from refnx.reflect import ReflectModel
    model = ReflectModel(bt)  #structure)
    from refnx.analysis import Transform, CurveFitter, Objective
    objective = Objective(model, data)
    fitter = CurveFitter(objective)
    fitter.fit('differential_evolution')
    import matplotlib.pyplot as plt
    #%matplotlib notebook
    #     plt.plot(*bt.sld_profile())
    objective.plot()
    plt.yscale('log')
    plt.xscale('log')
    plt.xlabel('Q')
    plt.ylabel('Reflectivity')
    plt.legend()
    print(bt)
    plt.show()
Beispiel #13
0
    def test_code_fragment(self):
        e361 = ReflectDataset(os.path.join(self.pth, "e361r.txt"))

        si = SLD(2.07, name="Si")
        sio2 = SLD(3.47, name="SiO2")
        d2o = SLD(6.36, name="D2O")
        polymer = SLD(1, name="polymer")

        # e361 is an older dataset, but well characterised
        self.structure361 = si | sio2(10, 4) | polymer(200, 3) | d2o(0, 3)
        self.model361 = ReflectModel(self.structure361, bkg=2e-5)

        self.model361.scale.vary = True
        self.model361.bkg.vary = True
        self.model361.scale.range(0.1, 2)
        self.model361.bkg.range(0, 5e-5)

        # d2o
        self.structure361[-1].sld.real.vary = True
        self.structure361[-1].sld.real.range(6, 6.36)

        self.structure361[1].thick.vary = True
        self.structure361[1].thick.range(5, 20)

        self.structure361[2].thick.vary = True
        self.structure361[2].thick.range(100, 220)

        self.structure361[2].sld.real.vary = True
        self.structure361[2].sld.real.range(0.2, 1.5)

        objective = Objective(self.model361, e361, transform=Transform("logY"))
        objective2 = eval(repr(objective))
        assert_allclose(objective2.chisqr(), objective.chisqr())

        exec(repr(objective))
        exec(code_fragment(objective))

        # artificially link the two thicknesses together
        # check that we can reproduce the objective from the repr
        self.structure361[2].thick.constraint = self.structure361[1].thick
        fragment = code_fragment(objective)
        fragment = fragment + "\nobj = objective()\nresult = obj.chisqr()"
        d = {}
        # need to provide the globals dictionary to exec, so it can see imports
        # e.g. https://bit.ly/2RFOF7i (from stackoverflow)
        exec(fragment, globals(), d)
        assert_allclose(d["result"], objective.chisqr())
Beispiel #14
0
    def test_reflectivity_emcee(self):
        model = self.model361
        model.dq = 5.
        objective = Objective(model,
                              (self.qvals361, self.rvals361, self.evals361),
                              transform=Transform('logY'))
        fitter = CurveFitter(objective, nwalkers=100)

        assert_(len(objective.generative().shape) == 1)
        assert_(len(objective.residuals().shape) == 1)

        res = fitter.fit('least_squares')
        res_mcmc = fitter.sample(steps=5, nthin=10, random_state=1,
                                 verbose=False)

        mcmc_val = [mcmc_result.median for mcmc_result in res_mcmc]
        assert_allclose(mcmc_val, res.x, rtol=0.05)
Beispiel #15
0
    def test_resolution_speed_comparator(self):
        fname = os.path.join(self.pth, "c_PLP0011859_q.txt")
        dataset = ReflectDataset(fname)

        sio2 = SLD(3.47, name="SiO2")
        si = SLD(2.07, name="Si")
        d2o = SLD(6.36, name="D2O")
        polymer = SLD(2.0, name="polymer")

        sio2_l = sio2(30, 3)
        polymer_l = polymer(125, 3)

        dx = dataset.x_err
        structure = si | sio2_l | polymer_l | polymer_l | d2o(0, 3)
        model = ReflectModel(structure, bkg=2e-6, dq_type="constant")
        objective = Objective(model,
                              dataset,
                              use_weights=False,
                              transform=Transform("logY"))

        # check that choose_resolution_approach doesn't change state
        # of model
        fastest_method = choose_dq_type(objective)
        assert model.dq_type == "constant"
        assert_equal(dx, objective.data.x_err)

        # check that the comparison worked
        const_time = time.time()
        for i in range(1000):
            objective.generative()
        const_time = time.time() - const_time

        model.dq_type = "pointwise"
        point_time = time.time()
        for i in range(1000):
            objective.generative()
        point_time = time.time() - point_time

        if fastest_method == "pointwise":
            assert point_time < const_time
        elif fastest_method == "constant":
            assert const_time < point_time

        # check that we could use the function to setup a reflectmodel
        ReflectModel(structure, bkg=2e-6, dq_type=choose_dq_type(objective))
Beispiel #16
0
    def setup_method(self):
        # Choose the "true" parameters.

        # Reproducible results!
        np.random.seed(123)

        self.m_true = -0.9594
        self.b_true = 4.294
        self.f_true = 0.534
        self.m_ls = -1.1040757010910947
        self.b_ls = 5.4405552502319505

        # Generate some synthetic data from the model.
        N = 50
        x = np.sort(10 * np.random.rand(N))
        y_err = 0.1 + 0.5 * np.random.rand(N)
        y = self.m_true * x + self.b_true
        y += np.abs(self.f_true * y) * np.random.randn(N)
        y += y_err * np.random.randn(N)

        self.data = Data1D(data=(x, y, y_err))

        self.p = Parameter(self.b_ls, 'b') | Parameter(self.m_ls, 'm')
        self.model = Model(self.p, fitfunc=line)
        self.objective = Objective(self.model, self.data)

        # want b and m
        self.p[0].vary = True
        self.p[1].vary = True

        mod = np.array([4.78166609, 4.42364699, 4.16404064, 3.50343504,
                        3.4257084, 2.93594347, 2.92035638, 2.67533842,
                        2.28136038, 2.19772983, 1.99295496, 1.93748334,
                        1.87484436, 1.65161016, 1.44613461, 1.11128101,
                        1.04584535, 0.86055984, 0.76913963, 0.73906649,
                        0.73331407, 0.68350418, 0.65216599, 0.59838566,
                        0.13070299, 0.10749131, -0.01010195, -0.10010155,
                        -0.29495372, -0.42817431, -0.43122391, -0.64637715,
                        -1.30560686, -1.32626428, -1.44835768, -1.52589881,
                        -1.56371158, -2.12048349, -2.24899179, -2.50292682,
                        -2.53576659, -2.55797996, -2.60870542, -2.7074727,
                        -3.93781479, -4.12415366, -4.42313742, -4.98368609,
                        -5.38782395, -5.44077086])
        self.mod = mod
Beispiel #17
0
    def test_modelvals_degenerate_layers(self):
        # try fitting dataset with a deposited layer split into two degenerate
        # layers
        fname = os.path.join(self.pth, "c_PLP0011859_q.txt")
        dataset = ReflectDataset(fname)

        sio2 = SLD(3.47, name="SiO2")
        si = SLD(2.07, name="Si")
        d2o = SLD(6.36, name="D2O")
        polymer = SLD(2.0, name="polymer")

        sio2_l = sio2(30, 3)
        polymer_l = polymer(125, 3)

        structure = si | sio2_l | polymer_l | polymer_l | d2o(0, 3)

        polymer_l.thick.setp(value=125, vary=True, bounds=(0, 250))
        polymer_l.rough.setp(value=4, vary=True, bounds=(0, 8))
        structure[-1].rough.setp(vary=True, bounds=(0, 6))
        sio2_l.rough.setp(value=3.16, vary=True, bounds=(0, 8))

        model = ReflectModel(structure, bkg=2e-6)
        objective = Objective(model,
                              dataset,
                              use_weights=False,
                              transform=Transform("logY"))

        model.scale.setp(vary=True, bounds=(0, 2))
        model.bkg.setp(vary=True, bounds=(0, 8e-6))

        slabs = structure.slabs()
        assert_equal(slabs[2, 0:2], slabs[3, 0:2])
        assert_equal(slabs[2, 3], slabs[3, 3])
        assert_equal(slabs[1, 3], sio2_l.rough.value)

        f = CurveFitter(objective)
        f.fit(method="differential_evolution", seed=1, maxiter=3)

        slabs = structure.slabs()
        assert_equal(slabs[2, 0:2], slabs[3, 0:2])
        assert_equal(slabs[2, 3], slabs[3, 3])
Beispiel #18
0
    def __init__(self, file_path, layers, predicted_slds, predicted_depths, xray):
        """Initialises the Model class by creating a refnx model with given predicted values.

        Args:
            file_path (string): a path to the file with the data to construct the model for.
            layers (int): the number of layers for the model predicted by the classifier.
            predicted_slds (ndarray): an array of predicted SLDs for each layer.
            predicted_depths (ndarray): an array of predicted depths for each layer.
            xray (Boolean): whether the model should use a neutron or x-ray probe.

        """
        self.structure = SLD(0, name='Air') #Model starts with air.

        if xray: #Use x-ray probe
            for i in range(layers):
                density = predicted_slds[i] / XRayGenerator.density_constant
                SLD_layer = MaterialSLD(XRayGenerator.material, density, probe='x-ray', wavelength=XRayGenerator.wavelength, name='Layer {}'.format(i+1))
                layer = SLD_layer(thick=predicted_depths[i], rough=Model.roughness)
                layer.density.setp(bounds=XRayGenerator.density_bounds, vary=True)
                layer.thick.setp(bounds=ImageGenerator.depth_bounds, vary=True)
                layer.rough.setp(bounds=Model.rough_bounds, vary=True)
                self.structure = self.structure | layer  #Next comes each layer.
            #Then substrate
            si_substrate = MaterialSLD(XRayGenerator.material, XRayGenerator.substrate_density, probe='x-ray', name='Si Substrate')(thick=0, rough=Model.roughness)

        else: #Use neutron probe
            for i in range(layers):
                layer = SLD(predicted_slds[i], name='Layer {}'.format(i+1))(thick=predicted_depths[i], rough=Model.roughness)
                layer.sld.real.setp(bounds=ImageGenerator.sld_neutron_bounds, vary=True)
                layer.thick.setp(bounds=ImageGenerator.depth_bounds, vary=True)
                layer.rough.setp(bounds=Model.rough_bounds, vary=True)
                self.structure = self.structure | layer  #Next comes each layer.
            #Then substrate
            si_substrate = SLD(Model.si_sld, name='Si Substrate')(thick=0, rough=Model.roughness)

        si_substrate.rough.setp(bounds=Model.rough_bounds, vary=True)
        self.structure = self.structure | si_substrate

        data = self.__load_data(file_path) #Pre-process and load given dataset.
        self.model = ReflectModel(self.structure, scale=Model.scale, dq=Model.dq, bkg=Model.bkg)
        self.objective = Objective(self.model, data)
Beispiel #19
0
def make_model(names, bs, thicks, roughs, fig_i, data, show=False, mcmc=False):
    no_layers = len(bs)
    layers = []
    for i in range(no_layers):
        names.append('layer' + str(i))

    for i in range(no_layers):
        sld = SLD(bs[i], name=names[i])
        layers.append(sld(thicks[i], roughs[i]))

    layers[0].thick.setp(vary=True, bounds=(thicks[i] - 1, thicks[i] + 1))
    layers[0].sld.real.setp(vary=True, bounds=(bs[i] - 1, bs[i] + 1))

    for layer in layers[1:]:
        layer.thick.setp(vary=True, bounds=(thicks[i] - 1, thicks[i] + 1))
        layer.sld.real.setp(vary=True, bounds=(bs[i] - 1, bs[i] + 1))
        layer.rough.setp(vary=True, bounds=(0, 5))

    structure = layers[0]
    for layer in layers[1:]:
        structure |= layer
    print(structure)
    model = ReflectModel(structure, bkg=3e-6, dq=5.0)
    #model.scale.setp(bounds=(0.6, 1.2), vary=True)
    #model.bkg.setp(bounds=(1e-9, 9e-6), vary=True)
    objective = Objective(model, data, transform=Transform('logY'))
    fitter = CurveFitter(objective)
    if mcmc:
        fitter.sample(1000)
        process_chain(objective, fitter.chain, nburn=300, nthin=100)
    else:
        fitter.fit('differential_evolution')
    print(objective.parameters)

    if show:
        plt.figure(fig_i)
        plt.plot(*structure.sld_profile())
        plt.ylabel('SLD /$10^{-6} \AA^{-2}$')
        plt.xlabel('distance / $\AA$')
    return structure, fitter, objective, fig_i + 1
Beispiel #20
0
def make_model(names, bs, thicks, roughs, fig_i, data, show=False, mcmc=False):
    extent = sum(
        thicks[:, 0])  # (float or Parameter) – Total extent of spline region
    vs = array(
        bs
    )[:,
      0]  #(Sequence of float/Parameter) – the real part of the SLD values of each of the knots.
    dz = cum_sum(
        array(thicks[:, 0])
    )  #(Sequence of float/Parameter) – the lateral offset between successive knots.
    print(dz)
    name = "number of nots " + str(len(names))  #(str) – Name of component
    component = Spline(extent, vs, dz, name)
    front = SLD(0)
    front = front(0, 0)
    back = SLD(0)
    back = back(0, 0)
    structure = front | component | back
    model = ReflectModel(structure, bkg=3e-6, dq=5.0)
    objective = Objective(model, data, transform=Transform('logY'))
    fitter = CurveFitter(objective)
    fitter.fit('differential_evolution')
    return structure, fitter, objective, fig_i + 1
Beispiel #21
0
    def test_multidimensionality(self):
        # Check that ND data can be used with an objective/model/data
        # (or at least it doesn't stand in the way)
        rng = np.random.default_rng()
        x = rng.uniform(size=100).reshape(50, 2)

        desired = line_ND(x, self.p)
        assert desired.shape == (50, 2)
        data = Data1D((x, desired))

        model = Model(self.p, fitfunc=line_ND)
        y = model(x)
        assert_allclose(y, desired)

        objective = Objective(model, data)
        assert_allclose(objective.chisqr(), 0)
        assert_allclose(objective.generative(), desired)
        assert_allclose(objective.residuals(), 0)
        assert objective.residuals().shape == (50, 2)

        objective.logl()
        objective.logpost()
        covar = objective.covar()
        assert covar.shape == (2, 2)
Beispiel #22
0
lipid_2.thick_heads.constraint = lipid_1.thick_heads
structure_lipid_2[-1].rough.constraint = structure_lipid_1[-1].rough

model_lipid1 = ReflectModel(structure_lipid_1)
model_lipid1.scale.setp(vary=True, bounds=(0.005, 10))
model_lipid1.bkg.setp(dataset1.y[-2], vary=False)

model_lipid2 = ReflectModel(structure_lipid_2)
model_lipid2.scale.setp(vary=True, bounds=(0.005, 10))
model_lipid2.bkg.setp(dataset2.y[-2], vary=False)

models = [model_lipid1, model_lipid2]
structures = [structure_lipid_1, structure_lipid_2]

# building the global objective
objective_n1 = Objective(model_lipid1, dataset1, transform=Transform('YX4'))
objective_n2 = Objective(model_lipid2, dataset2, transform=Transform('YX4'))

global_objective = GlobalObjective([objective_n1, objective_n2])

# The chain is read in by refnx, and processed to assigned it to the global objective.

# In[ ]:

chain = refnx.analysis.load_chain('{}/{}/{}_chain_neutron.txt'.format(
    analysis_dir, lipid, sp))

processed_chain = refnx.analysis.process_chain(global_objective, chain)

# The global objective is printed to check it is accurate.
Beispiel #23
0
    hold_phih=True,
)

models = []
t = len(cont)

for i in range(t):
    models.append(ReflectModel(structures[i]))
    models[i].scale.setp(vary=True, bounds=(0.005, 10))
    models[i].bkg.setp(datasets[i].y[-1], vary=True, bounds=(1e-4, 1e-10))

objectives = []
t = len(cont)
for i in range(t):
    objectives.append(
        Objective(models[i], datasets[i], transform=Transform("YX4")))

global_objective = GlobalObjective(objectives)

chain = refnx.analysis.load_chain("{}_chain.txt".format(anal_dir))

pchain = refnx.analysis.process_chain(global_objective, chain)

para_labels = [
    '_scale_{}_{}'.format(sp, cont[0]), '_bkg_{}_{}'.format(sp, cont[0]),
    '-d_h_{}'.format(sp), '-d_t_{}'.format(sp), '_rough_{}'.format(sp),
    '_scale_{}_{}'.format(sp, cont[1]), '_bkg_{}_{}'.format(sp, cont[1]),
    '_scale_{}_{}'.format(sp, cont[2]), '_bkg_{}_{}'.format(sp, cont[2]),
    '_scale_{}_{}'.format(sp, cont[3]), '_bkg_{}_{}'.format(sp, cont[3]),
    '_scale_{}_{}'.format(sp, cont[4]), '_bkg_{}_{}'.format(sp, cont[4]),
    '_scale_{}_{}'.format(sp, cont[5]), '_bkg_{}_{}'.format(sp, cont[5]),
    def test_multipledataset_corefinement(self):
        # test corefinement of three datasets
        data361 = ReflectDataset(os.path.join(self.pth, 'e361r.txt'))
        data365 = ReflectDataset(os.path.join(self.pth, 'e365r.txt'))
        data366 = ReflectDataset(os.path.join(self.pth, 'e366r.txt'))

        si = SLD(2.07, name='Si')
        sio2 = SLD(3.47, name='SiO2')
        d2o = SLD(6.36, name='d2o')
        h2o = SLD(-0.56, name='h2o')
        cm3 = SLD(3.47, name='cm3')
        polymer = SLD(1, name='polymer')

        structure361 = si | sio2(10, 4) | polymer(200, 3) | d2o(0, 3)
        structure365 = si | structure361[1] | structure361[2] | cm3(0, 3)
        structure366 = si | structure361[1] | structure361[2] | h2o(0, 3)

        structure365[-1].rough = structure361[-1].rough
        structure366[-1].rough = structure361[-1].rough

        structure361[1].thick.setp(vary=True, bounds=(0, 20))
        structure361[2].thick.setp(value=200., bounds=(200., 250.), vary=True)
        structure361[2].sld.real.setp(vary=True, bounds=(0, 2))
        structure361[2].vfsolv.setp(value=5., bounds=(0., 100.), vary=True)

        model361 = ReflectModel(structure361, bkg=2e-5)
        model365 = ReflectModel(structure365, bkg=2e-5)
        model366 = ReflectModel(structure366, bkg=2e-5)

        model361.bkg.setp(vary=True, bounds=(1e-6, 5e-5))
        model365.bkg.setp(vary=True, bounds=(1e-6, 5e-5))
        model366.bkg.setp(vary=True, bounds=(1e-6, 5e-5))

        objective361 = Objective(model361, data361)
        objective365 = Objective(model365, data365)
        objective366 = Objective(model366, data366)

        global_objective = GlobalObjective(
            [objective361, objective365, objective366])
        # are the right numbers of parameters varying?
        assert_equal(len(global_objective.varying_parameters()), 7)

        # can we set the parameters?
        global_objective.setp(np.array([1e-5, 10, 212, 1, 10, 1e-5, 1e-5]))

        f = CurveFitter(global_objective)
        f.fit()

        indiv_chisqr = np.sum(
            [objective.chisqr() for objective in global_objective.objectives])

        # the overall chi2 should be sum of individual chi2
        global_chisqr = global_objective.chisqr()
        assert_almost_equal(global_chisqr, indiv_chisqr)

        # now check that the parameters were held in common correctly.
        slabs361 = structure361.slabs()
        slabs365 = structure365.slabs()
        slabs366 = structure366.slabs()

        assert_equal(slabs365[0:2, 0:5], slabs361[0:2, 0:5])
        assert_equal(slabs366[0:2, 0:5], slabs361[0:2, 0:5])
        assert_equal(slabs365[-1, 3], slabs361[-1, 3])
        assert_equal(slabs366[-1, 3], slabs361[-1, 3])

        # check that the residuals are the correct lengths
        res361 = objective361.residuals()
        res365 = objective365.residuals()
        res366 = objective366.residuals()
        res_global = global_objective.residuals()
        assert_allclose(res_global[0:len(res361)], res361, rtol=1e-5)
        assert_allclose(res_global[len(res361):len(res361) + len(res365)],
                        res365,
                        rtol=1e-5)
        assert_allclose(res_global[len(res361) + len(res365):],
                        res366,
                        rtol=1e-5)

        repr(global_objective)
Beispiel #25
0
    n = l.reshape(timesteps, sim.layers.shape[1]-layers_to_cut, sim.layers.shape[2])

    data_dir = '../data/reflectometry2/dspc_{}/'.format(surface_pressure)
    dataset = ReflectDataset(os.path.join(data_dir, '{}{}.dat'.format(contrast, surface_pressure)))

    refy = np.zeros((n.shape[0], dataset.x.size))
    sldy = []
    chi = np.zeros((n.shape[0]))
    print(n.shape[0])
    for i in range(n.shape[0]):
        sim.av_layers = n[i, :, :]
        model = ReflectModel(sim)
        model.scale.setp(1, vary=True, bounds=(0.00000001, np.inf))
        model.bkg.setp(dataset.y[-1], vary=False)
        objective = Objective(model, dataset, transform=Transform('YX4'))
        fitter = CurveFitter(objective)
        res = fitter.fit()
        refy[i] = model(dataset.x, x_err=dataset.x_err)*(dataset.x)**4
        sldy.append(sim.sld_profile()[1])
        chi[i] = objective.chisqr()
        all_chi = np.append(all_chi, objective.chisqr())
        if i == 0:
            ax1.errorbar(dataset.x,
                         dataset.y*(dataset.x)**4 * 10**(ci-1),
                         yerr=dataset.y_err*(
                             dataset.x)**4 * 10**(ci-1),
                         linestyle='', marker='o',
                         color=sns.color_palette()[ci])
        if i % 5 == 0:
            ax1.plot(dataset.x,
model_lipid2 = ReflectModel(structure_lipid2)
model_lipid2.scale.setp(vary=True, bounds=(0.005, 10))
model_lipid2.bkg.setp(dataset2.y[-1], vary=False)

model_lipid3 = ReflectModel(structure_lipid3)
model_lipid3.scale.setp(vary=True, bounds=(0.005, 10))
model_lipid3.bkg.setp(dataset3.y[-1], vary=False)

model_lipid4 = ReflectModel(structure_lipid4)
model_lipid4.scale.setp(vary=True, bounds=(0.005, 10))
model_lipid4.bkg.setp(dataset4.y[-1], vary=False)

models = [model_lipid1, model_lipid2, model_lipid3, model_lipid4]

objective1 = Objective(model_lipid1, dataset1, transform=Transform('YX4'))
objective2 = Objective(model_lipid2, dataset2, transform=Transform('YX4'))
objective3 = Objective(model_lipid3, dataset3, transform=Transform('YX4'))
objective4 = Objective(model_lipid4, dataset4, transform=Transform('YX4'))

global_objective = GlobalObjective(
    [objective1, objective2, objective3, objective4])

# The chain is read in by refnx, and processed to assigned it to the global objective.

# In[8]:

chain = refnx.analysis.load_chain('{}/{}/chain.txt'.format(
    analysis_dir, lipid))

processed_chain = refnx.analysis.process_chain(global_objective, chain)
Beispiel #27
0
    def test_covar(self):
        # checks objective.covar against optimize.least_squares covariance.
        path = os.path.dirname(os.path.abspath(__file__))

        theoretical = np.loadtxt(os.path.join(path, 'gauss_data.txt'))
        xvals, yvals, evals = np.hsplit(theoretical, 3)
        xvals = xvals.flatten()
        yvals = yvals.flatten()
        evals = evals.flatten()

        p0 = np.array([0.1, 20., 0.1, 0.1])
        names = ['bkg', 'A', 'x0', 'width']
        bounds = [(-1, 1), (0, 30), (-5., 5.), (0.001, 2)]

        params = Parameters(name="gauss_params")
        for p, name, bound in zip(p0, names, bounds):
            param = Parameter(p, name=name)
            param.range(*bound)
            param.vary = True
            params.append(param)

        model = Model(params, fitfunc=gauss)
        data = Data1D((xvals, yvals, evals))
        objective = Objective(model, data)

        # first calculate least_squares jac/hess/covariance matrices
        res = least_squares(objective.residuals,
                            np.array(params),
                            jac='3-point')

        hess_least_squares = np.matmul(res.jac.T, res.jac)
        covar_least_squares = np.linalg.inv(hess_least_squares)

        # now calculate corresponding matrices by hand, to see if the approach
        # concurs with least_squares
        objective.setp(res.x)
        _pvals = np.array(res.x)

        def residuals_scaler(vals):
            return np.squeeze(objective.residuals(_pvals * vals))

        jac = approx_derivative(residuals_scaler, np.ones_like(_pvals))
        hess = np.matmul(jac.T, jac)
        covar = np.linalg.inv(hess)

        covar = covar * np.atleast_2d(_pvals) * np.atleast_2d(_pvals).T

        assert_allclose(covar, covar_least_squares)

        # check that objective.covar corresponds to the least_squares
        # covariance matrix
        objective.setp(res.x)
        _pvals = np.array(res.x)
        covar_objective = objective.covar()
        assert_allclose(covar_objective, covar_least_squares)

        # now see what happens with a parameter that has no effect on residuals
        param = Parameter(1.234, name='dummy')
        param.vary = True
        params.append(param)

        from pytest import raises
        with raises(LinAlgError):
            objective.covar()
Beispiel #28
0
d2o = SLD(6.36, name='d2o')

structure = si | sio2(30, 3) | film(250, 3) | d2o(0, 3)
structure[1].thick.setp(vary=True, bounds=(15., 50.))
structure[1].rough.setp(vary=True, bounds=(1., 6.))
structure[2].thick.setp(vary=True, bounds=(200, 300))
structure[2].sld.real.setp(vary=True, bounds=(0.1, 3))
structure[2].rough.setp(vary=True, bounds=(1, 6))

model = ReflectModel(structure, bkg=9e-6, scale=1.)
model.bkg.setp(vary=True, bounds=(1e-8, 1e-5))
model.scale.setp(vary=True, bounds=(0.9, 1.1))

# fit on a logR scale, but use weighting
objective = Objective(model,
                      data,
                      transform=Transform('logY'),
                      use_weights=True)

# create the fit instance
fitter = CurveFitter(objective)

# do the fit
res = fitter.fit(method='differential_evolution')

# see the fit results
print(objective)

fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax.scatter(data.x, data.y, label=DATASET_NAME)
ax.semilogy()
Beispiel #29
0
def getObjective(data, thicknesses, slds, layerNames, logpExtra=None):

    air = SLD(0, name="air layer")
    airSlab = air(10, 0)
    sio2 = SLD(10, name="bottem layer")
    sio2Slab = sio2(10, 0)

    #     print(" ... ",slds[0].startPoint)
    if len(layerNames) >= 1:
        i = 0
        sld1 = SLD(float(slds[i].startPoint), name=layerNames[i])
        sld1Slab = sld1(thicknesses[i].startPoint, thicknesses[i].roughness)
        sld1Slab.thick.setp(vary=thicknesses[i].vary,
                            bounds=(thicknesses[i].lower,
                                    thicknesses[i].upper))
        sld1Slab.sld.real.setp(vary=slds[i].vary,
                               bounds=(slds[i].lower, slds[i].upper))
    else:
        print(layerNames, " : variable 'layerNames' is empty")

    if len(layerNames) >= 2:
        i = 1
        sld2 = SLD(slds[i].startPoint, name=layerNames[i])
        sld2Slab = sld2(thicknesses[i].startPoint, thicknesses[i].roughness)
        sld2Slab.thick.setp(vary=thicknesses[i].vary,
                            bounds=(thicknesses[i].lower,
                                    thicknesses[i].upper))
        sld2Slab.sld.real.setp(vary=slds[i].vary,
                               bounds=(slds[i].lower, slds[i].upper))

    if len(layerNames) >= 3:
        i = 2
        sld3 = SLD(slds[i].startPoint, name=layerNames[i])
        sld3Slab = sld3(thicknesses[i].startPoint, thicknesses[i].roughness)
        sld3Slab.thick.setp(vary=thicknesses[i].vary,
                            bounds=(thicknesses[i].lower,
                                    thicknesses[i].upper))
        sld3Slab.sld.real.setp(vary=slds[i].vary,
                               bounds=(slds[i].lower, slds[i].upper))

    if len(layerNames) >= 4:
        i = 3
        sld4 = SLD(slds[i].startPoint, name=layerNames[i])
        sld4Slab = sld4(thicknesses[i].startPoint, thicknesses[i].roughness)
        sld4Slab.thick.setp(vary=thicknesses[i].vary,
                            bounds=(thicknesses[i].lower,
                                    thicknesses[i].upper))
        sld4Slab.sld.real.setp(vary=slds[i].vary,
                               bounds=(slds[i].lower, slds[i].upper))

    if len(layerNames) == 1:
        structure = airSlab | sld1Slab | sio2Slab
    if len(layerNames) == 2:
        structure = airSlab | sld1Slab | sld2Slab | sio2Slab
    if len(layerNames) == 3:
        structure = airSlab | sld1Slab | sld2Slab | sld3Slab | sio2Slab
    if len(layerNames) == 4:
        structure = airSlab | sld1Slab | sld2Slab | sld3Slab | sld4Slab | sio2Slab
    model = ReflectModel(structure, bkg=3e-6, dq=5.0)
    objective = Objective(model,
                          data,
                          transform=Transform('logY'),
                          logp_extra=logpExtra)
    return objective, structure
Beispiel #30
0
def getObjective(data, nLayers, bs_contrast_layer=None,
                 contrast_layer=None,
                 limits = None, doMCMC=False,
                 logpExtra=None, onlyStructure=False,
                 both=False, globalObjective=False):

    if globalObjective:
        if bs_contrast_layer is None:
            bs_contrast_layer = 6
        if contrast_layer is None:
            contrast_layer = 1
#         print("data, nLayers, bs_contrast_layer=None,\n contrast_layer=None,\nlimits = None, doMCMC=False,\nlogpExtra=None, onlyStructure=False,\nboth=False, globalObjective=False: ",
#                      data, nLayers, bs_contrast_layer,
#                      contrast_layer,
#                      limits, doMCMC,
#                      logpExtra, onlyStructure,
#                      both, globalObjective)

    air = SLD(0,name="air layer")
    airSlab = air(10,0)

    sio2 = SLD(10,name="bottem layer")
    sio2Slab = sio2(10,0)


    if limits is None:
        limits = [350,50,4,6]
    
#     maxThick = 350
#     lowerThick = 50
#     upperThick = maxThick - nLayers*lowerThick
#     lowerB = 4
#     upperB = 6

    maxThick = float(limits[0])
    lowerThick = limits[1]
    upperThick = maxThick - nLayers*lowerThick
    lowerB = limits[2]
    upperB = limits[3]

    if globalObjective:
        thick_contrast_layer=Parameter(maxThick/nLayers,
                                        "layer1 thickness")
        rough_contrast_layer=Parameter(0,
                                    "layer0/contrast roughness")
        sldcontrastA=SLD(5,name="contrast A layer")
        sldcontrastASlab= sldcontrastA(thick_contrast_layer,rough_contrast_layer)
        sldcontrastASlab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sldcontrastASlab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

        sldcontrastB=SLD(5,name="contrast B layer")
        sldcontrastBSlab = sldcontrastB(thick_contrast_layer,rough_contrast_layer)
        sldcontrastBSlab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sldcontrastBSlab.sld.real.setp(vary=True, bounds=(lowerB,upperB))


    if nLayers>=1 and not globalObjective:
        sld1 = SLD(5,name="first layer")
        sld1Slab = sld1(maxThick/nLayers,0)
        sld1Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sld1Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

    if nLayers>=2:
        sld2 = SLD(5,name="second layer")
        sld2Slab = sld2(maxThick/nLayers,0)
        sld2Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sld2Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

    if nLayers>=3:
        sld3 = SLD(5,name="third layer")
        sld3Slab = sld3(maxThick/nLayers,0)
        sld3Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sld3Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

    if nLayers>=4:
        sld4 = SLD(5,name="forth layer")
        sld4Slab = sld4(maxThick/nLayers,0)
        sld4Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
        sld4Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

#     if nLayers>=1:
#         sld1Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
#         sld1Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

#     if nLayers>=2:
#         sld2Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
#         sld2Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

#     if nLayers>=3:
#         sld3Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
#         sld3Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

#     if nLayers>=4:
#         sld4Slab.thick.setp(vary=True, bounds=(lowerThick,upperThick))
#         sld4Slab.sld.real.setp(vary=True, bounds=(lowerB,upperB))

    if globalObjective and contrast_layer==1:
        if nLayers==1:
            structure1 = airSlab|sldcontrastASlab|sio2Slab
            structure2 = airSlab|sldcontrastBSlab|sio2Slab
        if nLayers==2:
            structure1 = airSlab|sldcontrastASlab|sld2Slab|sio2Slab
            structure2 = airSlab|sldcontrastBSlab|sld2Slab|sio2Slab
        if nLayers==3:
            structure1 = airSlab|sldcontrastASlab|sld2Slab|sld3Slab|sio2Slab
            structure2 = airSlab|sldcontrastBSlab|sld2Slab|sld3Slab|sio2Slab
        if nLayers==4:
            structure1 = airSlab|sldcontrastASlab|sld2Slab|sld3Slab|sld4Slab|sio2Slab
            structure2 = airSlab|sldcontrastBSlab|sld2Slab|sld3Slab|sld4Slab|sio2Slab
        if onlyStructure:
            returns = structure1,structure2
        elif both:
            model1 = ReflectModel(structure1, bkg=3e-6, dq=5.0)
            model1.scale.setp(bounds=(0.85, 1.2), vary=True)
            model1.bkg.setp(bounds=(1e-9, 9e-6), vary=True)
            objective1 = Objective(model1, data[0],
                      transform=Transform('logY'),
                      logp_extra=logpExtra)
            model2 = ReflectModel(structure2, bkg=3e-6, dq=5.0)
            model2.scale.setp(bounds=(0.85, 1.2), vary=True)
            model2.bkg.setp(bounds=(1e-9, 9e-6), vary=True)
            objective2 = Objective(model2, data[1],
                      transform=Transform('logY'),
                      logp_extra=logpExtra)
            returns = GlobalObjective([objective1, objective2]), structure1, structure2
            print("GlobalObjective and 2 structures")
        else:
            model1 = ReflectModel(structure1, bkg=3e-6, dq=5.0)
            model1.scale.setp(bounds=(0.85, 1.2), vary=True)
            model1.bkg.setp(bounds=(1e-9, 9e-6), vary=True)
            objective1 = Objective(model1, data[0],
                      transform=Transform('logY'),
                      logp_extra=logpExtra)
            model2 = ReflectModel(structure2, bkg=3e-6, dq=5.0)
            model2.scale.setp(bounds=(0.85, 1.2), vary=True)
            model2.bkg.setp(bounds=(1e-9, 9e-6), vary=True)
            objective2 = Objective(model2, data[1],
                      transform=Transform('logY'),
                      logp_extra=logpExtra)
            returns = GlobalObjective([objective1, objective2])

    elif not globalObjective:
        if nLayers==1:
            structure = airSlab|sld1Slab|sio2Slab
        if nLayers==2:
            structure = airSlab|sld1Slab|sld2Slab|sio2Slab
        if nLayers==3:
            structure = airSlab|sld1Slab|sld2Slab|sld3Slab|sio2Slab
        if nLayers==4:
            structure = airSlab|sld1Slab|sld2Slab|sld3Slab|sld4Slab|sio2Slab
        if onlyStructure:
            returns = structure
        elif both:
            model = ReflectModel(structure, bkg=3e-6, dq=5.0)
            objective = Objective(model, data,
                      transform=Transform('logY'),
                      logp_extra=logpExtra)
            returns = objective, structure
        else:
            model = ReflectModel(structure, bkg=3e-6, dq=5.0)
            objective = Objective(model, data, transform=Transform('logY'),logp_extra=logpExtra)
            returns = objective
    else:
        print("error contrast layer not at sld1Slab ie contrast_layer!=0")
#     print(returns)
    return returns