コード例 #1
0
ファイル: spectrum.py プロジェクト: baklanovp/pystella
    def mags_bands(self, bands, z=0., d=rf.pc_to_cm(10.), magnification=1.):
        mags = dict((k, None) for k in bands)
        for n in bands:
            b = band.band_by_name(n)
            mags[n] = self.flux_to_mags(b, z=z, d=d, magnification=magnification)

        mags['time'] = self.Time * (1. + z)
        return mags
コード例 #2
0
def curves_compute(name, path, bands, z=0., distance=10., magnification=1.,
                   t_beg=0., t_end=None, is_show_info=False, is_save=False):
    """
        Compute magnitude in bands for the 'name' model.
    :param name: the name of a model and data files
    :param path: the directory with data-files
    :param bands: photometric bands
    :param z: redshift, default 0
    :param distance: distance to star in parsec, default 10 pc
    :param magnification: gravitational lensing magnification
    :param t_end:
    :param t_beg:
    :param is_show_info: flag to write some information, default True
    :param is_save: flag to save result in file, default False
    :return: dictionary with keys = bands, value = star's magnitudes
    """
    if len(bands) == 0:
        raise ValueError("You have not set any bands for model: " + str(name))

    model = Stella(name, path=path)
    if not model.is_ph_data:
        model.show_info()
        raise ValueError("Error: No spectral data for: " + str(model))

    if is_show_info:
        print ''
        model.show_info()

    # serial_spec = model.read_serial_spectrum(t_diff=0.)
    serial_spec = model.read_series_spectrum(t_diff=1.05, t_beg=t_beg, t_end=t_end)
    curves = serial_spec.flux_to_curves(bands, z=z, d=rf.pc_to_cm(distance), magnification=magnification)
    # curves = SetLightCurve(name)
    # for n in bands:
    #     b = band.band_by_name(n)
    #     lc = serial_spec.flux_to_curve(b, z=z, dl=rf.pc_to_cm(distance), magnification=magnification)
    #     # time = serial_spec.times * (1. + z)
    #     # lc = LightCurve(b, time, mags)
    #     curves.add(lc)

    if is_save:
        fname = os.path.join(path, name + '.ubv')
        curves_save(curves, fname)
        print "Magnitudes have been saved to " + fname

    if is_show_info:
        # print the time of maximum LC
        tmin = 2.0
        t = curves.TimeDef
        for n in bands:
            t_min = t[t > tmin][curves[n][t > tmin].argmin()]
            print "t_max(%s) = %f" % (n, t_min)

    return curves
コード例 #3
0
def compute_mag(name, path, bands, ext=None, z=0., distance=10., magnification=1., t_diff=1.05, is_show_info=True,
                is_save=False):
    """
        Compute magnitude in bands for the 'name' model.
    :param name: the name of a model and data files
    :param path: the directory with data-files
    :param bands: photometric bands
    :param ext: extinction
    :param z: redshift, default 0
    :param distance: distance to star in parsec, default 10 pc
    :param magnification: gravitational lensing magnification
    :param t_diff:  depression between time points
    :param is_show_info: flag to write some information, default True
    :param is_save: flag to save result in file, default False
    :return: dictionary with keys = bands, value = star's magnitudes
    """
    model = Stella(name, path=path)
    if is_show_info:
        print ''
        model.show_info()

    if not model.is_ph_data:
        model.show_info()
        print "Error: No data for: " + str(model)
        return None

    # serial_spec = model.read_serial_spectrum(t_diff=0.)
    serial_spec = model.read_series_spectrum(t_diff=t_diff)
    mags = serial_spec.mags_bands(bands, z=z, d=rf.pc_to_cm(distance), magnification=magnification)

    if mags is not None:
        fname = os.path.join(path, name + '.ubv')
        if is_save:
            mags_save(mags, bands, fname)
            print "Magnitudes have been saved to " + fname

    if is_show_info:
        # print the time of maximum LC
        tmin = 2.0
        t = mags['time']
        for n in bands:
            t_min = t[t > tmin][mags[n][t > tmin].argmin()]
            print "t_max(%s) = %f" % (n, t_min)

    if ext is not None:  # add extinction
        for n in bands:
            mags[n] = mags[n] + ext[n]

    return mags
コード例 #4
0
ファイル: spectrum.py プロジェクト: baklanovp/pystella
    def flux_to_curves(self, bands, z=0., d=rf.pc_to_cm(10.), magnification=1.):
        """

        :param bands:
        :param z:
        :param d:
        :param magnification:
        :return:
        """
        curves = SetLightCurve(self.name)
        for n in bands:

            b = band.band_by_name(n)
            lc = self.flux_to_curve(b, z=z, d=d, magnification=magnification)
            curves.add(lc)
        return curves
コード例 #5
0
def compute_mag(name,
                path,
                bands,
                z=0.,
                distance=10.,
                t_cut=0.,
                t_up=400.,
                tdiff=0.):
    """
        Compute magnitude in bands for the 'name' model.
    :param name: the name of a model and data files
    :param path: the directory with data-files
    :param bands: photometric bands
    :param z: redshift, default 0
    :param distance: distance to star in parsec, default 10 pc
    :param t_cut:
    :param t_up:
    :param tdiff:
    :return: dictionary with keys = bands, value = star's magnitudes
    """
    model = Stella(name, path=path)

    if not model.is_ph:
        print("No data for: " + str(model))
        return None

    # serial_spec = model.read_serial_spectrum(t_diff=0.)
    serial_spec = model.read_series_spectrum(t_diff=1.05)
    mags = serial_spec.mags_bands(bands, z=z, d=rf.pc_to_cm(distance))

    # t_cut
    time = mags['time']
    cut = (t_cut < time) & (time < t_up)
    mags['time'] = time[cut]
    for n in bands:
        mags[n] = mags[n][cut]

    time = mags['time']
    if tdiff > 0.:
        ts = np.arange(np.min(time), np.max(time), tdiff)
        for n in bands:
            tck = interpolate.splrep(time, mags[n])
            mags[n] = interpolate.splev(ts, tck)
        mags['time'] = ts

    return mags
コード例 #6
0
ファイル: zeta.py プロジェクト: baklanovp/pystella
def compute_tcolor(name, path, bands, d=rf.pc_to_cm(10.0), z=0.0, t_cut=1.0):
    model = Stella(name, path=path)

    if not model.is_ph_data:
        print "No ph-data for: " + str(model)
        return None

    if not model.is_tt_data:
        print "No tt-data for: " + str(model)
        return None

    # serial_spec = model.read_series_spectrum(t_diff=1.)
    # curves = serial_spec.flux_to_curves(bands, d=distance)
    serial_spec = model.read_series_spectrum(t_diff=1.05, t_beg=t_cut)
    # curves = serial_spec.
    mags = serial_spec.mags_bands(bands, z=z, d=d)

    # read R_ph
    tt = model.read_tt_data()
    tt = tt[tt["time"] > t_cut]  # time cut  days

    # compute Tnu, W
    Tnu, Teff, W = compute_Tnu_w(serial_spec, tt=tt)

    # fit mags by B(T_col) and get \zeta\theta & T_col
    Tcolors, zetaR, times = compute_Tcolor_zeta(mags, tt=tt, bands=bands, freq=serial_spec.Freq, d=d, z=z)

    # show results
    res = np.array(
        np.zeros(len(Tcolors)),
        dtype=np.dtype({"names": ["time", "Tcol", "zeta", "Tnu", "Teff", "W"], "formats": [np.float64] * 6}),
    )
    res["time"] = times
    res["Tcol"] = Tcolors
    res["zeta"] = zetaR
    res["Tnu"] = Tnu
    res["Teff"] = Teff
    res["W"] = W

    return res
コード例 #7
0
ファイル: dmdt.py プロジェクト: baklanovp/pystella
def compute_mag(name, path, bands, z=0.0, distance=10.0, t_cut=0.0, t_up=400.0, tdiff=0.0):
    """
        Compute magnitude in bands for the 'name' model.
    :param name: the name of a model and data files
    :param path: the directory with data-files
    :param bands: photometric bands
    :param z: redshift, default 0
    :param distance: distance to star in parsec, default 10 pc
    :return: dictionary with keys = bands, value = star's magnitudes
    """
    model = Stella(name, path=path)

    if not model.is_ph_data:
        print "No data for: " + str(model)
        return None

    # serial_spec = model.read_serial_spectrum(t_diff=0.)
    serial_spec = model.read_series_spectrum(t_diff=1.05)
    mags = serial_spec.mags_bands(bands, z=z, d=rf.pc_to_cm(distance))

    # t_cut
    time = mags["time"]
    cut = (t_cut < time) & (time < t_up)
    mags["time"] = time[cut]
    for n in bands:
        mags[n] = mags[n][cut]

    time = mags["time"]
    if tdiff > 0.0:
        ts = np.arange(np.min(time), np.max(time), tdiff)
        for n in bands:
            tck = interpolate.splrep(time, mags[n])
            mags[n] = interpolate.splev(ts, tck)
        mags["time"] = ts

    return mags
コード例 #8
0
ファイル: zeta.py プロジェクト: baklanovp/pystella
def main(name="", path="./", is_force=False, is_save=False, is_plot_Tnu=False, is_plot_time_points=False):
    is_info = False
    is_fit = False
    is_save_plot = False
    is_fit_bakl = False
    model_ext = ".tt"
    theta_dic = None
    distance = rf.pc_to_cm(10.0)  # pc
    z = 0.0

    band.Band.load_settings()

    try:
        opts, args = getopt.getopt(sys.argv[1:], "fhswtb:d:e:i:p:o:z:")
    except getopt.GetoptError as err:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    if len(args) > 0:
        path, name = os.path.split(str(args[0]))
        path = os.path.expanduser(path)
    elif len(opts) == 0:
        usage()
        sys.exit(2)

    if not name:
        for opt, arg in opts:
            if opt == "-i":
                name = os.path.splitext(os.path.basename(str(arg)))[0]
                break

    set_bands = ["B-V", "B-V-I", "V-I", "J-H-K"]
    # set_bands = ['B-V', 'B-V-I', 'V-I', 'J-H-K']
    # set_bands = ['U-B-V-I', 'U-B-V-R-I', 'U-B', 'V-R', 'B-V-I', 'B-V', 'V-I']

    for opt, arg in opts:
        if opt == "-e":
            model_ext = "." + arg
            continue
        if opt == "-b":
            set_bands = str(arg).split("_")
            for bset in set_bands:
                for b in bset.split("-"):
                    if not band.band_is_exist(b):
                        print "No such band: " + b
                        sys.exit(2)
            continue
        if opt == "-z":
            z = float(arg)
            continue
        if opt == "-d":
            distance = rf.pc_to_cm(float(arg))
            continue
        if opt == "-s":
            is_save_plot = True
            continue
        if opt == "-o":
            ops = str(arg).split(":")
            is_plot_Tnu = "Tnu" in ops
            is_plot_time_points = "time" in ops
            is_fit = "fit" in ops
            is_fit_bakl = "fitb" in ops
            continue
        if opt == "-w":
            is_save = True
            continue
        if opt == "-f":
            is_force = True
            is_save = True
            continue
        if opt == "-p":
            path = os.path.expanduser(str(arg))
            if not (os.path.isdir(path) and os.path.exists(path)):
                print "No such directory: " + path
                sys.exit(2)
            continue
        elif opt == "-h":
            usage()
            sys.exit(2)

    names = []
    if name != "":
        names.append(name)
    else:  # run for all files in the path
        names = get_model_names(path, model_ext)

    if len(names) > 0:
        results = {}  # dict((k, None) for k in names)
        ib = 0
        for bset in set_bands:
            ib += 1
            im = 0
            dic = {}
            print "\nRun: %s [%d/%d], z=%.2f, d=%.2e" % (bset, ib, len(set_bands), z, distance)
            for name in names:
                res = None
                im += 1
                print "Run: %s [%d/%d]" % (name, im, len(names))
                is_err = False
                fname = cache_name(name, path, bset)
                if not is_force and os.path.exists(fname):
                    res = cache_load(fname)
                else:
                    res = compute_tcolor(name, path, bset.split("-"), d=distance, z=z, t_cut=0.9)
                    if is_save and res is not None:
                        print "Save Tcolor & Zeta for %s in %s" % (bset, fname)
                        cache_save(res, fname=fname)

                dic[name] = res
                # check for errors
                idx = np.argmin(np.abs(res["Tcol"] - 1.0e4))
                if abs(res["zeta"][idx] - 1.0) <= 1e-3:
                    is_err = True
            if is_err:
                print " ERROR for %s in %s" % (name, bset)

            results[bset] = dic
            print "Finish: %s" % name
        if is_fit:
            theta_dic = {}
            im = 0
            results_flter = {}
            for bset in set_bands:
                im += 1
                models = results[bset]
                tlim = (7.0, 80)
                if tlim is not None:
                    models_zt_new = {}
                    for mname, tbl in models.iteritems():
                        models_zt_new[mname] = table_cut_by_col(tbl, tlim, "time")
                    models = models_zt_new

                # templim = (4.e3, 12e3)
                # if templim is not None:
                #     models_zt_new = {}
                #     for mname, tbl in models.iteritems():
                #         models_zt_new[mname] = table_cut_by_col(tbl, templim, 'Tcol')
                #     models = models_zt_new

                print "\nFit: %s [%d/%d]" % (bset, im, len(set_bands))
                theta = fit_bayesian(models, is_debug=True, is_info=is_info, title=bset)
                results_flter[bset] = models
                theta_dic[bset] = theta
                print_coef(theta)

        # fig = plot_zeta(results, set_bands, theta_dic, t_cut=1.9, is_fit=is_fit, is_fit_bakl=is_fit_bakl,
        fig = plot_zeta(
            results_flter,
            set_bands,
            theta_dic,
            t_cut=1.9,
            is_fit=is_fit,
            is_fit_bakl=is_fit_bakl,
            is_plot_Tnu=is_plot_Tnu,
            is_time_points=is_plot_time_points,
        )
        if is_save_plot and len(results) > 0:
            fsave = os.path.join(os.path.expanduser("~/"), "epm_" + "_".join(set_bands) + ".pdf")
            print "Save plot in %s" % fsave
            fig.savefig(fsave, bbox_inches="tight", format="pdf")

    else:
        print "There are no models in the directory: %s with extension: %s " % (path, model_ext)