Ejemplo n.º 1
0
def eqtn_x0cr_r(Iext1, yc, a, b, d, x1_rest, x1_cr, x0_rest, x0_cr, zmode=np.array("lin")):
    # Correspondence with EpileptorDP2D
    b = b - d
    if isequal_string(str(zmode), 'lin'):
        return 0.25 * (x0_rest * (a * x1_cr ** 3 - a * x1_rest ** 3 - b * x1_cr ** 2 +
                                  b * x1_rest ** 2 + 4.0 * x1_cr - 4.0 * x1_rest) +
                       (x0_cr - x0_rest) * (Iext1 - a * x1_rest ** 3 + b * x1_rest ** 2 -
                                            4.0 * x1_rest + yc)) / (x0_cr - x0_rest), \
               0.25 * (a * x1_cr ** 3 - a * x1_rest ** 3 - b * x1_cr ** 2 + b * x1_rest ** 2 + 4.0 * x1_cr -
                       4.0 * x1_rest) / (x0_cr - x0_rest)
    elif isequal_string(str(zmode), 'sig'):
        return (-x0_cr*(3.2e+66*20000000000000.0**(10*x1_cr) + 4.74922109128249e+68*54365636569181.0**(10*x1_cr))
                *(3.2e+66*1.024e+133**x1_rest*(Iext1 - a*x1_rest**3 + b*x1_rest**2 + yc)
                + 4.74922109128249e+68*2.25551009738825e+137**x1_rest*(Iext1 - a*x1_rest**3 + b*x1_rest**2 + yc - 3.0))
                + x0_rest*(3.2e+66*20000000000000.0**(10*x1_rest) +
                4.74922109128249e+68*54365636569181.0**(10*x1_rest))*(3.2e+66*1.024e+133**x1_cr*(Iext1 - a*x1_cr**3 +
                b*x1_cr**2 + yc) + 4.74922109128249e+68*2.25551009738825e+137**x1_cr*(Iext1 - a*x1_cr**3 + b*x1_cr**2 +
                yc - 3.0)))/((3.2e+66*20000000000000.0**(10.0*x1_cr) +
                4.74922109128249e+68*54365636569181.0**(10.0*x1_cr))*(3.2e+66*20000000000000.0**(10.0*x1_rest) +
                4.74922109128249e+68*54365636569181.0**(10.0*x1_rest))*(-x0_cr + x0_rest)), \
                (-(3.2e+66 * 20000000000000.0 ** (10 * x1_cr) +
                   4.74922109128249e+68 * 54365636569181.0 ** (10 * x1_cr)) * (3.2e+66 * 1.024e+133 ** x1_rest * (
                Iext1 - a * x1_rest ** 3 + b * x1_rest ** 2 + yc) +
                4.74922109128249e+68 * 2.25551009738825e+137 ** x1_rest * (
                Iext1 - a * x1_rest ** 3 + b * x1_rest ** 2 + yc - 3.0)) + (
                3.2e+66 * 20000000000000.0 ** (10 * x1_rest) + 4.74922109128249e+68 * 54365636569181.0 ** (
                10 * x1_rest)) * (3.2e+66 * 1.024e+133 ** x1_cr * (Iext1 - a * x1_cr ** 3 + b * x1_cr ** 2 + yc) +
                                  4.74922109128249e+68 * 2.25551009738825e+137 ** x1_cr * 
                                  (Iext1 - a * x1_cr ** 3 + b * x1_cr ** 2 + yc - 3.0))) / \
               ((3.2e+66 * 20000000000000.0 ** (10.0 * x1_cr) + 4.74922109128249e+68 * 54365636569181.0 ** (
                       10.0 * x1_cr)) * (3.2e+66 * 20000000000000.0 ** (10.0 * x1_rest) +
                                         4.74922109128249e+68 * 54365636569181.0 ** (10.0 * x1_rest)) *
                (-x0_cr + x0_rest))
    else:
        raise_value_error('zmode is neither "lin" nor "sig"')
Ejemplo n.º 2
0
 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 [], []
 def __update_params__(self,
                       loc=0.0,
                       scale=1.0,
                       use="scipy",
                       check_constraint=True,
                       **params):
     if len(params) == 0:
         params = self.pdf_params()
     self.__set_params__(**params)
     # params = self.__squeeze_parameters__(update=False, loc=loc, scale=scale, use=use)
     # self.__set_params__(**params)
     self.__p_shape = self.__update_shape__(loc, scale)
     self.__p_size = shape_to_size(self.p_shape)
     self.n_params = len(self.pdf_params())
     if check_constraint and not (self.__check_constraint__()):
         raise_value_error("Constraint for " + self.type +
                           " distribution " + self.constraint_string +
                           "\nwith parameters " + str(self.pdf_params()) +
                           " is not satisfied!")
     self.__mean = self._calc_mean(loc, scale, use)
     self.__median = self._calc_median(loc, scale, use)
     self.__mode = self._calc_mode(loc, scale)
     self.__var = self._calc_var(loc, scale, use)
     self.__std = self._calc_std(loc, scale, use)
     self.__skew = self._calc_skew()
     self.__kurt = self._calc_kurt()
Ejemplo n.º 4
0
def eqtn_fz_square_taylor(zeq, yc, Iext1, K, w, tau1, tau0):
    n_regions = zeq.size
    tau = np.divide(tau1, tau0)
    tau = np.repeat(tau.T, n_regions, 1)
    # The z derivative of the function
    # x1 = F(z) = -4/3 -1/2*sqrt(2(z-yc-Iext1)+64/27)
    dfz = -np.divide(0.5, np.power(2.0 * (zeq - yc - Iext1) + 64.0 / 27.0, 0.5))
    # Tim Proix: dfz = -np.divide(1, np.power(8.0 * zeq - 629.6/27, 0.5))
    try:
        if np.any([np.any(np.isnan(dfz)), np.any(np.isinf(dfz))]):
            raise_value_error("nan or inf values in dfz")
    except:
        pass
    # Jacobian: diagonal elements at first row
    # Diagonal elements: -1 + dfz_i * (4 + K_i * sum_j_not_i{wij})
    # Off diagonal elements: -K_i * wij_not_i * dfz_j_not_i
    i = np.ones((1, n_regions), dtype=np.float32)
    fz_jac = np.diag((-1.0 + np.multiply(dfz, (4.0 + np.multiply(K, np.expand_dims(np.sum(w, axis=1), 1).T)))).T[:,
                     0]) - np.multiply(np.multiply(np.dot(K.T, i), np.dot(i.T, dfz)), w)
    try:
        if np.any([np.any(np.isnan(fz_jac.flatten())), np.any(np.isinf(fz_jac.flatten()))]):
            raise_value_error("nan or inf values in dfz")
    except:
        pass
    return np.multiply(fz_jac, tau)
Ejemplo n.º 5
0
 def _prepare_distribution_axes(self,
                                distribution,
                                loc=0.0,
                                scale=1.0,
                                x=numpy.array([]),
                                ax=None,
                                linestyle="-",
                                lgnd=False):
     if len(x) < 1:
         x = linspace_broadcast(
             distribution._scipy_method("ppf", distribution.loc,
                                        distribution.scale, 0.01),
             distribution._scipy_method("ppf", distribution.loc,
                                        distribution.scale, 0.99), 100)
     if x is not None:
         if x.ndim == 1:
             x = x[:, numpy.newaxis]
         pdf = distribution._scipy_method("pdf", loc, scale, x)
         if ax is None:
             _, ax = pyplot.subplots(1, 1)
         for ip, (xx, pp) in enumerate(zip(x.T, pdf.T)):
             ax.plot(xx.T,
                     pp.T,
                     linestyle=linestyle,
                     linewidth=1,
                     label=str(ip),
                     alpha=0.5)
         if lgnd:
             pyplot.legend()
         return ax
     else:
         # TODO: is this message correct??
         raise_value_error("Distribution parameters do not broadcast!")
Ejemplo n.º 6
0
 def prepare_params(self, params_pse):
     if isinstance(params_pse, list):
         temp = []
         for param in params_pse:
             self.params_paths.append(param["path"])
             temp2 = param["samples"].flatten()
             temp.append(temp2)
             self.n_params_vals.append(temp2.size)
             indices = param.get("indices", [])
             self.params_indices.append(indices)
             self.params_names.append(
                 param.get("name",
                           param["path"].rsplit('.', 1)[-1] + str(indices)))
         self.n_params_vals = np.array(self.n_params_vals)
         self.n_params = len(self.params_paths)
         if not (np.all(self.n_params_vals == self.n_params_vals[0])):
             raise_value_error(
                 "\nNot all parameters have the same number of samples!: " +
                 "\n" + str(self.params_paths) + " = " +
                 str(self.n_params_vals))
         else:
             self.n_params_vals = self.n_params_vals[0]
         self.params_vals = np.vstack(temp).T
         self.params_paths = np.array(self.params_paths)
         self.params_indices = np.array(self.params_indices)
         self.n_loops = self.params_vals.shape[0]
         print "\nGenerated a parameter search exploration for " + str(
             "lsa/sim task") + ","
         print "with " + str(self.n_params) + " parameters of " + str(
             self.n_params_vals) + " values each,"
         print "leading to " + str(self.n_loops) + " total execution loops"
     else:
         self.logger.warning("\nparams_pse is not a list of tuples!")
Ejemplo n.º 7
0
    def _compute_jacobian(self, model_configuration):

        # Check if any of the equilibria are in the supercritical regime (beyond the separatrix) and set it right before
        # the bifurcation.
        zeq = model_configuration.zeq
        if self.lsa_method == "2D":
            fz_jacobian = calc_jac(model_configuration.x1eq, model_configuration.zeq, model_configuration.yc,
                                   model_configuration.Iext1, model_configuration.x0, model_configuration.K,
                                   model_configuration.model_connectivity, model_vars=2, zmode="lin",
                                   a=model_configuration.a, b=model_configuration.b, d=model_configuration.d,
                                   tau1= model_configuration.tau1, tau0=model_configuration.tau0)
        else:
            temp = model_configuration.x1eq > X1EQ_CR_DEF - 10 ** (-3)
            if temp.any():
                correction_value = X1EQ_CR_DEF - 10 ** (-3)
                self.logger.warning("Equilibria x1eq[" + str(numpy.where(temp)[0]) + "]  = "
                                    + str(model_configuration.x1eq[temp]) +
                                    "\nwere corrected for LSA to value: X1EQ_CR_DEF - 10 ** (-3) = "
                                    + str(correction_value) + " to be sub-critical!")
                model_configuration.x1eq[temp] = correction_value
                i_temp = numpy.ones(model_configuration.x1eq.shape)
                zeq[temp] = calc_eq_z(model_configuration.x1eq[temp], model_configuration.yc * i_temp[temp],
                                      model_configuration.Iext1 * i_temp[temp], "2d", 0.0,
                                      model_configuration.slope * i_temp[temp],
                                      model_configuration.a * i_temp[temp], model_configuration.b * i_temp[temp],
                                      model_configuration.d * i_temp[temp])
            fz_jacobian = calc_fz_jac_square_taylor(model_configuration.zeq, model_configuration.yc,
                                                    model_configuration.Iext1, model_configuration.K,
                                                    model_configuration.model_connectivity,
                                                    model_configuration.a, model_configuration.b, model_configuration.d)

        if numpy.any([numpy.any(numpy.isnan(fz_jacobian.flatten())), numpy.any(numpy.isinf(fz_jacobian.flatten()))]):
            raise_value_error("nan or inf values in dfz")

        return fz_jacobian
Ejemplo n.º 8
0
 def __init__(self,
              name="Parameter",
              low=-CalculusConfig.MAX_SINGLE_VALUE,
              high=CalculusConfig.MAX_SINGLE_VALUE,
              loc=0.0,
              scale=1.0,
              p_shape=(),
              use="scipy",
              **target_params):
     StochasticParameterBase.__init__(self, name, low, high, loc, scale,
                                      p_shape)
     thisProbabilityDistribution.__init__(self, **target_params)
     success = True
     for p_key, p_val in target_params.iteritems():
         if np.any(p_val != getattr(self, p_key)):
             success = False
     if success is False:
         if optimize_pdf:
             pdf_params = compute_pdf_params(
                 probability_distribution.lower(), target_params, loc,
                 scale, use)
             thisProbabilityDistribution.__init__(self, **pdf_params)
             success = True
             for p_key, p_val in target_params.iteritems():
                 if np.any(np.abs(p_val - getattr(self, p_key)) > 0.1):
                     success = False
     if success is False:
         raise_value_error(
             "Cannot generate probability distribution of type " +
             probability_distribution + " with parameters " +
             str(target_params) + " !")
         self._update_params(use=use)
Ejemplo n.º 9
0
def eqtn_jac_fz_2d(x1,
                   z,
                   tau1,
                   tau0,
                   zmode=np.array("lin"),
                   z_pos=True,
                   K=None,
                   w=None):
    tau = np.divide(tau1, tau0)
    jac_z = -np.ones(z.shape, dtype=z.dtype)
    if zmode == 'lin':
        jac_x1 = 4.0 * np.ones(z.shape, dtype=z.dtype)
        if not (z_pos):
            jac_z -= 0.7 * np.power(z, 6.0)
    elif zmode == 'sig':
        jac_x1 = np.divide(30 * np.power(np.exp(1), (-10.0 * (x1 + 0.5))),
                           1 + np.power(np.exp(1), (-10.0 * (x1 + 0.5))))
    else:
        raise_value_error('zmode is neither "lin" nor "sig"')
    # Assuming that wii = 0
    jac_x1 += np.multiply(K, np.sum(w, 1))
    jac_x1 = np.diag(jac_x1.flatten()) - np.multiply(
        np.repeat(np.reshape(K, (x1.size, 1)), x1.size, axis=1), w)
    jac_x1 *= np.repeat(np.reshape(tau, (x1.size, 1)), x1.size, axis=1)
    jac_z *= tau
    jac_z = np.diag(jac_z.flatten())
    return np.concatenate([jac_x1, jac_z], axis=1)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
0
 def _check_regions_inds_range(self, indices, type):
     if numpy.any(numpy.array(indices) < 0) or numpy.any(numpy.array(indices) >= self.number_of_regions):
         raise_value_error(type + "_indices out of range! " +
                           "\nThe maximum indice is " + str(self.number_of_regions)
                           + " for number of brain regions " + str(self.number_of_regions) + " but"
                           "\n" + type + "_indices = " + str(indices))
     return indices
Ejemplo n.º 13
0
 def set_model_name(self, model_name):
     # TODO: check that model_name is one of the available ones
     if model_name not in AVAILABLE_DYNAMICAL_MODELS_NAMES:
         raise_value_error(model_name + " is not one of the available models: \n" +
                           str(AVAILABLE_DYNAMICAL_MODELS_NAMES) + " !")
     self.model_name = model_name
     return self
Ejemplo n.º 14
0
 def __init__(self,
              model_name=None,
              model=None,
              model_code=None,
              model_code_path="",
              model_data_path="",
              fitmethod="sample",
              random_seed=12345,
              init="random",
              config=None,
              **options):
     super(CmdStanService,
           self).__init__(model_name, model, model_code, model_code_path,
                          model_data_path, fitmethod, config)
     if not os.path.isfile(
             os.path.join(self.config.generic.CMDSTAN_PATH,
                          'runCmdStanTests.py')):
         raise_value_error(
             'Please provide CmdStan path, e.g. lib.cmdstan_path("/path/to/")!'
         )
     self.path = self.config.generic.CMDSTAN_PATH
     self.assert_fitmethod()
     self.command = ""
     self.options = {"init": init, "random_seed": random_seed}
     self.options = self.set_options(**options)
     self.context_str = "from " + construct_import_path(
         __file__) + " import " + self.__class__.__name__
     self.create_str = self.__class__.__name__ + "()"
Ejemplo n.º 15
0
 def set_diseased_regions_values(self, disease_values):
     n = len(disease_values)
     if n != self.number_of_regions:
         raise_value_error("Diseased region values size (" + str(n) +
                           ") doesn't match the number of regions (" + str(self.number_of_regions) + ")!")
     self.diseased_regions_values = disease_values
     return self
Ejemplo n.º 16
0
    def write_ts_epi(self, raw_ts, sampling_period, path, source_ts=None):
        path = change_filename_or_overwrite(os.path.join(path))

        if raw_ts is None or len(raw_ts.squeezed.shape) != 3:
            raise_value_error(
                "Invalid TS data 3D (time, regions, sv) expected", self.logger)
        self.logger.info("Writing a TS at:\n" + path)
        if source_ts is None:
            source_ts = raw_ts.source
        h5_file = h5py.File(path, 'a', libver='latest')
        h5_file.create_dataset("/data", data=raw_ts.squeezed)
        h5_file.create_dataset("/lfpdata", data=source_ts.squeezed)
        write_metadata({KEY_TYPE: "TimeSeries"}, h5_file, KEY_DATE,
                       KEY_VERSION)
        write_metadata(
            {
                KEY_MAX: raw_ts.squeezed.max(),
                KEY_MIN: raw_ts.squeezed.min(),
                KEY_STEPS: raw_ts.squeezed.shape[0],
                KEY_CHANNELS: raw_ts.squeezed.shape[1],
                KEY_SV: raw_ts.squeezed.shape[2],
                KEY_SAMPLING: sampling_period,
                KEY_START: raw_ts.time_start
            }, h5_file, KEY_DATE, KEY_VERSION, "/data")
        write_metadata(
            {
                KEY_MAX: source_ts.squeezed.max(),
                KEY_MIN: source_ts.squeezed.min(),
                KEY_STEPS: source_ts.squeezed.shape[0],
                KEY_CHANNELS: source_ts.squeezed.shape[1],
                KEY_SV: 1,
                KEY_SAMPLING: sampling_period,
                KEY_START: source_ts.time_start
            }, h5_file, KEY_DATE, KEY_VERSION, "/lfpdata")
        h5_file.close()
Ejemplo n.º 17
0
    def _ensure_eigen_vectors_number(self, eigen_values, e_values, x0_values,
                                     disease_indices):
        if self.eigen_vectors_number is None:
            if self.eigen_vectors_number_selection is "auto_eigenvals":
                self.eigen_vectors_number = self.get_curve_elbow_point(
                    numpy.abs(eigen_values)) + 1

            elif self.eigen_vectors_number_selection is "auto_disease":
                self.eigen_vectors_number = len(disease_indices)

            elif self.eigen_vectors_number_selection is "auto_epileptogenicity":
                self.eigen_vectors_number = self.get_curve_elbow_point(
                    e_values) + 1

            elif self.eigen_vectors_number_selection is "auto_excitability":
                self.eigen_vectors_number = self.get_curve_elbow_point(
                    x0_values) + 1

            else:
                raise_value_error(
                    "\n" + self.eigen_vectors_number_selection +
                    "is not a valid option when for automatic computation of self.eigen_vectors_number"
                )
        else:
            self.eigen_vectors_number_selection = "user_defined"
def prepare_target_stats(distribution, target_stats, loc=0.0, scale=1.0):
    # Make sure that the shapes of target stats are all matching one to the other:
    target_shape = np.ones(()) * loc * scale
    target_shape = np.ones(target_shape.shape)
    try:
        for ts in target_stats.values():
            target_shape = target_shape * np.ones(np.array(ts).shape)
    except:
        raise_value_error(
            "Target statistics (" +
            str([np.array(ts).shape
                 for ts in target_stats.values()]) + ") and distribution (" +
            str(distribution.p_shape) + ") shapes do not propagate!")
    for ts_key in target_stats.keys():
        target_stats[ts_key] *= target_shape
        if np.sum(target_stats[ts_key].shape) > 0:
            target_stats[ts_key] = target_stats[ts_key].flatten()
    target_size = target_shape.size
    target_shape = target_shape.shape
    target_stats_array = np.around(np.vstack(target_stats.values()).T,
                                   decimals=2)
    target_stats_unique = np.unique(target_stats_array, axis=0)
    # target_stats_unique = np.vstack({tuple(row) for row in target_stats_array})
    target_stats_unique = dict(
        zip(target_stats.keys(), [
            np.around(target_stats_unique[:, ii], decimals=3)
            for ii in range(distribution.n_params)
        ]))
    target_stats_unique = dicts_of_lists_to_lists_of_dicts(target_stats_unique)
    return target_stats_unique, target_stats_array, target_shape, target_size
Ejemplo n.º 19
0
def eqtn_fz(x1,
            z,
            x0,
            tau1,
            tau0,
            zmode=np.array("lin"),
            z_pos=True,
            K=None,
            w=None,
            coupl=None):
    if coupl is None:
        if np.all(K == 0.0) or np.all(w == 0.0) or (K is None) or (w is None):
            coupl = 0.0
        else:
            from tvb_epilepsy.base.computations.calculations_utils import calc_coupling
            coupl = calc_coupling(x1, K, w)
    tau = np.divide(tau1, tau0)
    if zmode == 'lin':
        return np.multiply(
            (4 * (x1 - x0) - np.where(z_pos, z, z + 0.1 * np.power(z, 7.0)) -
             coupl), tau)
    elif zmode == 'sig':
        return np.multiply(
            np.divide(3.0,
                      (1 + np.power(np.exp(1),
                                    (-10.0 * (x1 + 0.5))))) - x0 - z - coupl,
            tau)
    else:
        raise_value_error('zmode is neither "lin" nor "sig"')
Ejemplo n.º 20
0
 def _set_conf_level(self, conf_level):
     if isinstance(conf_level,
                   float) and conf_level > 0.0 and conf_level < 1.0:
         self.conf_level = conf_level
     else:
         raise_value_error(
             "conf_level = " + str(conf_level) +
             "is not a float in the (0.0, 1.0) interval as it should!")
Ejemplo n.º 21
0
 def _set_method(self, method):
     method = method.lower()
     if np.in1d(method, METHODS):
         self.method = method
     else:
         raise_value_error("Method " + str(method) +
                           " is not one of the available methods " +
                           str(METHODS) + " !")
Ejemplo n.º 22
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) + ")!")
Ejemplo n.º 23
0
 def assert_fitmethod(self):
     if self.fitmethod.lower().find("sampl") >= 0:  # for sample or sampling
         self.fitmethod = "sampling"
     elif self.fitmethod.lower().find("v") >= 0:  # for variational or vb or advi
         self.fitmethod = "vb"
     elif self.fitmethod.lower().find("optimiz") >= 0:  # for optimization or optimizing or optimize
         self.fitmethod = "optimizing"
     else:
         raise_value_error(self.fitmethod + " does not correspond to one of the input methods:\n" +
                           "sampling, vb, optimizing")
Ejemplo n.º 24
0
 def _check_indices_vals_sizes(self, indices, values, type):
     n_inds = len(indices)
     n_vals = len(values)
     if n_inds != n_vals:
         if n_vals != 1:
             values *= n_inds
         else:
             raise_value_error("Sizes of " + type + "_indices (" + str(n_inds) + ") " +
                               "and " + type + "_values (" + str(n_vals) + ") do not match!")
     return values
Ejemplo n.º 25
0
 def select_sensors_rois(self, sensors, rois=None, initial_selection=[], gain_matrix_th=0.5):
     if len(initial_selection) == 0:
         initial_selection = range(sensors.number_of_sensors)
     selection = []
     if sensors.gain_matrix is None:
         raise_value_error("Projection matrix is not set!")
     else:
         for proj in sensors.gain_matrix[initial_selection].T[rois]:
             selection += (
                 np.array(initial_selection)[select_greater_values_array_inds(proj, gain_matrix_th)]).tolist()
     return np.unique(selection).tolist()
Ejemplo n.º 26
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
Ejemplo n.º 27
0
 def generate_model(self, model_configuration):
     if isequal_string(self.model_name,
                       EpileptorModel._ui_name) and not isequal_string(
                           self.simulator, "java"):
         raise_value_error(
             "Custom EpileptorModel can be used only with java simulator!")
     elif not isequal_string(self.model_name,
                             EpileptorModel._ui_name) and isequal_string(
                                 self.simulator, "java"):
         raise_value_error(
             "Only java EpileptorModel can be used with java simulator!")
     return model_build_dict[self.model_name](model_configuration)
Ejemplo n.º 28
0
 def __init__(
     self,
     name='vep_ode',
     number_of_regions=0,
     active_regions=[],
     n_signals=0,
     n_times=0,
     dt=1.0,
     x1eq_min=X1EQ_MIN,
     x1eq_max=X1EQ_MAX,
     MC_scale=MC_SCALE,
     sig_init=SIG_INIT_DEF,
     observation_model=OBSERVATION_MODEL_DEF,
     # observation_expression=OBSERVATION_EXPRESSION_DEF, euler_method="forward",
     **defaults):
     super(ODEStatisticalModel,
           self).__init__(name, number_of_regions, x1eq_min, x1eq_max,
                          MC_scale, **defaults)
     self.sig_init = sig_init
     if np.all(np.in1d(active_regions, range(self.number_of_regions))):
         self.active_regions = np.unique(active_regions).tolist()
         self.n_active_regions = len(self.active_regions)
         self.n_nonactive_regions = self.number_of_regions - self.n_active_regions
     else:
         raise_value_error("Active regions indices:\n" +
                           str(active_regions) +
                           "\nbeyond number of regions (" +
                           str(self.number_of_regions) + ")!")
     self.n_signals = n_signals
     self.n_times = n_times
     self.dt = dt
     # if np.in1d(euler_method.lower(), EULER_METHODS):
     #     if euler_method.lower() == "midpoint":
     #         warning("Midpoint Euler method is not implemented yet! Switching to default forward one!")
     #     self.euler_method = euler_method.lower()
     # else:
     #     raise_value_error("Statistical model's euler_method " + str(euler_method) + " is not one of the valid ones: "
     #                       + str(["backward", "forward"]) + "!")
     # if np.in1d(observation_expression.lower(), OBSERVATION_MODEL_EXPRESSIONS):
     #     self.observation_expression = observation_expression.lower()
     # else:
     #     raise_value_error("Statistical model's observation expression " + str(observation_expression) +
     #                       " is not one of the valid ones: "
     #                       + str(OBSERVATION_MODEL_EXPRESSIONS) + "!")
     if np.in1d(observation_model.lower(), OBSERVATION_MODELS):
         self.observation_model = observation_model.lower()
     else:
         raise_value_error("Statistical model's observation expression " +
                           str(observation_model) +
                           " is not one of the valid ones: " +
                           str(OBSERVATION_MODELS) + "!")
     self.__add_parameters(**defaults)
Ejemplo n.º 29
0
 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
Ejemplo n.º 30
0
def eqtn_x0(x1, z, zmode=np.array("lin"), z_pos=True, K=None, w=None, coupl=None):
    if coupl is None:
        if np.all(K == 0.0) or np.all(w == 0.0) or (K is None) or (w is None):
            coupl = 0.0
        else:
            from tvb_epilepsy.base.computations.calculations_utils import calc_coupling
            coupl = calc_coupling(x1, K, w)
    if  isequal_string(str(zmode), 'lin'):
        return x1 - (z + np.where(z_pos, 0.0, 0.1 * np.power(z, 7.0)) + coupl) / 4.0
    elif  isequal_string(str(zmode), 'sig'):
        return np.divide(3.0, 1.0 + np.power(np.exp(1), -10.0 * (x1 + 0.5))) - z - coupl
    else:
        raise_value_error('zmode is neither "lin" nor "sig"')