Esempio n. 1
0
    def read_head(self, root_folder, name=''):
        conn = self.read_connectivity(
            os.path.join(root_folder, "Connectivity.h5"))
        srf = self.read_cortical_surface(
            os.path.join(root_folder, "CorticalSurface.h5"))
        rm = self.read_region_mapping(
            os.path.join(root_folder, "RegionMapping.h5"))
        vm = self.read_volume_mapping(
            os.path.join(root_folder, "VolumeMapping.h5"))
        t1 = self.read_volume_mapping(
            os.path.join(root_folder, "StructuralMRI.h5"))

        s_114 = self.read_sensors(
            os.path.join(root_folder, "SensorsSEEG_114.h5"), Sensors.TYPE_SEEG)
        s_125 = self.read_sensors(
            os.path.join(root_folder, "SensorsSEEG_125.h5"), Sensors.TYPE_SEEG)
        seeg_sensors_dict = {
            s_114: calculate_projection(s_114, conn),
            s_125: calculate_projection(s_125, conn)
        }
        eeg_sensors_dict = {}
        meg_sensors_dict = {}

        return Head(conn, srf, rm, vm, t1, name, eeg_sensors_dict,
                    meg_sensors_dict, seeg_sensors_dict)
Esempio n. 2
0
    #Adjust pathological connectivity
    w_hyp = np.ones((nRegions, nRegions), dtype='float')
    if Khyp > 1.0:
        w_hyp[(nRegions - 2):, :] = Khyp
        w_hyp[:, (nRegions - 2):] = Khyp
    TRECHHcon.normalized_weights = w_hyp * TRECHHcon.normalized_weights

    #Update head with the correct connectivity and sensors' projections
    head.connectivity = TRECHHcon
    sensorsSEEG = []
    projections = []
    for sensors, projection in head.sensorsSEEG.iteritems():
        if projection is None:
            continue
        else:
            projection = calculate_projection(sensors, head.connectivity)
            head.sensorsSEEG[sensors] = projection
            print projection.shape
            sensorsSEEG.append(sensors)
            projections.append(projection)
    plot_head(head,
              save_flag=SAVE_FLAG,
              show_flag=SHOW_FLAG,
              figure_dir=FOLDER_FIGURES,
              figsize=VERY_LARGE_SIZE)

    #--------------------------Hypotheis and LSA-----------------------------------

    # Next configure two seizure hypothesis

    #%Tim:
Esempio n. 3
0
def main_vep(test_write_read=False):

    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)

    # --------------------------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,
        excitability_hypothesis={tuple(disease_indices): disease_values},
        epileptogenicity_hypothesis={},
        connectivity_hypothesis={})

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

    if len(e_indices) > 0:
        # This is an example of x0 mixed Excitability and Epileptogenicity Hypothesis:
        hyp_x0_E = DiseaseHypothesis(
            head.connectivity,
            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)

    # --------------------------Projections computations-----------------------------------

    sensorsSEEG = []
    projections = []
    for sensors, projection in head.sensorsSEEG.iteritems():
        if projection is None:
            continue
        else:
            projection = calculate_projection(sensors, head.connectivity)
            head.sensorsSEEG[sensors] = projection
            sensorsSEEG.append(sensors)
            projections.append(projection)

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

    # TODO: maybe use a custom Monitor class
    fs = 2 * 4096.0
    scale_time = 2.0
    time_length = 10000.0
    scale_fsavg = 2.0
    report_every_n_monitor_steps = 10.0
    (dt, fsAVG, sim_length, monitor_period, n_report_blocks) = \
        set_time_scales(fs=fs, dt=None, time_length=time_length, scale_time=scale_time, scale_fsavg=scale_fsavg,
                        report_every_n_monitor_steps=report_every_n_monitor_steps)

    model_name = "EpileptorDP"

    # We don't want any time delays for the moment
    head.connectivity.tract_lengths *= 0.0

    hpf_flag = False
    hpf_low = max(16.0, 1000.0 / time_length)  # msec
    hpf_high = min(250.0, fsAVG)

    # --------------------------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.get_number_of_regions())
        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)
        else:
            model_configuration = model_configuration_service.configure_model_from_hypothesis(
                hyp)
        model_configuration.write_to_h5(FOLDER_RES,
                                        hyp.name + "_ModelConfig.h5")

        # # Plot nullclines and equilibria of model configuration
        # model_configuration.plot_nullclines_eq(head.connectivity.region_labels,
        #                                        special_idx=lsa_hypothesis.propagation_indices,
        #                                        model=str(model.nvar) + "d", zmode=model.zmode,
        #                                        figure_name=lsa_hypothesis.name + "_Nullclines and equilibria",
        #                                        save_flag=SAVE_FLAG, show_flag=SHOW_FLAG,
        #                                        figure_dir=FOLDER_FIGURES)

        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_hypothesis.plot_lsa(
            model_configuration,
            weighted_eigenvector_sum=lsa_service.weighted_eigenvector_sum,
            n_eig=lsa_service.eigen_vectors_number,
            figure_name=lsa_hypothesis.name + "_LSA.h5")

        #--------------Parameter Search Exploration (PSE)-------------------------------

        logger.info("\n\nRunning PSE LSA...")
        pse_results = pse_from_hypothesis(
            lsa_hypothesis,
            n_samples,
            half_range=0.1,
            global_coupling=[{
                "indices": all_regions_indices
            }],
            healthy_regions_parameters=[{
                "name": "x0",
                "indices": healthy_indices
            }],
            model_configuration=model_configuration,
            model_configuration_service=model_configuration_service,
            lsa_service=lsa_service)[0]

        lsa_hypothesis.plot_lsa_pse(
            pse_results,
            model_configuration,
            weighted_eigenvector_sum=lsa_service.weighted_eigenvector_sum,
            n_eig=lsa_service.eigen_vectors_number)
        # , show_flag=True, save_flag=False

        convert_to_h5_model(pse_results).write_to_h5(
            FOLDER_RES, lsa_hypothesis.name + "_PSE_LSA_results.h5")

        # --------------Sensitivity Analysis Parameter Search Exploration (PSE)-------------------------------

        logger.info("\n\nrunning sensitivity analysis PSE LSA...")
        sa_results, pse_sa_results = \
            sensitivity_analysis_pse_from_hypothesis(lsa_hypothesis, 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", "indices": healthy_indices}],
                                     model_configuration=model_configuration,
                                     model_configuration_service=model_configuration_service, lsa_service=lsa_service)

        lsa_hypothesis.plot_lsa_pse(
            pse_sa_results,
            model_configuration,
            weighted_eigenvector_sum=lsa_service.weighted_eigenvector_sum,
            n_eig=lsa_service.eigen_vectors_number,
            figure_name="SA PSE LSA overview " + lsa_hypothesis.name)
        # , 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")

        # ------------------------------Simulation--------------------------------------
        logger.info("\n\nSimulating...")
        sim = setup_simulation_from_model_configuration(model_configuration,
                                                        head.connectivity,
                                                        dt,
                                                        sim_length,
                                                        monitor_period,
                                                        model_name,
                                                        scale_time=scale_time,
                                                        noise_intensity=10**-8)

        sim.config_simulation()
        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:
            warnings.warn("\nSimulation failed!")

        else:

            tavg_data = tavg_data[:, :, :, 0]

            vois = VOIS[model_name]

            model = sim.model

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

            time = scale_time * np.array(ttavg, dtype='float32')
            sampling_time = np.min(np.diff(time))

            vois_ts_dict = prepare_vois_ts_dict(vois, tavg_data)

            prepare_ts_and_seeg_h5_file(FOLDER_RES,
                                        lsa_hypothesis.name + "_ts.h5", model,
                                        projections, vois_ts_dict, hpf_flag,
                                        hpf_low, hpf_high, fsAVG,
                                        sampling_time)

            vois_ts_dict['time'] = time

            # Plot results
            plot_sim_results(model, lsa_hypothesis.propagation_indices,
                             lsa_hypothesis.name, head, vois_ts_dict,
                             sensorsSEEG, hpf_flag)

            # Save results
            vois_ts_dict['time_units'] = 'msec'
            # savemat(os.path.join(FOLDER_RES, hypothesis.name + "_ts.mat"), vois_ts_dict)

        if test_write_read:

            hypothesis_template = DiseaseHypothesis(
                Connectivity("", np.array([]), np.array([])))

            logger.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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))))
            logger.info(
                "Written and read model configuration services are identical?: "
                + assert_equal_objects(
                    lsa_hypothesis,
                    read_h5_model(
                        os.path.join(FOLDER_RES, lsa_hypothesis.name +
                                     "_LSA.h5")).convert_from_h5_model(
                                         children_dict=hypothesis_template)))
            logger.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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.info(
                "Written and read model configuration services are identical?: "
                + 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))))