Exemple #1
0
 def test_projection_surface_meg(self):
     dt = projections.ProjectionSurfaceMEG(sensors=SensorsMEG(),projection_data=numpy.array([]), sources=CorticalSurface())
     assert dt.sources is not None
     assert dt.skin_air is None
     assert dt.skull_skin is None
     assert dt.sensors is not None
     assert dt.projection_data is not None
    def __init__(self):
        """
        Initialise the structural information, coupling function, and monitors.

        """

        # Initialise some Monitors with period in physical time
        raw = monitors.Raw()
        gavg = monitors.GlobalAverage(period=2 ** -2)
        subsamp = monitors.SubSample(period=2 ** -2)
        tavg = monitors.TemporalAverage(period=2 ** -2)
        # DON'T load a projection because it'll make this behave like it
        # has a surface and do very, very bad things
        eeg = monitors.EEG(sensors=SensorsEEG(load_file="eeg_brainstorm_65.txt"),
                           period=2 ** -2)
        eeg2 = monitors.EEG(sensors=SensorsEEG(load_file="eeg_brainstorm_65.txt"),
                            period=2 ** -2,
                            reference='Fp2')  # EEG with a reference electrode
        meg = monitors.MEG(sensors=SensorsMEG(load_file='meg_brainstorm_276.txt'),
                           period=2 ** -2)

        self.monitors = (raw, gavg, subsamp, tavg, eeg, eeg2, meg)

        self.method = None
        self.sim = None
Exemple #3
0
 def from_tvb_file(self, filepath, remove_leading_zeros_from_labels=False):
     self._tvb = TVBSensorsMEG.from_file(filepath, self._tvb)
     if len(self._tvb.labels) > 0:
         if remove_leading_zeros_from_labels:
             self.remove_leading_zeros_from_labels()
     self.file_path = filepath
     return self
    def launch(self, sensors_file, sensors_type):
        """
        Creates required sensors from the uploaded file.

        :param sensors_file: the file containing sensor data
        :param sensors_type: a string from "EEG Sensors", "MEG sensors", "Internal Sensors"

        :returns: a list of sensors instances of the specified type

        :raises LaunchException: when
                    * no sensors_file specified
                    * sensors_type is invalid (not one of the mentioned options)
                    * sensors_type is "MEG sensors" and no orientation is specified
        """
        if sensors_file is None:
            raise LaunchException(
                "Please select sensors file which contains data to import")

        self.logger.debug("Create sensors instance")
        if sensors_type == SensorsEEG.sensors_type.default:
            sensors_inst = SensorsEEG()
        elif sensors_type == SensorsMEG.sensors_type.default:
            sensors_inst = SensorsMEG()
        elif sensors_type == SensorsInternal.sensors_type.default:
            sensors_inst = SensorsInternal()
        else:
            exception_str = "Could not determine sensors type (selected option %s)" % sensors_type
            raise LaunchException(exception_str)

        locations = self.read_list_data(sensors_file, usecols=[1, 2, 3])

        # NOTE: TVB has the nose pointing -y and left ear pointing +x
        # If the sensors are in CTF coordinates : nose pointing +x left ear +y
        # to rotate the sensors by -90 along z uncomment below
        # locations = numpy.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]]).dot(locations.T).T
        sensors_inst.locations = locations
        sensors_inst.labels = self.read_list_data(sensors_file,
                                                  dtype=MEMORY_STRING,
                                                  usecols=[0])
        sensors_inst.number_of_sensors = sensors_inst.labels.size

        if isinstance(sensors_inst, SensorsMEG):
            try:
                sensors_inst.orientations = self.read_list_data(
                    sensors_file, usecols=[4, 5, 6])
                sensors_inst.has_orientation = True
            except IndexError:
                raise LaunchException(
                    "Uploaded file does not contains sensors orientation.")

        sensors_inst.configure()
        self.logger.debug("Sensors instance ready to be stored")

        sensors_idx = h5.store_complete(sensors_inst, self.storage_path)
        self.generic_attributes.user_tag_1 = sensors_inst.sensors_type
        return sensors_idx
Exemple #5
0
 def test_timeseriesmeg(self):
     data = numpy.random.random((10, 10))
     dt = time_series.TimeSeriesMEG(data=data, sensors=SensorsMEG(orientations=numpy.array([])))
     assert dt.data.shape == (10, 10)
     assert ('Time', '1', 'MEG Sensor', '1') == dt.labels_ordering
     assert dt.sample_period == 1.0
     assert dt.sample_rate == 1.0
     assert dt.sensors is not None
     assert dt.start_time == 0.0
     assert dt.time is None
 def test_import_meg_without_orientation(self):
     """
     This method tests import of a file without orientation.
     """
     try:
         self._import(self.EEG_FILE, self.importer.MEG_SENSORS, SensorsMEG())
         self.fail("Import should fail in case of a MEG import without orientation.")
     except OperationException:
         # Expected exception
         pass
    def launch(self, sensors_file, sensors_type):
        """
        Creates required sensors from the uploaded file.

        :param sensors_file: the file containing sensor data
        :param sensors_type: a string from "EEG Sensors", "MEG sensors", "Internal Sensors"

        :returns: a list of sensors instances of the specified type

        :raises LaunchException: when
                    * no sensors_file specified
                    * sensors_type is invalid (not one of the mentioned options)
                    * sensors_type is "MEG sensors" and no orientation is specified
        """
        if sensors_file is None:
            raise LaunchException(
                "Please select sensors file which contains data to import")

        self.logger.debug("Create sensors instance")
        if sensors_type == self.EEG_SENSORS:
            sensors_inst = SensorsEEG()
        elif sensors_type == self.MEG_SENSORS:
            sensors_inst = SensorsMEG()
        elif sensors_type == self.INTERNAL_SENSORS:
            sensors_inst = SensorsInternal()
        else:
            exception_str = "Could not determine sensors type (selected option %s)" % sensors_type
            raise LaunchException(exception_str)

        sensors_inst.storage_path = self.storage_path
        locations = self.read_list_data(sensors_file, usecols=[1, 2, 3])

        # NOTE: TVB has the nose pointing -y and left ear pointing +x
        # If the sensors are in CTF coordinates : nose pointing +x left ear +y
        # to rotate the sensors by -90 along z uncomment below
        # locations = numpy.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]]).dot(locations.T).T
        sensors_inst.locations = locations
        sensors_inst.labels = self.read_list_data(sensors_file,
                                                  dtype=numpy.str,
                                                  usecols=[0])

        if isinstance(sensors_inst, SensorsMEG):
            try:
                sensors_inst.orientations = self.read_list_data(
                    sensors_file, usecols=[4, 5, 6])
            except IndexError:
                raise LaunchException(
                    "Uploaded file does not contains sensors orientation.")

        self.logger.debug("Sensors instance ready to be stored")

        return [sensors_inst]
    def deserialize_simulator(simulator_gid, storage_path):
        simulator_in_path = h5.path_for(storage_path, SimulatorH5,
                                        simulator_gid)
        simulator_in = SimulatorAdapterModel()

        with SimulatorH5(simulator_in_path) as simulator_in_h5:
            simulator_in_h5.load_into(simulator_in)
            simulator_in.connectivity = simulator_in_h5.connectivity.load()
            simulator_in.stimulus = simulator_in_h5.stimulus.load()
            simulator_in.history_gid = simulator_in_h5.simulation_state.load()

        if isinstance(simulator_in.monitors[0], Projection):
            # TODO: simplify this part
            with SimulatorH5(simulator_in_path) as simulator_in_h5:
                monitor_h5_path = simulator_in_h5.get_reference_path(
                    simulator_in.monitors[0].gid)

            monitor_h5_class = h5_factory.monitor_h5_factory(
                type(simulator_in.monitors[0]))

            with monitor_h5_class(monitor_h5_path) as monitor_h5:
                sensors_gid = monitor_h5.sensors.load()
                region_mapping_gid = monitor_h5.region_mapping.load()

            sensors = ABCAdapter.load_traited_by_gid(sensors_gid)

            if isinstance(simulator_in.monitors[0], EEG):
                sensors = SensorsEEG.build_sensors_subclass(sensors)
            elif isinstance(simulator_in.monitors[0], MEG):
                sensors = SensorsMEG.build_sensors_subclass(sensors)
            elif isinstance(simulator_in.monitors[0], iEEG):
                sensors = SensorsInternal.build_sensors_subclass(sensors)

            simulator_in.monitors[0].sensors = sensors
            region_mapping = ABCAdapter.load_traited_by_gid(region_mapping_gid)
            simulator_in.monitors[0].region_mapping = region_mapping

        if simulator_in.surface:
            cortex_path = h5.path_for(storage_path, CortexH5,
                                      simulator_in.surface.gid)
            with CortexH5(cortex_path) as cortex_h5:
                simulator_in.surface.local_connectivity = cortex_h5.local_connectivity.load(
                )
                simulator_in.surface.region_mapping_data = cortex_h5.region_mapping_data.load(
                )
                rm_index = dao.get_datatype_by_gid(
                    simulator_in.surface.region_mapping_data.hex)
                simulator_in.surface.surface_gid = uuid.UUID(
                    rm_index.surface_gid)

        return simulator_in
Exemple #9
0
    def launch(self, sensors_file, sensors_type):
        """
        Creates required sensors from the uploaded file.

        :param sensors_file: the file containing sensor data
        :param sensors_type: a string from "EEG Sensors", "MEG sensors", "Internal Sensors"

        :returns: a list of sensors instances of the specified type

        :raises LaunchException: when
                    * no sensors_file specified
                    * sensors_type is invalid (not one of the mentioned options)
                    * sensors_type is "MEG sensors" and no orientation is specified
        """
        if sensors_file is None:
            raise LaunchException(
                "Please select sensors file which contains data to import")
        sensors_inst = None

        self.logger.debug("Create sensors instance")
        if sensors_type == self.EEG_SENSORS:
            sensors_inst = SensorsEEG()
        elif sensors_type == self.MEG_SENSORS:
            sensors_inst = SensorsMEG()
        elif sensors_type == self.INTERNAL_SENSORS:
            sensors_inst = SensorsInternal()
        else:
            exception_str = "Could not determine sensors type (selected option %s)" % sensors_type
            raise LaunchException(exception_str)

        sensors_inst.storage_path = self.storage_path

        sensors_inst.locations = read_list_data(sensors_file,
                                                usecols=[1, 2, 3])
        sensors_inst.labels = read_list_data(sensors_file,
                                             dtype=numpy.str,
                                             usecols=[0])

        if isinstance(sensors_inst, SensorsMEG):
            try:
                sensors_inst.orientations = read_list_data(sensors_file,
                                                           usecols=[4, 5, 6])
            except IndexError:
                raise LaunchException(
                    "Uploaded file does not contains sensors orientation.")

        self.logger.debug("Sensors instance ready to be stored")

        return [sensors_inst]
    def test_import_meg_sensors(self):
        """
        This method tests import of a file containing MEG sensors.
        """
        meg_sensors = self._import(self.MEG_FILE, self.importer.MEG_SENSORS, SensorsMEG())

        expected_size = 151
        self.assertTrue(meg_sensors.labels is not None)
        self.assertEqual(expected_size, len(meg_sensors.labels))
        self.assertEqual(expected_size, len(meg_sensors.locations))
        self.assertEqual((expected_size, 3), meg_sensors.locations.shape)
        self.assertEqual(expected_size, meg_sensors.number_of_sensors)
        self.assertTrue(meg_sensors.has_orientation)
        self.assertEqual(expected_size, len(meg_sensors.orientations))
        self.assertEqual((expected_size, 3), meg_sensors.orientations.shape)
Exemple #11
0
    def test_import_meg_sensors(self):
        """
        This method tests import of a file containing MEG sensors.
        """
        meg_sensors = self._import(self.MEG_FILE, self.importer.MEG_SENSORS,
                                   SensorsMEG())

        expected_size = 151
        assert meg_sensors.labels is not None
        assert expected_size == len(meg_sensors.labels)
        assert expected_size == len(meg_sensors.locations)
        assert (expected_size, 3) == meg_sensors.locations.shape
        assert expected_size == meg_sensors.number_of_sensors
        assert meg_sensors.has_orientation
        assert expected_size == len(meg_sensors.orientations)
        assert (expected_size, 3) == meg_sensors.orientations.shape
    def test_launch_MEG(self):
        """
        Check that all required keys are present in output from MEGSensorViewer launch.
        """

        zip_path = os.path.join(os.path.dirname(tvb_data.sensors.__file__),
                                'meg_channels_reg13.txt.bz2')
        TestFactory.import_sensors(self.test_user, self.test_project, zip_path,
                                   Sensors_Importer.MEG_SENSORS)
        sensors = TestFactory.get_entity(self.test_project, SensorsMEG())

        viewer = SensorsViewer()
        viewer.current_project_id = self.test_project.id

        result = viewer.launch(sensors)
        self.assert_compliant_dictionary(self.EXPECTED_KEYS_MEG, result)
Exemple #13
0
    def launch(self, sensors_file, sensors_type):
        """
        Created required sensors from the uploaded file.
        """
        if sensors_file is None:
            raise LaunchException(
                "Please select sensors file which contains data to import")
        sensors_inst = None

        self.logger.debug("Create sensors instance")
        if sensors_type == self.EEG_SENSORS:
            sensors_inst = SensorsEEG()
        elif sensors_type == self.MEG_SENSORS:
            sensors_inst = SensorsMEG()
        elif sensors_type == self.INTERNAL_SENSORS:
            sensors_inst = SensorsInternal()
        else:
            exception_str = "Could not determine sensors type (selected option %s)" % sensors_type
            raise LaunchException(exception_str)

        sensors_inst.storage_path = self.storage_path

        sensors_inst.locations = read_list_data(sensors_file,
                                                usecols=[1, 2, 3])
        sensors_inst.labels = read_list_data(sensors_file,
                                             dtype=numpy.str,
                                             usecols=[0])

        if isinstance(sensors_inst, SensorsMEG):
            try:
                sensors_inst.orientations = read_list_data(sensors_file,
                                                           usecols=[4, 5, 6])
            except IndexError:
                raise LaunchException(
                    "Uploaded file does not contains sensors orientation.")

        self.logger.debug("Sensors instance ready to be stored")

        return [sensors_inst]
 def setup_method(self):
     oscillator = models.Generic2dOscillator()
     white_matter = connectivity.Connectivity(load_file='connectivity_' +
                                              str(self.n_regions) + '.zip')
     white_matter.speed = numpy.array([self.speed])
     white_matter_coupling = coupling.Difference(a=self.coupling_a)
     heunint = integrators.HeunStochastic(
         dt=2**-4, noise=noise.Additive(nsig=numpy.array([
             2**-10,
         ])))
     mons = (
         monitors.EEG(projection=ProjectionMatrix(
             load_file='projection_eeg_65_surface_16k.npy'),
                      sensors=SensorsEEG(load_file="eeg_brainstorm_65.txt"),
                      period=self.period),
         monitors.MEG(
             projection=ProjectionMatrix(
                 load_file='projection_meg_276_surface_16k.npy'),
             sensors=SensorsMEG(load_file='meg_brainstorm_276.txt'),
             period=self.period),
         monitors.iEEG(projection=ProjectionMatrix(
             load_file='projection_seeg_588_surface_16k.npy'),
                       sensors=SensorsInternal(load_file='seeg_588.txt'),
                       period=self.period),
     )
     local_coupling_strength = numpy.array([2**-10])
     region_mapping = RegionMapping(load_file='regionMapping_16k_' +
                                    str(self.n_regions) + '.txt')
     default_cortex = Cortex(
         region_mapping_data=region_mapping, load_file="cortex_16384.zip"
     )  #region_mapping_file="regionMapping_16k_192.txt")
     default_cortex.coupling_strength = local_coupling_strength
     self.sim = simulator.Simulator(model=oscillator,
                                    connectivity=white_matter,
                                    coupling=white_matter_coupling,
                                    integrator=heunint,
                                    monitors=mons,
                                    surface=default_cortex)
     self.sim.configure()