Ejemplo n.º 1
0
    def create_local_connectivity(user, project, surface_gid):

        op = TestFactory.create_operation(test_user=user, test_project=project)

        wrapper_surf = CorticalSurface()
        wrapper_surf.gid = uuid.UUID(surface_gid)
        lc_ht = LocalConnectivity.from_file()
        lc_ht.surface = wrapper_surf
        lc_idx = h5.store_complete(lc_ht, op.id, project.name)
        lc_idx.fk_surface_gid = surface_gid
        lc_idx.fk_from_operation = op.id
        dao.store_entity(lc_idx)

        return TestFactory._assert_one_more_datatype(project,
                                                     LocalConnectivityIndex)
Ejemplo n.º 2
0
    def setUp(self):
        self.datatypeFactory = DatatypesFactory()
        self.test_project = self.datatypeFactory.get_project()
        self.test_user = self.datatypeFactory.get_user()

        TestFactory.import_cff(test_user=self.test_user,
                               test_project=self.test_project)
        zip_path = os.path.join(os.path.dirname(surface_dataset.__file__),
                                'face-surface.zip')
        TestFactory.import_surface_zip(self.test_user, self.test_project,
                                       zip_path, 'Face', 1)
        zip_path = os.path.join(os.path.dirname(surface_dataset.__file__),
                                'eeg_skin_surface.zip')
        TestFactory.import_surface_zip(self.test_user, self.test_project,
                                       zip_path, 'EEG Cap', 1)
        self.connectivity = TestFactory.get_entity(self.test_project,
                                                   Connectivity())
        self.assertTrue(self.connectivity is not None)
        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)
        self.face_surface = TestFactory.get_entity(self.test_project,
                                                   FaceSurface())
        self.assertTrue(self.face_surface is not None)
        self.assertTrue(
            TestFactory.get_entity(self.test_project, EEGCap()) is not None)
    def setUp(self):
        """
        Reset the database before each test.
        """
        self.test_user = TestFactory.create_user("UserPM")
        self.test_project = TestFactory.create_project(self.test_user)

        zip_path = os.path.join(os.path.dirname(tvb_data.sensors.__file__),
                                'eeg_brainstorm_65.txt')
        TestFactory.import_sensors(self.test_user, self.test_project, zip_path,
                                   Sensors_Importer.EEG_SENSORS)

        zip_path = os.path.join(os.path.dirname(tvb_data.surfaceData.__file__),
                                'cortex_16384.zip')
        TestFactory.import_surface_zip(self.test_user, self.test_project,
                                       zip_path, CORTICAL, True)

        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)
        self.sensors = TestFactory.get_entity(self.test_project, SensorsEEG())
        self.assertTrue(self.sensors is not None)

        self.importer = TestFactory.create_adapter(
            'tvb.adapters.uploaders.projection_matrix_importer',
            'ProjectionMatrixSurfaceEEGImporter')
Ejemplo n.º 4
0
    def _importSurface(self, import_file_path=None):
        """
        This method is used for importing data in GIFIT format
        :param import_file_path: absolute path of the file to be imported
        """

        ### Retrieve Adapter instance
        group = dao.find_group('tvb.adapters.uploaders.gifti_surface_importer',
                               'GIFTISurfaceImporter')
        importer = ABCAdapter.build_adapter(group)

        args = {
            'data_file': import_file_path,
            DataTypeMetaData.KEY_SUBJECT: ""
        }

        ### Launch import Operation
        FlowService().fire_operation(importer, self.test_user,
                                     self.test_project.id, **args)

        surface = CorticalSurface()
        data_types = FlowService().get_available_datatypes(
            self.test_project.id, surface.module + "." + surface.type)[0]
        self.assertEqual(1, len(data_types),
                         "Project should contain only one data type.")

        surface = ABCAdapter.load_entity_by_gid(data_types[0][2])
        self.assertTrue(surface is not None, "TimeSeries should not be none")

        return surface
Ejemplo n.º 5
0
    def build(nr_vertices=10, valid_for_simulation=True, cortical=False):
        if cortical:
            return CorticalSurface(
                vertices=numpy.zeros((nr_vertices, 3)),
                triangles=numpy.zeros((3, 3), dtype=int),
                vertex_normals=numpy.zeros((nr_vertices, 3)),
                triangle_normals=numpy.zeros((3, 3)),
                number_of_vertices=nr_vertices,
                number_of_triangles=3,
                edge_mean_length=1.0,
                edge_min_length=0.0,
                edge_max_length=2.0,
                zero_based_triangles=False,
                bi_hemispheric=False,
                valid_for_simulations=True
            )

        return Surface(
            vertices=numpy.zeros((nr_vertices, 3)),
            triangles=numpy.zeros((3, 3), dtype=int),
            vertex_normals=numpy.zeros((nr_vertices, 3)),
            triangle_normals=numpy.zeros((3, 3)),
            number_of_vertices=nr_vertices,
            number_of_triangles=3,
            edge_mean_length=1.0,
            edge_min_length=0.0,
            edge_max_length=2.0,
            zero_based_triangles=False,
            bi_hemispheric=False,
            surface_type=SurfaceTypesEnum.CORTICAL_SURFACE.value,
            valid_for_simulations=valid_for_simulation)
Ejemplo n.º 6
0
 def test_projectionmatrix(self):
     dt = projections.ProjectionMatrix(projection_type=str(""),
                                       sources=CorticalSurface(),
                                       projection_data=numpy.array([]))
     assert dt.sources is not None
     assert dt.sensors is None
     assert dt.projection_data is not None
Ejemplo n.º 7
0
    def setUp(self):
        """
        Sets up the environment for running the tests;
        creates a test user, a test project, a connectivity, a cortical surface and a face surface;
        imports a CFF data-set
        """
        self.datatypeFactory = DatatypesFactory()
        self.test_project = self.datatypeFactory.get_project()
        self.test_user = self.datatypeFactory.get_user()

        TestFactory.import_cff(test_user=self.test_user,
                               test_project=self.test_project)
        zip_path = os.path.join(os.path.dirname(surface_dataset.__file__),
                                'face-surface.zip')
        TestFactory.import_surface_zip(self.test_user, self.test_project,
                                       zip_path, 'Face', 1)
        zip_path = os.path.join(os.path.dirname(surface_dataset.__file__),
                                'eeg_skin_surface.zip')
        TestFactory.import_surface_zip(self.test_user, self.test_project,
                                       zip_path, 'EEG Cap', 1)
        self.connectivity = TestFactory.get_entity(self.test_project,
                                                   Connectivity())
        self.assertTrue(self.connectivity is not None)
        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)
        self.face_surface = TestFactory.get_entity(self.test_project,
                                                   FaceSurface())
        self.assertTrue(self.face_surface is not None)
        self.assertTrue(
            TestFactory.get_entity(self.test_project, EEGCap()) is not None)
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def setUp(self):
        self.datatypeFactory = DatatypesFactory()
        self.test_project = self.datatypeFactory.get_project()
        self.test_user = self.datatypeFactory.get_user()

        TestFactory.import_cff(test_user=self.test_user,
                               test_project=self.test_project)
        self.connectivity = self._get_entity(Connectivity())
        self.surface = self._get_entity(CorticalSurface())
Ejemplo n.º 10
0
 def setUp(self):
     """
     Sets up the environment for running the tests;
     creates a test user, a test project, a connectivity and a surface;
     imports a CFF data-set
     """
     self.test_user = TestFactory.create_user("UserRM")
     self.test_project = TestFactory.import_default_project(self.test_user)
     self.connectivity = self._get_entity(Connectivity())
     self.surface = self._get_entity(CorticalSurface())
Ejemplo n.º 11
0
    def test_surface_sim_with_projections(self):

        # Setup Simulator obj
        oscillator = models.Generic2dOscillator()
        white_matter = connectivity.Connectivity.from_file('connectivity_%d.zip' % (self.n_regions,))
        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.from_file(period=self.period),
            monitors.MEG.from_file(period=self.period),
            # monitors.iEEG.from_file(period=self.period),
            # SEEG projection data is not part of tvb-data on Pypi, thus this can not work generic
        )
        local_coupling_strength = numpy.array([2 ** -10])
        region_mapping = RegionMapping.from_file('regionMapping_16k_%d.txt' % (self.n_regions,))
        region_mapping.surface = CorticalSurface.from_file()
        default_cortex = Cortex.from_file()
        default_cortex.region_mapping_data = region_mapping
        default_cortex.coupling_strength = local_coupling_strength

        sim = simulator.Simulator(model=oscillator, connectivity=white_matter, coupling=white_matter_coupling,
                                  integrator=heunint, monitors=mons, surface=default_cortex)
        sim.configure()

        # check configured simulation connectivity attribute
        conn = sim.connectivity
        assert conn.number_of_regions == self.n_regions
        assert conn.speed == self.speed

        # test monitor properties
        lc_n_node = sim.surface.local_connectivity.matrix.shape[0]
        for mon in sim.monitors:
            assert mon.period == self.period
            n_sens, g_n_node = mon.gain.shape
            assert g_n_node == sim.number_of_nodes
            assert n_sens == mon.sensors.number_of_sensors
            assert lc_n_node == g_n_node

        # check output shape
        ys = {}
        mons = 'eeg meg seeg'.split()
        for key in mons:
            ys[key] = []
        for data in sim(simulation_length=3.0):
            for key, dat in zip(mons, data):
                if dat:
                    _, y = dat
                    ys[key].append(y)
        for mon, key in zip(sim.monitors, mons):
            ys[key] = numpy.array(ys[key])
            assert ys[key].shape[2] == mon.gain.shape[0]
Ejemplo n.º 12
0
    def setUp(self):
        """
        Reset the database before each test.
        """
        self.test_user = TestFactory.create_user("UserPM")
        self.test_project = TestFactory.import_default_project(self.test_user)

        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)
        self.sensors = TestFactory.get_entity(self.test_project, SensorsEEG())
        self.assertTrue(self.sensors is not None)
Ejemplo n.º 13
0
    def deserialize_simulator(simulator_gid, storage_path):
        simulator_in_path = h5.path_for(storage_path, SimulatorH5,
                                        simulator_gid)
        simulator_in = Simulator()

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

        conn_index = dao.get_datatype_by_gid(connectivity_gid.hex)
        conn = h5.load_from_index(conn_index)

        simulator_in.connectivity = conn

        if simulator_in.surface:
            cortex_path = h5.path_for(storage_path, CortexH5,
                                      simulator_in.surface.gid)
            with CortexH5(cortex_path) as cortex_h5:
                local_conn_gid = cortex_h5.local_connectivity.load()
                region_mapping_gid = cortex_h5.region_mapping_data.load()

            region_mapping_index = dao.get_datatype_by_gid(
                region_mapping_gid.hex)
            region_mapping_path = h5.path_for_stored_index(
                region_mapping_index)
            region_mapping = RegionMapping()
            with RegionMappingH5(region_mapping_path) as region_mapping_h5:
                region_mapping_h5.load_into(region_mapping)
                region_mapping.gid = region_mapping_h5.gid.load()
                surf_gid = region_mapping_h5.surface.load()

            surf_index = dao.get_datatype_by_gid(surf_gid.hex)
            surf_h5 = h5.h5_file_for_index(surf_index)
            surf = CorticalSurface()
            surf_h5.load_into(surf)
            surf_h5.close()
            region_mapping.surface = surf
            simulator_in.surface.region_mapping_data = region_mapping

            if local_conn_gid:
                local_conn_index = dao.get_datatype_by_gid(local_conn_gid.hex)
                local_conn = h5.load_from_index(local_conn_index)
                simulator_in.surface.local_connectivity = local_conn

        if stimulus_gid:
            stimulus_index = dao.get_datatype_by_gid(stimulus_gid.hex)
            stimulus = h5.load_from_index(stimulus_index)
            simulator_in.stimulus = stimulus

        return simulator_in, simulation_state_gid
    def setUp(self):
        self.datatypeFactory = DatatypesFactory()
        self.test_project = self.datatypeFactory.get_project()
        self.test_user = self.datatypeFactory.get_user()

        TestFactory.import_cff(test_user=self.test_user,
                               test_project=self.test_project)
        self.connectivity = TestFactory.get_entity(self.test_project,
                                                   Connectivity())
        self.assertTrue(self.connectivity is not None)
        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)
Ejemplo n.º 15
0
 def create_surface(self):
     """
     Create a dummy surface entity.
     :return: (Algorithm Identifier, stored Surface entity)
     """
     operation, algo_id, storage_path = self.__create_operation()
     surface = CorticalSurface(storage_path=storage_path)
     surface.vertices = numpy.array(
         [[-10, 0, 0], [0, 0, -10], [10, 0, 0], [0, 10, 0]], dtype=float)
     surface.triangles = numpy.array(
         [[0, 1, 2], [0, 1, 3], [1, 2, 3], [0, 2, 3]], dtype=int)
     surface.number_of_triangles = 4
     surface.number_of_vertices = 4
     surface.triangle_normals = numpy.ones((4, 3))
     surface.vertex_normals = numpy.ones((4, 3))
     surface.zero_based_triangles = True
     adapter_instance = StoreAdapter([surface])
     OperationService().initiate_prelaunch(operation, adapter_instance, {})
     return algo_id, surface
Ejemplo n.º 16
0
    def setUp(self):
        """
        Sets up the environment for running the tests;
        creates a test user, a test project, a connectivity and a surface;
        imports a CFF data-set
        """
        self.datatypeFactory = DatatypesFactory()
        self.test_project = self.datatypeFactory.get_project()
        self.test_user = self.datatypeFactory.get_user()

        TestFactory.import_cff(test_user=self.test_user,
                               test_project=self.test_project)
        self.connectivity = self._get_entity(Connectivity())
        self.surface = self._get_entity(CorticalSurface())
Ejemplo n.º 17
0
    def get_data_for_model_param(self, param_name):
        """
        Compute the equation configured for the current param_name.
        If no equation was set for param_name, return the default array.
        """
        surface_dt = CorticalSurface()
        surface_h5 = h5.h5_file_for_index(self.surface_index)
        surface_h5.load_into(surface_dt)
        surface_h5.close()

        if param_name in self.applied_equations:
            temp = self.applied_equations[param_name]
            equation = temp[KEY_EQUATION]
            focal_points = temp[KEY_FOCAL_POINTS]
            # if focal points or the equation are missing do not update this model parameter
            if focal_points and equation:
                res = surface_dt.compute_equation(focal_points, equation)
                return res
            self.logger.warning(
                'Focal points or Equation are missing for %s. Defaults will be used.',
                param_name)
            return self._get_default_value_for_model_param(param_name)
        else:
            return self._get_default_value_for_model_param(param_name)
Ejemplo n.º 18
0
 def create_surface(self):
     """
     Create a dummy surface entity.
     :returns: (Algorithm Identifier, stored Surface entity)
     """
     operation, algo_id, storage_path = self.__create_operation()
     surface = CorticalSurface(storage_path=storage_path)
     surface.vertices = numpy.array([[-10, 0, 0],
                                     [0, 0, -10],
                                     [10, 0, 0],
                                     [0, 10, 0]], dtype=float)
     surface.triangles = numpy.array([[0, 1, 2],
                                      [0, 1, 3],
                                      [1, 2, 3],
                                      [0, 2, 3]], dtype=int)
     surface.number_of_triangles = 4
     surface.number_of_vertices = 4
     surface.triangle_normals = numpy.ones((4, 3))
     surface.vertex_normals = numpy.ones((4, 3))
     surface.zero_based_triangles = True
     surface.validate()
     adapter_instance = StoreAdapter([surface])
     OperationService().initiate_prelaunch(operation, adapter_instance, {})
     return algo_id, surface
Ejemplo n.º 19
0
    def setUp(self):
        """
        Sets up the environment for running the tests;
        creates a test user, a test project, a connectivity and a surface;
        imports a CFF data-set
        """
        self.test_user = TestFactory.create_user()
        self.test_project = TestFactory.import_default_project(self.test_user)

        self.surface = TestFactory.get_entity(self.test_project,
                                              CorticalSurface())
        self.assertTrue(self.surface is not None)

        self.region_mapping = TestFactory.get_entity(self.test_project,
                                                     RegionMapping())
        self.assertTrue(self.region_mapping is not None)
Ejemplo n.º 20
0
    def prepare_stimuli_surface_from_view_model(view_model, load_full_surface=False):
        # type: (SurfaceStimulusCreatorModel, bool) -> StimuliSurface
        stimuli_surface = StimuliSurface()

        stimuli_surface.focal_points_triangles = view_model.focal_points_triangles
        stimuli_surface.spatial = view_model.spatial
        stimuli_surface.temporal = view_model.temporal

        surface_index = SurfaceStimulusCreator.load_entity_by_gid(view_model.surface.hex)
        if load_full_surface:
            stimuli_surface.surface = h5.load_from_index(surface_index)
        else:
            stimuli_surface.surface = CorticalSurface()
            stimuli_surface.gid = view_model.surface
            surface_h5 = h5.h5_file_for_index(surface_index)
            # We need to load surface triangles on stimuli because focal_points_surface property needs to acces them
            stimuli_surface.surface.triangles = surface_h5.triangles.load()
            surface_h5.close()

        return stimuli_surface
Ejemplo n.º 21
0
 def setUp(self):
     """
     Reset the database before each test.
     """
     self.test_user = TestFactory.create_user('CFF_User')
     self.test_project = TestFactory.create_project(self.test_user,
                                                    "CFF_Project")
     TestFactory.import_cff(test_user=self.test_user,
                            test_project=self.test_project)
     zip_path = os.path.join(os.path.dirname(sensors_dataset.__file__),
                             'EEG_unit_vectors_BrainProducts_62.txt.bz2')
     TestFactory.import_sensors(self.test_user, self.test_project, zip_path,
                                'EEG Sensors')
     self.connectivity = TestFactory.get_entity(self.test_project,
                                                Connectivity())
     self.assertTrue(self.connectivity is not None)
     self.surface = TestFactory.get_entity(self.test_project,
                                           CorticalSurface())
     self.assertTrue(self.surface is not None)
     self.sensors = TestFactory.get_entity(self.test_project, SensorsEEG())
     self.assertTrue(self.sensors is not None)
Ejemplo n.º 22
0
    def prepare_stimuli_surface_from_view_model(self,
                                                view_model,
                                                load_full_surface=False):
        # type: (SurfaceStimulusCreatorModel, bool) -> StimuliSurface
        stimuli_surface = StimuliSurface()

        stimuli_surface.focal_points_triangles = view_model.focal_points_triangles
        stimuli_surface.spatial = view_model.spatial
        stimuli_surface.temporal = view_model.temporal

        if load_full_surface:
            stimuli_surface.surface = self.load_traited_by_gid(
                view_model.surface)
        else:
            stimuli_surface.surface = CorticalSurface()
            stimuli_surface.gid = view_model.surface
            # We need to load surface triangles on stimuli because focal_points_surface property needs to acces them
            with h5.h5_file_for_gid(view_model.surface) as surface_h5:
                stimuli_surface.surface.triangles = surface_h5.triangles.load()

        return stimuli_surface
Ejemplo n.º 23
0
    def build(nr_vertices=10, valid_for_simulation=True, cortical=False):
        if cortical:
            return CorticalSurface(
                vertices=numpy.zeros((nr_vertices, 3)),
                triangles=numpy.zeros((3, 3), dtype=int),
                vertex_normals=numpy.zeros((nr_vertices, 3)),
                triangle_normals=numpy.zeros((3, 3)),
                number_of_vertices=nr_vertices,
                number_of_triangles=3,
                edge_mean_length=1.0,
                edge_min_length=0.0,
                edge_max_length=2.0,
                zero_based_triangles=False,
                split_triangles=numpy.arange(0),
                number_of_split_slices=1,
                split_slices=dict(),
                bi_hemispheric=False,
                # surface_type="surface",
                valid_for_simulations=True)

        return Surface(vertices=numpy.zeros((nr_vertices, 3)),
                       triangles=numpy.zeros((3, 3), dtype=int),
                       vertex_normals=numpy.zeros((nr_vertices, 3)),
                       triangle_normals=numpy.zeros((3, 3)),
                       number_of_vertices=nr_vertices,
                       number_of_triangles=3,
                       edge_mean_length=1.0,
                       edge_min_length=0.0,
                       edge_max_length=2.0,
                       zero_based_triangles=False,
                       split_triangles=numpy.arange(0),
                       number_of_split_slices=1,
                       split_slices=dict(),
                       bi_hemispheric=False,
                       surface_type="surface_cortical",
                       valid_for_simulations=valid_for_simulation)
Ejemplo n.º 24
0
    def configure(self,
                  dt=2**-3,
                  model=ModelsEnum.GENERIC_2D_OSCILLATOR.get_class(),
                  speed=4.0,
                  coupling_strength=0.00042,
                  method=HeunDeterministic,
                  surface_sim=False,
                  default_connectivity=True,
                  with_stimulus=False):
        """
        Create an instance of the Simulator class, by default use the
        generic plane oscillator local dynamic model and the deterministic 
        version of Heun's method for the numerical integration.
        
        """
        self.method = method

        if default_connectivity:
            white_matter = Connectivity.from_file()
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_76.txt")
        else:
            white_matter = Connectivity.from_file(
                source_file="connectivity_192.zip")
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_192.txt")
        region_mapping.surface = CorticalSurface.from_file()

        white_matter_coupling = coupling.Linear(
            a=numpy.array([coupling_strength]))
        white_matter.speed = numpy.array(
            [speed])  # no longer allow scalars to numpy array promotion

        dynamics = model()

        if issubclass(method, IntegratorStochastic):
            hisss = noise.Additive(nsig=numpy.array([2**-11]))
            integrator = method(dt=dt, noise=hisss)
        else:
            integrator = method(dt=dt)

        if surface_sim:
            local_coupling_strength = numpy.array([2**-10])
            default_cortex = Cortex.from_file()
            default_cortex.region_mapping_data = region_mapping
            default_cortex.coupling_strength = local_coupling_strength
            if default_connectivity:
                default_cortex.local_connectivity = LocalConnectivity.from_file(
                )
            else:
                default_cortex.local_connectivity = LocalConnectivity()
            default_cortex.local_connectivity.surface = default_cortex.region_mapping_data.surface
            # TODO stimulus
        else:
            default_cortex = None
            if with_stimulus:
                weights = StimuliRegion.get_default_weights(
                    white_matter.weights.shape[0])
                weights[self.stim_nodes] = 1.
                stimulus = StimuliRegion(temporal=Linear(parameters={
                    "a": 0.0,
                    "b": self.stim_value
                }),
                                         connectivity=white_matter,
                                         weight=weights)

        # Order of monitors determines order of returned values.
        self.sim = simulator.Simulator()
        self.sim.surface = default_cortex
        self.sim.model = dynamics
        self.sim.integrator = integrator
        self.sim.connectivity = white_matter
        self.sim.coupling = white_matter_coupling
        self.sim.monitors = self.monitors
        if with_stimulus:
            self.sim.stimulus = stimulus
        self.sim.configure()
Ejemplo n.º 25
0
 def from_tvb_file(self, filepath):
     self._tvb = TVBCorticalSurface.from_file(filepath, self._tvb)
     self.vox2ras = np.array([])
     self.file_path = filepath
     return self
Ejemplo n.º 26
0
class GIFTIParser():
    """
        This class reads content of a GIFTI file and builds / returns a Surface instance 
        filled with details.
    """
    UNIQUE_ID_ATTR = "UniqueID"
    SUBJECT_ATTR = "SubjectID"
    ASP_ATTR = "AnatomicalStructurePrimary"
    DATE_ATTR = "Date"
    DESCRIPTION_ATTR = "Description"
    NAME_ATTR = "Name"
    TIME_STEP_ATTR = "TimeStep"
    
    def __init__(self, storage_path, operation_id):
        self.logger = get_logger(__name__)
        self.storage_path = storage_path
        self.operation_id = operation_id
        
    def parse(self, data_file):
        """
            Parse NIFTI file and returns TimeSeries for it. 
        """
        self.logger.debug("Start to parse GIFTI file: %s"%data_file)
        if data_file is None:
            raise ParseException ("Please select GIFTI file which contains data to import")
        if not os.path.exists(data_file):
            raise ParseException ("Provided file %s does not exists"%data_file)
        try:
            gifti_image = giftiio.read(data_file)
            self.logger.debug("File parsed successfully")
        except Exception, excep:
            self.logger.exception(excep)
            msg = "File: %s does not have a valid GIFTI format." % data_file
            raise ParseException(msg)
        
        
        # Now try to determine what data is stored in GIFTI file
        data_arrays = gifti_image.darrays
        
        self.logger.debug("Determine data type stored in GIFTI file")
        
        # First check if it's a surface
        if (len(data_arrays) == 2 
            and intent_codes.code["NIFTI_INTENT_POINTSET"] == data_arrays[0].intent
            and data_type_codes.code["NIFTI_TYPE_FLOAT32"] == data_arrays[0].datatype
            and intent_codes.code["NIFTI_INTENT_TRIANGLE"] == data_arrays[1].intent
            and data_type_codes.code["NIFTI_TYPE_INT32"] == data_arrays[1].datatype):
            
            # Now try to determine what type of surface we have
            data_array_meta = data_arrays[0].meta
            surface = None
            gid = None
            subject = None
            title = None
            
            if (data_array_meta is not None and data_array_meta.data is not None 
                   and len(data_array_meta.data) > 0):
                anatomical_structure_primary = None
                
                for meta_pair in data_array_meta.data:
                    if meta_pair.name == self.ASP_ATTR:
                        anatomical_structure_primary = meta_pair.value
                    elif meta_pair.name == self.UNIQUE_ID_ATTR:
                        gid = meta_pair.value.replace("{", "").replace("}", "")
                    elif meta_pair.name == self.SUBJECT_ATTR:
                        subject = meta_pair.value
                    elif meta_pair.name == self.NAME_ATTR:
                        title = meta_pair.value
                        
                # Based on info found in meta create correct surface type
                if anatomical_structure_primary == "Head":
                    surface = SkinAir()
                elif anatomical_structure_primary.startswith("Cortex"):
                    surface = CorticalSurface()
                
            
            if surface is None:
                raise ParseException("Could not determine type of the surface")
            
            # Now fill TVB data type with info
            if gid is not None:
                surface.gid = gid
            
            surface.storage_path = self.storage_path
            surface.set_operation_id(self.operation_id)
            
            surface.zero_based_triangles = True
            surface.vertices = data_arrays[0].data
            surface.triangles = data_arrays[1].data
            
            if subject is not None:
                surface.subject = subject
            if title is not None:
                surface.title = title
            
            return surface
        
        elif(len(data_arrays) > 1 
            and intent_codes.code["NIFTI_INTENT_TIME_SERIES"] == data_arrays[0].intent
            and data_type_codes.code["NIFTI_TYPE_FLOAT32"] == data_arrays[0].datatype):
            
            # Create TVB time series to be filled
            time_series = TimeSeriesSurface()
            time_series.storage_path = self.storage_path
            time_series.set_operation_id(self.operation_id)
            time_series.start_time = 0.0
            time_series.sample_period = 1.0

            # First process first data_array and extract important data from it's metadata            
            data_array_meta = data_arrays[0].meta
            if (data_array_meta is not None and data_array_meta.data is not None 
                   and len(data_array_meta.data) > 0):
                for meta_pair in data_array_meta.data:
                    if meta_pair.name == self.UNIQUE_ID_ATTR:
                        gid = meta_pair.value.replace("{", "").replace("}", "")
                        if gid is not None and len(gid) > 0:
                            time_series.gid = gid
                    elif meta_pair.name == self.SUBJECT_ATTR:
                        time_series.subject = meta_pair.value
                    elif meta_pair.name == self.NAME_ATTR:
                        time_series.title = meta_pair.value
                    elif meta_pair.name == self.TIME_STEP_ATTR:
                        time_series.sample_period = float(meta_pair.value)
            
            
            # Now read time series data
            for data_array in data_arrays:
                time_series.write_data_slice([data_array.data])
            
            # Close file after writing data
            time_series.close_file()
            
            return time_series
        else:
            raise ParseException("Could not map data from GIFTI file to a TVB data type")
Ejemplo n.º 27
0
 def test_localconnectivity_empty(self):
     dt = LocalConnectivity(surface=CorticalSurface())
     assert dt.surface is not None
Ejemplo n.º 28
0
    def configure(self,
                  dt=2**-3,
                  model=models.Generic2dOscillator,
                  speed=4.0,
                  coupling_strength=0.00042,
                  method=HeunDeterministic,
                  surface_sim=False,
                  default_connectivity=True):
        """
        Create an instance of the Simulator class, by default use the
        generic plane oscillator local dynamic model and the deterministic 
        version of Heun's method for the numerical integration.
        
        """
        self.method = method

        if default_connectivity:
            white_matter = Connectivity.from_file()
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_76.txt")
        else:
            white_matter = Connectivity.from_file(
                source_file="connectivity_192.zip")
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_192.txt")
        region_mapping.surface = CorticalSurface.from_file()

        white_matter_coupling = coupling.Linear(
            a=numpy.array([coupling_strength]))
        white_matter.speed = numpy.array(
            [speed])  # no longer allow scalars to numpy array promotion

        dynamics = model()

        if issubclass(method, IntegratorStochastic):
            hisss = noise.Additive(nsig=numpy.array([2**-11]))
            integrator = method(dt=dt, noise=hisss)
        else:
            integrator = method(dt=dt)

        if surface_sim:
            local_coupling_strength = numpy.array([2**-10])
            default_cortex = Cortex.from_file()
            default_cortex.region_mapping_data = region_mapping
            default_cortex.coupling_strength = local_coupling_strength
            if default_connectivity:
                default_cortex.local_connectivity = LocalConnectivity.from_file(
                )
            else:
                default_cortex.local_connectivity = LocalConnectivity()
            default_cortex.local_connectivity.surface = default_cortex.region_mapping_data.surface
        else:
            default_cortex = None

        # Order of monitors determines order of returned values.
        self.sim = simulator.Simulator()
        self.sim.surface = default_cortex
        self.sim.model = dynamics
        self.sim.integrator = integrator
        self.sim.connectivity = white_matter
        self.sim.coupling = white_matter_coupling
        self.sim.monitors = self.monitors
        self.sim.configure()
Ejemplo n.º 29
0
    def launch(self, uploaded, surface_type, zero_based_triangles = False):
        """
        Execute import operations: unpack ZIP and build Surface object as result.
        """
        if uploaded is None:
            raise LaunchException ("Please select ZIP file which contains data to import")
  
        self.logger.debug("Start to import surface: '%s' from file: %s"%(surface_type, uploaded))
        try:
            files = FilesHelper().unpack_zip(uploaded, self.storage_path)
        except IOError:
            exception_str = "Did not find the specified ZIP at %s" % uploaded
            raise LaunchException(exception_str)
        
        vertices = []
        normals = []
        triangles = []
        for file_name in files:
            if file_name.lower().find(self.VERTICES_TOKEN) >= 0:
                vertices.append(file_name)            
                continue
            if file_name.lower().find(self.NORMALS_TOKEN) >= 0:
                normals.append(file_name)            
                continue
            if file_name.lower().find(self.TRIANGLES_TOKEN) >= 0:
                triangles.append(file_name)
                
        # Now detect and instantiate correct surface type
        self.logger.debug("Create surface instance")
        if surface_type == CORTICAL:
            surface = CorticalSurface()
        elif surface_type == INNER_SKULL:
            surface = BrainSkull()
        elif surface_type == OUTER_SKULL:
            surface = SkullSkin()
        elif surface_type == OUTER_SKIN:
            surface = SkinAir()
        elif surface_type == EEG_CAP:
            surface = EEGCap()
        elif surface_type == FACE:
            surface = FaceSurface()
        else:
            exception_str = "Could not determine surface type (selected option %s)" % surface_type
            raise LaunchException(exception_str)
            
        surface.storage_path = self.storage_path

        all_vertices, all_normals, all_triangles = self._process_files(vertices, normals, triangles)
        FilesHelper.remove_files(files, True)
        surface.zero_based_triangles = zero_based_triangles
        surface.vertices = all_vertices
        surface.vertex_normals = all_normals
        if zero_based_triangles:
            surface.triangles = all_triangles
        else :
            surface.triangles = all_triangles - 1
        surface.triangle_normals = None

        # Now check if the triangles of the surface are valid   
        triangles_min_vertex = numpy.amin(surface.triangles)
        if triangles_min_vertex < 0:
            if triangles_min_vertex == -1 and not zero_based_triangles:
                raise RuntimeError("Triangles contain a negative vertex index. Maybe you have a ZERO based surface.")
            else:
                raise RuntimeError("Your triangles contain a negative vertex index: %d" %triangles_min_vertex)
        
        no_of_vertices = len(surface.vertices)        
        triangles_max_vertex = numpy.amax(surface.triangles)
        if triangles_max_vertex >= no_of_vertices:
            if triangles_max_vertex == no_of_vertices and zero_based_triangles:
                raise RuntimeError("Your triangles contain an invalid vertex index: %d. \
                Maybe your surface is NOT ZERO Based."%triangles_max_vertex)
            else:
                raise RuntimeError("Your triangles contain an invalid vertex index: %d." %triangles_max_vertex)
            
        self.logger.debug("Surface ready to be stored")
        return surface
Ejemplo n.º 30
0
                  surface_type="surface",
                  valid_for_simulations=True)

region_mapping = RegionMapping(array_data=numpy.arange(5),
                               connectivity=connectivity,
                               surface=surface)

cortical_surface = CorticalSurface(
    vertices=numpy.zeros((5, 3)),
    triangles=numpy.zeros((3, 3), dtype=int),
    vertex_normals=numpy.zeros((5, 3)),
    triangle_normals=numpy.zeros((3, 3)),
    number_of_vertices=5,
    number_of_triangles=3,
    edge_mean_length=1.0,
    edge_min_length=0.0,
    edge_max_length=2.0,
    zero_based_triangles=False,
    split_triangles=numpy.arange(0),
    number_of_split_slices=1,
    split_slices=dict(),
    bi_hemispheric=False,
    # surface_type="surface",
    valid_for_simulations=True)

sensors = Sensors(sensors_type="SEEG",
                  labels=numpy.array(["s1", "s2", "s3"]),
                  locations=numpy.zeros((3, 3)),
                  number_of_sensors=3,
                  has_orientation=True,
                  orientations=numpy.zeros((3, 3)),