예제 #1
0
def from_hypothesis_to_model_config_lsa(hyp,
                                        head,
                                        eigen_vectors_number=None,
                                        weighted_eigenvector_sum=True,
                                        config=Config(),
                                        save_flag=None,
                                        plot_flag=None,
                                        **kwargs):
    logger.info("\n\nRunning hypothesis: " + hyp.name)
    logger.info("\n\nCreating model configuration...")
    if save_flag is None:
        save_flag = config.figures.SAVE_FLAG
    if plot_flag is None:
        plot_flag = config.figures.SHOW_FLAG
    builder = ModelConfigurationBuilder(hyp.number_of_regions, **kwargs)
    if hyp.type == "Epileptogenicity":
        model_configuration = builder.build_model_from_E_hypothesis(
            hyp, head.connectivity.normalized_weights)
    else:
        model_configuration = builder.build_model_from_hypothesis(
            hyp, head.connectivity.normalized_weights)
    logger.info("\n\nRunning LSA...")
    lsa_service = LSAService(eigen_vectors_number=eigen_vectors_number,
                             weighted_eigenvector_sum=weighted_eigenvector_sum)
    lsa_hypothesis = lsa_service.run_lsa(hyp, model_configuration)
    if save_flag:
        writer = H5Writer()
        path_mc = os.path.join(config.out.FOLDER_RES,
                               hyp.name + "_ModelConfig.h5")
        writer.write_model_configuration(model_configuration, path_mc)
        writer.write_hypothesis(
            lsa_hypothesis,
            os.path.join(config.out.FOLDER_RES, lsa_hypothesis.name + ".h5"))
    if plot_flag:
        plotter = Plotter(config)
        # Plot nullclines and equilibria of model configuration
        plotter.plot_state_space(model_configuration,
                                 "6d",
                                 head.connectivity.region_labels,
                                 special_idx=hyp.regions_disease_indices,
                                 zmode="lin",
                                 figure_name=hyp.name + "_StateSpace")
        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)
    return model_configuration, lsa_hypothesis, builder, lsa_service
예제 #2
0
def lsa_run_fun(hypothesis_input,
                connectivity_matrix,
                params_paths,
                params_values,
                params_indices,
                out_fun=lsa_out_fun,
                model_configuration_service_input=None,
                yc=YC_DEF,
                Iext1=I_EXT1_DEF,
                K=K_DEF,
                a=A_DEF,
                b=B_DEF,
                x1eq_mode="optimize",
                lsa_service_input=None,
                n_eigenvectors=EIGENVECTORS_NUMBER_SELECTION,
                weighted_eigenvector_sum=True):
    try:
        # Update hypothesis and create a new model_configuration:
        hypothesis, model_configuration, params_paths, params_values, params_indices \
            = update_hypothesis(hypothesis_input, connectivity_matrix, params_paths, params_values, params_indices,
                                model_configuration_service_input, yc, Iext1, K, a, b, x1eq_mode)

        # ...create/update lsa service:
        if isinstance(lsa_service_input, LSAService):
            lsa_service = deepcopy(lsa_service_input)
        else:
            lsa_service = LSAService(
                n_eigenvectors=n_eigenvectors,
                weighted_eigenvector_sum=weighted_eigenvector_sum)

        # ...and modify possible related parameters:
        lsa_service = \
            update_object(lsa_service, "lsa_service", params_paths, params_values, params_indices)[0]

        # Run LSA:
        lsa_hypothesis = lsa_service.run_lsa(hypothesis, model_configuration)

        if callable(out_fun):
            output = out_fun(lsa_hypothesis,
                             model_configuration=model_configuration)
        else:
            output = lsa_hypothesis

        return True, output

    except:

        return False, None
예제 #3
0
def start_lsa_run(hypothesis, model_connectivity, config=Config()):
    logger.info("creating model configuration...")
    model_configuration_builder = ModelConfigurationBuilder(
        hypothesis.number_of_regions)
    model_configuration = model_configuration_builder.build_model_from_hypothesis(
        hypothesis, model_connectivity)

    logger.info("running LSA...")
    lsa_service = LSAService(
        eigen_vectors_number_selection=config.calcul.
        EIGENVECTORS_NUMBER_SELECTION,
        eigen_vectors_number=None,
        weighted_eigenvector_sum=config.calcul.WEIGHTED_EIGENVECTOR_SUM,
        normalize_propagation_strength=False)
    lsa_hypothesis = lsa_service.run_lsa(hypothesis, model_configuration)

    return model_configuration_builder, model_configuration, lsa_service, lsa_hypothesis
예제 #4
0
    def test_write_lsa_service(self):
        test_file = os.path.join(self.config.out.FOLDER_TEMP, "TestLSAService.h5")
        dummy_lsa_service = LSAService()

        assert not os.path.exists(test_file)

        self.writer.write_lsa_service(dummy_lsa_service, test_file)

        assert os.path.exists(test_file)
예제 #5
0
 def run(self, params, conn_matrix, model_config_service_input=None, lsa_service_input=None,
         yc=YC_DEF, Iext1=I_EXT1_DEF, K=K_DEF, a=A_DEF, b=B_DEF, tau1=TAU1_DEF, tau0=TAU0_DEF, x1eq_mode="optimize",
         lsa_method=CalculusConfig.LSA_METHOD, n_eigenvectors=CalculusConfig.EIGENVECTORS_NUMBER_SELECTION,
         weighted_eigenvector_sum=CalculusConfig.WEIGHTED_EIGENVECTOR_SUM):
     #try:
     # Copy and update hypothesis
     hypo_copy, model_configuration = self.update_hypo_model_config(self.hypothesis, params, conn_matrix,
                                                                    model_config_service_input, yc, Iext1, K, a,
                                                                    b, tau1, tau0, x1eq_mode)
     # Copy a LSAService and update it
     # ...create/update lsa service:
     if isinstance(lsa_service_input, LSAService):
         lsa_service = deepcopy(lsa_service_input)
     else:
         lsa_service = LSAService(lsa_method=lsa_method, eigen_vectors_number=n_eigenvectors,
                                  weighted_eigenvector_sum=weighted_eigenvector_sum)
     lsa_service.update_for_pse(params, self.params_paths, self.params_indices)
     lsa_hypothesis = lsa_service.run_lsa(hypo_copy, model_configuration)
     output = self.prepare_run_results(lsa_hypothesis, model_configuration)
     return True, output
def start_lsa_run(hypothesis, connectivity_matrix, logger=None):

    if logger is None:
        logger = initialize_logger(__name__)

    logger.info("creating model configuration...")
    model_configuration_service = ModelConfigurationService(
        hypothesis.number_of_regions)
    model_configuration = model_configuration_service. \
        configure_model_from_hypothesis(hypothesis, connectivity_matrix)

    logger.info("running LSA...")
    lsa_service = LSAService(
        eigen_vectors_number_selection=EIGENVECTORS_NUMBER_SELECTION,
        eigen_vectors_number=None,
        weighted_eigenvector_sum=WEIGHTED_EIGENVECTOR_SUM,
        normalize_propagation_strength=False)
    lsa_hypothesis = lsa_service.run_lsa(hypothesis, model_configuration)

    return model_configuration_service, model_configuration, lsa_service, lsa_hypothesis
예제 #7
0
    def test_read_lsa_service(self):
        test_file = os.path.join(self.config.out.FOLDER_TEMP, "TestLSAService.h5")
        dummy_lsa_service = LSAService()
        self.writer.write_lsa_service(dummy_lsa_service, test_file)

        lsa_service = self.reader.read_lsa_service(test_file)

        assert dummy_lsa_service.eigen_vectors_number_selection == lsa_service.eigen_vectors_number_selection
        assert dummy_lsa_service.eigen_vectors_number == lsa_service.eigen_vectors_number
        assert dummy_lsa_service.eigen_values == lsa_service.eigen_values
        assert dummy_lsa_service.eigen_vectors == lsa_service.eigen_vectors
        assert dummy_lsa_service.weighted_eigenvector_sum == lsa_service.weighted_eigenvector_sum
        assert dummy_lsa_service.normalize_propagation_strength == lsa_service.normalize_propagation_strength
예제 #8
0
    def read_lsa_service(self, path):
        """
        :param path: Path towards a LSAService H5 file
        :return: LSAService object
        """
        self.logger.info("Starting to read LSAService from: %s" % path)
        h5_file = h5py.File(path, 'r', libver='latest')
        from tvb_epilepsy.service.lsa_service import LSAService
        lsa_service = LSAService()

        for dataset in h5_file.keys():
            lsa_service.set_attribute(dataset, h5_file["/" + dataset][()])

        for attr in h5_file.attrs.keys():
            lsa_service.set_attribute(attr, h5_file.attrs[attr])

        h5_file.close()
        return lsa_service
예제 #9
0
def main_fit_sim_hyplsa(stats_model_name="vep_original",
                        EMPIRICAL='',
                        times_on_off=[],
                        channel_lbls=[],
                        channel_inds=[]):

    # ------------------------------Model code--------------------------------------
    # Compile or load model:
    model_file = os.path.join(FOLDER_VEP_HOME,
                              stats_model_name + "_stan_model.pkl")
    if os.path.isfile(model_file):
        stats_model = pickle.load(open(model_file, 'rb'))
    else:
        # vep_original_DP
        if stats_model_name is "vep_dWt":
            model_path = os.path.join(STATISTICAL_MODELS_PATH, "vep_dWt.stan")
        elif stats_model_name is "vep_original_x0":
            model_path = os.path.join(STATISTICAL_MODELS_PATH,
                                      "vep_original_x0.stan")
        else:
            model_path = os.path.join(STATISTICAL_MODELS_PATH,
                                      "vep_original_DP.stan")
        stats_model = compile_model(model_stan_code_path=model_path)
        with open(model_file, 'wb') as f:
            pickle.dump(stats_model, f)

    # -------------------------------Reading data-----------------------------------

    data_folder = os.path.join(DATA_CUSTOM, 'Head')

    reader = Reader()

    logger.info("Reading from: " + data_folder)
    head = reader.read_head(data_folder,
                            seeg_sensors_files=[("SensorsInternal.h5", "")])

    # head.plot()

    if len(channel_inds) > 1:
        channel_inds, _ = get_bipolar_channels(channel_inds, channel_lbls)

    # --------------------------Hypothesis definition-----------------------------------

    n_samples = 100

    # # 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:
    ep_name = "ep_l_frontal_complex"
    # FOLDER_RES = os.path.join(data_folder, ep_name)
    from tvb_epilepsy.custom.readers_custom import CustomReader

    if not isinstance(reader, CustomReader):
        reader = CustomReader()
    disease_values = reader.read_epileptogenicity(data_folder, name=ep_name)
    disease_indices, = np.where(disease_values > np.min([X0_DEF, E_DEF]))
    disease_values = disease_values[disease_indices]
    inds = np.argsort(disease_values)
    disease_values = disease_values[inds]
    disease_indices = disease_indices[inds]
    x0_indices = [disease_indices[-1]]
    x0_values = [disease_values[-1]]
    e_indices = disease_indices[0:-1].tolist()
    e_values = disease_values[0:-1].tolist()
    disease_indices = list(disease_indices)

    n_x0 = len(x0_indices)
    n_e = len(e_indices)
    n_disease = len(disease_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 Excitability Hypothesis:
    hyp_x0 = DiseaseHypothesis(
        head.connectivity.number_of_regions,
        excitability_hypothesis={tuple(disease_indices): disease_values},
        epileptogenicity_hypothesis={},
        connectivity_hypothesis={})

    # This is an example of Mixed Hypothesis:
    hyp_x0_E = DiseaseHypothesis(
        head.connectivity.number_of_regions,
        excitability_hypothesis={tuple(x0_indices): x0_values},
        epileptogenicity_hypothesis={tuple(e_indices): e_values},
        connectivity_hypothesis={})

    hyp_E = DiseaseHypothesis(
        head.connectivity.number_of_regions,
        excitability_hypothesis={},
        epileptogenicity_hypothesis={tuple(disease_indices): disease_values},
        connectivity_hypothesis={})

    hypos = (hyp_x0_E, hyp_x0, hyp_E)
    # --------------------------Simulation preparations-----------------------------------
    tau1 = 0.5
    # TODO: maybe use a custom Monitor class
    fs = 10 * 2048.0 * (
        2 * tau1
    )  # this is the simulation sampling rate that is necessary for the simulation to be stable
    time_length = 50.0 / tau1  # msecs, the final output nominal time length of the simulation
    report_every_n_monitor_steps = 100.0
    (dt, fsAVG, sim_length, monitor_period, n_report_blocks) = \
        set_time_scales(fs=fs, time_length=time_length, scale_fsavg=1,
                        report_every_n_monitor_steps=report_every_n_monitor_steps)

    # 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,
    #      -multiplicative correlated noise is also used
    # Optional variations:
    zmode = "lin"  # by default, or "sig" for the sigmoidal expression for the slow z variable in Proix et al. 2014
    pmode = "z"  # by default, "g" or "z*g" for the feedback coupling to Iext2 and slope for EpileptorDPrealistic

    model_name = "EpileptorDP2D"
    if model_name is "EpileptorDP2D":
        spectral_raster_plot = False
        trajectories_plot = True
    else:
        spectral_raster_plot = False  # "lfp"
        trajectories_plot = False
    # We don't want any time delays for the moment
    # head.connectivity.tract_lengths *= TIME_DELAYS_FLAG

    # --------------------------Hypothesis and LSA-----------------------------------

    for hyp in hypos:  #hypotheses:

        logger.info("\n\nRunning hypothesis: " + hyp.name)

        # hyp.write_to_h5(FOLDER_RES, hyp.name + ".h5")

        logger.info("\n\nCreating model configuration...")
        model_configuration_service = ModelConfigurationService(
            hyp.number_of_regions, K=10.0)
        # model_configuration_service.write_to_h5(FOLDER_RES, hyp.name + "_model_config_service.h5")

        if hyp.type == "Epileptogenicity":
            model_configuration = model_configuration_service. \
                configure_model_from_E_hypothesis(hyp, head.connectivity.normalized_weights)
        else:
            model_configuration = model_configuration_service. \
                configure_model_from_hypothesis(hyp, head.connectivity.normalized_weights)
        model_configuration.write_to_h5(FOLDER_RES,
                                        hyp.name + "_ModelConfig.h5")

        # Plot nullclines and equilibria of model configuration
        model_configuration_service.plot_nullclines_eq(
            model_configuration,
            head.connectivity.region_labels,
            special_idx=disease_indices,
            model="6d",
            zmode="lin",
            figure_name=hyp.name + "_Nullclines and equilibria")

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

        lsa_hypothesis.write_to_h5(FOLDER_RES, lsa_hypothesis.name + "_LSA.h5")
        lsa_service.write_to_h5(FOLDER_RES,
                                lsa_hypothesis.name + "_LSAConfig.h5")

        lsa_service.plot_lsa(lsa_hypothesis, model_configuration,
                             head.connectivity.region_labels, None)

        # ------------------------------Simulation--------------------------------------
        logger.info("\n\nConfiguring simulation...")
        noise_intensity = 10**-2.8
        sim = setup_simulation_from_model_configuration(
            model_configuration,
            head.connectivity,
            dt,
            sim_length,
            monitor_period,
            model_name,
            zmode=np.array(zmode),
            pmode=np.array(pmode),
            noise_instance=None,
            noise_intensity=noise_intensity,
            monitor_expressions=None)
        sim.model.tau1 = tau1
        sim.model.tau0 = 30.0

        # Integrator and initial conditions initialization.
        # By default initial condition is set right on the equilibrium point.
        sim.config_simulation(initial_conditions=None)

        # convert_to_h5_model(sim.model).write_to_h5(FOLDER_RES, lsa_hypothesis.name + "_sim_model.h5")

        if os.path.isfile(EMPIRICAL):

            observation, time, fs = prepare_seeg_observable(EMPIRICAL,
                                                            times_on_off,
                                                            channel_lbls,
                                                            log_flag=True)
            vois_ts_dict = {"time": time, "signals": observation}
            #
            # prepare_seeg_observable(os.path.join(SEEG_data, 'SZ2_0001.edf'), [15.0, 40.0], channel_lbls)

            # prepare_seeg_observable(os.path.join(SEEG_data, 'SZ5_0001.edf'), [20.0, 45.0], channel_lbls)
        else:

            ts_file = os.path.join(FOLDER_VEP_HOME,
                                   lsa_hypothesis.name + "_ts.mat")
            if os.path.isfile(ts_file):
                logger.info("\n\nLoading previously simulated time series...")
                vois_ts_dict = loadmat(ts_file)
            else:
                logger.info("\n\nSimulating...")
                ttavg, tavg_data, status = sim.launch_simulation(
                    n_report_blocks)

                # convert_to_h5_model(sim.simulation_settings).write_to_h5(FOLDER_RES,
                #                                                          lsa_hypothesis.name + "_sim_settings.h5")

                if not status:
                    warning("\nSimulation failed!")

                else:

                    time = np.array(ttavg, dtype='float32').flatten()

                    output_sampling_time = np.mean(np.diff(time))
                    tavg_data = tavg_data[:, :, :, 0]

                    logger.info("\n\nSimulated signal return shape: %s",
                                tavg_data.shape)
                    logger.info("Time: %s - %s", time[0], time[-1])
                    logger.info("Values: %s - %s", tavg_data.min(),
                                tavg_data.max())

                    # Variables of interest in a dictionary:
                    vois_ts_dict = prepare_vois_ts_dict(
                        VOIS[model_name], tavg_data)
                    vois_ts_dict['time'] = time
                    vois_ts_dict['time_units'] = 'msec'

                    vois_ts_dict = compute_seeg_and_write_ts_h5_file(
                        FOLDER_RES,
                        lsa_hypothesis.name + "_ts.h5",
                        sim.model,
                        vois_ts_dict,
                        output_sampling_time,
                        time_length,
                        hpf_flag=True,
                        hpf_low=10.0,
                        hpf_high=512.0,
                        sensor_dicts_list=[head.sensorsSEEG])

                    # Plot results
                    plot_sim_results(sim.model,
                                     lsa_hypothesis.propagation_indices,
                                     lsa_hypothesis.name,
                                     head,
                                     vois_ts_dict,
                                     head.sensorsSEEG.keys(),
                                     hpf_flag=False,
                                     trajectories_plot=trajectories_plot,
                                     spectral_raster_plot=spectral_raster_plot,
                                     log_scale=True)

                    # Optionally save results in mat files
                    savemat(
                        os.path.join(FOLDER_RES,
                                     lsa_hypothesis.name + "_ts.mat"),
                        vois_ts_dict)

        # Get data and observation signals:
        data, active_regions = prepare_data_for_fitting_vep(
            stats_model_name,
            model_configuration,
            lsa_hypothesis,
            fsAVG,
            vois_ts_dict,
            sim.model,
            noise_intensity,
            active_regions=None,
            active_regions_th=0.1,
            euler_method=1,
            observation_model=1,
            channel_inds=channel_inds,
            mixing=head.sensorsSEEG.values()[0])
        savemat(
            os.path.join(FOLDER_RES, lsa_hypothesis.name + "_fit_data.mat"),
            data)

        # Fit and get estimates:
        est, fit = stanfit_model(stats_model,
                                 data,
                                 mode="optimizing",
                                 iter=30000)  #
        savemat(os.path.join(FOLDER_RES, lsa_hypothesis.name + "_fit_est.mat"),
                est)

        plot_fit_results(lsa_hypothesis.name,
                         head,
                         est,
                         data,
                         active_regions,
                         time=vois_ts_dict['time'],
                         seizure_indices=[0, 1],
                         trajectories_plot=True)

        # Reconfigure model after fitting:
        fit_model_configuration_service = ModelConfigurationService(
            hyp.number_of_regions, K=est['K'] * hyp.number_of_regions)

        x0_values_fit = fit_model_configuration_service._compute_x0_values_from_x0_model(
            est['x0'])
        disease_indices = active_regions.tolist()
        hyp_fit = DiseaseHypothesis(
            head.connectivity.number_of_regions,
            excitability_hypothesis={tuple(disease_indices): x0_values_fit},
            epileptogenicity_hypothesis={},
            connectivity_hypothesis={},
            name='fit_' + hyp_x0.name)

        connectivity_matrix_fit = np.array(
            model_configuration.connectivity_matrix)
        connectivity_matrix_fit[active_regions][:, active_regions] = est["FC"]
        model_configuration_fit = fit_model_configuration_service.configure_model_from_hypothesis(
            hyp_fit, connectivity_matrix_fit)
        model_configuration_fit.write_to_h5(FOLDER_RES,
                                            hyp_fit.name + "_ModelConfig.h5")

        # Plot nullclines and equilibria of model configuration
        model_configuration_service.plot_nullclines_eq(
            model_configuration_fit,
            head.connectivity.region_labels,
            special_idx=disease_indices,
            model="6d",
            zmode="lin",
            figure_name=hyp_fit.name + "_Nullclines and equilibria")

        print("Done!")
예제 #10
0
def main_vep(config=Config(),
             ep_name=EP_NAME,
             K_unscaled=K_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=1000,
             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()
    logger.info("Reading from: " + config.input.HEAD)
    head = reader.read_head(config.input.HEAD)
    plotter = Plotter(config)
    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(hyp.number_of_regions,
                                                         K=K_unscaled,
                                                         tau1=TAU1_DEF,
                                                         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 services 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, head.connectivity.normalized_weights)
        # Fix healthy regions to default x0s:
        model_configuration = \
                model_config_builder.build_model_from_hypothesis(hyp, head.connectivity.normalized_weights)
        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,
                                 "6d",
                                 head.connectivity.region_labels,
                                 special_idx=hyp.regions_disease_indices,
                                 zmode="lin",
                                 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,
                head.connectivity.normalized_weights,
                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 sensitivity analysis 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,
                                                             head.connectivity.normalized_weights,
                                                             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)
            integrator = "HeunStochastic"
            for sim_type in sim_types:
                # ------------------------------Simulation--------------------------------------
                logger.info(
                    "\n\nConfiguring simulation from model_configuration...")
                sim_builder = SimulatorBuilder(config.simulator.MODE)
                if isequal_string(sim_type, "realistic"):
                    model.tau0 = 60000.0
                    model.tau1 = 0.2
                    model.slope = 0.25
                    model.Iext2 = 0.45
                    model.pmode = np.array(
                        "z")  # np.array("None") to opt out for feedback
                    sim_settings = \
                        sim_builder.set_fs(2048.0).set_fs_monitor(1024.0).set_simulated_period(60000).build_sim_settings()
                    sim_settings.noise_type = COLORED_NOISE
                    sim_settings.noise_ntau = 20
                    integrator = "Dop853Stochastic"
                elif isequal_string(sim_type, "fitting"):
                    sim_settings = sim_builder.set_model_name("EpileptorDP2D").set_fs(2048.0).set_fs_monitor(2048.0).\
                                                                    set_simulated_period(2000).build_sim_settings()
                    sim_settings.noise_intensity = 1e-5
                    model = sim_builder.generate_model_tvb(model_configuration)
                    model.tau0 = 300.0
                    model.tau1 = 0.5
                elif isequal_string(sim_type, "reduced"):
                    sim_settings = sim_builder.set_model_name("EpileptorDP2D").set_fs(4096.0). \
                                                                    set_simulated_period(1000).build_sim_settings()
                    model = sim_builder.generate_model_tvb(model_configuration)
                elif isequal_string(sim_type, "paper"):
                    sim_builder.set_model_name("Epileptor")
                    sim_settings = sim_builder.build_sim_settings()
                    model = sim_builder.generate_model_tvb(model_configuration)
                else:
                    sim_settings = sim_builder.build_sim_settings()
                    model = sim_builder.generate_model_tvb(model_configuration)

                sim, sim_settings, model = \
                    sim_builder.build_simulator_TVB_from_model_sim_settings(model_configuration,head.connectivity,
                                                                            model, sim_settings, integrator=integrator)

                # Integrator and initial conditions initialization.
                # By default initial condition is set right on the equilibrium point.
                writer.write_simulator_model(
                    sim.model, sim.connectivity.number_of_regions,
                    os.path.join(config.out.FOLDER_RES,
                                 lsa_hypothesis.name + "_sim_model.h5"))
                logger.info("\n\nSimulating...")
                sim_output, status = sim.launch_simulation(
                    report_every_n_monitor_steps=100)

                sim_path = os.path.join(
                    config.out.FOLDER_RES,
                    lsa_hypothesis.name + "_sim_settings.h5")
                writer.write_simulation_settings(sim.simulation_settings,
                                                 sim_path)
                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.simulation_settings,
                                reader.read_simulation_settings(sim_path),
                                logger=logger)))
                if not status:
                    logger.warning("\nSimulation failed!")
                else:
                    time = np.array(sim_output.time_line).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,
                                         model._ui_name + "_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_list=seeg,
                        spectral_raster_plot=False,
                        title_prefix=hyp.name,
                        spectral_options={"log_scale": True})
예제 #11
0
def main_vep(config=Config(), sim_type="default", test_write_read=False,
             pse_flag=PSE_FLAG, sa_pse_flag=SA_PSE_FLAG, sim_flag=SIM_FLAG):
    logger = initialize_logger(__name__, config.out.FOLDER_LOGS)
    # -------------------------------Reading data-----------------------------------
    reader = TVBReader() if config.input.IS_TVB_MODE else H5Reader()
    writer = H5Writer()
    logger.info("Reading from: " + config.input.HEAD)
    head = reader.read_head(config.input.HEAD)
    plotter = Plotter(config)
    plotter.plot_head(head)
    if test_write_read:
        writer.write_head(head, os.path.join(config.out.FOLDER_RES, "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_values = x0_values + e_values
    # disease_indices = x0_indices + e_indices
    # ...or reading a custom file:

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

    # This is an example of Epileptogenicity Hypothesis: you give as ep all indices for values > 0
    hyp_E = hypo_builder.build_hypothesis_from_file(EP_NAME, e_indices=[1, 3, 16, 25])
    # print(hyp_E.string_regions_disease(head.connectivity.region_labels))

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

    # # This is an example of Mixed Hypothesis set manually by the user:
    # 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()

    # This is an example of x0_values mixed Excitability and Epileptogenicity Hypothesis set from file:
    all_regions_indices = np.array(range(head.number_of_regions))
    healthy_indices = np.delete(all_regions_indices, hyp_E.x0_indices + hyp_E.e_indices).tolist()
    hyp_x0_E = hypo_builder.build_hypothesis_from_file(EP_NAME, e_indices=[16, 25])

    hypotheses = (hyp_x0_E, hyp_x0, hyp_E)

    # --------------------------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,
    #      -multiplicative 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_builder = SimulatorBuilder(config.simulator.MODE)
    if isequal_string(sim_type, "realistic"):
        sim_settings = sim_builder.set_model_name("EpileptorDPrealistic").set_simulated_period(50000).build_sim_settings()
        sim_settings.noise_type = COLORED_NOISE
        sim_settings.noise_ntau = 10
    elif isequal_string(sim_type, "fitting"):
        sim_settings = sim_builder.set_model_name("EpileptorDP2D").build_sim_settings()
        sim_settings.noise_intensity = 1e-3
    elif isequal_string(sim_type, "paper"):
        sim_builder.set_model_name("Epileptor")
        sim_settings = sim_builder.build_sim_settings()
    else:
        sim_settings = sim_builder.build_sim_settings()

    # --------------------------Hypothesis and LSA-----------------------------------
    for hyp in hypotheses:
        logger.info("\n\nRunning hypothesis: " + hyp.name)
        logger.info("\n\nCreating model configuration...")
        builder = ModelConfigurationBuilder(hyp.number_of_regions)

        mcs_file = os.path.join(config.out.FOLDER_RES, hyp.name + "_model_config_service.h5")
        writer.write_model_configuration_builder(builder, mcs_file)
        if test_write_read:
            logger.info("Written and read model configuration services are identical?: " +
                        str(assert_equal_objects(builder, reader.read_model_configuration_builder(mcs_file),
                                                 logger=logger)))

        if hyp.type == "Epileptogenicity":
            model_configuration = builder.build_model_from_E_hypothesis(hyp, head.connectivity.normalized_weights)
        else:
            model_configuration = builder.build_model_from_hypothesis(hyp, head.connectivity.normalized_weights)
        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, "6d", head.connectivity.region_labels,
                                 special_idx=hyp_x0.x0_indices + hyp_E.e_indices, zmode="lin",
                                 figure_name=hyp.name + "_StateSpace")

        logger.info("\n\nRunning LSA...")
        lsa_service = LSAService(eigen_vectors_number=None, weighted_eigenvector_sum=True)
        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)

        if pse_flag:
            # --------------Parameter Search Exploration (PSE)-------------------------------
            logger.info("\n\nRunning PSE LSA...")
            pse_results = pse_from_lsa_hypothesis(lsa_hypothesis,
                                                  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}],
                                                  model_configuration_builder=builder,
                                                  lsa_service=lsa_service, 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 sensitivity analysis 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(lsa_hypothesis,
                                                             head.connectivity.normalized_weights,
                                                             head.connectivity.region_labels,
                                                             n_samples, method="sobol", param_range=0.1,
                                                             global_coupling=[{"indices": all_regions_indices,
                                                                               "bounds": [0.0, 2 *
                                                                                          builder.K_unscaled[
                                                                                              0]]}],
                                                             healthy_regions_parameters=[
                                                                 {"name": "x0_values", "indices": healthy_indices}],
                                                             model_configuration_builder=builder,
                                                             lsa_service=lsa_service, 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--------------------------------------
            logger.info("\n\nConfiguring simulation from model_configuration...")
            model = sim_builder.generate_model(model_configuration)
            if isequal_string(sim_type, "realistic"):
                model.tau0 = 30000.0
                model.tau1 = 0.2
                model.slope = 0.25
            elif isequal_string(sim_type, "fitting"):
                model.tau0 = 10.0
                model.tau1 = 0.5
            sim, sim_settings, model = sim_builder.build_simulator_TVB_from_model_sim_settings(model_configuration,
                                                                                 head.connectivity, model, sim_settings)

            # Integrator and initial conditions initialization.
            # By default initial condition is set right on the equilibrium point.
            writer.write_generic(sim.model, config.out.FOLDER_RES, lsa_hypothesis.name + "_sim_model.h5")
            logger.info("\n\nSimulating...")
            ttavg, tavg_data, status = sim.launch_simulation(report_every_n_monitor_steps=100)

            sim_path = os.path.join(config.out.FOLDER_RES, lsa_hypothesis.name + "_sim_settings.h5")
            writer.write_simulation_settings(sim.simulation_settings, sim_path)
            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.simulation_settings,
                                                     reader.read_simulation_settings(sim_path), logger=logger)))
            if not status:
                logger.warning("\nSimulation failed!")
            else:
                time = np.array(ttavg, dtype='float32')
                output_sampling_time = np.mean(np.diff(time))
                tavg_data = tavg_data[:, :, :, 0]
                logger.info("\n\nSimulated signal return shape: %s", tavg_data.shape)
                logger.info("Time: %s - %s", time[0], time[-1])
                logger.info("Values: %s - %s", tavg_data.min(), tavg_data.max())
                # Variables of interest in a dictionary:
                res_ts = prepare_vois_ts_dict(sim_settings.monitor_expressions, tavg_data)
                res_ts['time'] = time
                res_ts['time_units'] = 'msec'
                res_ts = compute_seeg_and_write_ts_h5_file(config.out.FOLDER_RES, lsa_hypothesis.name + "_ts.h5",
                                                                 sim.model, res_ts, output_sampling_time,
                                                                 sim_settings.simulated_period,
                                                                 hpf_flag=True, hpf_low=10.0, hpf_high=512.0,
                                                                 sensors_list=head.sensorsSEEG)
                # Plot results
                if model._ui_name is "EpileptorDP2D":
                    spectral_raster_plot = False
                    trajectories_plot = True
                else:
                    spectral_raster_plot = "lfp"
                    trajectories_plot = False
                #TODO: plotting fails when spectral_raster_plot="lfp". Denis will fix this
                plotter.plot_sim_results(sim.model, lsa_hypothesis.lsa_propagation_indices, res_ts,
                                         head.sensorsSEEG, hpf_flag=True, trajectories_plot=trajectories_plot,
                                         spectral_raster_plot=False, log_scale=True)
예제 #12
0
def main_cc_vep(config,
                head_folder,
                ep_name="clinical_hypothesis",
                x0_indices=[],
                pse_flag=False,
                sim_flag=True):
    if not (os.path.isdir(config.out.FOLDER_RES)):
        os.mkdir(config.out.FOLDER_RES)
    logger = initialize_logger(__name__, config.out.FOLDER_LOGS)

    # -------------------------------Reading data-----------------------------------
    reader = TVBReader() if config.input.IS_TVB_MODE else H5Reader()
    writer = H5Writer()
    logger.info("Reading from: %s", head_folder)
    head = reader.read_head(head_folder)
    plotter = Plotter(config)
    plotter.plot_head(head)

    # --------------------------Hypothesis definition-----------------------------------
    hypo_builder = HypothesisBuilder(head.connectivity.number_of_regions)
    all_regions_indices = np.array(range(head.number_of_regions))

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

    disease_indices = hyp_E.e_indices + hyp_x0.x0_indices
    healthy_indices = np.delete(all_regions_indices, disease_indices).tolist()

    if len(x0_indices) > 0:
        # This is an example of x0_values mixed Excitability and Epileptogenicity Hypothesis:
        disease_values = reader.read_epileptogenicity(head_folder,
                                                      name=ep_name)
        disease_values = disease_values.tolist()
        x0_values = []
        for ix0 in x0_indices:
            ind = disease_indices.index(ix0)
            del disease_indices[ind]
            x0_values.append(disease_values.pop(ind))
        e_indices = disease_indices
        e_values = np.array(disease_values)
        x0_values = np.array(x0_values)
        hyp_x0_E = hypo_builder.set_x0_hypothesis(
            x0_indices,
            x0_values).set_e_hypothesis(e_indices,
                                        e_values).build_hypothesis()
        hypotheses = (hyp_E, hyp_x0, hyp_x0_E)

    else:
        hypotheses = (
            hyp_E,
            hyp_x0,
        )

    # --------------------------Hypothesis and LSA-----------------------------------
    for hyp in hypotheses:
        logger.info("Running hypothesis: %s", hyp.name)
        logger.info("Creating model configuration...")
        builder = ModelConfigurationBuilder(hyp.number_of_regions)
        writer.write_model_configuration_builder(
            builder,
            os.path.join(config.out.FOLDER_RES, "model_config_service.h5"))
        if hyp.type == "Epileptogenicity":
            model_configuration = builder.build_model_from_E_hypothesis(
                hyp, head.connectivity.normalized_weights)
        else:
            model_configuration = builder.build_model_from_hypothesis(
                hyp, head.connectivity.normalized_weights)
        writer.write_model_configuration(
            model_configuration,
            os.path.join(config.out.FOLDER_RES, "ModelConfiguration.h5"))
        # Plot nullclines and equilibria of model configuration
        plotter.plot_state_space(model_configuration,
                                 region_labels=head.connectivity.region_labels,
                                 special_idx=disease_indices,
                                 model="2d",
                                 zmode="lin",
                                 figure_name=hyp.name + "_StateSpace")
        logger.info("Running LSA...")
        lsa_service = LSAService(eigen_vectors_number=None,
                                 weighted_eigenvector_sum=True)
        lsa_hypothesis = lsa_service.run_lsa(hyp, model_configuration)
        writer.write_hypothesis(
            lsa_hypothesis,
            os.path.join(config.out.FOLDER_RES, lsa_hypothesis.name + ".h5"))
        writer.write_lsa_service(
            lsa_service,
            os.path.join(config.out.FOLDER_RES, "lsa_config_service.h5"))
        plotter.plot_lsa(lsa_hypothesis, model_configuration,
                         lsa_service.weighted_eigenvector_sum,
                         lsa_service.eigen_vectors_number,
                         head.connectivity.region_labels, None)
        if pse_flag:
            n_samples = 100
            # --------------Parameter Search Exploration (PSE)-------------------------------
            logger.info("Running PSE LSA...")
            pse_results = pse_from_lsa_hypothesis(
                lsa_hypothesis,
                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
                }],
                model_configuration_builder=builder,
                lsa_service=lsa_service,
                save_flag=True,
                folder_res=config.out.FOLDER_RES,
                filename="PSE_LSA",
                logger=logger)[0]
            plotter.plot_lsa(lsa_hypothesis,
                             model_configuration,
                             lsa_service.weighted_eigenvector_sum,
                             lsa_service.eigen_vectors_number,
                             head.connectivity.region_labels,
                             pse_results,
                             title="Hypothesis PSE LSA Overview")
        if sim_flag:
            config.out.subfolder = "simulations"
            for folder in (config.out.FOLDER_RES, config.out.FOLDER_FIGURES):
                if not (os.path.isdir(folder)):
                    os.mkdir(folder)
            dynamical_models = ["EpileptorDP2D", "EpileptorDPrealistic"]

            for dynamical_model, sim_type in zip(dynamical_models,
                                                 ["fitting", "realistic"]):
                ts_file = None  # os.path.join(sim_folder_res, dynamical_model + "_ts.h5")
                vois_ts_dict = \
                    from_model_configuration_to_simulation(model_configuration, head, lsa_hypothesis,
                                                           sim_type=sim_type, dynamical_model=dynamical_model,
                                                           ts_file=ts_file, plot_flag=True, config=config)
예제 #13
0
def main_vep(test_write_read=False,
             pse_flag=PSE_FLAG,
             sa_pse_flag=SA_PSE_FLAG,
             sim_flag=SIM_FLAG):

    logger = initialize_logger(__name__)

    # -------------------------------Reading data-----------------------------------

    data_folder = os.path.join(DATA_CUSTOM, 'Head')

    reader = Reader()

    logger.info("Reading from: " + data_folder)
    head = reader.read_head(data_folder)

    head.plot()

    # --------------------------Hypothesis definition-----------------------------------

    n_samples = 100

    # # 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:
    ep_name = "ep_test1"
    #FOLDER_RES = os.path.join(data_folder, ep_name)
    from tvb_epilepsy.custom.readers_custom import CustomReader

    if not isinstance(reader, CustomReader):
        reader = CustomReader()
    disease_values = reader.read_epileptogenicity(data_folder, name=ep_name)
    disease_indices, = np.where(disease_values > np.min([X0_DEF, E_DEF]))
    disease_values = disease_values[disease_indices]
    if disease_values.size > 1:
        inds_split = np.ceil(disease_values.size * 1.0 / 2).astype("int")
        x0_indices = disease_indices[:inds_split].tolist()
        e_indices = disease_indices[inds_split:].tolist()
        x0_values = disease_values[:inds_split].tolist()
        e_values = disease_values[inds_split:].tolist()
    else:
        x0_indices = disease_indices.tolist()
        x0_values = disease_values.tolist()
        e_indices = []
        e_values = []
    disease_indices = list(disease_indices)

    n_x0 = len(x0_indices)
    n_e = len(e_indices)
    n_disease = len(disease_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 Excitability Hypothesis:
    hyp_x0 = DiseaseHypothesis(
        head.connectivity.number_of_regions,
        excitability_hypothesis={tuple(disease_indices): disease_values},
        epileptogenicity_hypothesis={},
        connectivity_hypothesis={})

    # This is an example of Epileptogenicity Hypothesis:
    hyp_E = DiseaseHypothesis(
        head.connectivity.number_of_regions,
        excitability_hypothesis={},
        epileptogenicity_hypothesis={tuple(disease_indices): disease_values},
        connectivity_hypothesis={})

    if len(e_indices) > 0:
        # This is an example of x0_values mixed Excitability and Epileptogenicity Hypothesis:
        hyp_x0_E = DiseaseHypothesis(
            head.connectivity.number_of_regions,
            excitability_hypothesis={tuple(x0_indices): x0_values},
            epileptogenicity_hypothesis={tuple(e_indices): e_values},
            connectivity_hypothesis={})
        hypotheses = (hyp_x0, hyp_E, hyp_x0_E)
    else:
        hypotheses = (hyp_x0, hyp_E)

    # --------------------------Simulation preparations-----------------------------------

    # TODO: maybe use a custom Monitor class
    fs = 2048.0  # this is the simulation sampling rate that is necessary for the simulation to be stable
    time_length = 10000.0  # =100 secs, the final output nominal time length of the simulation
    report_every_n_monitor_steps = 100.0
    (dt, fsAVG, sim_length, monitor_period, n_report_blocks) = \
        set_time_scales(fs=fs, time_length=time_length, scale_fsavg=None,
                        report_every_n_monitor_steps=report_every_n_monitor_steps)

    # 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,
    #      -multiplicative correlated noise is also used
    # Optional variations:
    zmode = "lin"  # by default, or "sig" for the sigmoidal expression for the slow z variable in Proix et al. 2014
    pmode = "z"  # by default, "g" or "z*g" for the feedback coupling to Iext2 and slope for EpileptorDPrealistic

    model_name = "EpileptorDPrealistic"
    if model_name is "EpileptorDP2D":
        spectral_raster_plot = False
        trajectories_plot = True
    else:
        spectral_raster_plot = "lfp"
        trajectories_plot = False
    # We don't want any time delays for the moment
    # head.connectivity.tract_lengths *= TIME_DELAYS_FLAG

    # --------------------------Hypothesis and LSA-----------------------------------

    for hyp in hypotheses:

        logger.info("\n\nRunning hypothesis: " + hyp.name)

        # hyp.write_to_h5(FOLDER_RES, hyp.name + ".h5")

        logger.info("\n\nCreating model configuration...")
        model_configuration_service = ModelConfigurationService(
            hyp.number_of_regions)
        model_configuration_service.write_to_h5(
            FOLDER_RES, hyp.name + "_model_config_service.h5")
        if test_write_read:
            logger.info(
                "Written and read model configuration services are identical?: "
                + str(
                    assert_equal_objects(
                        model_configuration_service,
                        read_h5_model(
                            os.path.join(FOLDER_RES, hyp.name +
                                         "_model_config_service.h5")
                        ).convert_from_h5_model(
                            obj=deepcopy(model_configuration_service)),
                        logger=logger)))

        if hyp.type == "Epileptogenicity":
            model_configuration = model_configuration_service.\
                                            configure_model_from_E_hypothesis(hyp, head.connectivity.normalized_weights)
        else:
            model_configuration = model_configuration_service.\
                                              configure_model_from_hypothesis(hyp, head.connectivity.normalized_weights)
        model_configuration.write_to_h5(FOLDER_RES,
                                        hyp.name + "_ModelConfig.h5")
        if test_write_read:
            logger.info(
                "Written and read model configuration are identical?: " + str(
                    assert_equal_objects(
                        model_configuration,
                        read_h5_model(
                            os.path.join(
                                FOLDER_RES, hyp.name +
                                "_ModelConfig.h5")).convert_from_h5_model(
                                    obj=deepcopy(model_configuration)),
                        logger=logger)))

        # Plot nullclines and equilibria of model configuration
        model_configuration_service.plot_nullclines_eq(
            model_configuration,
            head.connectivity.region_labels,
            special_idx=disease_indices,
            model="6d",
            zmode="lin",
            figure_name=hyp.name + "_Nullclines and equilibria")

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

        lsa_hypothesis.write_to_h5(FOLDER_RES, lsa_hypothesis.name + "_LSA.h5")
        lsa_service.write_to_h5(FOLDER_RES,
                                lsa_hypothesis.name + "_LSAConfig.h5")
        if test_write_read:

            hypothesis_template = DiseaseHypothesis(hyp.number_of_regions)

            logger.info("Written and read LSA services are identical?: " + str(
                assert_equal_objects(
                    lsa_service,
                    read_h5_model(
                        os.path.join(FOLDER_RES, lsa_hypothesis.name +
                                     "_LSAConfig.h5")).convert_from_h5_model(
                                         obj=deepcopy(lsa_service)),
                    logger=logger)))
            logger.info(
                "Written and read LSA hypotheses are identical (input object check)?: "
                + str(
                    assert_equal_objects(
                        lsa_hypothesis,
                        read_h5_model(
                            os.path.join(FOLDER_RES, lsa_hypothesis.name +
                                         "_LSA.h5")).convert_from_h5_model(
                                             obj=deepcopy(lsa_hypothesis),
                                             hypothesis=True),
                        logger=logger)))
            logger.info(
                "Written and read LSA hypotheses are identical (input template check)?: "
                + str(
                    assert_equal_objects(
                        lsa_hypothesis,
                        read_h5_model(
                            os.path.join(FOLDER_RES, lsa_hypothesis.name +
                                         "_LSA.h5")).convert_from_h5_model(
                                             obj=hypothesis_template,
                                             hypothesis=True),
                        logger=logger)))

        lsa_service.plot_lsa(lsa_hypothesis, model_configuration,
                             head.connectivity.region_labels, None)

        if pse_flag:
            #--------------Parameter Search Exploration (PSE)-------------------------------

            logger.info("\n\nRunning PSE LSA...")
            pse_results = pse_from_lsa_hypothesis(
                lsa_hypothesis,
                head.connectivity.normalized_weights,
                head.connectivity.region_labels,
                n_samples,
                half_range=0.1,
                global_coupling=[{
                    "indices": all_regions_indices
                }],
                healthy_regions_parameters=[{
                    "name": "x0_values",
                    "indices": healthy_indices
                }],
                model_configuration_service=model_configuration_service,
                lsa_service=lsa_service,
                logger=logger)[0]

            lsa_service.plot_lsa(lsa_hypothesis, model_configuration,
                                 head.connectivity.region_labels, pse_results)
            # , show_flag=True, save_flag=False

            convert_to_h5_model(pse_results).write_to_h5(
                FOLDER_RES, lsa_hypothesis.name + "_PSE_LSA_results.h5")
            if test_write_read:
                logger.info(
                    "Written and read sensitivity analysis parameter search results are identical?: "
                    + str(
                        assert_equal_objects(
                            pse_results,
                            read_h5_model(
                                os.path.join(
                                    FOLDER_RES, lsa_hypothesis.name +
                                    "_PSE_LSA_results.h5")
                            ).convert_from_h5_model(),
                            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(lsa_hypothesis,
                                                         head.connectivity.normalized_weights,
                                                         head.connectivity.region_labels,
                                                         n_samples, method="sobol", half_range=0.1,
                                         global_coupling=[{"indices": all_regions_indices,
                                                     "bounds":[0.0, 2 * model_configuration_service.K_unscaled[ 0]]}],
                                         healthy_regions_parameters=[{"name": "x0_values", "indices": healthy_indices}],
                                         model_configuration_service=model_configuration_service,
                                         lsa_service=lsa_service, logger=logger)

            lsa_service.plot_lsa(lsa_hypothesis,
                                 model_configuration,
                                 head.connectivity.region_labels,
                                 pse_sa_results,
                                 title="SA PSE Hypothesis Overview")
            # , show_flag=True, save_flag=False

            convert_to_h5_model(pse_sa_results).write_to_h5(
                FOLDER_RES, lsa_hypothesis.name + "_SA_PSE_LSA_results.h5")
            convert_to_h5_model(sa_results).write_to_h5(
                FOLDER_RES, lsa_hypothesis.name + "_SA_LSA_results.h5")
            if test_write_read:
                logger.info(
                    "Written and read sensitivity analysis results are identical?: "
                    + str(
                        assert_equal_objects(
                            sa_results,
                            read_h5_model(
                                os.path.join(
                                    FOLDER_RES, lsa_hypothesis.name +
                                    "_SA_LSA_results.h5")
                            ).convert_from_h5_model(),
                            logger=logger)))
                logger.info(
                    "Written and read sensitivity analysis parameter search results are identical?: "
                    + str(
                        assert_equal_objects(
                            pse_sa_results,
                            read_h5_model(
                                os.path.join(
                                    FOLDER_RES, lsa_hypothesis.name +
                                    "_SA_PSE_LSA_results.h5")
                            ).convert_from_h5_model(),
                            logger=logger)))

        if sim_flag:
            # ------------------------------Simulation--------------------------------------
            logger.info("\n\nConfiguring simulation...")
            sim = setup_simulation_from_model_configuration(
                model_configuration,
                head.connectivity,
                dt,
                sim_length,
                monitor_period,
                model_name,
                zmode=np.array(zmode),
                pmode=np.array(pmode),
                noise_instance=None,
                noise_intensity=None,
                monitor_expressions=None)

            # Integrator and initial conditions initialization.
            # By default initial condition is set right on the equilibrium point.
            sim.config_simulation(initial_conditions=None)

            convert_to_h5_model(sim.model).write_to_h5(
                FOLDER_RES, lsa_hypothesis.name + "_sim_model.h5")

            logger.info("\n\nSimulating...")
            ttavg, tavg_data, status = sim.launch_simulation(n_report_blocks)

            convert_to_h5_model(sim.simulation_settings).write_to_h5(
                FOLDER_RES, lsa_hypothesis.name + "_sim_settings.h5")

            if test_write_read:
                logger.info(
                    "Written and read simulation settings are identical?: " +
                    str(
                        assert_equal_objects(
                            sim.simulation_settings,
                            read_h5_model(
                                os.path.join(
                                    FOLDER_RES, lsa_hypothesis.name +
                                    "_sim_settings.h5")).convert_from_h5_model(
                                        obj=deepcopy(sim.simulation_settings)),
                            logger=logger)))

            if not status:
                warning("\nSimulation failed!")

            else:

                time = np.array(ttavg, dtype='float32')

                output_sampling_time = np.mean(np.diff(time))
                tavg_data = tavg_data[:, :, :, 0]

                logger.info("\n\nSimulated signal return shape: %s",
                            tavg_data.shape)
                logger.info("Time: %s - %s", time[0], time[-1])
                logger.info("Values: %s - %s", tavg_data.min(),
                            tavg_data.max())

                # Variables of interest in a dictionary:
                vois_ts_dict = prepare_vois_ts_dict(VOIS[model_name],
                                                    tavg_data)
                vois_ts_dict['time'] = time
                vois_ts_dict['time_units'] = 'msec'

                vois_ts_dict = compute_seeg_and_write_ts_h5_file(
                    FOLDER_RES,
                    lsa_hypothesis.name + "_ts.h5",
                    sim.model,
                    vois_ts_dict,
                    output_sampling_time,
                    time_length,
                    hpf_flag=True,
                    hpf_low=10.0,
                    hpf_high=512.0,
                    sensor_dicts_list=[head.sensorsSEEG])

                # Plot results
                plot_sim_results(sim.model,
                                 lsa_hypothesis.propagation_indices,
                                 lsa_hypothesis.name,
                                 head,
                                 vois_ts_dict,
                                 head.sensorsSEEG.keys(),
                                 hpf_flag=True,
                                 trajectories_plot=trajectories_plot,
                                 spectral_raster_plot=spectral_raster_plot,
                                 log_scale=True)
예제 #14
0
def set_model_config_LSA(head,
                         hyp,
                         reader,
                         config,
                         K_unscaled=K_DEF,
                         tau1=TAU1_DEF,
                         tau0=TAU0_DEF,
                         pse_flag=True,
                         plotter=None,
                         writer=None):
    model_configuration_builder = None
    lsa_service = None
    # --------------------------Model configuration and LSA-----------------------------------
    model_config_file = os.path.join(config.out.FOLDER_RES,
                                     hyp.name + "_ModelConfig.h5")
    hyp_file = os.path.join(config.out.FOLDER_RES, hyp.name + "_LSA.h5")
    if os.path.isfile(hyp_file) and os.path.isfile(model_config_file):
        # Read existing model configuration and LSA hypotheses...
        model_configuration = reader.read_model_configuration(
            model_config_file)
        lsa_hypothesis = reader.read_hypothesis(hyp_file)
    else:
        # ...or generate new ones
        model_configuration, lsa_hypothesis, model_configuration_builder, lsa_service = \
            from_hypothesis_to_model_config_lsa(hyp, head, eigen_vectors_number=None, weighted_eigenvector_sum=True,
                                                config=config, K=K_unscaled, tau1=tau1, tau0=tau0,
                                                save_flag=True, plot_flag=True)
        # --------------Parameter Search Exploration (PSE)-------------------------------
    if pse_flag:
        psa_lsa_file = os.path.join(config.out.FOLDER_RES,
                                    hyp.name + "_PSE_LSA_results.h5")
        try:
            pse_results = reader.read_dictionary(psa_lsa_file)
        except:
            logger.info("\n\nRunning PSE LSA...")
            n_samples = 100
            all_regions_indices = np.array(range(head.number_of_regions))
            disease_indices = lsa_hypothesis.regions_disease_indices
            healthy_indices = np.delete(all_regions_indices,
                                        disease_indices).tolist()
            if model_configuration_builder is None:
                model_configuration_builder = ModelConfigurationBuilder(
                    hyp.number_of_regions, K=K_unscaled)
            if lsa_service is None:
                lsa_service = LSAService(eigen_vectors_number=None,
                                         weighted_eigenvector_sum=True)
            pse_results = \
                pse_from_lsa_hypothesis(n_samples, lsa_hypothesis, head.connectivity.normalized_weights,
                                        model_configuration_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=False)[0]
            if plotter:
                plotter.plot_lsa(lsa_hypothesis, model_configuration,
                                 lsa_service.weighted_eigenvector_sum,
                                 lsa_service.eigen_vectors_number,
                                 head.connectivity.region_labels, pse_results)
            if writer:
                writer.write_dictionary(pse_results, psa_lsa_file)
    else:
        pse_results = {}
    return model_configuration, lsa_hypothesis, pse_results