示例#1
0
 def axYticks(labels, nTS, ivar, offsets=offset):
     pyplot.gca().set_yticks((offset * numpy.array([range(nTS)]).flatten()).tolist())
     try:
         pyplot.gca().set_yticklabels(labels.flatten().tolist())
     except:
         labels = generate_region_labels(nTS, [], "")
         self.logger.warning("Cannot convert region labels' strings for y axis ticks!")
 def string_connectivity_disease(self, region_labels=[]):
     region_labels = generate_region_labels(self.number_of_regions,
                                            region_labels,
                                            str=". ")
     disease_string = ""
     for w_ind, w_val in zip(self.w_indices, self.w_values):
         disease_string += region_labels[w_ind[0]] + " -> " + region_labels[
             w_ind[1]] + ": " + str(w_val) + "\n"
     return disease_string[:-1]
 def string_regions_disease(self, region_labels=[]):
     region_labels = generate_region_labels(self.number_of_regions,
                                            region_labels,
                                            str=". ")
     disease_values = self.regions_disease
     disease_string = ""
     for iRegion in self.regions_disease_indices:
         if iRegion in self.e_indices:
             hyp_type = "E"
         else:
             hyp_type = "x0"
         disease_string += region_labels[
             iRegion] + ": " + hyp_type + "=" + str(
                 disease_values[iRegion]) + "\n"
     return disease_string[:-1]
示例#4
0
 def _plot_gain_matrix(self,
                       sensors,
                       region_labels,
                       figure=None,
                       title="Projection",
                       y_labels=1,
                       x_labels=1,
                       x_ticks=numpy.array([]),
                       y_ticks=numpy.array([]),
                       figsize=FiguresConfig.VERY_LARGE_SIZE):
     if not (isinstance(figure, pyplot.Figure)):
         figure = pyplot.figure(title, figsize=figsize)
     n_sensors = sensors.number_of_sensors
     number_of_regions = len(region_labels)
     if len(x_ticks) == 0:
         x_ticks = numpy.array(range(n_sensors), dtype=numpy.int32)
     if len(y_ticks) == 0:
         y_ticks = numpy.array(range(number_of_regions), dtype=numpy.int32)
     cmap = pyplot.set_cmap('autumn_r')
     img = pyplot.imshow(sensors.gain_matrix[x_ticks][:, y_ticks].T,
                         cmap=cmap,
                         interpolation='none')
     pyplot.grid(True, color='black')
     if y_labels > 0:
         # region_labels = numpy.array(["%d. %s" % l for l in zip(range(number_of_regions), region_labels)])
         region_labels = generate_region_labels(number_of_regions,
                                                region_labels, ". ")
         pyplot.yticks(y_ticks, region_labels[y_ticks])
     else:
         pyplot.yticks(y_ticks)
     if x_labels > 0:
         sensor_labels = numpy.array(
             ["%d. %s" % l for l in zip(range(n_sensors), sensors.labels)])
         pyplot.xticks(x_ticks, sensor_labels[x_ticks], rotation=90)
     else:
         pyplot.xticks(x_ticks)
     ax = figure.get_axes()[0]
     ax.autoscale(tight=True)
     pyplot.title(title)
     divider = make_axes_locatable(ax)
     cax1 = divider.append_axes("right", size="5%", pad=0.05)
     pyplot.colorbar(
         img,
         cax=cax1)  # fraction=0.046, pad=0.04) #fraction=0.15, shrink=1.0
     self._save_figure(None, title)
     self._check_show()
     return figure, ax, cax1
示例#5
0
    def plot_timeseries(self, data_dict, time=None, mode="ts", subplots=None, special_idx=[], subtitles=[],
                        offset=1.0, time_units="ms", title='Time series', figure_name=None, labels=[],
                        figsize=FiguresConfig.LARGE_SIZE):
        n_vars = len(data_dict)
        vars = data_dict.keys()
        data = data_dict.values()
        data_lims = []
        for id, d in enumerate(data):
            if isequal_string(mode, "raster"):
                drange = numpy.percentile(d.flatten(), 95) - numpy.percentile(d.flatten(), 5)
                data[id] = d / drange # zscore(d, axis=None)
            data_lims.append([d.min(), d.max()])
        data_shape = data[0].shape
        n_times, nTS = data_shape[:2]
        if len(data_shape) > 2:
            nSamples = data_shape[2]
        else:
            nSamples = 1
        if len(subtitles) == 0:
            subtitles = vars
        labels = generate_region_labels(nTS, labels)
        if isequal_string(mode, "traj"):
            data_fun, plot_lines, projection, n_rows, n_cols, def_alpha, loopfun, \
            subtitle, subtitle_col, axlabels, axlimits = self._trajectories_plot(n_vars, nTS, nSamples, subplots)
        else:
            if isequal_string(mode, "raster"):
                data_fun, time, plot_lines, projection, n_rows, n_cols, def_alpha, loopfun, \
                subtitle, subtitle_col, axlabels, axlimits, axYticks = \
                    self._timeseries_plot(time, n_vars, nTS, n_times, time_units, 0, offset, data_lims)

            else:
                data_fun, time, plot_lines, projection, n_rows, n_cols, def_alpha, loopfun, \
                subtitle, subtitle_col, axlabels, axlimits, axYticks = \
                    self._timeseries_plot(time, n_vars, nTS, n_times, time_units, ensure_list(subplots)[0])
        alpha_ratio = 1.0 / nSamples
        colors = numpy.array(['k'] * nTS)
        alphas = numpy.maximum(numpy.array([def_alpha] * nTS) * alpha_ratio, 0.1)
        colors[special_idx] = 'r'
        alphas[special_idx] = numpy.maximum(alpha_ratio, 0.1)
        lines = []
        pyplot.figure(title, figsize=figsize)
        pyplot.hold(True)
        axes = []
        for icol in range(n_cols):
            if n_rows == 1:
                # If there are no more rows, create axis, and set its limits, labels and possible subtitle
                axes += ensure_list(pyplot.subplot(n_rows, n_cols, icol + 1, projection=projection))
                axlimits(data_lims, time, n_vars, icol)
                axlabels(labels, vars, n_vars, n_rows, 1, 0)
                pyplot.gca().set_title(subtitles[icol])
            for iTS in loopfun(nTS, n_rows, icol):
                if n_rows > 1:
                    # If there are more rows, create axes, and set their limits, labels and possible subtitles
                    axes += ensure_list(pyplot.subplot(n_rows, n_cols, iTS + 1, projection=projection))
                    subtitle(labels, iTS)
                    axlimits(data_lims, time, n_vars, icol)
                    axlabels(labels, vars, n_vars, n_rows, (iTS % n_rows) + 1, iTS)
                lines += ensure_list(plot_lines(data_fun(data, time, icol), iTS, colors, alphas, labels))
            if isequal_string(mode, "raster"):  # set yticks as labels if this is a raster plot
                axYticks(labels, nTS, icol)
                pyplot.gca().invert_yaxis()

        if self.config.figures.MOUSE_HOOVER:
            for line in lines:
                self.HighlightingDataCursor(line, formatter='{label}'.format, bbox=dict(fc='white'),
                                            arrowprops=dict(arrowstyle='simple', fc='white', alpha=0.5))

        self._save_figure(pyplot.gcf(), figure_name)
        self._check_show()
        return pyplot.gcf(), axes, lines
 def _region_parameters_violin_plots(
         self,
         samples_all,
         values=None,
         lines=None,
         stats=None,
         params=["x0", "x1_init", "z_init"],
         skip_samples=0,
         per_chain_or_run=False,
         labels=[],
         seizure_indices=None,
         figure_name="Regions parameters samples",
         figsize=FiguresConfig.VERY_LARGE_SIZE):
     if isinstance(values, dict):
         vals_fun = lambda param: values.get(param, numpy.array([]))
     else:
         vals_fun = lambda param: []
     if isinstance(lines, dict):
         lines_fun = lambda param: lines.get(param, numpy.array([]))
     else:
         lines_fun = lambda param: []
     samples_all = ensure_list(samples_all)
     params = [param for param in params if param in samples_all[0].keys()]
     samples = []
     for sample in samples_all:
         samples.append(
             extract_dict_stringkeys(sample, params, modefun="equal"))
     labels = generate_region_labels(samples[0].values()[0].shape[-1],
                                     labels)
     n_chains = len(samples_all)
     n_samples = samples[0].values()[0].shape[0]
     if n_samples > 1:
         violin_flag = True
     else:
         violin_flag = False
     if not per_chain_or_run and n_chains > 1:
         samples = [merge_samples(samples)]
         plot_samples = lambda s: numpy.concatenate(numpy.split(
             s[:, skip_samples:].T, n_chains, axis=2),
                                                    axis=1).squeeze().T
         plot_figure_name = lambda ichain: figure_name
     else:
         plot_samples = lambda s: s[skip_samples:]
         plot_figure_name = lambda ichain: figure_name + ": chain " + str(
             ichain + 1)
     params_labels = {}
     for ip, p in enumerate(params):
         if ip == 0:
             params_labels[p] = self._params_stats_labels(p, stats, labels)
         else:
             params_labels[p] = self._params_stats_labels(p, stats, "")
     n_params = len(params)
     if n_params > 9:
         warning(
             "Number of subplots in column wise vector-violin-plots cannot be > 9 and it is "
             + str(n_params) + "!")
     subplot_ind = 100 + n_params * 10
     figs = []
     for ichain, chain_sample in enumerate(samples):
         pyplot.figure(plot_figure_name(ichain), figsize=figsize)
         for ip, param in enumerate(params):
             fig = self.plot_vector_violin(plot_samples(
                 chain_sample[param]),
                                           vals_fun(param),
                                           lines_fun(param),
                                           params_labels[param],
                                           subplot_ind + ip + 1,
                                           param,
                                           violin_flag=violin_flag,
                                           colormap="YlOrRd",
                                           show_y_labels=True,
                                           indices_red=seizure_indices,
                                           sharey=None)
         self._save_figure(pyplot.gcf(), None)
         self._check_show()
         figs.append(fig)
     return tuple(figs)
    def plot_fit_results(self,
                         ests,
                         samples,
                         model_data,
                         target_data,
                         probabilistic_model=None,
                         info_crit=None,
                         stats=None,
                         pair_plot_params=[
                             "tau1", "K", "sigma", "epsilon", "scale", "offset"
                         ],
                         region_violin_params=["x0", "x1_init", "z_init"],
                         regions_labels=[],
                         regions_mode="active",
                         n_regions=1,
                         trajectories_plot=True,
                         connectivity_plot=False,
                         skip_samples=0,
                         title_prefix=""):
        if probabilistic_model is not None:
            active_regions = probabilistic_model.active_regions
        else:
            active_regions = model_data.get("active_regions", range(n_regions))
            regions_labels = generate_region_labels(n_regions, regions_labels,
                                                    ". ", False)
        if isequal_string(regions_mode, "all"):
            seizure_indices = active_regions
        else:
            region_inds = active_regions
            seizure_indices = None
            regions_labels = regions_labels[region_inds]

        figs = []
        if info_crit is not None:
            figs.append(
                self.plot_scalar_model_comparison(info_crit, title_prefix))
            figs.append(
                self.plot_array_model_comparison(
                    info_crit,
                    title_prefix,
                    labels=target_data.space_labels,
                    xdata=target_data.time_line,
                    xlabel="Time"))

        figs.append(
            self.plot_fit_scalar_params(samples, stats, probabilistic_model,
                                        pair_plot_params, skip_samples,
                                        title_prefix))

        figs.append(
            self.plot_fit_scalar_params_iters(samples,
                                              pair_plot_params,
                                              skip_samples,
                                              title_prefix,
                                              subplot_shape=None))

        figs.append(
            self.plot_fit_region_params(samples, stats, probabilistic_model,
                                        region_violin_params, seizure_indices,
                                        regions_labels, regions_mode, False,
                                        skip_samples, title_prefix))

        figs.append(
            self.plot_fit_region_params(samples, stats, probabilistic_model,
                                        region_violin_params, seizure_indices,
                                        regions_labels, regions_mode, True,
                                        skip_samples, title_prefix))

        # Pack fit samples time series into timeseries objects:
        from tvb_epilepsy.top.scripts.fitting_scripts import samples_to_timeseries
        samples, target_data = samples_to_timeseries(samples, model_data,
                                                     target_data,
                                                     regions_labels)
        figs.append(
            self.plot_fit_timeseries(target_data, samples, ests, stats,
                                     probabilistic_model, seizure_indices,
                                     skip_samples, trajectories_plot,
                                     title_prefix))

        if connectivity_plot:
            figs.append(
                self.plot_fit_connectivity(ests, stats, probabilistic_model,
                                           regions_labels, title_prefix))

        return tuple(figs)
    def plot_state_space(self, model_config, model="6D", region_labels=[], special_idx=[], zmode="lin", figure_name="",
                         approximations=False):
        add_name = " " + "Epileptor " + model + " z-" + str(zmode)
        figure_name = figure_name + add_name

        region_labels = generate_region_labels(model_config.number_of_regions, region_labels, ". ")
        # n_region_labels = len(region_labels)
        # if n_region_labels == model_config.number_of_regions:
        #     region_labels = numpy.array(["%d. %s" % l for l in zip(range(model_config.number_of_regions), region_labels)])
        # else:
        #     region_labels = numpy.array(["%d" % l for l in range(model_config.number_of_regions)])

        # Fixed parameters for all regions:
        x1eq = model_config.x1eq
        zeq = model_config.zeq
        x0 = a = b = d = yc = slope = Iext1 = Iext2 = s = 0.0
        for p in ["x0", "a", "b", "d", "yc", "slope", "Iext1", "Iext2", "s"]:
            exec (p + " = numpy.mean(model_config." + p + ")")

        fig = pyplot.figure(figure_name, figsize=FiguresConfig.SMALL_SIZE)

        # Lines:
        x1 = numpy.linspace(-2.0, 1.0, 100)
        if isequal_string(model, "2d"):
            y1 = yc
        else:
            y1 = calc_eq_y1(x1, yc, d=d)
        # x1 nullcline:
        zX1 = calc_fx1(x1, z=0, y1=y1, Iext1=Iext1, slope=slope, a=a, b=b, d=d, tau1=1.0, x1_neg=True, model=model,
                       x2=0.0)  # yc + Iext1 - x1 ** 3 - 2.0 * x1 ** 2
        x1null, = pyplot.plot(x1, zX1, 'b-', label='x1 nullcline', linewidth=1)
        ax = pyplot.gca()
        ax.axes.hold(True)
        # z nullcines
        # center point (critical equilibrium point) without approximation:
        # zsq0 = yc + Iext1 - x1sq0 ** 3 - 2.0 * x1sq0 ** 2
        x0e = calc_x0_val_to_model_x0(X0_CR_DEF, yc, Iext1, a=a, b=b, d=d, zmode=zmode)
        x0ne = calc_x0_val_to_model_x0(X0_DEF, yc, Iext1, a=a, b=b, d=d, zmode=zmode)
        zZe = calc_fz(x1, z=0.0, x0=x0e, tau1=1.0, tau0=1.0, zmode=zmode)  # for epileptogenic regions
        zZne = calc_fz(x1, z=0.0, x0=x0ne, tau1=1.0, tau0=1.0, zmode=zmode)  # for non-epileptogenic regions
        zE1null, = pyplot.plot(x1, zZe, 'g-', label='z nullcline at critical point (e_values=1)', linewidth=1)
        zE2null, = pyplot.plot(x1, zZne, 'g--', label='z nullcline for e_values=0', linewidth=1)
        if approximations:
            # The point of the linear approximation (1st order Taylor expansion)
            x1LIN = def_x1lin(X1_DEF, X1EQ_CR_DEF, len(region_labels))
            x1SQ = X1EQ_CR_DEF
            x1lin0 = numpy.mean(x1LIN)
            # The point of the square (parabolic) approximation (2nd order Taylor expansion)
            x1sq0 = numpy.mean(x1SQ)
            # approximations:
            # linear:
            x1lin = numpy.linspace(-5.5 / 3.0, -3.5 / 3, 30)
            # x1 nullcline after linear approximation:
            # yc + Iext1 + 2.0 * x1lin0 ** 3 + 2.0 * x1lin0 ** 2 - \
            # (3.0 * x1lin0 ** 2 + 4.0 * x1lin0) * x1lin  # x1
            zX1lin = calc_fx1_2d_taylor(x1lin, x1lin0, z=0, y1=yc, Iext1=Iext1, slope=slope, a=a, b=b, d=d, tau1=1.0,
                                        x1_neg=None, order=2)  #
            # center point without approximation:
            # zlin0 = yc + Iext1 - x1lin0 ** 3 - 2.0 * x1lin0 ** 2
            # square:
            x1sq = numpy.linspace(-5.0 / 3, -1.0, 30)
            # x1 nullcline after parabolic approximation:
            # + 2.0 * x1sq ** 2 + 16.0 * x1sq / 3.0 + yc + Iext1 + 64.0 / 27.0
            zX1sq = calc_fx1_2d_taylor(x1sq, x1sq0, z=0, y1=yc, Iext1=Iext1, slope=slope, a=a, b=b, d=d, tau1=1.0,
                                       x1_neg=None, order=3, shape=x1sq.shape)
            sq, = pyplot.plot(x1sq, zX1sq, 'm--', label='Parabolic local approximation', linewidth=2)
            lin, = pyplot.plot(x1lin, zX1lin, 'c--', label='Linear local approximation', linewidth=2)
            pyplot.legend(handles=[x1null, zE1null, zE2null, lin, sq])
        else:
            pyplot.legend(handles=[x1null, zE1null, zE2null])

        # Points:
        ii = range(len(region_labels))
        n_special_idx = len(special_idx)
        if n_special_idx > 0:
            ii = numpy.delete(ii, special_idx)
        points = []
        for i in ii:
            point = pyplot.text(x1eq[i], zeq[i], str(i), fontsize=10, color='k', alpha=0.3,
                                 label=str(i) + '.' + region_labels[i])
            # point, = pyplot.plot(x1eq[i], zeq[i], '*', mfc='k', mec='k',
            #                      ms=10, alpha=0.3, label=str(i) + '.' + region_labels[i])
            points.append(point)
        if n_special_idx > 0:
            for i in special_idx:
                point = pyplot.text(x1eq[i], zeq[i], str(i), fontsize=10, color='r', alpha=0.8,
                                     label=str(i) + '.' + region_labels[i])
                # point, = pyplot.plot(x1eq[i], zeq[i], '*', mfc='r', mec='r', ms=10, alpha=0.8,
                #                      label=str(i) + '.' + region_labels[i])
                points.append(point)
        # ax.plot(x1lin0, zlin0, '*', mfc='r', mec='r', ms=10)
        # ax.axes.text(x1lin0 - 0.1, zlin0 + 0.2, 'e_values=0.0', fontsize=10, color='r')
        # ax.plot(x1sq0, zsq0, '*', mfc='m', mec='m', ms=10)
        # ax.axes.text(x1sq0, zsq0 - 0.2, 'e_values=1.0', fontsize=10, color='m')

        # Vector field
        X1, Z = numpy.meshgrid(numpy.linspace(-2.0, 1.0, 41), numpy.linspace(0.0, 6.0, 31), indexing='ij')
        if isequal_string(model, "2d"):
            y1 = yc
            x2 = 0.0
        else:
            y1 = calc_eq_y1(X1, yc, d=d)
            x2 = 0.0  # as a simplification for faster computation without important consequences
            # x2 = calc_eq_x2(Iext2, y2eq=None, zeq=X1, x1eq=Z, s=s)[0]
        fx1 = calc_fx1(X1, Z, y1=y1, Iext1=Iext1, slope=slope, a=a, b=b, d=d, tau1=model_config.tau1, x1_neg=None, model=model,
                       x2=x2)
        fz = calc_fz(X1, Z, x0=x0, tau1=model_config.tau1, tau0=model_config.tau0, zmode=zmode)
        C = numpy.abs(fx1) + numpy.abs(fz)
        pyplot.quiver(X1, Z, fx1, fz, C, edgecolor='k', alpha=.5, linewidth=.5)
        pyplot.contour(X1, Z, fx1, 0, colors='b', linestyles="dashed")

        ax.set_title("Epileptor states pace at the x1-z phase plane of the" + add_name)
        ax.axes.autoscale(tight=True)
        ax.axes.set_ylim([0.0, 6.0])
        ax.axes.set_xlabel('x1')
        ax.axes.set_ylabel('z')

        if self.config.figures.MOUSE_HOOVER:
            self.HighlightingDataCursor(points[0], formatter='{label}'.format, bbox=dict(fc='white'),
                                        arrowprops=dict(arrowstyle='simple', fc='white', alpha=0.5))

        if len(fig.get_label()) == 0:
            fig.set_label(figure_name)
        else:
            figure_name = fig.get_label().replace(": ", "_").replace(" ", "_").replace("\t", "_")

        self._save_figure(None, figure_name)
        self._check_show()
        return fig
示例#9
0
def samples_to_timeseries(samples,
                          model_data,
                          target_data=None,
                          regions_labels=[]):
    samples = ensure_list(samples)

    if isinstance(target_data, Timeseries):
        time = target_data.time_line
        n_target_data = target_data.number_of_labels
        target_data_labels = target_data.space_labels
    else:
        time = model_data.get("time", False)
        n_target_data = samples[0]["fit_target_data"]
        target_data_labels = generate_region_labels(n_target_data, [], ". ",
                                                    False)

    if time is not False:
        time_start = time[0]
        time_step = np.diff(time).mean()
    else:
        time_start = 0
        time_step = 1

    if not isinstance(target_data, Timeseries):
        target_data = Timeseries(
            target_data, {
                TimeseriesDimensions.SPACE.value: target_data_labels,
                TimeseriesDimensions.VARIABLES.value: ["target_data"]
            },
            time_start=time_start,
            time_step=time_step)

    (n_times, n_regions, n_samples) = samples[0]["x1"].T.shape
    active_regions = model_data.get("active_regions", range(n_regions))
    regions_labels = generate_region_labels(
        np.maximum(n_regions, len(regions_labels)), regions_labels, ". ",
        False)
    if len(regions_labels) > len(active_regions):
        regions_labels = regions_labels[active_regions]

    for sample in ensure_list(samples):
        for x in ["x1", "z", "dX1t", "dZt"]:
            try:
                sample[x] = Timeseries(
                    np.expand_dims(sample[x].T, 2), {
                        TimeseriesDimensions.SPACE.value: regions_labels,
                        TimeseriesDimensions.VARIABLES.value: [x]
                    },
                    time_start=time_start,
                    time_step=time_step,
                    time_unit=target_data.time_unit)
            except:
                pass

        sample["fit_target_data"] = Timeseries(
            np.expand_dims(sample["fit_target_data"].T, 2), {
                TimeseriesDimensions.SPACE.value: target_data_labels,
                TimeseriesDimensions.VARIABLES.value: ["fit_target_data"]
            },
            time_start=time_start,
            time_step=time_step)

    return samples, target_data