Esempio n. 1
0
method = 'least_squares'

sp = EdiblesSpectrum(filename)
print(sp.target)
sp.getSpectrum(xmin=7661, xmax=7670)

# #################################################################################

cont_model = ContinuumModel(n_anchors=4)
cont_pars = cont_model.guess(sp.flux, x=sp.wave)
model = cont_model
pars = cont_pars

result = model.fit(data=sp.flux, params=pars, x=sp.wave, method=method)
out = cont_model.eval(data=sp.flux, params=result.params, x=sp.wave)
resid = sp.flux - out

# result.plot_fit()
# plt.show()

# #################################################################################

voigt1 = VoigtModel(prefix='voigt1_')
voigt1_pars = voigt1.guess(resid, x=sp.wave)

model = model * voigt1
pars = result.params + voigt1_pars

result = model.fit(data=sp.flux, params=pars, x=sp.wave, method=method)
out = model.eval(data=sp.flux, params=result.params, x=sp.wave)
Esempio n. 2
0
from edibles.models import ContinuumModel

# #################################################################################
# Example 1

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

cont_model = ContinuumModel(n_anchors=4)
cont_pars = cont_model.guess(y, x=x)

# ##############################
# Show initial model

out = cont_model.eval(data=y, params=cont_pars, x=x)

y_param_names = []
for i in range(cont_model.n_anchors):
    y_param_names.append('y_' + str(i))

x_param_names = []
for i in range(cont_model.n_anchors):
    x_param_names.append('x_' + str(i))

init_y = []
for par_name in y_param_names:
    init_y.append(cont_pars[par_name].value)

init_x = []
for par_name in x_param_names:
Esempio n. 3
0
    def prebuilt_model(self, chosen_save_num=None, plot=False, verbose=0):
        """A function that generates continua based on data saved in csv files.


        Args:
            chosen_save_num (int): The 'save number' of the continuum data, default=None.
                If None, the function will create all saved models and (possibly) plot them.
            plot (bool): If True, plot the model(s) once it is created
            verbose (int): If > 0, print more information about the data

        """

        # assert self.num_saved_continua is not 0, otherwise there is no known continuum point
        assert self.num_saved_continua > 0, "There is no saved continuum."

        # read and parse file contents
        saves_counter = 0
        saves_dict = {}
        with open(self.Spectrum.continuum_filename, mode="r") as f:
            for line in f:
                line = line.split("\n")[0]

                # initialize new save group
                if len(line) > 0:
                    if line == "######":
                        name = "save" + str(saves_counter)
                        saves_counter += 1
                        saves_dict[name] = {"x": None, "y": None}

                    # update dict
                    elif line[0:2] == "# ":
                        key, val = line.split("# ")[1].split("=")

                        if key == "n_anchors":
                            val = int(val)
                        if key == "datetime":
                            val = datetime.strptime(val, "%Y-%m-%d %H:%M:%S.%f")

                        saves_dict[name][key] = val

                    else:
                        if saves_dict[name]["x"] is None:
                            saves_dict[name]["x"] = [
                                float(item) for item in line.split(",")
                            ]
                        else:
                            saves_dict[name]["y"] = [
                                float(item) for item in line.split(",")
                            ]

        if chosen_save_num is not None:
            assert chosen_save_num < self.num_saved_continua, (
                "There are only " + str(self.num_saved_continua) + " saved continua."
            )
            chosen_save = saves_dict["save" + str(chosen_save_num)]

            if verbose > 0:
                print("Number of saved continuum datasets: ", saves_counter)
                print("Save chosen: save" + str(chosen_save_num))
                pprint(chosen_save)

            cont_model = ContinuumModel(n_anchors=chosen_save['n_anchors'])
            params = cont_model.make_params()
            for i in range(cont_model.n_anchors):
                params['%sx_%i' % (cont_model.prefix, i)].set(value=chosen_save["x"][i], vary=False)
                params['%sy_%i' % (cont_model.prefix, i)].set(value=chosen_save["y"][i], vary=False)

            params = update_param_vals(params, cont_model.prefix)

            out = cont_model.eval(params=params, x=self.Spectrum.wave)

            if plot:
                plt.plot(self.Spectrum.wave, self.Spectrum.flux)
                plt.plot(self.Spectrum.wave, out)
                plt.scatter(chosen_save["x"], chosen_save["y"], marker="x", s=80, color="k")
                plt.show()

            return out
        else:
            for j in range(saves_counter):
                chosen_save = saves_dict["save" + str(j)]
                try:
                    method = str(chosen_save["method"])
                except:
                    method = "unknown"

                try:
                    n_anchors = str(chosen_save["n_anchors"])
                except:
                    n_anchors = "unknown"

                try:
                    date_time = str(chosen_save["datetime"])
                except:
                    date_time = "unknown"

                try:
                    user = str(chosen_save["user"])
                except:
                    user = "******"

                try:
                    comments = str(chosen_save["comments"])
                except:
                    comments = "None"

                print("Continuum group {a}/{b}".format(a = j, b=saves_counter-1))
                print("Method: " + method + ", n_anchors: " + n_anchors + ";")
                print("Added by: " + user + ", at time:" + date_time + ";")
                print("Comments: " + comments)

                if plot:
                    cont_model = ContinuumModel(n_anchors=chosen_save['n_anchors'])
                    params = cont_model.make_params()
                    for i in range(cont_model.n_anchors):
                        params['%sx_%i' % (cont_model.prefix, i)].set(value=chosen_save["x"][i], vary=False)
                        params['%sy_%i' % (cont_model.prefix, i)].set(value=chosen_save["y"][i], vary=False)

                    params = update_param_vals(params, cont_model.prefix)

                    out = cont_model.eval(params=params, x=self.Spectrum.wave)

                    plt.plot(self.Spectrum.wave, self.Spectrum.flux)
                    plt.plot(self.Spectrum.wave, out)
                    plt.scatter(chosen_save["x"], chosen_save["y"], marker="x", s=80, color="k")
                    plt.show()
                print("Please make your selection back in the script.")