Heatmap of pseudotime series.

    Parameters
    ----------
    as_heatmap : bool (default: False)
        Plot the timeseries as heatmap.
181974
def dpt_timeseries(adata, color_map=None, show=None, save=None, as_heatmap=True):
    
    if adata.n_vars > 100:
        logg.warn('Plotting more than 100 genes might take some while,'
                  'consider selecting only highly variable genes, for example.')
    # only if number of genes is not too high
    if as_heatmap:
        # plot time series as heatmap, as in Haghverdi et al. (2016), Fig. 1d
        timeseries_as_heatmap(adata.X[adata.obs['dpt_order_indices'].values],
                              var_names=adata.var_names,
                              highlightsX=adata.uns['dpt_changepoints'],
                              color_map=color_map)
    else:
        # plot time series as gene expression vs time
        timeseries(adata.X[adata.obs['dpt_order_indices'].values],
                   var_names=adata.var_names,
                   highlightsX=adata.uns['dpt_changepoints'],
                   xlim=[0, 1.3*adata.X.shape[0]])
    pl.xlabel('dpt order')
    utils.savefig_or_show('dpt_timeseries', save=save, show=show)
1009997
def heatmap(args):
    
    p = OptionParser(heatmap.__doc__)
    p.add_option("--stacks",
                 default="Exons,Introns,DNA_transposons,Retrotransposons",
                 help="Features to plot in stackplot [default: %default]")
    p.add_option("--heatmaps",
                 default="Copia,Gypsy,hAT,Helitron,Introns,Exons",
                 help="Features to plot in heatmaps [default: %default]")
    p.add_option("--meres", default=None,
                 help="Extra centromere / telomere features [default: %default]")
    add_window_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="8x5")

    if len(args) != 2:
        sys.exit(not p.print_help())

    fastafile, chr = args
    window, shift, subtract, merge = check_window_options(opts)

    stacks = opts.stacks.split(",")
    heatmaps = opts.heatmaps.split(",")
    stackbeds = get_beds(stacks)
    heatmapbeds = get_beds(heatmaps)
    stackbins = get_binfiles(stackbeds, fastafile, shift,
                             subtract=subtract, merge=merge)
    heatmapbins = get_binfiles(heatmapbeds, fastafile, shift,
                               subtract=subtract, merge=merge)

    margin = .06
    inner = .015
    clen = Sizes(fastafile).mapping[chr]

    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    # Gauge
    ratio = draw_gauge(root, margin, clen, rightmargin=4 * margin)
    yinterval = .3
    xx = margin
    yy = 1 - margin
    yy -= yinterval
    xlen = clen / ratio
    cc = chr
    if "_" in chr:
        ca, cb = chr.split("_")
        cc = ca[0].upper() + cb

    root.add_patch(Rectangle((xx, yy), xlen, yinterval - inner, color=gray))
    ax = fig.add_axes([xx, yy, xlen, yinterval - inner])

    nbins = get_nbins(clen, shift)

    owindow = clen / 100
    if owindow > window:
        window = owindow / shift * shift

    stackplot(ax, stackbins, nbins, palette, chr, window, shift)
    ax.text(.1, .9, cc, va="top", zorder=100, transform=ax.transAxes,
              bbox=dict(boxstyle="round", fc="w", alpha=.5))

    # Legends
    xx += xlen + .01
    yspace = (yinterval - inner) / (len(stackbins) + 1)
    yy = 1 - margin - yinterval
    for s, p in zip(stacks, palette):
        s = s.replace("_", " ")
        s = Registration.get(s, s)

        yy += yspace
        root.add_patch(Rectangle((xx, yy), inner, inner, color=p, lw=0))
        root.text(xx + 1.5 * inner, yy, s, size=10)

    yh = .05  # Heatmap height
    # Heatmaps
    xx = margin
    yy = 1 - margin - yinterval - inner
    for s, p in zip(heatmaps, heatmapbins):
        s = s.replace("_", " ")
        s = Registration.get(s, s)

        yy -= yh
        m = stackarray(p, chr, window, shift)

        Y = np.array([m, m])
        root.imshow(Y, extent=(xx, xx + xlen, yy, yy + yh - inner),
                    interpolation="nearest", aspect="auto", cmap=iopts.cmap)
        root.text(xx + xlen + .01, yy, s, size=10)

    yy -= yh

    meres = opts.meres
    if meres:
        bed = Bed(meres)
        for b in bed:
            if b.seqid != chr:
                continue
            pos = (b.start + b.end) / 2
            cpos = pos / ratio
            xx = margin + cpos
            accn = b.accn.capitalize()
            root.add_patch(CirclePolygon((xx, yy), radius=.01, fc="m", ec="m"))
            root.text(xx + .014, yy, accn, va="center", color="m")

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = chr + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
76643
def heatmap(x, y, step=None, min_pt=None, max_pt=None,
                 colormap='Blues', alpha=1, grid=False,
                 colorbar=True, scale='lin',
                 vmax='auto', vmin='auto', crop=True):
    
    (x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt)

    # simple in this case because it is positive counts
    if scale == 'log':
        for row in hist_matrix:
            for i, el in enumerate(row):
                row[i] = 0 if row[i] == 0 else log10(row[i])

    # plot
    fig = plt.figure()
    init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap=colormap,
                 alpha=alpha, grid=grid, colorbar=colorbar,
                 vmax=vmax, vmin=vmin, crop=crop)

    return fig
1094854
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
        
        if ax == None:
            ax = pl.gca()

        if ax_channels is not None:
            flip = self._find_orientation(ax_channels)

        plot_func = ax.axes.axhline if flip else ax.axes.axvline

        kwargs.setdefault('color', 'black')
        a1 = plot_func(self.vert[0], *args, **kwargs)
        a2 = plot_func(self.vert[1], *args, **kwargs)

        return (a1, a2)
382792
def asfreq_actual(series, freq, method='ffill', how='end', normalize=False):
    
    orig = series
    is_series = False
    if isinstance(series, pd.Series):
        is_series = True
        name = series.name if series.name else 'data'
        orig = pd.DataFrame({name: series})

    # add date column
    t = pd.concat([orig, pd.DataFrame({'dt': orig.index.values},
                                      index=orig.index.values)], axis=1)
    # fetch dates
    dts = t.asfreq(freq=freq, method=method, how=how,
                   normalize=normalize)['dt']

    res = orig.loc[dts.values]

    if is_series:
        return res[name]
    else:
        return res
391287
def plot_weights(self, index=None, plot_type="motif_raw", figsize=None, ncol=1, **kwargs):
        

        if "heatmap" in self.AVAILABLE_PLOTS and plot_type == "heatmap":
            return self._plot_weights_heatmap(index=index, figsize=figsize, ncol=ncol, **kwargs)
        elif plot_type[:5] == "motif":
            return self._plot_weights_motif(index=index, plot_type=plot_type, figsize=figsize, ncol=ncol, **kwargs)
        else:
            raise ValueError("plot_type needs to be from {0}".format(self.AVAILABLE_PLOTS))
219081
def tsplot(series, plotf, ax=None, **kwargs):
    import warnings
    
    warnings.warn("'tsplot' is deprecated and will be removed in a "
                  "future version. Please use Series.plot() instead.",
                  FutureWarning, stacklevel=2)

    # Used inferred freq is possible, need a test case for inferred
    if ax is None:
        import matplotlib.pyplot as plt
        ax = plt.gca()

    freq, series = _maybe_resample(series, ax, kwargs)

    # Set ax with freq info
    _decorate_axes(ax, freq, kwargs)
    ax._plot_data.append((series, plotf, kwargs))
    lines = plotf(ax, series.index._mpl_repr(), series.values, **kwargs)

    # set date formatter, locators and rescale limits
    format_dateaxis(ax, ax.freq, series.index)
    return lines
786441
def plot(self, **kwargs):
        
        set_kwargs_drawstyle(kwargs, "default")
        return _plot_estimate(
            self, estimate=getattr(self, self._estimate_name), confidence_intervals=self.confidence_interval_, **kwargs
        )
669708
def parallel_plot(df, color=None, palette=None):
    
    npts = df.shape[0]
    ndims = len(df.columns)

    if color is None:
        color = np.ones(npts)
    if palette is None:
        palette = ['#ff0000']

    cmap = LinearColorMapper(high=color.min(),
                             low=color.max(),
                             palette=palette)

    data_source = ColumnDataSource(dict(
        xs=np.arange(ndims)[None, :].repeat(npts, axis=0).tolist(),
        ys=np.array((df-df.min())/(df.max()-df.min())).tolist(),
        color=color))

    p = figure(x_range=(-1, ndims),
               y_range=(0, 1),
               width=1000,
               tools="pan, box_zoom")

    # Create x axis ticks from columns contained in dataframe
    fixed_x_ticks = FixedTicker(
        ticks=np.arange(ndims), minor_ticks=[])
    formatter_x_ticks = FuncTickFormatter(
        code="return columns[index]", args={"columns": df.columns})
    p.xaxis.ticker = fixed_x_ticks
    p.xaxis.formatter = formatter_x_ticks

    p.yaxis.visible = False
    p.y_range.start = 0
    p.y_range.end = 1
    p.y_range.bounds = (-0.1, 1.1) # add a little padding around y axis
    p.xgrid.visible = False
    p.ygrid.visible = False

    # Create extra y axis for each dataframe column
    tickformatter = BasicTickFormatter(precision=1)
    for index, col in enumerate(df.columns):
        start = df[col].min()
        end = df[col].max()
        bound_min = start + abs(end-start) * (p.y_range.bounds[0] - p.y_range.start)
        bound_max = end + abs(end-start) * (p.y_range.bounds[1] - p.y_range.end)
        p.extra_y_ranges.update(
            {col: Range1d(start=bound_min, end=bound_max, bounds=(bound_min, bound_max))})

        fixedticks = FixedTicker(
            ticks=np.linspace(start, end, 8), minor_ticks=[])

        p.add_layout(LinearAxis(fixed_location=index, y_range_name=col,
                                ticker=fixedticks, formatter=tickformatter), 'right')

    # create the data renderer ( MultiLine )
    # specify selected and non selected style
    non_selected_line_style = dict(line_color='grey', line_width=0.1, line_alpha=0.5)

    selected_line_style = dict(line_color={'field': 'color', 'transform': cmap}, line_width=1)

    parallel_renderer = p.multi_line(
        xs="xs", ys="ys", source=data_source, **non_selected_line_style)

    # Specify selection style
    selected_lines = MultiLine(**selected_line_style)

    # Specify non selection style
    nonselected_lines = MultiLine(**non_selected_line_style)

    parallel_renderer.selection_glyph = selected_lines
    parallel_renderer.nonselection_glyph = nonselected_lines
    p.y_range.start = p.y_range.bounds[0]
    p.y_range.end = p.y_range.bounds[1]

    rect_source = ColumnDataSource({
        'x': [], 'y': [], 'width': [], 'height': []
    })

    # add rectangle selections
    selection_renderer = p.rect(x='x', y='y', width='width', height='height',
                                source=rect_source,
                                fill_alpha=0.7, fill_color='#009933')
    selection_tool = ParallelSelectionTool(
        renderer_select=selection_renderer, renderer_data=parallel_renderer,
        box_width=10)
    # custom resets (reset only axes not selections)
    reset_axes = ParallelResetTool()

    # add tools and activate selection ones
    p.add_tools(selection_tool, reset_axes)
    p.toolbar.active_drag = selection_tool
    return p
511660
def draw(filestems, gformat):
    
    # Draw heatmaps
    for filestem in filestems:
        fullstem = os.path.join(args.outdirname, filestem)
        outfilename = fullstem + ".%s" % gformat
        infilename = fullstem + ".tab"
        df = pd.read_csv(infilename, index_col=0, sep="\t")
        logger.info("Writing heatmap to %s", outfilename)
        params = pyani_graphics.Params(
            params_mpl(df)[filestem],
            pyani_tools.get_labels(args.labels),
            pyani_tools.get_labels(args.classes),
        )
        if args.gmethod == "mpl":
            pyani_graphics.heatmap_mpl(
                df, outfilename=outfilename, title=filestem, params=params
            )
        elif args.gmethod == "seaborn":
            pyani_graphics.heatmap_seaborn(
                df, outfilename=outfilename, title=filestem, params=params
            )
1207561
def plot_obsseries(self, **kwargs: Any) -> None:
        
        self.__plot_series([self.sequences.obs], kwargs)
292834
def timeseries(self):
        """"""
        if self._timeseries is None:
            self.compute()
        if isinstance(self.system, NetworkModel):
            return self.system._reshape_timeseries(self._timeseries)
        else:
            return self._timeseries
787109
def timeseries(datasets):
    """"""
    expanded_ds = []
    for ds in datasets:
        tmp = ds.expand_dims("time")
        tmp.coords["time"] = pd.DatetimeIndex([ds.attrs["start_time"]])
        expanded_ds.append(tmp)

    res = xr.concat(expanded_ds, dim="time")
    res.attrs = combine_metadata(*[x.attrs for x in expanded_ds])
    return res
1325658
def plot_fit(self,intervals=False,**kwargs):
        
        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))
        series_type = kwargs.get('series_type','Smoothed')

        if self.latent_variables.estimated is False:
            raise Exception("No latent variables estimated!")
        else:
            date_index = copy.deepcopy(self.index)
            date_index = date_index[:self.y.shape[0]+1]

            if series_type == 'Smoothed':
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())
            elif series_type == 'Filtered':
                mu, V, _, _, _ = self._model(self.data,self.latent_variables.get_z_values())
            else:
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())

            # Create smoothed/filtered aggregate series
            _, Z, _, _, _ = self._ss_matrices(self.latent_variables.get_z_values())
            smoothed_series = np.zeros(self.y.shape[0])

            for t in range(0,self.y.shape[0]):
                smoothed_series[t] = np.dot(Z[t],mu[:,t])

            plt.figure(figsize=figsize) 
            
            plt.subplot(self.z_no+1, 1, 1)
            plt.title(self.y_name + " Raw and " + series_type)  
            plt.plot(date_index,self.data,label='Data')
            plt.plot(date_index,smoothed_series,label=series_type,c='black')
            plt.legend(loc=2)

            for coef in range(0,self.z_no-1):
                V_coef = V[0][coef][:-1]    
                plt.subplot(self.z_no+1, 1, 2+coef)
                plt.title("Beta " + self.X_names[coef]) 

                if intervals == True:
                    alpha =[0.15*i/float(100) for i in range(50,12,-2)]
                    plt.fill_between(date_index[5:], mu[coef,0:mu.shape[1]-1][5:] + 1.98*np.sqrt(V_coef[5:]), mu[coef,0:mu.shape[1]-1][5:] - 1.98*np.sqrt(V_coef[5:]), alpha=0.15,label='95% C.I.') 
                plt.plot(date_index,mu[coef,0:mu.shape[1]-1],label='Data')
                plt.legend(loc=2)               
            
            plt.subplot(self.z_no+1, 1, self.z_no+1)
            plt.title("Measurement Error")
            plt.plot(date_index,self.data-smoothed_series,label='Irregular')
            plt.legend(loc=2)   

            plt.show()
57866
def plot_legend(ax, no_legend=True, legend_arg=None):
    
    legend_arg = dict_if_none(legend_arg)

    if not no_legend:
        ax.legend(**legend_arg)
593234
def project_wave(self, hp, hc, longitude, latitude, polarization):
        
        h_lal = lalsimulation.SimDetectorStrainREAL8TimeSeries(
                hp.astype(np.float64).lal(), hc.astype(np.float64).lal(),
                longitude, latitude, polarization, self.frDetector)
        return TimeSeries(
                h_lal.data.data, delta_t=h_lal.deltaT, epoch=h_lal.epoch,
                dtype=np.float64, copy=False)
301512
def _reshape_timeseries(self, ts):
        """"""
        if np.count_nonzero(np.diff(self._sublengths)) == 0:
            # then all submodels have the same dimension, so can reshape array
            # in place without copying data:
            subdim = self.dimension // self._n
            shp = list(ts.shape)
            shp[1] = self._n
            shp.insert(2, subdim)
            ts = ts.reshape(tuple(shp)).swapaxes(1, 2)
            # label variables only if all sub-models agree on the labels:
            all_var_labels = [m.labels for m in self.submodels]
            var_labels = all_var_labels[0]
            if all(v == var_labels for v in all_var_labels[1:]):
                ts.labels[1] = var_labels
            ts.labels[2] = self._node_labels()
            return ts
        else:
            # will pad with zeros for submodels with less variables
            subdim = max(self._sublengths)
            shp = list(ts.shape)
            shp[1] = subdim
            shp.insert(2, self._n)
            ar = np.zeros(shp)
            labels = ts.labels
            labels.insert(2, self._node_labels())
            for k in range(self._n):
                sl = slice(self._si[k], self._si[k+1])
                ar[:,:,k,...] = ts[:,sl,...]
            return Timeseries(ar, ts.tspan, labels)