示例#1
0
    def test_lc_gp_Ntime(self):
        from plugin import sn1999em
        from pystella.fit.fit_gp import FitGP

        Ntime = 50
        colors = band.colors()
        fig, ax = plt.subplots(figsize=(12, 10))
        ax.invert_yaxis()

        curves_o = sn1999em.read_curves()
        for bname in curves_o.BandNames:
            lc_o = curves_o.get(bname)
            lc_o_gp, gp = FitGP.fit_lc(lc_o, Ntime=Ntime)
            # plot
            ax.errorbar(lc_o.Time, lc_o.Mag, label='{0} {1}'.format(bname, 'obs'), yerr=lc_o.MagErr,
                        fmt='s', color=colors[bname], ls='', markersize=2.5)
            x = lc_o_gp.Time
            y_pred = lc_o_gp.Mag
            sigma = lc_o_gp.MagErr
            ax.fill(np.concatenate([x, x[::-1]]),
                    np.concatenate([y_pred - sigma,
                                    (y_pred + sigma)[::-1]]),
                    #              np.concatenate([y_pred - 1.9600 * sigma,
                    #                             (y_pred + 1.9600 * sigma)[::-1]]),
                    alpha=.7, fc='grey', ec='None', label='95% confidence interval')
            ax.plot(x, y_pred, ls='', marker='o', markersize=2, color=colors[bname])
        plt.show()
示例#2
0
def plot_ubv(ax, path, jd_shift=0., mshift=0.):
    colors = band.colors()
    curves = read_curves(path)
    for lc in curves:
        x = lc.Time + jd_shift
        y = lc.Mag + mshift
        bcolor = colors[lc.Band.Name]
        ax.plot(x, y, label='%s SN 1999em' % lc.Band.Name,
                ls="", color=bcolor, markersize=8, marker="o")
示例#3
0
    def test_fit_GP_SNRefsdal_all_lc(self):
        # k = gptools.SquaredExponentialKernel(param_bounds=[(0, 1e3), (0, 100)])
        # gp = gptools.GaussianProcess(k, mu=gptools.LinearMeanFunction())

        # add data
        dm = -29.38  # D = 7.5e6 pc
        # dm = -30.4  # D = 12.e6 pc
        image = "S1"
        bands = ['F160W', 'F105W', 'F125W']
        # bands = ('F160W','F140W','F105W', 'F125W')
        curves = snrefsdal.read_curves(snrefsdal.path_data, image)
        for bname in bands:
            lc = curves.get(bname)
            # lc.mshift = dm
            t = lc.Time
            y = lc.Mag
            yerr = lc.Err

            #  Gaussian process
            k = gptools.SquaredExponentialKernel(param_bounds=[(min(np.abs(y)), max(np.abs(y))),
                                                               (0, np.std(t))])
            # k = gptools.SquaredExponentialKernel(param_bounds=[(min(np.abs(y)), max(np.abs(y))),
            #                                                    (0, np.std(t))])
            gp = gptools.GaussianProcess(k)
            # gp = gptools.GaussianProcess(k, mu=gptools.LinearMeanFunction())
            gp.add_data(t, y, err_y=yerr)

            is_mcmc = True
            if is_mcmc:
                out = gp.predict(t, use_MCMC=True, full_MCMC=True, return_std=True,
                                 num_proc=0, nsamp=100,
                                 plot_posterior=True, plot_chains=False,
                                 burn=10, thin=1)

            else:
                gp.optimize_hyperparameters()
                out = gp.predict(t, use_MCMC=False)
            y_star, err_y_star = out
            # y_star, err_y_star = gp.predict(t)

            fig = plt.figure()
            ax = fig.add_axes((0.1, 0.3, 0.8, 0.65))
            ax.invert_yaxis()

            bcolor = band.colors()[bname]
            ax.plot(t, y, color=bcolor, label='L bol', lw=2.5)
            ax.errorbar(t, y, yerr=yerr, fmt='o', color=bcolor, label='%s obs.')

            #
            # ax.plot(t, y_star, color='red', ls='--', lw=1.5, label='GP')
            ax.plot(t, y_star, '-', color=bcolor)
            ax.fill_between(t, y_star - 2 * err_y_star, y_star + 2 * err_y_star, color=bcolor, alpha=0.3)

        plt.show()
示例#4
0
def plot(ax, arg):
    lw = 2.
    band_shift = arg
    colors = band.colors()
    fname = "~/Desktop/Downloads/2/100z0E60Ni_6.ph.hsc.2"
    data = np.loadtxt(fname, comments='#')
    fs = list('grizy')
    x = data[:, 0]
    for i in range(len(fs)):
        y = data[:, i + 1]
        bcolor = colors[fs[i]]
        ax.plot(x, y, label='%s Tolstov' % lc.lbl(fs[i], band_shift),
                color=bcolor, ls="-.", linewidth=lw)
示例#5
0
    def test_band_ubvri(self):
        import pylab as plt

        b = band.band_by_name(band.Band.NameUBVRI)
        plt.plot(b.wl * phys.cm_to_angs,
                 b.resp_wl,
                 band.colors(b.Name),
                 label=b.Name,
                 linewidth=2)
        plt.legend(loc=4)
        plt.ylabel('Amplitude Response')
        plt.xlabel('Wave [A]')
        plt.grid(linestyle=':')
        plt.show()
示例#6
0
def plot_bands(bands, color_dic=None):
    if color_dic is None:
        color_dic = band.colors()

    for bname in bands:
        b = band.band_by_name(bname)
        plt.plot(b.wl * phys.cm_to_angs,
                 b.resp_wl,
                 color_dic[bname],
                 label=bname,
                 linewidth=2)
    plt.legend(loc=4)
    plt.ylabel('Amplitude Response')
    plt.xlabel('Wave [A]')
    plt.grid(linestyle=':')
    plt.show()
示例#7
0
def plot_ubv(ax, path, jd_shift=0., mshift=0., **kwargs):
    markersize = kwargs.pop('markersize', 7)
    is_mas = kwargs.pop('is_mas', True)
    is_kur = kwargs.pop('is_kur', True)
    is_wil = kwargs.pop('is_wil', True)
    bnames_fix = kwargs.pop('bnames', None)
    colors = kwargs.pop('bcolors', band.colors())
    path = os.path.expanduser(path)

    print("Plot RedNova: jd_shift=%f mshift=%f " % (jd_shift, mshift))

    def plot_lc(cs, band_names, lbl, fmt):
        if band_names is None:
            band_names = cs.BandNames
        for lc in cs:
            if lc.Band.Name in band_names:
                x = lc.Time + jd_shift
                y = lc.Mag + mshift
                bcolor = colors[lc.Band.Name]
                # ax.plot(x, y, label='%s Master' % lc.Band.Name,
                #         ls="", color=bcolor, markersize=markersize, marker="o")
                ax.errorbar(x, y, yerr=lc.Err, label=lbl % lc.Band.Name,
                            color=bcolor, fmt=fmt, fillstyle='none', ecolor=bcolor,
                            mec=bcolor, markersize=markersize, zorder=1)

    if is_mas:
        curves_mst = read_curves_master(path)
        plot_lc(curves_mst, bnames_fix, lbl='%s Master', fmt='o')

    if is_kur:
        curves_kur = read_curves_kurtenkov(path)
        plot_lc(curves_kur, bnames_fix, lbl='%s Kurtenkov', fmt='.')
        # for lc in curves:
        #     x = lc.Time + jd_shift
        #     y = lc.Mag + mshift
        #     bcolor = colors[lc.Band.Name]
        #     # ax.plot(x, y, label='%s Kurtenkov' % lc.Band.Name,
        #     #         ls="", color=bcolor, markersize=markersize, marker="x")
        #     ax.errorbar(x, y, yerr=lc.MagErr,  label='%s Kurtenkov' % lc.Band.Name,
        #                 color=bcolor, fmt='.')

    if is_wil:            
        curves_wil = read_curves_williams(path)
        plot_lc(curves_wil, bnames_fix, lbl='%s Williams', fmt='d')
示例#8
0
    def test_stella_curves_VS_tt_plot(self):
        from pystella.rf.band import colors
        name = 'cat_R500_M15_Ni006_E12'
        path = join(dirname(abspath(__file__)), 'data', 'stella')
        bands = ('U', 'B', 'V', 'R', 'I')

        mdl = ps.Stella(name, path=path)
        curves = mdl.curves(bands)

        tt = mdl.get_tt().load()

        ax = ps.lcp.curves_plot(curves)
        for bname in bands:
            ax.plot(tt['time'],
                    tt['M' + bname],
                    label="tt " + bname,
                    color=colors(bname),
                    marker='*',
                    markersize=3,
                    ls='')
        ax.legend()

        plt.grid(linestyle=':', linewidth=1)
        plt.show()
示例#9
0
def plot(ax, dic=None, mag_lim=30.):
    """
    Plot points from dat-files. Format fname:marker:jd_shift:mshift
    Header should be:  time  U [errU]  B [errB]  ...
    :param ax:
    :param dic:
    :param mag_lim:
    :return:
    """

    if isinstance(ax, (list, tuple)):
        ax = ax[0]

    if dic is None:
        dic = {}
    fname = dic.get('fname', None)
    jd_shift = dic.get('jd_shift', 0.)
    mshift = dic.get('mshift', 0.)
    marker = dic.get('marker', 'o')
    markersize = dic.get('markersize', 5)
    bnames = dic.get('bnames', None)
    bcolors = dic.get('bcolors', band.colors())
    comments = dic.get('comments', '#')

    arg = dic.get('args', [])
    if len(arg) > 0:
        fname = arg.pop(0)
        fname = os.path.expanduser(fname)
    if len(arg) > 0:
        marker = arg.pop(0)
    if len(arg) > 0:
        jd_shift = float(arg.pop(0))
    if len(arg) > 0:
        mshift = float(arg.pop(0))

    print("Plot {0} [{1}]  jd_shift={2}  mshift={3}".format(
        fname, marker, jd_shift, mshift))

    # read header
    with open(fname) as f:
        a = f.readline().split()
        header = ' '.join(a[1:])  # to remove #
    # read data
    tbl, cols_data = read_obs_table_header(
        fname,
        header=header,
        include_names=band.band_get_names_alias(),
        is_out=True,
        comments=comments)
    # tbl = read_table_header_float(fname)
    curves = table2curves(os.path.basename(fname), tbl)

    # filter bands
    if bnames is not None:
        bands = curves.BandNames
        for b in bands:
            if b not in bnames:
                curves.pop(b)
    # plot data
    for lc in curves:
        bname = lc.Band.Name
        is_good = lc.Mag < (mag_lim - mshift)
        x = lc.Time[is_good] + jd_shift
        y = lc.Mag[is_good] + mshift
        if lc.IsErr:
            yyerr = abs(lc.Err[is_good])
            ax.errorbar(x,
                        y,
                        label='{0} {1}'.format(bname, fname),
                        yerr=yyerr,
                        fmt=marker,
                        color=bcolors[bname],
                        ls='')
        else:
            ax.plot(x,
                    y,
                    label='{0} {1}'.format(bname, fname),
                    color=bcolors[bname],
                    ls='',
                    marker=marker,
                    markersize=markersize)
示例#10
0
def plot_ubv_models(ax, models_dic, bands, **kwargs):
    # bshift=None, xlim=None, ylim=None, colors=lc_colors, is_time_points=False):
    global linestyles
    xlim = kwargs.get('xlim', None)
    ylim = kwargs.get('ylim', None)
    bshift = kwargs.get('bshift', None)
    ls1 = kwargs.get('ls1', "-")
    ls_multi = kwargs.get('ls_multi', ":")
    lw = kwargs.get('lw', 2)
    markersize = kwargs.get('markersize', 6)
    is_time_points = kwargs.get('is_time_points', False)
    is_dashes = kwargs.get('is_dashes', False)
    line_styles = kwargs.get('linestyles', linestyles)
    #    linestyles = kwargs.get('linestyles', ['-'])

    is_compute_x_lim = xlim is None
    is_compute_y_lim = ylim is None

    t_points = [0.2, 1, 2, 3, 4, 5, 10, 20, 40, 80, 150]
    colors = band.colors()
    band_shift = dict((k, 0) for k, v in colors.items())  # no y-shift
    if bshift is not None:
        for k, v in bshift.items():
            band_shift[k] = v

    lbl_len = lbl_length(band_shift)

    mi = 0
    x_max = []
    y_mid = []
    lc_min = {}
    line_cycle = cycle(line_styles)
    dashes = get_dashes(len(bands) + 1, scale=2)

    for mname, mdic in models_dic.items():
        mi += 1
        ls = next(line_cycle)
        for ib, bname in enumerate(bands):
            lc = mdic[bname]
            x = lc.Time
            y = lc.Mag + band_shift[bname]
            bcolor = colors[bname]
            dash = dashes[ib]
            if len(models_dic) == 1:
                if is_dashes:
                    ax.plot(x,
                            y,
                            label='%s  %s' %
                            (lbl(bname, band_shift, lbl_len), mname),
                            color=bcolor,
                            ls=ls1,
                            linewidth=lw,
                            dashes=dash)
                else:
                    ax.plot(x,
                            y,
                            label='%s  %s' %
                            (lbl(bname, band_shift, lbl_len), mname),
                            color=bcolor,
                            ls=ls,
                            linewidth=lw)
            # ax.plot(x, y, label='%s  %s' % (lbl(bname, band_shift), mname), color=bcolor, ls=ls1, linewidth=lw)
            elif len(models_dic) <= len(line_styles):
                ax.plot(x,
                        y,
                        label='%s  %s' %
                        (lbl(bname, band_shift, lbl_len), mname),
                        color=bcolor,
                        ls=ls,
                        linewidth=lw)
            else:
                ax.plot(x,
                        y,
                        marker=markers[mi % (len(markers) - 1)],
                        label='%s  %s' %
                        (lbl(bname, band_shift, lbl_len), mname),
                        markersize=markersize,
                        color=bcolor,
                        ls=ls_multi,
                        linewidth=lw)

            if is_time_points:
                integers = [np.abs(x - t).argmin()
                            for t in t_points]  # set time points
                for (X, Y) in zip(x[integers], y[integers]):
                    ax.annotate('{:.0f}'.format(X),
                                xy=(X, Y),
                                xytext=(-10, 20),
                                ha='right',
                                textcoords='offset points',
                                color=bcolor,
                                arrowprops=dict(arrowstyle='->', shrinkA=0))
            idx = np.argmin(y)
            lc_min[bname] = (x[idx], y[idx])
            if is_compute_x_lim:
                x_max.append(np.max(x))
            if is_compute_y_lim:
                y_mid.append(np.min(y))

    if is_compute_x_lim:
        xlim = [-10, np.max(x_max) + 10.]
    if is_compute_y_lim:
        ylim = [np.min(y_mid) + 7., np.min(y_mid) - 2.]

    ax.set_xlim(xlim)
    ax.invert_yaxis()
    ax.set_ylim(ylim)

    return lc_min
示例#11
0
def plot_swd_tau(dic_axes,
                 stella,
                 times,
                 bnames=('B', ),
                 tau_ph=2. / 3.,
                 is_obs_time=False,
                 **kwargs):
    """Add photospheric data to the plot_shock_details plot
    :type dic_axes: object
    :param stella:
    :param times:
    :param bnames:
    :param tau_ph: the photosphere location. Default: 2/3
    :param is_obs_time:  If True to compute Obs.Time as ProperTime - R(N-1)/c and use them. Default: False
    :param tnorm: the T normalization. Default: None = log10(T)
    :param vnorm: the V normalization. Default: 1e8
    :param alpha: the transparent. Default: 0.5
    """
    from pystella.rf.band import band_by_name

    tnorm = kwargs.get('tnorm', None)
    vnorm = kwargs.get('vnorm', 1e8)
    alpha = kwargs.get('alpha', 0.5)
    markersize = kwargs.get('markersize', 6)
    marker = kwargs.get('marker', 'o')

    if not stella.is_tau:
        print('There is no tau-file for model {} in path: {}'.format(
            stella.Name, stella.Path))
        return

    print('Add tau [{}] for {} at tau_ph= {:.3f}'.format(
        ':'.join(bnames), stella.Name, tau_ph))
    pars_data = ['T', 'V', 'R']
    tau = stella.get_tau().load(is_info=False)
    tau_data = tau.params_ph(pars=pars_data,
                             moments=times,
                             tau_ph=tau_ph,
                             is_obs_time=is_obs_time)

    # Extract phot data
    data = {bn: {p: [] for p in pars_data} for bn in bnames}

    for bname in bnames:
        b = band_by_name(bname)
        fr_eff = b.freq_eff
        for p in pars_data:
            for i, (t, freq, y) in enumerate(tau_data[p]):
                s = '{:9.4f} '.format(t)
                idx = (np.abs(freq - fr_eff)).argmin()
                s += ' {:10e}'.format(y[idx])
                data[bname][p].append(y[idx])

    # Plot
    for ii, d in enumerate(dic_axes['r']):
        ax = d['par']
        # t = d['t']
        # print('{:9s} {}'.format('t_real',  ' '.join([f'{p}_{b:10s}' for b in bnames])))
        # s = '{:9.4f} '.format(t)
        for i, bname in enumerate(bnames):
            r_ph = np.array(data[bname]['R'])
            color = band.colors(bname)
            # print(bname)
            xr = r_ph[ii]
            ax.text(xr, 0.5 + i, bname, fontsize=12, color=color)
            ax.axvline(x=xr,
                       ymin=0.,
                       ymax=0.99,
                       linestyle='--',
                       color=color,
                       alpha=alpha)
            # Temperature
            if tnorm is None:
                yt = np.log10(data[bname]['T'][ii])
                ax.plot(xr,
                        yt,
                        color='green',
                        ls='',
                        marker=marker,
                        markersize=markersize,
                        alpha=alpha)
            else:
                yt = data[bname]['T'][ii] / tnorm
                ax.plot(xr,
                        yt,
                        color='green',
                        ls='',
                        marker=marker,
                        markersize=markersize,
                        alpha=alpha)
            # Velocity
            yv = data[bname]['V'][ii] / vnorm
            ax.plot(xr,
                    yv,
                    color='blue',
                    ls='',
                    marker=marker,
                    markersize=markersize,
                    alpha=alpha)
        #     print(f't={t:9.3f}  R= {xr:e}  V= {yv:e} T= {yt:e}')
        #     s += f'R= {xr:e}  V= {yv:e} T= {yt:e}'
        # print(s)

    # Print
    for p in pars_data:
        print('{:9s} {}'.format(
            't_real', ' '.join([
                f'{p}({b:4s}:{band_by_name(b).wl_eff_angs:.0f})'
                for b in bnames
            ])))
        # print(p)
        for ii, d in enumerate(dic_axes['r']):
            t = d['t']
            s = '{:9.4f} '.format(t)
            for i, bname in enumerate(bnames):
                v = np.array(data[bname][p][ii])
                s += f'{v:12e} '
            print(s)
示例#12
0
def curves_plot(curves,
                ax=None,
                xlim=None,
                ylim=None,
                title=None,
                fname=None,
                **kwargs):
    """
    Plot curves.
    If err = -1, it's upper limit, if err = -2 it's lower limit
    :param curves:
    :param ax: Axis. If ax is None, it would be created.
    :param xlim:
    :param ylim:
    :param title:
    :param fname:
    :param kwargs:
        linewidth = kwargs.get('linewidth', 2.0)
        markersize = kwargs.get('markersize', 5)
        fontsize = kwargs.get('fontsize', 18)
        figsize = kwargs.get('figsize', (20, 10))
        legncol = kwargs.get('legncol', 1)
        legloc = kwargs.get('legloc', 1)
        alpha = kwargs.get('alpha', 1.)
        is_legend = kwargs.get('is_legend', True)
        is_line = kwargs.get('is_line', True)
        is_fill = kwargs.get('is_fill', False)
        if 'marker' in kwargs:
            is_line = False
        marker = kwargs.get('marker', 'o')
        if not isinstance(marker, (list, dict, tuple)):
            marker = {lc.Band.Name: marker for lc in curves}
        colors = like {'B': 'blue', 'V': 'green}
        if not isinstance(colors, (list, dict, tuple)):
            colors = {lc.Band.Name: colors for lc in curves}
    :return: ax
    """
    ls = kwargs.get('ls', {lc.Band.Name: '-' for lc in curves})
    if isinstance(ls, str):
        c = ls.strip()
        ls = {lc.Band.Name: c for lc in curves}
    is_legend = kwargs.get('is_legend', True)
    is_line = kwargs.get('is_line', True)
    is_fill = kwargs.get('is_fill', False)
    if 'marker' in kwargs:
        is_line = False
    marker = kwargs.get('marker', 'o')
    if not isinstance(marker, (list, dict, tuple)):
        marker = {lc.Band.Name: marker for lc in curves}
    colors = kwargs.get('colors', None)
    if colors is not None and not isinstance(colors, (list, dict, tuple)):
        colors = {lc.Band.Name: colors for lc in curves}
    linewidth = kwargs.get('linewidth', 2.0)
    markersize = kwargs.get('markersize', 5)
    # rect = kwargs.get('rect', (0.1, 0.2, 0.8, 0.65))
    fontsize = kwargs.get('fontsize', 18)
    figsize = kwargs.get('figsize', (20, 10))
    legncol = kwargs.get('legncol', 1)
    legloc = kwargs.get('legloc', 1)
    alpha = kwargs.get('alpha', 1.)
    flabel = kwargs.get('flabel', None)
    label = kwargs.get('label', None)
    length_lo_up_lims = kwargs.get('length_lo_up_lims', 0.5)

    is_new_fig = ax is None
    if is_new_fig:
        plt.matplotlib.rcParams.update({'font.size': 14})
        fig = plt.figure(figsize=figsize)
        # fig = plt.figure(num=None, figsize=(7, 11), dpi=100, facecolor='w', edgecolor='k')
        # ax = fig.add_axes(rect)
        ax = fig.add_subplot(1, 1, 1)

        for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                     ax.get_xticklabels() + ax.get_yticklabels()):
            item.set_fontsize(fontsize)
            # ax = fig.add_axes((0.1, 0.3, 0.8, 0.65))

    # ax.set_title(''.join(bands) + ' filter response')
    is_xlim = False
    is_ylim = False
    if xlim is None:
        is_xlim = True
        xlim = [float('inf'), float('-inf')]
    if ylim is None:
        is_ylim = True
        ylim = [float('-inf'), float('inf')]

    for lc in curves:
        x = lc.Time
        y = lc.Mag
        bname = lc.Band.Name
        lbl = '{0} {1}'.format(bname, curves.Name.replace("_", ""))
        if flabel is not None:
            lbl = flabel(bname)
        elif label is not None:
            lbl = label.format(bname)

        if colors is not None:
            color = colors[bname]
        else:
            color = band.colors(bname)

        if is_line:
            ax.plot(x,
                    y,
                    label=lbl,
                    color=color,
                    ls=ls[bname],
                    linewidth=linewidth)
        else:
            if lc.IsErr:
                y_el = np.copy(lc.MagErr)
                y_eu = np.copy(lc.MagErr)
                lolims = np.array(y_el == -2, dtype=bool)
                uplims = np.array(y_eu == -1, dtype=bool)
                y_el[lolims] = length_lo_up_lims
                y_eu[uplims] = length_lo_up_lims
                ax.errorbar(
                    x,
                    y,
                    label=lbl,
                    yerr=[y_el, y_eu],
                    fmt=marker[bname],
                    lolims=lolims,
                    uplims=uplims,
                    xlolims=lolims,
                    xuplims=uplims,
                    color=color,
                    ls='',
                    markersize=markersize,
                )
            else:
                # ax.plot(x, y, label='{0} {1}'.format(bname, fname), color=bcolors[bname], ls='',
                #         marker=marker, markersize=markersize)
                ax.plot(x,
                        y,
                        label=lbl,
                        color=color,
                        ls='',
                        marker=marker[bname],
                        markersize=markersize)
        if is_fill and lc.IsErr:
            yy_err = abs(lc.MagErr)
            # ax.fill(np.concatenate([x, x[::-1]]), np.concatenate([y - yyerr, (y + yyerr)[::-1]]),
            #         alpha=.3, fc=color, ec='None', label=label)  # '95% confidence interval')
            ax.fill_between(x,
                            y - yy_err,
                            y + yy_err,
                            facecolor=color,
                            alpha=alpha)

        if is_xlim:
            xlim[0] = min(xlim[0], np.min(x))
            xlim[1] = max(xlim[1], np.max(x))
        if is_ylim:
            ylim[0] = max(ylim[0], np.max(y))
            ylim[1] = min(ylim[1], np.min(y))

    if is_ylim:
        ylim = [ylim[1] + 10, ylim[1] - 2]
    # ylim = np.add(ylim, [1, -1])
    ax.invert_yaxis()
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    if is_legend:
        ax.legend(ncol=legncol, loc=legloc)
    ax.set_ylabel('Magnitude')
    ax.set_xlabel('Time [days]')
    # ax.grid()
    if title is not None:
        ax.get_figure().title(title)
        # ax.text(0.17, 0.07, title, family='monospace')
    if fname is not None:
        print('Save plot to {}'.format(fname))
        ax.get_figure().savefig(fname)
    return ax
示例#13
0
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
except ImportError as ex:
    # import traceback
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fn = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fn, exc_tb.tb_lineno, ex)
    print('  Probably, you should install module: {}'.format('matplotlib'))
    #    print(ex)
    plt = None
    gridspec = None
    pass

__author__ = 'bakl'

lc_colors = band.colors()

lc_lntypes = band.lntypes()

linestyles = ('-', '--', '-.', ':')
linestyles_extend = list(
    OrderedDict(  # ref https://stackoverflow.com/a/54804349
        [('solid', (0, ())), ('dashed', (0, (5, 5))),
         ('dashdotted', (0, (3, 5, 1, 5))), ('densely dotted', (0, (1, 1))),
         ('densely dashed', (0, (5, 1))), ('dotted', (0, (1, 5))),
         ('loosely dashed', (0, (5, 10))), ('loosely dotted', (0, (1, 10))),
         ('loosely dashdotted', (0, (3, 10, 1, 10))),
         ('densely dashdotted', (0, (3, 1, 1, 1))),
         ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
         ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
         ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]).values())
示例#14
0
def plot(ax, dic=None, mag_lim=30.):
    """
    Plot points from dat-files. Format fname:marker:jd_shift:mshift
    Header should be:  time  U [errU]  B [errB]  ...
    :param ax:
    :param dic:
    :param mag_lim:
    :return:
    """
    # colors = band.bands_colors()
    if dic is None:
        dic = {}
    fname = dic.get('fname', None)
    jd_shift = dic.get('jd_shift', 0.)
    mshift = dic.get('mshift', 0.)
    marker = dic.get('marker', 'o')
    markersize = dic.get('markersize', 9)
    bnames = dic.get('bnames', None)
    bcolors = dic.get('bcolors', band.colors())

    arg = dic.get('args', [])
    if len(arg) > 0:
        fname = arg.pop(0)
        fname = os.path.expanduser(fname)
    if len(arg) > 0:
        marker = arg.pop(0)
    if len(arg) > 0:
        jd_shift = float(arg.pop(0))
    if len(arg) > 0:
        mshift = float(arg.pop(0))

    print("Plot {0} [{1}]  jd_shift={2}  mshift={3}".format(
        fname, marker, jd_shift, mshift))

    # read data
    # tbl, cols_data = read_obs_table_header(fname, include_names=band.band_get_names_alias(), is_out=True)
    # # tbl = read_table_header_float(fname)
    # curves = table2curves(os.path.basename(fname), tbl)
    curves = load(dic={'args': [fname]})

    # filter bands
    if bnames is not None:
        bands = curves.BandNames
        for b in bands:
            if b not in bnames:
                curves.pop(b)
    # plot data
    for lc in curves:
        bname = lc.Band.Name
        is_good = lc.Mag < (mag_lim - mshift)
        x = lc.Time[is_good] + jd_shift
        y = lc.Mag[is_good] + mshift
        if lc.IsErr:  # todo Make plot with errors
            yyerr = np.abs(lc.Err[is_good])
            # is_e = np.isnan(yyerr)
            ax.errorbar(x,
                        y,
                        label='{0} {1}'.format(bname, fname),
                        yerr=yyerr,
                        fmt=marker,
                        color=bcolors[bname],
                        ls='')
            # ax.plot(x, y, label='{0} {1}'.format(bname, fname), color=bcolors[bname], ls='',
            #         marker=marker, markersize=markersize)
        else:
            ax.plot(x,
                    y,
                    label='{0} {1}'.format(bname, fname),
                    color=bcolors[bname],
                    ls='',
                    marker=marker,
                    markersize=markersize)
    # d = {'curves': curves, 'fname': fname}
    return curves
示例#15
0
 def test_band_colors_name(self):
     bands = band.band_load_names()
     for bname in bands:
         self.assertTrue(bname in band.colors(),
                         "You have not color for band: %s" % bname)