def test_read_hypothesis(self):
        test_file = os.path.join(self.config.out.FOLDER_TEMP,
                                 "TestHypothesis.h5")
        hypothesis_builder = HypothesisBuilder(3, self.config)
        dummy_hypothesis = hypothesis_builder.set_e_hypothesis(
            [0], [0.6]).build_hypothesis()

        self.writer.write_hypothesis(dummy_hypothesis, test_file)
        hypothesis = self.reader.read_hypothesis(test_file)

        assert dummy_hypothesis.number_of_regions == hypothesis.number_of_regions
        assert numpy.array_equal(dummy_hypothesis.x0_values,
                                 hypothesis.x0_values)
        assert dummy_hypothesis.x0_indices == hypothesis.x0_indices
        assert numpy.array_equal(dummy_hypothesis.e_values,
                                 hypothesis.e_values)
        assert dummy_hypothesis.e_indices == hypothesis.e_indices
        assert numpy.array_equal(dummy_hypothesis.w_values,
                                 hypothesis.w_values)
        assert dummy_hypothesis.w_indices == hypothesis.w_indices
        assert numpy.array_equal(dummy_hypothesis.lsa_propagation_indices,
                                 hypothesis.lsa_propagation_indices)
        if len(dummy_hypothesis.lsa_propagation_indices) == 0:
            assert numpy.array_equal([0, 0, 0],
                                     hypothesis.lsa_propagation_strengths)
        else:
            assert numpy.array_equal(
                dummy_hypothesis.lsa_propagation_strengths,
                hypothesis.lsa_propagation_strengths)
    def test_build_hypothesis_from_file_mixed(self):
        hypo_builder = HypothesisBuilder(76, self.config)
        hypo = hypo_builder.build_hypothesis_from_file(self.ep, [55, 56])

        assert hypo.name == "e_x0_Hypothesis"
        assert not len(hypo.e_indices) == 0
        assert not len(hypo.e_values) == 0
        assert not len(hypo.x0_indices) == 0
        assert not len(hypo.x0_values) == 0
        assert len(hypo.w_indices) == 0
        assert len(hypo.w_values) == 0
        assert len(hypo.lsa_propagation_indices) == 0
        assert len(hypo.lsa_propagation_strengths) == 0
    def test_build_hypothesis_from_file_epileptogenicity(self):
        hypo_builder = HypothesisBuilder(76, self.config)
        hypo = hypo_builder.build_hypothesis_from_file(
            self.ep, [55, 56, 57, 58, 59, 60, 61])

        assert hypo.name == "e_Hypothesis"
        assert not len(hypo.e_indices) == 0
        assert not len(hypo.e_values) == 0
        assert len(hypo.x0_indices) == 0
        assert len(hypo.x0_values) == 0
        assert len(hypo.w_indices) == 0
        assert len(hypo.w_values) == 0
        assert len(hypo.lsa_propagation_indices) == 0
        assert len(hypo.lsa_propagation_strengths) == 0
    def test_build_empty_hypothesis(self):
        hypo_builder = HypothesisBuilder(config=self.config)
        hypo = hypo_builder.build_hypothesis()

        assert hypo.name == "Hypothesis"
        assert hypo.number_of_regions == 0
        assert len(hypo.x0_indices) == 0
        assert len(hypo.x0_values) == 0
        assert len(hypo.e_indices) == 0
        assert len(hypo.e_values) == 0
        assert len(hypo.w_indices) == 0
        assert len(hypo.w_values) == 0
        assert len(hypo.lsa_propagation_indices) == 0
        assert len(hypo.lsa_propagation_strengths) == 0
    def test_plot_sim_results(self):
        lsa_hypothesis = HypothesisBuilder(
            config=self.config).build_lsa_hypothesis()
        mc = ModelConfigurationBuilder("EpileptorDP", numpy.array([[1.0, 0.0], [0.0, 1.0]])). \
            build_model_from_E_hypothesis(lsa_hypothesis)
        model = build_EpileptorDP2D_from_model_config(mc)

        # TODO: this figure_name is constructed inside plot method, so it can change
        figure_name = "Simulated_TAVG"
        file_name = os.path.join(self.config.out.FOLDER_FIGURES,
                                 figure_name + ".png")
        assert not os.path.exists(file_name)

        data_3D = numpy.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 1, 2]],
                               [[3, 4, 5], [6, 7, 8], [9, 0, 1], [2, 3, 4]],
                               [[5, 6, 7], [8, 9, 0], [1, 2, 3], [4, 5, 6]]])

        self.plotter.plot_simulated_timeseries(
            Timeseries(
                data_3D, {
                    TimeseriesDimensions.SPACE.value:
                    numpy.array(["r1", "r2", "r3", "r4"]),
                    TimeseriesDimensions.VARIABLES.value:
                    numpy.array(["x1", "x2", "z"])
                }, 0, 1), model, [0])

        assert os.path.exists(file_name)
    def test_build_hypothesis_by_user_preferences(self):
        hypo_builder = HypothesisBuilder(76, self.config).set_x0_hypothesis(
            [1, 2, 3], [1, 1, 1]).set_e_hypothesis([10, 11],
                                                   [1, 1]).set_normalize(0.90)
        hypo = hypo_builder.build_hypothesis()

        assert hypo.name == "e_x0_Hypothesis"
        assert hypo.number_of_regions == 76
        assert len(hypo.x0_indices) == 3
        assert len(hypo.x0_values) == 3
        assert len(hypo.e_indices) == 2
        assert len(hypo.e_values) == 2
        assert len(hypo.w_indices) == 0
        assert len(hypo.w_values) == 0
        assert len(hypo.lsa_propagation_indices) == 0
        assert len(hypo.lsa_propagation_strengths) == 0
Esempio n. 7
0
def main_pse(config=Config()):
    # -------------------------------Reading data-----------------------------------
    reader = Reader()
    writer = H5Writer()
    head = reader.read_head(config.input.HEAD)
    logger = initialize_logger(__name__, config.out.FOLDER_LOGS)

    # --------------------------Manual Hypothesis definition-----------------------------------
    n_samples = 100
    x0_indices = [20]
    x0_values = [0.9]
    e_indices = [70]
    e_values = [0.9]
    disease_indices = x0_indices + e_indices
    n_disease = len(disease_indices)

    n_x0 = len(x0_indices)
    n_e = len(e_indices)
    all_regions_indices = np.array(range(head.number_of_regions))
    healthy_indices = np.delete(all_regions_indices, disease_indices).tolist()
    n_healthy = len(healthy_indices)
    # This is an example of x0_values mixed Excitability and Epileptogenicity Hypothesis:
    hyp_x0_E = HypothesisBuilder(
        head.connectivity.number_of_regions).set_x0_hypothesis(
            x0_indices,
            x0_values).set_e_hypothesis(e_indices,
                                        e_values).build_hypothesis()

    # Now running the parameter search analysis:
    logger.info("running PSE LSA...")
    model_config, lsa_service, lsa_hypothesis, pse_res = pse_from_hypothesis(
        hyp_x0_E,
        head.connectivity.normalized_weights,
        head.connectivity.region_labels,
        n_samples,
        param_range=0.1,
        global_coupling=[{
            "indices": all_regions_indices
        }],
        healthy_regions_parameters=[{
            "name": "x0_values",
            "indices": healthy_indices
        }],
        save_services=True)[:4]

    logger.info("Plotting LSA...")
    Plotter(config).plot_lsa(lsa_hypothesis,
                             model_config,
                             lsa_service.weighted_eigenvector_sum,
                             lsa_service.eigen_vectors_number,
                             region_labels=head.connectivity.region_labels,
                             pse_results=pse_res,
                             lsa_service=lsa_service)

    logger.info("Saving LSA results ...")
    writer.write_dictionary(
        pse_res,
        os.path.join(config.out.FOLDER_RES,
                     lsa_hypothesis.name + "_PSE_LSA_results.h5"))
Esempio n. 8
0
def main_sensitivity_analysis(config=Config()):
    # -------------------------------Reading data-----------------------------------
    reader = Reader()
    writer = H5Writer()
    head = reader.read_head(config.input.HEAD)
    # --------------------------Hypothesis definition-----------------------------------
    n_samples = 100
    # Manual definition of hypothesis...:
    x0_indices = [20]
    x0_values = [0.9]
    e_indices = [70]
    e_values = [0.9]
    disease_indices = x0_indices + e_indices
    n_disease = len(disease_indices)
    n_x0 = len(x0_indices)
    n_e = len(e_indices)
    all_regions_indices = np.array(range(head.connectivity.number_of_regions))
    healthy_indices = np.delete(all_regions_indices, disease_indices).tolist()
    n_healthy = len(healthy_indices)
    # This is an example of x0_values mixed Excitability and Epileptogenicity Hypothesis:
    hyp_x0_E = HypothesisBuilder(
        head.connectivity.number_of_regions).set_x0_hypothesis(
            x0_indices,
            x0_values).set_e_hypothesis(e_indices,
                                        e_values).build_hypothesis()
    # Now running the sensitivity analysis:
    logger.info("running sensitivity analysis PSE LSA...")
    for m in METHODS:
        try:
            model_configuration_builder, model_configuration, lsa_service, lsa_hypothesis, sa_results, pse_results = \
                sensitivity_analysis_pse_from_hypothesis(hyp_x0_E,
                                                         head.connectivity.normalized_weights,
                                                         head.connectivity.region_labels,
                                                         n_samples, method=m, param_range=0.1,
                                                         global_coupling=[{"indices": all_regions_indices,
                                                                           "low": 0.0, "high": 2 * K_UNSCALED_DEF}],
                                                         healthy_regions_parameters=[
                                                             {"name": "x0_values", "indices": healthy_indices}],
                                                         config=config, save_services=True)
            Plotter(config).plot_lsa(
                lsa_hypothesis,
                model_configuration,
                lsa_service.weighted_eigenvector_sum,
                lsa_service.eigen_vectors_number,
                region_labels=head.connectivity.region_labels,
                pse_results=pse_results,
                title=m + "_PSE_LSA_overview_" + lsa_hypothesis.name,
                lsa_service=lsa_service)
            # , show_flag=True, save_flag=False
            result_file = os.path.join(
                config.out.FOLDER_RES,
                m + "_PSE_LSA_results_" + lsa_hypothesis.name + ".h5")
            writer.write_dictionary(pse_results, result_file)
            result_file = os.path.join(
                config.out.FOLDER_RES,
                m + "_SA_LSA_results_" + lsa_hypothesis.name + ".h5")
            writer.write_dictionary(sa_results, result_file)
        except:
            logger.warning("Method " + m + " failed!")
def set_hypotheses(head, config):
    hypotheses = []

    # Formulate a VEP hypothesis manually
    hyp_builder = HypothesisBuilder(head.connectivity.number_of_regions,
                                    config)  # .set_normalize(1.5)

    # # Regions of Pathological Excitability hypothesis:
    # x0_indices = [6, 15, 52, 53] # [1, 26] #
    # x0_values = 2.5*np.array([0.9, 0.9, 0.5, 0.5])
    x0_indices = [1, 26]  # DK, D: [6, 15] #
    x0_values = 2.5 * np.array([0.9, 0.9])
    hyp_builder.set_x0_hypothesis(x0_indices, x0_values)

    # Regions of Model Epileptogenicity hypothesis:
    # e_indices = [6, 15, 52, 53]  # DK: [2, 25]
    e_indices = [2, 25]  # DK, D: [52, 53] #
    # e_values = np.array([0.9, 0.9, 0.5, 0.5])  # np.array([0.99] * 2)
    e_values = np.array([0.5, 0.5])  # np.array([0.99] * 2)
    hyp_builder.set_e_hypothesis(e_indices, e_values)

    # Regions of Connectivity hypothesis:
    # w_indices = []  # [(0, 1), (0, 2)]
    # w_values = []  # [0.5, 2.0]
    # hypo_builder.set_w_indices(w_indices).set_w_values(w_values)

    hypotheses.append(hyp_builder.build_hypothesis())

    # e_indices = [6, 15]  # [1, 2, 25, 26]
    # hypotheses.append(hyp_builder.build_hypothesis_from_file("postseeg", e_indices))
    # Change something manually if necessary
    # hypothesis2.x0_values = [0.01, 0.01]

    return tuple(hypotheses)
    def test_build_lsa_hypothesis(self):
        hypo_builder = HypothesisBuilder(76,
                                         self.config).set_x0_hypothesis([1, 2],
                                                                        [1, 1])
        hypo = hypo_builder.build_hypothesis()

        lsa_hypo = hypo_builder.set_attributes_based_on_hypothesis(
            hypo).set_lsa_propagation([3, 4], [0.5, 1]).build_lsa_hypothesis()

        assert lsa_hypo.name == "x0_Hypothesis"
        assert lsa_hypo.number_of_regions == 76
        assert len(lsa_hypo.x0_indices) == 2
        assert len(lsa_hypo.x0_values) == 2
        assert len(lsa_hypo.e_indices) == 0
        assert len(lsa_hypo.e_values) == 0
        assert len(lsa_hypo.w_indices) == 0
        assert len(lsa_hypo.w_values) == 0
        assert len(lsa_hypo.lsa_propagation_indices) == 2
        assert len(lsa_hypo.lsa_propagation_strengths) == 2
    def test_plot_lsa(self):
        figure_name = "LSAPlot"
        hypo_builder = HypothesisBuilder(
            config=self.config).set_name(figure_name)
        lsa_hypothesis = hypo_builder.build_lsa_hypothesis()
        mc = ModelConfigurationBuilder("EpileptorDP", numpy.array([[1.0, 0.0], [0.0, 1.0]])). \
            build_model_from_E_hypothesis(lsa_hypothesis)

        figure_file = os.path.join(self.config.out.FOLDER_FIGURES,
                                   figure_name + ".png")
        assert not os.path.exists(figure_file)

        self.plotter.plot_lsa(lsa_hypothesis,
                              mc,
                              True,
                              None,
                              region_labels=numpy.array(["a", "b"]),
                              title="")

        assert not os.path.exists(figure_file)
    def test_write_hypothesis(self):
        test_file = os.path.join(self.config.out.FOLDER_TEMP,
                                 "TestHypothesis.h5")
        dummy_hypothesis = HypothesisBuilder(3).set_e_hypothesis(
            [0], [0.6]).build_hypothesis()

        assert not os.path.exists(test_file)

        self.writer.write_hypothesis(dummy_hypothesis, test_file)

        assert os.path.exists(test_file)
Esempio n. 13
0
def from_head_to_hypotheses(ep_name, config, plot_head=False):
    # -------------------------------Reading model_data-----------------------------------
    reader = TVBReader() if config.input.IS_TVB_MODE else H5Reader()
    logger.info("Reading from: " + config.input.HEAD)
    head = reader.read_head(config.input.HEAD)
    if plot_head:
        Plotter(config).plot_head(head)
    # --------------------------Hypothesis definition-----------------------------------
    # # Manual definition of hypothesis...:
    # x0_indices = [20]
    # x0_values = [0.9]
    # e_indices = [70]
    # e_values = [0.9]
    # disease_values = x0_values + e_values
    # disease_indices = x0_indices + e_indices
    # ...or reading a custom file:
    # FOLDER_RES = os.path.join(data_folder, ep_name)

    hypo_builder = HypothesisBuilder(head.connectivity.number_of_regions,
                                     config=config).set_normalize(0.95)

    # This is an example of Excitability Hypothesis:
    hyp_x0 = hypo_builder.build_hypothesis_from_file(ep_name)

    # This is an example of Epileptogenicity Hypothesis:
    hyp_E = hypo_builder.build_hypothesis_from_file(
        ep_name, e_indices=hyp_x0.x0_indices)

    # This is an example of Mixed Hypothesis:
    x0_indices = [hyp_x0.x0_indices[-1]]
    x0_values = [hyp_x0.x0_values[-1]]
    e_indices = hyp_x0.x0_indices[0:-1].tolist()
    e_values = hyp_x0.x0_values[0:-1].tolist()
    hyp_x0_E = hypo_builder.set_x0_hypothesis(x0_indices, x0_values). \
                                set_e_hypothesis(e_indices, e_values).build_hypothesis()

    hypos = (hyp_x0, hyp_E, hyp_x0_E)

    return head, hypos
    def test_write_pse_service(self):
        test_file = os.path.join(self.config.out.FOLDER_TEMP,
                                 "TestPSEService.h5")
        hypothesis = HypothesisBuilder(3).set_e_hypothesis(
            [0], [0.6]).build_hypothesis()
        dummy_pse_service = LSAPSEService(hypothesis=hypothesis,
                                          params_pse={
                                              "path": [],
                                              "indices": [],
                                              "name": [],
                                              "bounds": []
                                          })

        assert not os.path.exists(test_file)

        self.writer.write_pse_service(dummy_pse_service, test_file)

        assert os.path.exists(test_file)
def reconfigure_model_with_fit_estimates(head,
                                         model_configuration,
                                         probabilistic_model,
                                         estimates,
                                         base_path,
                                         writer=None,
                                         plotter=None):
    # -------------------------- Reconfigure model after fitting:---------------------------------------------------
    for id_est, est in enumerate(ensure_list(estimates)):
        K = est.get("K", np.mean(model_configuration.K))
        tau1 = est.get("tau1", np.mean(model_configuration.tau1))
        tau0 = est.get("tau0", np.mean(model_configuration.tau0))
        fit_conn = est.get("MC", model_configuration.connectivity)
        fit_model_configuration_builder = \
            ModelConfigurationBuilder(model_configuration.model_name, fit_conn,
                                      K_unscaled=K * model_configuration.number_of_regions). \
                set_parameter("tau1", tau1).set_parameter("tau0", tau0)
        x0 = model_configuration.x0
        x0[probabilistic_model.active_regions] = est["x0"]
        x0_values_fit = fit_model_configuration_builder._compute_x0_values_from_x0_model(
            x0)
        hyp_fit = HypothesisBuilder().set_nr_of_regions(head.connectivity.number_of_regions). \
            set_name('fit' + str(id_est + 1)). \
            set_x0_hypothesis(list(probabilistic_model.active_regions),
                              x0_values_fit[probabilistic_model.active_regions]). \
            build_hypothesis()

        model_configuration_fit = \
            fit_model_configuration_builder.build_model_from_hypothesis(hyp_fit)

        if writer:
            writer.write_hypothesis(hyp_fit, path("fit_Hypothesis", base_path))
            writer.write_model_configuration(
                model_configuration_fit, path("fit_ModelConfig", base_path))

        # Plot nullclines and equilibria of model configuration
        if plotter:
            plotter.plot_state_space(
                model_configuration_fit,
                region_labels=head.connectivity.region_labels,
                special_idx=probabilistic_model.active_regions,
                figure_name="fit_Nullclines and equilibria")
        return model_configuration_fit
    def test_plot_state_space(self):
        lsa_hypothesis = HypothesisBuilder(
            config=self.config).build_lsa_hypothesis()
        mc = ModelConfigurationBuilder("EpileptorDP", numpy.array([[1.0, 0.0], [0.0, 1.0]])). \
                                                        build_model_from_E_hypothesis(lsa_hypothesis)

        model = "6d"
        zmode = "lin"
        # TODO: this figure_name is constructed inside plot method, so it can change
        figure_name = "_" + "Epileptor_" + model + "_z-" + str(zmode)
        file_name = os.path.join(self.config.out.FOLDER_FIGURES,
                                 figure_name + ".png")
        assert not os.path.exists(file_name)

        self.plotter.plot_state_space(mc,
                                      region_labels=numpy.array(["a", "b"]),
                                      special_idx=[0],
                                      figure_name="")

        assert os.path.exists(file_name)
Esempio n. 17
0
    def run_lsa(self, disease_hypothesis, model_configuration):

        if self.lsa_method == "auto":
            if numpy.any(model_configuration.x1eq > X1EQ_CR_DEF):
                self.lsa_method = "2D"
            else:
                self.lsa_method = "1D"

        if self.lsa_method == "2D" and numpy.all(
                model_configuration.x1eq <= X1EQ_CR_DEF):
            warning(
                "LSA with the '2D' method (on the 2D Epileptor model) will not produce interpretable results when"
                " the equilibrium point of the system is not supercritical (unstable)!"
            )

        jacobian = self._compute_jacobian(model_configuration)

        # Perform eigenvalue decomposition
        eigen_values, eigen_vectors = numpy.linalg.eig(jacobian)
        eigen_values = numpy.real(eigen_values)
        eigen_vectors = numpy.real(eigen_vectors)
        sorted_indices = numpy.argsort(eigen_values, kind='mergesort')
        if self.lsa_method == "2D":
            sorted_indices = sorted_indices[::-1]
        self.eigen_vectors = eigen_vectors[:, sorted_indices]
        self.eigen_values = eigen_values[sorted_indices]

        self._ensure_eigen_vectors_number(
            self.eigen_values[:disease_hypothesis.number_of_regions],
            model_configuration.e_values, model_configuration.x0_values,
            disease_hypothesis.regions_disease_indices)

        if self.eigen_vectors_number == disease_hypothesis.number_of_regions:
            # Calculate the propagation strength index by summing all eigenvectors
            lsa_propagation_strength = numpy.abs(
                numpy.sum(self.eigen_vectors, axis=1))

        else:
            sorted_indices = max(self.eigen_vectors_number, 1)
            # Calculate the propagation strength index by summing the first n eigenvectors (minimum 1)
            if self.weighted_eigenvector_sum:
                lsa_propagation_strength = \
                    numpy.abs(weighted_vector_sum(numpy.array(self.eigen_values[:self.eigen_vectors_number]),
                                                  numpy.array(self.eigen_vectors[:, :self.eigen_vectors_number]),
                                                              normalize=True))
            else:
                lsa_propagation_strength = \
                    numpy.abs(numpy.sum(self.eigen_vectors[:, :self.eigen_vectors_number], axis=1))

        if self.lsa_method == "2D":
            # lsa_propagation_strength = lsa_propagation_strength[:disease_hypothesis.number_of_regions]
            # or
            # lsa_propagation_strength = numpy.where(lsa_propagation_strength[:disease_hypothesis.number_of_regions] >=
            #                                        lsa_propagation_strength[disease_hypothesis.number_of_regions:],
            #                                        lsa_propagation_strength[:disease_hypothesis.number_of_regions],
            #                                        lsa_propagation_strength[disease_hypothesis.number_of_regions:])
            # or
            lsa_propagation_strength = numpy.sqrt(
                lsa_propagation_strength[:disease_hypothesis.number_of_regions]
                **2 +
                lsa_propagation_strength[disease_hypothesis.number_of_regions:]
                **2)
            lsa_propagation_strength = numpy.log10(lsa_propagation_strength)
            lsa_propagation_strength -= lsa_propagation_strength.min()

        if self.normalize_propagation_strength:
            # Normalize by the maximum
            lsa_propagation_strength /= numpy.max(lsa_propagation_strength)

        # # TODO: this has to be corrected
        # if self.eigen_vectors_number < 0.2 * disease_hypothesis.number_of_regions:
        #     propagation_strength_elbow = numpy.max([self.get_curve_elbow_point(lsa_propagation_strength),
        #                                     self.eigen_vectors_number])
        # else:
        propagation_strength_elbow = self.get_curve_elbow_point(
            lsa_propagation_strength)
        propagation_indices = lsa_propagation_strength.argsort(
        )[-propagation_strength_elbow:]

        hypothesis_builder = HypothesisBuilder(disease_hypothesis.number_of_regions). \
                                set_attributes_based_on_hypothesis(disease_hypothesis). \
                                    set_name(disease_hypothesis.name + "_LSA"). \
                                        set_lsa_propagation(propagation_indices, lsa_propagation_strength)

        return hypothesis_builder.build_lsa_hypothesis()
Esempio n. 18
0
def main_vep(config=Config(),
             ep_name=EP_NAME,
             K_unscaled=K_UNSCALED_DEF,
             ep_indices=[],
             hyp_norm=0.99,
             manual_hypos=[],
             sim_type="paper",
             pse_flag=PSE_FLAG,
             sa_pse_flag=SA_PSE_FLAG,
             sim_flag=SIM_FLAG,
             n_samples=100,
             test_write_read=False):
    logger = initialize_logger(__name__, config.out.FOLDER_LOGS)
    # -------------------------------Reading data-----------------------------------
    reader = TVBReader() if config.input.IS_TVB_MODE else H5Reader()
    writer = H5Writer()
    plotter = Plotter(config)
    logger.info("Reading from: " + config.input.HEAD)
    head = reader.read_head(config.input.HEAD)
    plotter.plot_head(head)
    if test_write_read:
        writer.write_head(head, os.path.join(config.out.FOLDER_RES, "Head"))
    # --------------------------Hypothesis definition-----------------------------------

    hypotheses = []
    # Reading a h5 file:

    if len(ep_name) > 0:
        # For an Excitability Hypothesis you leave e_indices empty
        # For a Mixed Hypothesis: you give as e_indices some indices for values > 0
        # For an Epileptogenicity Hypothesis: you give as e_indices all indices for values > 0
        hyp_file = HypothesisBuilder(head.connectivity.number_of_regions, config=config).set_normalize(hyp_norm). \
            build_hypothesis_from_file(ep_name, e_indices=ep_indices)
        hyp_file.name += ep_name
        # print(hyp_file.string_regions_disease(head.connectivity.region_labels))
        hypotheses.append(hyp_file)

    hypotheses += manual_hypos

    # --------------------------Hypothesis and LSA-----------------------------------
    for hyp in hypotheses:
        logger.info("\n\nRunning hypothesis: " + hyp.name)

        all_regions_indices = np.array(range(head.number_of_regions))
        healthy_indices = np.delete(all_regions_indices,
                                    hyp.regions_disease_indices).tolist()

        logger.info("\n\nCreating model configuration...")
        model_config_builder = ModelConfigurationBuilder("EpileptorDP2D", head.connectivity, K_unscaled=K_unscaled). \
                                    set_parameter("tau1", TAU1_DEF).set_parameter("tau0", TAU0_DEF)
        mcs_file = os.path.join(config.out.FOLDER_RES,
                                hyp.name + "_model_config_builder.h5")
        writer.write_model_configuration_builder(model_config_builder,
                                                 mcs_file)
        if test_write_read:
            logger.info(
                "Written and read model configuration builders are identical?: "
                + str(
                    assert_equal_objects(
                        model_config_builder,
                        reader.read_model_configuration_builder(mcs_file),
                        logger=logger)))
        # Fix healthy regions to default equilibria:
        # model_configuration = \
        #        model_config_builder.build_model_from_E_hypothesis(hyp)
        # Fix healthy regions to default x0s:
        model_configuration = model_config_builder.build_model_from_hypothesis(
            hyp)
        mc_path = os.path.join(config.out.FOLDER_RES,
                               hyp.name + "_ModelConfig.h5")
        writer.write_model_configuration(model_configuration, mc_path)
        if test_write_read:
            logger.info(
                "Written and read model configuration are identical?: " + str(
                    assert_equal_objects(model_configuration,
                                         reader.read_model_configuration(
                                             mc_path),
                                         logger=logger)))
        # Plot nullclines and equilibria of model configuration
        plotter.plot_state_space(model_configuration,
                                 head.connectivity.region_labels,
                                 special_idx=hyp.regions_disease_indices,
                                 figure_name=hyp.name + "_StateSpace")

        logger.info("\n\nRunning LSA...")
        lsa_service = LSAService(eigen_vectors_number=1)
        lsa_hypothesis = lsa_service.run_lsa(hyp, model_configuration)

        lsa_path = os.path.join(config.out.FOLDER_RES,
                                lsa_hypothesis.name + "_LSA.h5")
        lsa_config_path = os.path.join(config.out.FOLDER_RES,
                                       lsa_hypothesis.name + "_LSAConfig.h5")
        writer.write_hypothesis(lsa_hypothesis, lsa_path)
        writer.write_lsa_service(lsa_service, lsa_config_path)
        if test_write_read:
            logger.info("Written and read LSA services are identical?: " + str(
                assert_equal_objects(lsa_service,
                                     reader.read_lsa_service(lsa_config_path),
                                     logger=logger)))
            logger.info(
                "Written and read LSA hypotheses are identical (no input check)?: "
                + str(
                    assert_equal_objects(lsa_hypothesis,
                                         reader.read_hypothesis(lsa_path),
                                         logger=logger)))
        plotter.plot_lsa(lsa_hypothesis,
                         model_configuration,
                         lsa_service.weighted_eigenvector_sum,
                         lsa_service.eigen_vectors_number,
                         head.connectivity.region_labels,
                         None,
                         lsa_service=lsa_service)

        if pse_flag:
            # --------------Parameter Search Exploration (PSE)-------------------------------
            logger.info("\n\nRunning PSE LSA...")
            pse_results = pse_from_lsa_hypothesis(
                n_samples,
                lsa_hypothesis,
                model_configuration.connectivity,
                model_config_builder,
                lsa_service,
                head.connectivity.region_labels,
                param_range=0.1,
                global_coupling=[{
                    "indices": all_regions_indices
                }],
                healthy_regions_parameters=[{
                    "name": "x0_values",
                    "indices": healthy_indices
                }],
                logger=logger,
                save_flag=True)[0]
            plotter.plot_lsa(lsa_hypothesis, model_configuration,
                             lsa_service.weighted_eigenvector_sum,
                             lsa_service.eigen_vectors_number,
                             head.connectivity.region_labels, pse_results)

            pse_lsa_path = os.path.join(
                config.out.FOLDER_RES,
                lsa_hypothesis.name + "_PSE_LSA_results.h5")
            writer.write_dictionary(pse_results, pse_lsa_path)
            if test_write_read:
                logger.info(
                    "Written and read parameter search results are identical?: "
                    + str(
                        assert_equal_objects(pse_results,
                                             reader.read_dictionary(
                                                 pse_lsa_path),
                                             logger=logger)))

        if sa_pse_flag:
            # --------------Sensitivity Analysis Parameter Search Exploration (PSE)-------------------------------
            logger.info("\n\nrunning sensitivity analysis PSE LSA...")
            sa_results, pse_sa_results = \
                sensitivity_analysis_pse_from_lsa_hypothesis(n_samples, lsa_hypothesis,
                                                             model_configuration.connectivity,
                                                             model_config_builder, lsa_service,
                                                             head.connectivity.region_labels,
                                                             method="sobol", param_range=0.1,
                                                             global_coupling=[{"indices": all_regions_indices,
                                                                               "bounds": [0.0, 2 *
                                                                                          model_config_builder.K_unscaled[
                                                                                              0]]}],
                                                             healthy_regions_parameters=[
                                                                 {"name": "x0_values", "indices": healthy_indices}],
                                                             config=config)
            plotter.plot_lsa(lsa_hypothesis,
                             model_configuration,
                             lsa_service.weighted_eigenvector_sum,
                             lsa_service.eigen_vectors_number,
                             head.connectivity.region_labels,
                             pse_sa_results,
                             title="SA PSE Hypothesis Overview")

            sa_pse_path = os.path.join(
                config.out.FOLDER_RES,
                lsa_hypothesis.name + "_SA_PSE_LSA_results.h5")
            sa_lsa_path = os.path.join(
                config.out.FOLDER_RES,
                lsa_hypothesis.name + "_SA_LSA_results.h5")
            writer.write_dictionary(pse_sa_results, sa_pse_path)
            writer.write_dictionary(sa_results, sa_lsa_path)
            if test_write_read:
                logger.info(
                    "Written and read sensitivity analysis results are identical?: "
                    + str(
                        assert_equal_objects(sa_results,
                                             reader.read_dictionary(
                                                 sa_lsa_path),
                                             logger=logger)))
                logger.info(
                    "Written and read sensitivity analysis parameter search results are identical?: "
                    + str(
                        assert_equal_objects(pse_sa_results,
                                             reader.read_dictionary(
                                                 sa_pse_path),
                                             logger=logger)))

        if sim_flag:
            # --------------------------Simulation preparations-----------------------------------
            # If you choose model...
            # Available models beyond the TVB Epileptor (they all encompass optional variations from the different papers):
            # EpileptorDP: similar to the TVB Epileptor + optional variations,
            # EpileptorDP2D: reduced 2D model, following Proix et all 2014 +optional variations,
            # EpleptorDPrealistic: starting from the TVB Epileptor + optional variations, but:
            #      -x0, Iext1, Iext2, slope and K become noisy state variables,
            #      -Iext2 and slope are coupled to z, g, or z*g in order for spikes to appear before seizure,
            #      -correlated noise is also used
            # We don't want any time delays for the moment
            head.connectivity.tract_lengths *= config.simulator.USE_TIME_DELAYS_FLAG
            sim_types = ensure_list(sim_type)
            for sim_type in sim_types:
                # ------------------------------Simulation--------------------------------------
                logger.info(
                    "\n\nConfiguring %s simulation from model_configuration..."
                    % sim_type)
                if isequal_string(sim_type, "realistic"):
                    sim_builder = SimulatorBuilder(model_configuration).set_model("EpileptorDPrealistic"). \
                        set_fs(2048.0).set_simulation_length(60000.0)
                    sim_builder.model_config.tau0 = 60000.0
                    sim_builder.model_config.tau1 = 0.2
                    sim_builder.model_config.slope = 0.25
                    sim_builder.model_config.pmode = np.array([PMODE_DEF])
                    sim_settings = sim_builder.build_sim_settings()
                    sim_settings.noise_type = COLORED_NOISE
                    sim_settings.noise_ntau = 20
                    # Necessary a more stable integrator:
                    sim_settings.integrator_type = "Dop853Stochastic"
                elif isequal_string(sim_type, "fitting"):
                    sim_builder = SimulatorBuilder(model_configuration).set_model("EpileptorDP2D"). \
                        set_fs(2048.0).set_fs_monitor(2048.0).set_simulation_length(300.0)
                    sim_builder.model_config.tau0 = 30.0
                    sim_builder.model_config.tau1 = 0.5
                    sim_settings = sim_builder.build_sim_settings()
                    sim_settings.noise_intensity = np.array([0.0, 1e-5])
                elif isequal_string(sim_type, "reduced"):
                    sim_builder = \
                        SimulatorBuilder(model_configuration).set_model("EpileptorDP2D").set_fs(
                            4096.0).set_simulation_length(1000.0)
                    sim_settings = sim_builder.build_sim_settings()
                elif isequal_string(sim_type, "paper"):
                    sim_builder = SimulatorBuilder(
                        model_configuration).set_model("Epileptor")
                    sim_settings = sim_builder.build_sim_settings()
                else:
                    sim_builder = SimulatorBuilder(
                        model_configuration).set_model("EpileptorDP")
                    sim_settings = sim_builder.build_sim_settings()

                # Integrator and initial conditions initialization.
                # By default initial condition is set right on the equilibrium point.
                sim, sim_settings = \
                    sim_builder.build_simulator_TVB_from_model_sim_settings(head.connectivity, sim_settings)
                sim_path = os.path.join(
                    config.out.FOLDER_RES,
                    lsa_hypothesis.name + "_" + sim_type + "_sim_settings.h5")
                model_path = os.path.join(
                    config.out.FOLDER_RES,
                    lsa_hypothesis.name + sim_type + "_model.h5")
                writer.write_simulation_settings(sim.settings, sim_path)
                writer.write_simulator_model(
                    sim.model, model_path, sim.connectivity.number_of_regions)
                if test_write_read:
                    # TODO: find out why it cannot set monitor expressions
                    logger.info(
                        "Written and read simulation settings are identical?: "
                        + str(
                            assert_equal_objects(
                                sim.settings,
                                reader.read_simulation_settings(sim_path),
                                logger=logger)))
                    # logger.info("Written and read simulation model are identical?: " +
                    #             str(assert_equal_objects(sim.model,
                    #                                      reader.read_epileptor_model(model_path), logger=logger)))

                logger.info("\n\nSimulating %s..." % sim_type)
                sim_output, status = sim.launch_simulation(
                    report_every_n_monitor_steps=100, timeseries=Timeseries)
                if not status:
                    logger.warning("\nSimulation failed!")
                else:
                    time = np.array(sim_output.time).astype("f")
                    logger.info("\n\nSimulated signal return shape: %s",
                                sim_output.shape)
                    logger.info("Time: %s - %s", time[0], time[-1])
                    logger.info("Values: %s - %s", sim_output.data.min(),
                                sim_output.data.max())
                    if not status:
                        logger.warning("\nSimulation failed!")
                    else:
                        sim_output, seeg = compute_seeg_and_write_ts_to_h5(
                            sim_output,
                            sim.model,
                            head.sensorsSEEG,
                            os.path.join(config.out.FOLDER_RES,
                                         sim_type + "_ts.h5"),
                            seeg_gain_mode="lin",
                            hpf_flag=True,
                            hpf_low=10.0,
                            hpf_high=512.0)

                        # Plot results
                        plotter.plot_simulated_timeseries(
                            sim_output,
                            sim.model,
                            lsa_hypothesis.lsa_propagation_indices,
                            seeg_dict=seeg,
                            spectral_raster_plot=False,
                            title_prefix=hyp.name,
                            spectral_options={"log_scale": True})
Esempio n. 19
0
 def _prepare_model_for_simulation(connectivity):
     hypothesis = HypothesisBuilder(connectivity.number_of_regions).set_e_hypothesis([0, 1],
                                                                                     [0.0, 10.0]).build_hypothesis()
     model_configuration_builder = ModelConfigurationBuilder("Epileptor", connectivity.normalized_weights)
     model_configuration = model_configuration_builder.build_model_from_hypothesis(hypothesis)
     return model_configuration
    if user_home == "/home/denis":
        output = os.path.join(user_home, 'Dropbox', 'Work', 'VBtech', 'VEP', "results", "INScluster")
        config = Config(head_folder=head_folder, output_base=output, separate_by_run=False)
    elif user_home == "/Users/lia.domide":
        config = Config(head_folder="/WORK/episense/tvb-epilepsy/data/TVB3/Head",
                        raw_data_folder="/WORK/episense/tvb-epilepsy/data/TVB3/ts_seizure")
    else:
        output = os.path.join(user_home, 'Dropbox', 'Work', 'VBtech', 'VEP', "results", "fit")
        config = Config(head_folder=head_folder, output_base=output, separate_by_run=False)

    # Read head
    reader = H5Reader()

    head = reader.read_head(config.input.HEAD)

    hyp_builder = HypothesisBuilder(head.connectivity.number_of_regions, config).set_normalize(0.99)
    e_indices = [1, 26]  # [1, 2, 25, 26]
    hypothesis = hyp_builder.build_hypothesis_from_file("clinical_hypothesis_postseeg", e_indices)

    model_configuration = \
        ModelConfigurationBuilder("Epileptor", head.connectivity.normalized_weights).\
            build_model_from_E_hypothesis(hypothesis)

    probabilistic_model = SDEProbabilisticModelBuilder(model_config=model_configuration).generate_model()
    H5Writer().write_probabilistic_model(probabilistic_model, config.out.FOLDER_RES, "TestProbModelorig.h5")

    probabilistic_model2 = reader.read_probabilistic_model(os.path.join(config.out.FOLDER_RES, "TestProbModelorig.h5"))
    H5Writer().write_probabilistic_model(probabilistic_model2, config.out.FOLDER_RES, "TestProbModelread.h5")