def _sort_disease_indices_values(self, disease_dict):
     indices = []
     values = []
     for key, value in disease_dict.iteritems():
         value = ensure_list(value)
         key = ensure_list(key)
         n = len(key)
         if n > 0:
             indices += key
             if len(value) == n:
                 values += value
             elif len(value) == 1 and n > 1:
                 values += value * n
             else:
                 raise_value_error("Length of disease indices " + str(n) +
                                   " and values " + str(len(value)) +
                                   " do not match!")
     if len(indices) > 0:
         if isinstance(indices[0], tuple):
             arg_sort = np.ravel_multi_index(
                 indices, (self.number_of_regions,
                           self.number_of_regions)).argsort()
         else:
             arg_sort = np.argsort(indices)
         return np.array(indices)[arg_sort].tolist(), np.array(
             values)[arg_sort]
     else:
         return [], []
Example #2
0
 def set_sensors(self,
                 input_sensors,
                 s_type=Sensors.TYPE_SEEG,
                 reset=False):
     if input_sensors is None:
         return
     sensors = ensure_list(self.get_sensors(s_type))
     if reset is False or len(sensors) == 0:
         sensors = []
     for s in ensure_list(input_sensors):
         if isinstance(s, Sensors) and (s.s_type == s_type):
             if s.gain_matrix is None or s.gain_matrix.shape != (
                     s.number_of_sensors, self.number_of_regions):
                 self.logger.warning(
                     "No correctly sized gain matrix found in sensors! Computing and adding gain matrix!"
                 )
                 s.gain_matrix = s.compute_gain_matrix(self.connectivity)
             # if s.orientations == None or s.orientations.shape != (s.number_of_sensors, 3):
             #     self.logger.warning("No orientations found in sensors!")
             sensors.append(s)
         else:
             if s is not None:
                 raise_value_error(
                     "Input sensors:\n" + str(s) +
                     "\nis not a valid Sensors object of type " +
                     str(s_type) + "!")
     if len(sensors) == 0:
         setattr(self, "sensors" + s_type, [])
     else:
         setattr(self, "sensors" + s_type, sensors)
Example #3
0
 def __init__(self, number_of_regions=1, x0_values=X0_DEF, e_values=E_DEF, yc=YC_DEF, Iext1=I_EXT1_DEF,
              Iext2=I_EXT2_DEF, K=K_DEF, a=A_DEF, b=B_DEF, d=D_DEF, slope=SLOPE_DEF, s=S_DEF, gamma=GAMMA_DEF,
              zmode=np.array("lin"), x1eq_mode="optimize"):
     self.number_of_regions = number_of_regions
     self.x0_values = x0_values * np.ones((self.number_of_regions,), dtype=np.float32)
     self.yc = yc
     self.Iext1 = Iext1
     self.Iext2 = Iext2
     self.a = a
     self.b = b
     self.d = d
     self.slope = slope
     self.s = s
     self.gamma = gamma
     self.zmode = zmode
     self.x1eq_mode = x1eq_mode
     if len(ensure_list(K)) == 1:
         self.K_unscaled = np.array(K) * np.ones((self.number_of_regions,), dtype=np.float32)
     elif len(ensure_list(K)) == self.number_of_regions:
         self.K_unscaled = np.array(K)
     else:
         self.logger.warning(
             "The length of input global coupling K is neither 1 nor equal to the number of regions!" +
             "\nSetting model_configuration_builder.K_unscaled = K_DEF for all regions")
     self.K = None
     self._normalize_global_coupling()
     self.e_values = e_values * np.ones((self.number_of_regions,), dtype=np.float32)
     self.x0cr = 0.0
     self.rx0 = 0.0
     self._compute_critical_x0_scaling()
Example #4
0
def convert_params_names_to_ins(dicts_list,
                                parameter_names=INS_PARAMS_NAMES_DICT):
    output = []
    for lst in ensure_list(dicts_list):
        for dct in ensure_list(lst):
            for p, p_ins in parameter_names.iteritems():
                try:
                    dct[p_ins] = dct[p]
                except:
                    warning("Parameter " + p + " not found in \n" +
                            str(dicts_list))
        output.append(lst)
    return tuple(output)
 def update_active_regions(self, statistical_model, methods=["e_values", "LSA"], reset=False, **kwargs):
     if reset:
         statistical_model.update_active_regions([])
     for m, th in zip(*assert_arrays([ensure_list(methods),
                                      ensure_list(kwargs.get("active_regions_th", None))])):
         if isequal_string(m, "e_values"):
             statistical_model = self.update_active_regions_e_values(statistical_model, th)
         elif isequal_string(m, "x0_values"):
             statistical_model = self.update_active_regions_x0_values(statistical_model, th)
         elif isequal_string(m, "lsa"):
             statistical_model = self.update_active_regions_lsa(statistical_model, th)
         elif isequal_string(m, "seeg"):
             statistical_model = self.update_active_regions_seeg(statistical_model, th,
                                                                 seeg_inds=kwargs.get("seeg_inds"))
     return statistical_model
Example #6
0
 def pair_plots(self, data, keys, transpose=False, skip=0, title='Pair plots', subtitles=None, figure_name=None,
                figsize=FiguresConfig.VERY_LARGE_SIZE):
     if subtitles is None:
         subtitles = keys
     data = ensure_list(data)
     n = len(keys)
     fig, axes = pyplot.subplots(n, n, figsize=figsize)
     fig.set_label(title)
     for i, key_i in enumerate(keys):
         for j, key_j in enumerate(keys):
             for datai in data:
                 if transpose:
                     di = datai[key_i].T[skip:]
                 else:
                     di = datai[key_i][skip:]
                 if i == j:
                     axes[i, j].hist(di, int(numpy.round(numpy.sqrt(len(di)))), log=True)
                 else:
                     if transpose:
                         dj = datai[key_j].T[skip:]
                     else:
                         dj = datai[key_j][skip:]
                     axes[i, j].plot(dj, di, '.')
             if i == 0:
                 axes[i, j].set_title(subtitles[j])
             if j == 0:
                 axes[i, j].set_ylabel(key_i)
     fig.tight_layout()
     self._save_figure(fig, figure_name)
     self._check_show()
     return fig, axes
Example #7
0
 def compute_nearest_regions_to_sensors(self, head, sensors=None, target_contacts=None, s_type=Sensors.TYPE_SEEG,
                                        sensors_id=0, n_regions=None, gain_matrix_th=None):
     if not (isinstance(sensors, Sensors)):
         sensors = head.get_sensors_id(s_type=s_type, sensor_ids=sensors_id)
     n_contacts = sensors.labels.shape[0]
     if isinstance(target_contacts, (list, tuple, np.ndarray)):
         target_contacts = ensure_list(target_contacts)
         for itc, tc in enumerate(target_contacts):
             if isinstance(tc, int):
                 continue
             elif isinstance(tc, basestring):
                 target_contacts[itc] = sensors.contact_label_to_index([tc])
             else:
                 raise_value_error("target_contacts[" + str(itc) + "] = " + str(tc) +
                                   "is neither an integer nor a string!")
     else:
         target_contacts = range(n_contacts)
     auto_flag = False
     if n_regions is "all":
         n_regions = head.connectivity.number_of_regions
     elif not (isinstance(n_regions, int)):
         auto_flag = True
     nearest_regions = []
     for tc in target_contacts:
         projs = sensors.gain_matrix[tc]
         inds = np.argsort(projs)[::-1]
         if auto_flag:
             n_regions = select_greater_values_array_inds(projs[inds], threshold=gain_matrix_th)
         inds = inds[:n_regions]
         nearest_regions.append((inds, head.connectivity.region_labels[inds], projs[inds]))
     return nearest_regions
    def _parameters_pair_plots(
            self,
            samples_all,
            params=["tau1", "K", "sigma", "epsilon", "scale", "offset"],
            stats=None,
            priors={},
            truth={},
            skip_samples=0,
            title='Parameters samples',
            figure_name=None,
            figsize=FiguresConfig.VERY_LARGE_SIZE):
        subtitles = list(self._params_stats_subtitles(params, stats))
        samples = []
        samples_all = ensure_list(samples_all)
        params = [param for param in params if param in samples_all[0].keys()]
        for sample in samples_all:
            samples.append(
                extract_dict_stringkeys(sample, params, modefun="equal"))
        if len(samples_all) > 1:
            samples = merge_samples(samples)
        else:
            samples = samples_all[0]
            n_samples = (samples.values()[0]).shape[0]
            for p_key, p_val in samples.items():
                samples[p_key] = numpy.reshape(p_val, (1, n_samples))
        diagonal_plots = {}
        # for param_key in samples.keys():
        for p_key in params:
            diagonal_plots.update(
                {p_key: [priors.get(p_key, ()),
                         truth.get(p_key, ())]})

        return self.pair_plots(samples, params, diagonal_plots, True,
                               skip_samples, title, "chains/runs ", subtitles,
                               figure_name, figsize)
Example #9
0
def select_by_hierarchical_group_metric_clustering(distance,
                                                   disconnectivity=np.array(
                                                       []),
                                                   metric=None,
                                                   n_groups=10,
                                                   members_per_group=1):
    if disconnectivity.shape == distance.shape:
        distance = distance * disconnectivity
    n_groups = np.minimum(np.maximum(n_groups, 3),
                          n_groups // members_per_group)
    clustering = AgglomerativeClustering(n_groups,
                                         affinity="precomputed",
                                         linkage="average")
    clusters_labels = clustering.fit_predict(distance)
    selection = []
    for cluster_id in range(len(np.unique(clusters_labels))):
        # For each cluster, select the first...
        cluster_inds = np.where(clusters_labels == cluster_id)[0]
        # ... at least members_per_group elements...
        n_select = np.minimum(members_per_group, len(cluster_inds))
        if metric is not None and len(ensure_list(metric)) == n_groups:
            #...optionally according to some metric
            inds_select = np.argsort(metric[cluster_inds])[-n_select:]
        else:
            #...otherwise, randomly
            inds_select = range(n_select)
        selection.append(cluster_inds[inds_select])
    return np.unique(np.hstack(selection)).tolist()
def compute_seeg_and_write_ts_h5_file(folder,
                                      filename,
                                      model,
                                      vois_ts_dict,
                                      dt,
                                      time_length,
                                      hpf_flag=False,
                                      hpf_low=10.0,
                                      hpf_high=256.0,
                                      sensors_list=[],
                                      save_flag=True):
    fsAVG = 1000.0 / dt
    sensors_list = ensure_list(sensors_list)
    # Optionally high pass filter, and compute SEEG:
    if isinstance(model, EpileptorDP2D):
        raw_data = np.dstack(
            [vois_ts_dict["x1"], vois_ts_dict["z"], vois_ts_dict["x1"]])
        vois_ts_dict["lfp"] = vois_ts_dict["x1"]
        idx_proj = -1
        for sensor in sensors_list:
            if isinstance(sensor, Sensors):
                idx_proj += 1
                sensor_name = sensor.s_type + '%d' % idx_proj
                vois_ts_dict[sensor_name] = vois_ts_dict['x1'].dot(
                    sensor.gain_matrix.T)
                vois_ts_dict[sensor_name] -= np.min(vois_ts_dict[sensor_name])
                vois_ts_dict[sensor_name] /= np.max(vois_ts_dict[sensor_name])
    else:
        vois_ts_dict["lfp"] = vois_ts_dict["x2"] - vois_ts_dict["x1"]
        raw_data = np.dstack(
            [vois_ts_dict["x1"], vois_ts_dict["z"], vois_ts_dict["x2"]])
        if hpf_flag:
            hpf_low = max(hpf_low, 1000.0 / time_length)
            hpf_high = min(fsAVG / 2.0 - 10.0, hpf_high)
        idx_proj = -1
        for sensor in sensors_list:
            if isinstance(sensor, Sensors):
                idx_proj += 1
                sensor_name = sensor.s_type + '%d' % idx_proj
                vois_ts_dict[sensor_name] = vois_ts_dict['lfp'].dot(
                    sensor.gain_matrix.T)
                if hpf_flag:
                    for i in range(vois_ts_dict[sensor_name].shape[1]):
                        vois_ts_dict[sensor_name][:, i] = \
                            filter_data(vois_ts_dict[sensor_name][:, i], fsAVG, hpf_low, hpf_high)
                vois_ts_dict[sensor_name] -= np.min(vois_ts_dict[sensor_name])
                vois_ts_dict[sensor_name] /= np.max(vois_ts_dict[sensor_name])

    if save_flag:
        h5_writer = H5Writer()
        h5_writer.write_ts_epi(raw_data, dt, os.path.join(folder, filename),
                               vois_ts_dict["lfp"])
        # Write files:
        if idx_proj > -1:
            for i_sensor, sensor in enumerate(sensors_list):
                h5_writer.write_ts_seeg_epi(
                    vois_ts_dict[sensor.s_type + '%d' % i_sensor], dt,
                    os.path.join(folder, filename))
    return vois_ts_dict
Example #11
0
 def update_active_regions(self, active_regions):
     if np.all(np.in1d(active_regions, range(self.number_of_regions))):
         self.active_regions = np.unique(
             ensure_list(active_regions) + self.active_regions).tolist()
     else:
         raise_value_error("Active regions indices:\n" +
                           str(active_regions) +
                           "\nbeyond number of regions (" +
                           str(self.number_of_regions) + ")!")
Example #12
0
 def read_head(
     self,
     root_folder,
     name='',
     connectivity_file="connectivity.zip",
     surface_file="surface.zip",
     region_mapping_file="region_mapping.txt",
     eeg_sensors_files=[("eeg_brainstorm_65.txt",
                         "gain_matrix_eeg_65_surface_16k.npy")],
     meg_sensors_files=[("meg_brainstorm_276.txt",
                         "gain_matrix_meg_276_surface_16k.npy")],
     seeg_sensors_files=[("seeg_588.txt",
                          "gain_matrix_seeg_588_surface_16k.npy")],
 ):
     conn = self.read_connectivity(
         os.path.join(root_folder, connectivity_file))
     srf = self.read_cortical_surface(
         os.path.join(root_folder, surface_file))
     rm = self.read_region_mapping(
         os.path.join(root_folder, region_mapping_file))
     vm = None
     t1 = None
     sensorsSEEG = []
     for s_files in ensure_list(seeg_sensors_files):
         sensorsSEEG.append(
             self.read_sensors(s_files, root_folder, Sensors.TYPE_SEEG))
     sensorsEEG = []
     for s_files in ensure_list(eeg_sensors_files):
         sensorsEEG.append(
             self.read_sensors(s_files, root_folder, Sensors.TYPE_EEG))
     sensorsMEG = []
     for s_files in ensure_list(meg_sensors_files):
         sensorsMEG.append(
             self.read_sensors(s_files, root_folder, Sensors.TYPE_MEG))
     return Head(conn,
                 srf,
                 rm,
                 vm,
                 t1,
                 name,
                 sensorsSEEG=sensorsSEEG,
                 sensorsEEG=sensorsEEG,
                 sensorsMEG=sensorsMEG)
Example #13
0
 def check_number_of_inputs(nmodels, input, input_str):
     input = ensure_list(input)
     ninput = len(input)
     if ninput != nmodels:
         if ninput == 1:
             input *= nmodels
         else:
             raise_value_error("The size of input " + input_str + " (" + str(ninput) +
                               ") is neither equal to the number of models (" + str(nmodels) +
                               ") nor equal to 1!")
     return input
 def set_normalize(self, values):
     values = ensure_list(values)
     n_vals = len(values)
     if n_vals > 0:
         if n_vals > 2:
             raise_value_error("Invalid disease hypothesis normalization values!: " + str(values) +
                               "\nThey cannot be more than 2!")
         else:
             if n_vals < 2:
                 # Assuming normalization only to a maximum value, keeping the existing minimum one
                 values = [numpy.min(self.diseased_regions_values)] + values
             self.normalize_values = values
     return self
Example #15
0
 def plot_simulated_seeg_timeseries(self, seeg_list, title_prefix="Ep"):
     figs = []
     for seeg in ensure_list(seeg_list):
         title = title_prefix + "Simulated SEEG" + str(
             len(seeg.space_labels)) + " raster plot"
         figs.append(
             self.plot_raster({'SEEG': seeg.squeezed},
                              seeg.time_line,
                              time_units=seeg.time_unit,
                              title=title,
                              offset=1.0,
                              labels=seeg.space_labels,
                              figsize=FiguresConfig.VERY_LARGE_SIZE))
     return tuple(figs)
    def __init__(self,
                 yc=YC_DEF,
                 Iext1=I_EXT1_DEF,
                 Iext2=I_EXT2_DEF,
                 K=K_DEF,
                 a=A_DEF,
                 b=B_DEF,
                 d=D_DEF,
                 slope=SLOPE_DEF,
                 s=S_DEF,
                 gamma=GAMMA_DEF,
                 tau1=TAU1_DEF,
                 tau0=TAU0_DEF,
                 x1eq=None,
                 zeq=None,
                 Ceq=None,
                 x0=None,
                 x0_values=X0_DEF,
                 e_values=None,
                 zmode=np.array("lin"),
                 model_connectivity=None,
                 number_of_regions=0):
        # These parameters are used for every Epileptor Model...
        self.x0_values = x0_values
        self.x0 = x0
        self.yc = yc
        self.Iext1 = Iext1
        self.Iext2 = Iext2
        self.K = K
        self.a = a
        self.b = b
        self.d = d
        self.s = s
        self.slope = slope
        self.gamma = gamma
        self.tau1 = tau1
        self.tau0 = tau0
        # These parameters are used only for EpileptorDP2D Model
        self.zmode = zmode

        # These parameters are not used for Epileptor Model, but are important to keep (h5 or plotting)
        self.x1eq = x1eq
        self.zeq = zeq
        self.Ceq = Ceq
        self.e_values = e_values
        self.model_connectivity = model_connectivity
        if number_of_regions == 0 and model_connectivity is not None:
            self.number_of_regions = model_connectivity.shape[0]
        else:
            self.number_of_regions = len(ensure_list(self.x1eq))
 def compute_seeg(self, source_timeseries, sensors, sum_mode="lin"):
     if sum_mode == "exp":
         seeg_fun = lambda source, gain_matrix: np.log(np.exp(source.squeezed).dot(gain_matrix.T))
     else:
         seeg_fun = lambda source, gain_matrix: source.squeezed.dot(gain_matrix.T)
     seeg = []
     for sensor in ensure_list(sensors):
         seeg.append(Timeseries(seeg_fun(source_timeseries, sensor.gain_matrix),
                                {TimeseriesDimensions.SPACE.value: sensor.labels,
                                 TimeseriesDimensions.VARIABLES.value:
                                     PossibleVariables.SEEG.value + str(sensor.labels)},
                                source_timeseries.time_start, source_timeseries.time_step,
                                source_timeseries.time_unit))
     return seeg
 def plot_fit_connectivity(self,
                           ests,
                           samples,
                           stats=None,
                           probabilistic_model=None,
                           region_labels=[],
                           title_prefix=""):
     # plot connectivity
     if len(title_prefix) > 0:
         title_prefix = title_prefix + "_"
     if probabilistic_model is not None:
         MC_prior = probabilistic_model.get_prior("MC")
         MC_subplot = 122
     else:
         MC_prior = False
         MC_subplot = 111
     for id_est, (est, sample) in enumerate(
             zip(ensure_list(ests), ensure_list(samples))):
         conn_figure_name = title_prefix + "chain" + str(
             id_est + 1) + ": Model Connectivity"
         pyplot.figure(conn_figure_name, FiguresConfig.VERY_LARGE_SIZE)
         # plot_regions2regions(conn.weights, conn.region_labels, 121, "weights")
         if MC_prior:
             self.plot_regions2regions(MC_prior, region_labels, 121,
                                       "Prior Model Connectivity")
         MC_title = "Posterior Model  Connectivity"
         if isinstance(stats, dict):
             MC_title = MC_title + ": "
             for skey, sval in stats.items():
                 MC_title = MC_title + skey + "_mean=" + str(
                     sval["MC"].mean()) + ", "
             MC_title = MC_title[:-2]
         fig = self.plot_regions2regions(est["MC"], region_labels,
                                         MC_subplot, MC_title)
         self._save_figure(pyplot.gcf(), conn_figure_name)
         self._check_show()
         return fig
Example #19
0
 def plot_head(self, head):
     output = []
     output.append(self._plot_connectivity(head.connectivity))
     output.append(self._plot_connectivity_stats(head.connectivity))
     count = 1
     for s_type in SensorTypes:
         sensors = getattr(head, "sensors" + s_type.value)
         if isinstance(sensors, (list, Sensors)):
             sensors_list = ensure_list(sensors)
             if len(sensors_list) > 0:
                 for s in sensors_list:
                     count, figure, ax, cax = self._plot_sensors(
                         s, head.connectivity.region_labels, count)
                     output.append((figure, ax, cax))
     return tuple(output)
Example #20
0
 def get_sensors_id(self, s_type=Sensors.TYPE_SEEG, sensor_ids=0):
     sensors = self.get_sensors(s_type)
     if sensors is None:
         return sensors
     else:
         out_sensors = []
         sensors = ensure_list(sensors)
         for iS, s in enumerate(sensors):
             if np.in1d(iS, sensor_ids):
                 out_sensors.append(sensors[iS])
         if len(out_sensors) == 0:
             return None
         elif len(out_sensors) == 1:
             return out_sensors[0]
         else:
             return out_sensors
Example #21
0
def merge_samples(samples, skip_samples=0, flatten=False):
    samples = ensure_list(samples)
    if len(samples) > 1:
        samples = list_of_dicts_to_dicts_of_ndarrays(samples)
        for skey in samples.keys():
            if len(samples[skey].shape) == 1:
                samples[skey] = (samples[skey]*np.ones((1, 1))).T
            if flatten:
                sshape = samples[skey].shape
                if len(sshape) > 2:
                    samples[skey] = np.reshape(samples[skey][:, skip_samples:], tuple((-1,) + sshape[2:]))
                else:
                    samples[skey] = samples[skey][:, skip_samples:].flatten()

        return samples
    else:
        return samples[0]
Example #22
0
 def select_sensors_corr(self,
                         sensors,
                         distance,
                         initial_selection=[],
                         n_electrodes=10,
                         sensors_per_electrode=1,
                         power=None,
                         group_electrodes=False):
     if len(initial_selection) == 0:
         initial_selection = range(sensors.number_of_sensors)
     n_sensors = len(initial_selection)
     if n_sensors > 2:
         initial_selection = np.array(initial_selection)
         distance = 1.0 - distance
         if group_electrodes:
             elec_labels, elec_inds = sensors.group_sensors_to_electrodes(
                 sensors.labels[initial_selection])
             if len(elec_labels) >= 2:
                 noconnectivity = np.ones((n_sensors, n_sensors))
                 for ch in elec_inds:
                     noconnectivity[np.meshgrid(ch, ch)] = 0.0
                 distance = distance * noconnectivity
         n_electrodes = np.minimum(np.maximum(n_electrodes, 3),
                                   n_sensors // sensors_per_electrode)
         clustering = AgglomerativeClustering(n_electrodes,
                                              affinity="precomputed",
                                              linkage="average")
         clusters_labels = clustering.fit_predict(distance)
         selection = []
         for cluster_id in range(len(np.unique(clusters_labels))):
             cluster_inds = np.where(clusters_labels == cluster_id)[0]
             n_select = np.minimum(sensors_per_electrode, len(cluster_inds))
             if power is not None and len(ensure_list(power)) == n_sensors:
                 inds_select = np.argsort(power[cluster_inds])[-n_select:]
             else:
                 inds_select = range(n_select)
             selection.append(initial_selection[cluster_inds[inds_select]])
         return np.unique(np.hstack(selection)).tolist()
     else:
         self.logger.warning(
             "Number of sensors' left < 6!\n" +
             "Skipping clustering and returning all of them!")
         return initial_selection
Example #23
0
 def compute_estimates_from_samples(self, samples):
     ests = []
     for chain_or_run_samples in ensure_list(samples):
         est = {}
         for pkey, pval in chain_or_run_samples.items():
             try:
                 est[pkey + "_low"], est[pkey], est[pkey + "_std"] = describe(chain_or_run_samples[pkey])[1:4]
                 est[pkey + "_high"] = est[pkey + "_low"][1]
                 est[pkey + "_low"] = est[pkey + "_low"][0]
                 est[pkey + "_std"] = np.sqrt(est[pkey + "_std"])
                 for skey in [pkey, pkey + "_low", pkey + "_high", pkey + "_std"]:
                     est[skey] = np.squeeze(est[skey])
             except:
                 est[pkey] = chain_or_run_samples[pkey]
         ests.append(sort_dict(est))
     if len(ests) == 1:
         return ests[0]
     else:
         return ests
 def update_active_regions(self,
                           probabilistic_model,
                           e_values=[],
                           x0_values=[],
                           lsa_propagation_strengths=[],
                           reset=False):
     if reset:
         probabilistic_model.update_active_regions([])
     for m in ensure_list(self.active_regions_selection_methods):
         if isequal_string(m, "E"):
             probabilistic_model = self.update_active_regions_e_values(
                 probabilistic_model, e_values, reset=False)
         elif isequal_string(m, "x0"):
             probabilistic_model = self.update_active_regions_x0_values(
                 probabilistic_model, x0_values, reset=False)
         elif isequal_string(m, "LSA"):
             probabilistic_model = self.update_active_regions_lsa(
                 probabilistic_model,
                 lsa_propagation_strengths,
                 reset=False)
     return probabilistic_model
 def plot_fit_scalar_params_iters(
         self,
         samples_all,
         params=["tau1", "K", "sigma", "epsilon", "scale", "offset"],
         skip_samples=0,
         title_prefix="",
         subplot_shape=None,
         figure_name=None,
         figsize=FiguresConfig.LARGE_SIZE):
     if len(title_prefix) > 0:
         title_prefix = title_prefix + ": "
     title = title_prefix + " Parameters samples per iteration"
     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"))
     if len(samples) > 1:
         samples = merge_samples(samples)
     else:
         samples = samples[0]
     if subplot_shape is None:
         n_params = len(samples)
         # subplot_shape = self.rect_subplot_shape(n_params, mode="col")
         if n_params > 1:
             subplot_shape = (int(numpy.ceil(1.0 * n_params / 2)), 2)
         else:
             subplot_shape = (1, 1)
     return self.plots(samples,
                       shape=subplot_shape,
                       transpose=True,
                       skip=skip_samples,
                       xlabels={},
                       xscales={},
                       yscales={},
                       title=title,
                       figure_name=figure_name,
                       figsize=figsize)
 def plot_HMC(self,
              samples,
              skip_samples=0,
              title='HMC NUTS trace',
              figure_name=None,
              figsize=FiguresConfig.LARGE_SIZE):
     nuts = []
     for sample in ensure_list(samples):
         nuts.append(extract_dict_stringkeys(sample, "__", modefun="find"))
     if len(nuts) > 1:
         nuts = merge_samples(nuts)
     else:
         nuts = nuts[0]
     return self.plots(nuts,
                       shape=(2, 4),
                       transpose=True,
                       skip=skip_samples,
                       xlabels={},
                       xscales={},
                       yscales={"stepsize__": "log"},
                       title=title,
                       figure_name=figure_name,
                       figsize=figsize)
Example #27
0
 def read_sensors(self, filename, root_folder, s_type):
     filename = ensure_list(filename)
     path = os.path.join(root_folder, filename[0])
     if os.path.isfile(path):
         if s_type == Sensors.TYPE_EEG:
             tvb_sensors = sensors.SensorsEEG.from_file(path)
         elif s_type == Sensors.TYPE_MEG:
             tvb_sensors = sensors.SensorsMEG.from_file(path)
         else:
             tvb_sensors = sensors.SensorsInternal.from_file(path)
         if len(filename) > 1:
             gain_matrix = self.read_gain_matrix(
                 os.path.join(root_folder, filename[1]), s_type)
         else:
             gain_matrix = np.array([])
         return Sensors(tvb_sensors.labels,
                        tvb_sensors.locations,
                        orientations=tvb_sensors.orientations,
                        gain_matrix=gain_matrix,
                        s_type=s_type)
     else:
         self.logger.warning("\nNo Sensor file found at path " + path + "!")
         return None
Example #28
0
 def _check_noise_intesity_size(self, noise_intensity):
     nn = len(ensure_list(noise_intensity))
     if nn != 1 and nn != EPILEPTOR_MODEL_NVARS[self.model_name]:
         raise_value_error(
             "Noise intensity is neither of size 1 nor of size equal to the number of model variables, "
             "\n but of size: " + str(nn) + "!")
Example #29
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)