Example #1
0
    def build_simulator(self, n=4):

        self.conn = numpy.zeros((n, n))  # , numpy.int32)
        for i in range(self.conn.shape[0] - 1):
            self.conn[i, i + 1] = 1

        self.dist = numpy.r_[:n * n].reshape((n, n))
        self.dist = numpy.array(self.dist, dtype=float)

        self.sim = Simulator(
            conduction_speed=1.0,
            coupling=IdCoupling(),
            surface=None,
            stimulus=None,
            integrator=Identity(dt=1.0),
            initial_conditions=numpy.ones((n * n, 1, n, 1)),
            simulation_length=10.0,
            connectivity=Connectivity(region_labels=numpy.array(['']),
                                      weights=self.conn,
                                      tract_lengths=self.dist,
                                      speed=numpy.array([1.0]),
                                      centres=numpy.array([0.0])),
            model=Sum(),
            monitors=(Raw(), ),
        )
        self.sim.configure()
    def test_server_fire_simulation(self, mocker, connectivity_factory):
        input_folder = self.files_helper.get_project_folder(self.test_project)
        sim_dir = os.path.join(input_folder, 'test_sim')
        if not os.path.isdir(sim_dir):
            os.makedirs(sim_dir)

        simulator = Simulator()
        simulator.connectivity = connectivity_factory()
        sim_serializer = SimulatorSerializer()
        sim_serializer.serialize_simulator(simulator, simulator.gid.hex, None,
                                           sim_dir)

        zip_filename = shutil.make_archive(sim_dir, 'zip', input_folder)

        # Mock flask.request.files to return a dictionary
        request_mock = mocker.patch.object(flask, 'request')
        fp = open(zip_filename, 'rb')
        request_mock.files = {
            'file': FileStorage(fp, os.path.basename(zip_filename))
        }

        def launch_sim(self, user_id, project, algorithm, zip_folder_path,
                       simulator_file):
            return Operation('', '', '', {})

        # Mock simulation launch
        mocker.patch.object(SimulatorService, 'prepare_simulation_on_server',
                            launch_sim)

        operation_gid, status = self.simulation_resource.post(
            self.test_project.gid)
        fp.close()

        assert type(operation_gid) is str
        assert status == 201
Example #3
0
 def _create_sim(self, integrator=None, inhom_mmpr=False, delays=False,
         run_sim=True):
     mpr = MontbrioPazoRoxin()
     conn = Connectivity.from_file()
     if inhom_mmpr:
         dispersion = 1 + np.random.randn(conn.weights.shape[0])*0.1
         mpr = MontbrioPazoRoxin(eta=mpr.eta*dispersion)
     conn.speed = np.r_[3.0 if delays else np.inf]
     if integrator is None:
         dt = 0.01
         integrator = EulerDeterministic(dt=dt)
     else:
         dt = integrator.dt
     sim = Simulator(connectivity=conn, model=mpr, integrator=integrator, 
         monitors=[Raw()],
         simulation_length=0.1)  # 10 steps
     sim.configure()
     if not delays:
         self.assertTrue((conn.idelays == 0).all())
     buf = sim.history.buffer[...,0]
     # kernel has history in reverse order except 1st element 🤕
     rbuf = np.concatenate((buf[0:1], buf[1:][::-1]), axis=0)
     state = np.transpose(rbuf, (1, 0, 2)).astype('f')
     self.assertEqual(state.shape[0], 2)
     self.assertEqual(state.shape[2], conn.weights.shape[0])
     if isinstance(sim.integrator, IntegratorStochastic):
         sim.integrator.noise.reset_random_stream()
     if run_sim:
         (t,y), = sim.run()
         return sim, state, t, y
     else:
         return sim
Example #4
0
    def test_shape(self):

        # try to avoid introspector picking up this model
        Gen2D = copy.deepcopy(models.Generic2dOscillator)

        class CouplingShapeTestModel(Gen2D):
            def __init__(self, test_case=None, n_node=None, **kwds):
                super(CouplingShapeTestModel, self).__init__(**kwds)
                self.cvar = numpy.r_[0, 1]
                self.n_node = n_node
                self.test_case = test_case

            def dfun(self, state, coupling, local_coupling):
                if self.test_case is not None:
                    self.test_case.assert_equal((2, self.n_node, 1),
                                                coupling.shape)
                    return state

        conn = connectivity.Connectivity.from_file()
        surf = cortex.Cortex.from_file()
        surf.region_mapping_data.connectivity = conn
        sim = Simulator(model=CouplingShapeTestModel(self,
                                                     surf.vertices.shape[0]),
                        connectivity=conn,
                        surface=surf)

        sim.configure()

        for _ in sim(simulation_length=sim.integrator.dt * 2):
            pass
    def test_experimental_similar_to_default(self):
        sim = Simulator()
        sim.trait.bound = 'attributes-only'
        itree = sim.interface['attributes']

        sim2 = Simulator()
        sim2.trait.bound = 'attributes-only'
        itree_exp = sim2.interface_experimental

        self._cmp_attributes_or_options(itree_exp, itree)
Example #6
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
Example #7
0
    def test_models_list(self, mocker):
        models_form = SimulatorModelFragment()
        simulator = Simulator()
        simulator.model = ModelsEnum.EPILEPTOR.instance
        models_form.fill_from_trait(simulator)

        rendering_rules = SimulatorFragmentRenderingRules(is_model_fragment=True)
        soup = self.prepare_simulator_form_for_search(mocker, rendering_rules, form=models_form)

        select_field = soup.find_all('select')
        assert len(select_field) == 1, 'Number of select inputs is different than 1'
        select_field_options = soup.find_all('option')
        assert len(select_field_options) == len(ModelsEnum), 'Number of select field options != number of models'
        select_field_choice = soup.find_all('option', selected=True)
        assert len(select_field_choice) == 1
        assert 'Epileptor' in select_field_choice[0].attrs['value']
Example #8
0
    def test_export_simulator_configuration(self, operation_factory):
        """
        Test export of a simulator configuration
        """
        operation = operation_factory()
        simulator = Simulator()
        simulator_index = SimulatorIndex()
        simulator_index.fill_from_has_traits(simulator)
        simulator_index.fk_from_operation = operation.id
        simulator_index = dao.store_entity(simulator_index)

        burst_configuration = BurstConfiguration(self.test_project.id,
                                                 simulator_index.id)
        burst_configuration = dao.store_entity(burst_configuration)
        simulator_index.fk_parent_burst = burst_configuration.id
        simulator_index = dao.store_entity(simulator_index)

        simulator_h5 = h5.path_for_stored_index(simulator_index)
        with SimulatorH5(simulator_h5) as h5_file:
            h5_file.store(simulator)

        export_file = self.export_manager.export_simulator_configuration(
            burst_configuration.id)

        assert export_file is not None, "Export process should return path to export file"
        assert os.path.exists(
            export_file
        ), "Could not find export file: %s on disk." % export_file
        assert zipfile.is_zipfile(
            export_file), "Generated file is not a valid ZIP file"
Example #9
0
    def test_models_list(self):
        all_models_for_ui = get_ui_name_to_model()
        models_form = SimulatorModelFragment()
        simulator = Simulator()
        simulator.model = ModelsEnum.EPILEPTOR.get_class()()
        models_form.fill_from_trait(simulator)

        html = str(models_form)
        soup = BeautifulSoup(html)

        select_field = soup.find_all('select')
        assert len(select_field) == 1, 'Number of select inputs is different than 1'
        select_field_options = soup.find_all('option')
        assert len(select_field_options) == len(all_models_for_ui), 'Number of select field options != number of models'
        select_field_choice = soup.find_all('option', selected=True)
        assert len(select_field_choice) == 1
        assert 'Epileptor' in select_field_choice[0].attrs['value']
def test(dt=0.1, noise_strength=0.001, config=CONFIGURED):

    # Select the regions for the fine scale modeling with NEST spiking networks
    nest_nodes_ids = []  # the indices of fine scale regions modeled with NEST
    # In this example, we model parahippocampal cortices (left and right) with NEST
    connectivity = Connectivity.from_file(CONFIGURED.DEFAULT_CONNECTIVITY_ZIP)
    for id in range(connectivity.region_labels.shape[0]):
        if connectivity.region_labels[id].find("hippo") > 0:
            nest_nodes_ids.append(id)
    connectivity.configure()

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.integrator.dt = dt
    simulator.integrator.noise.nsig = np.array([noise_strength])
    simulator.model = ReducedWongWangExcIOInhI()

    simulator.connectivity = connectivity
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )

    # Build a NEST network model with the corresponding builder
    # Using all default parameters for this example
    nest_model_builder = RedWWExcIOInhIMultisynapseBuilder(simulator,
                                                           nest_nodes_ids,
                                                           config=config)
    nest_model_builder.configure()
    for prop in [
            "min_delay", "tvb_dt", "tvb_model", "tvb_connectivity",
            "tvb_weights", "tvb_delays", "number_of_nodes",
            "number_of_spiking_nodes", "spiking_nodes_labels",
            "number_of_populations", "populations_models", "populations_nodes",
            "populations_scales", "populations_sizes", "populations_params",
            "populations_connections_labels", "populations_connections_models",
            "populations_connections_nodes", "populations_connections_weights",
            "populations_connections_delays",
            "populations_connections_receptor_types",
            "populations_connections_conn_spec", "nodes_connections_labels",
            "nodes_connections_models", "nodes_connections_source_nodes",
            "nodes_connections_target_nodes", "nodes_connections_weights",
            "nodes_connections_delays", "nodes_connections_receptor_types",
            "nodes_connections_conn_spec"
    ]:
        print("%s:\n%s\n\n" % (prop, str(getattr(nest_model_builder, prop))))
Example #11
0
 def _prep_sim(self, coupling) -> Simulator:
     "Prepare simulator for testing a coupling function."
     con = Connectivity.from_file()
     con.weights[:] = 1.0
     # con = Connectivity(
     #     region_labels=np.array(['']),
     #     weights=con.weights[:5][:,:5],
     #     tract_lengths=con.tract_lengths[:5][:,:5],
     #     speed=np.array([10.0]),
     #     centres=np.array([0.0]))
     sim = Simulator(connectivity=con,
                     model=LinearModel(gamma=np.r_[0.0]),
                     coupling=coupling,
                     integrator=Identity(dt=1.0),
                     monitors=[Raw()],
                     simulation_length=0.5)
     sim.configure()
     return sim
Example #12
0
    def prepare_simulator_form_for_search(self, dict_to_render):
        sim_adapter_form = SimulatorAdapterForm(project_id=1)
        sim_adapter_form.fill_from_trait(Simulator())
        dict_to_render[SimulatorController.FORM_KEY] = sim_adapter_form

        html = self.dummy_renderer(dict_to_render)
        soup = BeautifulSoup(html)

        return soup
Example #13
0
class TestsExactPropagation(BaseTestCase):
    def build_simulator(self, n=4):

        self.conn = numpy.zeros((n, n))  # , numpy.int32)
        for i in range(self.conn.shape[0] - 1):
            self.conn[i, i + 1] = 1

        self.dist = numpy.r_[:n * n].reshape((n, n))
        self.dist = numpy.array(self.dist, dtype=float)

        self.sim = Simulator(
            conduction_speed=1.0,
            coupling=IdCoupling(),
            surface=None,
            stimulus=None,
            integrator=Identity(dt=1.0),
            initial_conditions=numpy.ones((n * n, 1, n, 1)),
            simulation_length=10.0,
            connectivity=Connectivity(region_labels=numpy.array(['']),
                                      weights=self.conn,
                                      tract_lengths=self.dist,
                                      speed=numpy.array([1.0]),
                                      centres=numpy.array([0.0])),
            model=Sum(),
            monitors=(Raw(), ),
        )

        self.sim.configure()

    def test_propagation(self):
        n = 4
        self.build_simulator(n=n)
        # x = numpy.zeros((n, ))
        xs = []
        for (t, raw), in self.sim(simulation_length=10):
            xs.append(raw.flat[:].copy())
        xs = numpy.array(xs)
        xs_ = numpy.array([[2., 2., 2., 1.], [3., 3., 3.,
                                              1.], [5., 4., 4., 1.],
                           [8., 5., 5., 1.], [12., 6., 6., 1.],
                           [17., 7., 7., 1.], [23., 8., 8., 1.],
                           [30., 10., 9., 1.], [38., 13., 10., 1.],
                           [48., 17., 11., 1.]])
        assert numpy.allclose(xs, xs_)
Example #14
0
def test(dt=0.1, noise_strength=0.001, config=CONFIGURED):
    # Select the regions for the fine scale modeling with ANNarchy spiking networks
    anarchy_nodes_ids = list(
        range(10))  # the indices of fine scale regions modeled with ANNarchy
    # In this example, we model parahippocampal cortices (left and right) with ANNarchy
    connectivity = Connectivity.from_file(CONFIGURED.DEFAULT_CONNECTIVITY_ZIP)
    connectivity.configure()

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.integrator.dt = dt
    # simulator.integrator.noise.nsig = np.array([noise_strength])
    simulator.model = ReducedWongWangExcIOInhI()

    simulator.connectivity = connectivity
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )

    # Build a ANNarchy network model with the corresponding builder
    # Using all default parameters for this example
    anarchy_model_builder = BasalGangliaIzhikevichBuilder(simulator,
                                                          anarchy_nodes_ids,
                                                          config=config)
    anarchy_model_builder.configure()
    for prop in [
            "min_delay", "tvb_dt", "tvb_model", "tvb_connectivity",
            "tvb_weights", "tvb_delays", "number_of_nodes",
            "number_of_spiking_nodes", "spiking_nodes_labels",
            "number_of_populations", "populations_models", "populations_nodes",
            "populations_scales", "populations_sizes", "populations_params",
            "populations_connections_labels", "populations_connections_models",
            "populations_connections_nodes", "populations_connections_weights",
            "populations_connections_delays",
            "populations_connections_receptor_types",
            "populations_connections_conn_spec", "nodes_connections_labels",
            "nodes_connections_models", "nodes_connections_source_nodes",
            "nodes_connections_target_nodes", "nodes_connections_weights",
            "nodes_connections_delays", "nodes_connections_receptor_types",
            "nodes_connections_conn_spec"
    ]:
        print("%s:\n%s\n\n" %
              (prop, str(getattr(anarchy_model_builder, prop))))
Example #15
0
    def prepare_simulator_form_for_search(self, rendering_rules, form=None):
        # type: (SimulatorFragmentRenderingRules, ABCAdapterForm) -> BeautifulSoup
        if form is None:
            form = SimulatorAdapterForm(project_id=1)
            form.fill_from_trait(Simulator())
        rendering_rules.form = form

        html = self.dummy_renderer(rendering_rules.to_dict())
        soup = BeautifulSoup(html)
        return soup
Example #16
0
 def _tvb_sim(self, dt):
     import numpy as np
     from tvb.simulator.simulator import Simulator, models, connectivity, monitors
     sim = Simulator(
         connectivity=connectivity.Connectivity.from_file(),
         model=models.MontbrioPazoRoxin(I=np.r_[1.0],
                                        Delta=np.r_[1.0],
                                        eta=np.r_[-5.0],
                                        tau=np.r_[100.0],
                                        J=np.r_[15.],
                                        cr=np.r_[0.01],
                                        cv=np.r_[0.0]),
         integrator=self._integrator(dt=dt),
         monitors=[monitors.Raw()],
     ).configure()
     assert sim.history.buffer.shape == (513, 2, 76, 1)
     sim.history.buffer[:, 0] = 0.0
     sim.history.buffer[:, 1] = -2.0
     sim.current_state[:] = sim.history.buffer[0]
     return sim
Example #17
0
 def get_input_tree(self):
     """
     Return a list of lists describing the interface to the simulator. This
     is used by the GUI to generate the menus and fields necessary for
     defining a simulation.
     """
     sim = Simulator()
     sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
     result = sim.interface[self.INTERFACE_ATTRIBUTES]
     # We should add as hidden the Simulator State attribute.
     result.append({'name': 'simulation_state', 'type': SimulationState, 'required': False, 'ui_hidden': True})
     return result
Example #18
0
def main_example(tvb_sim_model,
                 connectivity_zip=CONFIGURED.DEFAULT_CONNECTIVITY_ZIP,
                 dt=0.1,
                 noise_strength=0.001,
                 simulation_length=100.0,
                 config=CONFIGURED):

    plotter = Plotter(config)

    # --------------------------------------1. Load TVB connectivity----------------------------------------------------
    connectivity = Connectivity.from_file(connectivity_zip)
    connectivity.configure()
    plotter.plot_tvb_connectivity(connectivity)

    # ----------------------2. Define a TVB simulator (model, integrator, monitors...)----------------------------------

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.integrator = HeunStochastic(dt=dt)
    simulator.integrator.noise.nsig = np.array(ensure_list(noise_strength))
    simulator.model = tvb_sim_model
    simulator.connectivity = connectivity
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )

    # -----------------------------------3. Simulate and gather results-------------------------------------------------

    # Configure the simulator with the TVB-NEST interface...
    # simulator.configure(tvb_nest_interface=tvb_nest_model)
    simulator.configure()
    # ...and simulate!
    t_start = time.time()
    results = simulator.run(simulation_length=simulation_length)
    print("\nSimulated in %f secs!" % (time.time() - t_start))

    # -------------------------------------------6. Plot results--------------------------------------------------------

    plot_results(results, simulator, None, "State Variables",
                 simulator.model.variables_of_interest, plotter)

    return connectivity, results
    def test_server_fire_simulation(self, mocker, connectivity_factory):
        self._mock_user(mocker)
        input_folder = self.files_helper.get_project_folder(self.test_project)
        sim_dir = os.path.join(input_folder, 'test_sim')
        if not os.path.isdir(sim_dir):
            os.makedirs(sim_dir)

        simulator = Simulator()
        simulator.connectivity = connectivity_factory()
        sim_serializer = SimulatorSerializer()
        sim_serializer.serialize_simulator(simulator, None, sim_dir)

        zip_filename = os.path.join(input_folder,
                                    RequestFileKey.SIMULATION_FILE_NAME.value)
        FilesHelper().zip_folder(zip_filename, sim_dir)

        # Mock flask.request.files to return a dictionary
        request_mock = mocker.patch.object(flask, 'request')
        fp = open(zip_filename, 'rb')
        request_mock.files = {
            RequestFileKey.SIMULATION_FILE_KEY.value:
            FileStorage(fp, os.path.basename(zip_filename))
        }

        def launch_sim(self, user_id, project, algorithm, zip_folder_path,
                       simulator_file):
            return Operation('', '', '', {})

        # Mock simulation launch and current user
        mocker.patch.object(SimulatorService, 'prepare_simulation_on_server',
                            launch_sim)

        operation_gid, status = self.simulation_resource.post(
            project_gid=self.test_project.gid)
        fp.close()

        assert type(operation_gid) is str
        assert status == 201
Example #20
0
 def get_input_tree(self):
     """
     Return a list of lists describing the interface to the simulator. This
     is used by the GUI to generate the menus and fields necessary for
     defining a simulation.
     """
     sim = Simulator()
     sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
     result = sim.interface[self.INTERFACE_ATTRIBUTES]
     # We should add as hidden the Simulator State attribute.
     result.append({self.KEY_NAME: 'simulation_state',
                    self.KEY_TYPE: 'tvb.datatypes.simulation_state.SimulationState',
                    self.KEY_LABEL: "Continuation of", self.KEY_REQUIRED: False, self.KEY_UI_HIDE: True})
     return result
    def transactional_setup_method(self):
        self.test_user = TestFactory.create_user(username="******")
        self.test_project = TestFactory.create_project(self.test_user, "Test")
        zip_path = path.join(path.dirname(tvb_data.__file__), 'connectivity',
                             'connectivity_66.zip')
        TestFactory.import_zip_connectivity(self.test_user, self.test_project,
                                            zip_path, "John")
        self.connectivity = TestFactory.get_entity(self.test_project,
                                                   ConnectivityIndex)

        sim_conf = Simulator(model=ModelsEnum.HOPFIELD.get_class()(),
                             integrator=HeunStochastic())

        self.s_manager = SerializationManager(sim_conf)
        self.empty_manager = SerializationManager(None)
Example #22
0
def fire_simulation(project_id=1, **kwargs):
    project = dao.get_project_by_id(project_id)

    # Prepare a Simulator instance with defaults and configure it to use the previously loaded Connectivity
    simulator = Simulator(**kwargs)

    # Load the SimulatorAdapter algorithm from DB
    cached_simulator_algorithm = FlowService(
    ).get_algorithm_by_module_and_class(IntrospectionRegistry.SIMULATOR_MODULE,
                                        IntrospectionRegistry.SIMULATOR_CLASS)

    # Instantiate a SimulatorService and launch the configured simulation
    simulator_service = SimulatorService()
    launched_operation = simulator_service.async_launch_and_prepare_simulation(
        None, project.administrator, project, cached_simulator_algorithm,
        simulator, None)
    return launched_operation
Example #23
0
    def prepare_simulator_form_for_search(self, mocker, rendering_rules, form=None):
        # type: (MockerFixture, SimulatorFragmentRenderingRules, ABCAdapterForm) -> BeautifulSoup
        if form is None:
            form = SimulatorAdapterForm()
            form.fill_from_trait(Simulator())
        rendering_rules.form = form

        def _is_online_help_active(self):
            return True

        def _get_logged_user():
            return User('test', 'test', 'test')

        mocker.patch('tvb.interfaces.web.controllers.common.get_logged_user', _get_logged_user)
        mocker.patch.object(User, 'is_online_help_active', _is_online_help_active)

        html = self.dummy_renderer(rendering_rules.to_dict())
        soup = BeautifulSoup(html, features="html.parser")
        return soup
    def build(self, **model_params):
        # Load, normalize and configure connectivity
        if isinstance(self.connectivity, string_types):
            connectivity = Connectivity.from_file(self.connectivity)
        else:
            connectivity = self.connectivity
        if self.scale_connectivity_weights is not None:
            if isinstance(self.scale_connectivity_weights, string_types):
                connectivity.weights = connectivity.scaled_weights(
                    mode=self.scale_connectivity_weights)
            else:
                connectivity.weights /= self.scale_connectivity_weights
        if not self.delays_flag:
            connectivity.configure()  # to set speed
            # Given that
            # idelays = numpy.rint(delays / dt).astype(numpy.int32)
            # and delays = tract_lengths / speed
            connectivity.tract_lengths = 0.1 * self.dt * connectivity.speed
        connectivity.configure()

        # Build model:
        model = self.model(**model_params)

        # Build integrator
        integrator = self.integrator(dt=self.dt)
        integrator.noise.nsig = np.array(ensure_list(self.noise_strength))

        # Build monitors:
        assert Raw in self.monitors
        monitors = []
        for monitor in self.monitors:
            monitors.append(monitor(period=self.dt))
        monitors = tuple(monitors)

        # Build simulator
        simulator = Simulator()

        simulator._config = self.config
        simulator.connectivity = connectivity
        simulator.model = model
        simulator.integrator = integrator
        simulator.monitors = monitors

        return simulator
Example #25
0
    def test_sim_interface(self):
        """
        Test that the interface method returns all attributes required for the UI.
        """
        sim = Simulator()
        sim.trait.bound = 'attributes-only'
        current_dict = sim.interface['attributes']
        self.assertFalse(current_dict is None)
        attr = self._get_attr_description(current_dict, 'monitors')
        self.assertEquals('selectMultiple', attr['type'])
        self.assertEqual('TemporalAverage', attr['default'])

        attr = self._get_attr_description(current_dict, 'model')
        self.assertEquals('select', attr['type'])
        self.assertFalse('datatype' in attr)
        self.assertTrue('options' in attr)
        self.assertTrue(len(attr['options']) >= 5)
        for model_attr in attr['options']:
            self.assertTrue(model_attr['name'] is not None)
            self.assertTrue(model_attr['value'] is not None)
            self.assertTrue(model_attr['value'] in model_attr['class'])
            self.assertTrue(len(model_attr['attributes']) >= 3)

        attr = self._get_attr_description(current_dict, 'connectivity')
        self.assertTrue(attr['datatype'])
        self.assertEqual(Connectivity.__module__ + "." + Connectivity.__name__,
                         attr['type'])
        attr = self._get_attr_description(current_dict, 'surface')
        self.assertTrue(attr['datatype'])
        self.assertEqual(
            CorticalSurface.__module__ + "." + CorticalSurface.__name__,
            attr['type'])

        attr = self._get_attr_description(current_dict, 'conduction_speed')
        self.assertEquals(attr['type'], 'float')
        attr = self._get_attr_description(current_dict, 'simulation_length')
        self.assertEquals(attr['type'], 'float')
        self.assertEquals(attr['default'], 1000.0)
        self._validate_list(current_dict)
Example #26
0
    def test_sim_interface(self):
        """
        Test that the interface method returns all attributes required for the UI.
        """
        sim = Simulator()
        sim.trait.bound = 'attributes-only'
        current_dict = sim.interface['attributes']
        assert not current_dict is None
        attr = self._get_attr_description(current_dict, 'monitors')
        assert 'selectMultiple' == attr['type']
        assert 'TemporalAverage' == attr['default']

        attr = self._get_attr_description(current_dict, 'model')
        assert 'select' == attr['type']
        assert not 'datatype' in attr
        assert 'options' in attr
        assert len(attr['options']) >= 5
        for model_attr in attr['options']:
            assert model_attr['name'] is not None
            assert model_attr['value'] is not None
            assert model_attr['value'] in model_attr['class']
            assert len(model_attr['attributes']) >= 3

        attr = self._get_attr_description(current_dict, 'connectivity')
        assert attr['datatype']
        assert Connectivity.__module__ + "." + Connectivity.__name__ == attr[
            'type']
        attr = self._get_attr_description(current_dict, 'surface')
        assert attr['datatype']
        assert CorticalSurface.__module__ + "." + CorticalSurface.__name__ == attr[
            'type']

        attr = self._get_attr_description(current_dict, 'conduction_speed')
        assert attr['type'] == 'float'
        attr = self._get_attr_description(current_dict, 'simulation_length')
        assert attr['type'] == 'float'
        assert attr['default'] == 1000.0
        self._validate_list(current_dict)
class SimulatorAdapter(ABCAsynchronous):
    """
    Interface between the Simulator and the Framework.
    """
    _ui_name = "Simulation Core"

    algorithm = None

    available_models = get_traited_subclasses(Model)
    available_monitors = get_traited_subclasses(Monitor)
    available_integrators = get_traited_subclasses(Integrator)
    available_couplings = get_traited_subclasses(Coupling)


### Info: This are the possible results returned with this adapter from different Monitors.
###       When a list appears(surface & region), we actually return only one based on param surface being None or not.

#    MONITOR_RESULTS = {"Raw": [time_series.TimeSeriesRegion, time_series.TimeSeriesSurface],
#                       "SubSample": [time_series.TimeSeriesRegion, time_series.TimeSeriesSurface],
#                       "SpatialAverage": time_series.TimeSeries,
#                       "GlobalAverage": time_series.TimeSeries,
#                       "TemporalAverage": [time_series.TimeSeriesRegion, time_series.TimeSeriesSurface],
#                       "EEG": time_series.TimeSeriesEEG,
#                       "SphericalEEG": time_series.TimeSeriesEEG,
#                       "SphericalMEG": time_series.TimeSeriesMEG,
#                       "Bold": [time_series.TimeSeriesRegion, time_series.TimeSeriesSurface]}

    RESULTS_MAP = {time_series.TimeSeriesEEG: ["SphericalEEG", "EEG"],
                   time_series.TimeSeriesMEG: ["SphericalMEG"],  # Add here also "MEG" monitor reference
                   time_series.TimeSeries: ["GlobalAverage", "SpatialAverage"],
                   time_series.TimeSeriesSEEG: ["SEEG"]}

                   # time_series.TimeSeriesVolume: ["Bold"],
                   #SK:   For a number of reasons, it's probably best to avoid returning TimeSeriesVolume ,
                   #      from a simulation directly, instead just stick with the source, i.e. Region and Surface,
                   #      then later we can add a voxelisation "analyser" to produce TimeSeriesVolume on which Volume
                   #      based analysers and visualisers (which don't exist yet) can operate.

    # This is a list with the monitors that actually return multi dimensions for the state variable dimension.
    # We exclude from this for example EEG, MEG or Bold which return 
    HAVE_STATE_VARIABLES = ["GlobalAverage", "SpatialAverage", "Raw", "SubSample", "TemporalAverage"]


    def __init__(self):
        super(SimulatorAdapter, self).__init__()
        self.log.debug("%s: Initialized..." % str(self))


    def get_input_tree(self):
        """
        Return a list of lists describing the interface to the simulator. This
        is used by the GUI to generate the menus and fields necessary for
        defining a simulation.
        """
        sim = Simulator()
        sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
        result = sim.interface[self.INTERFACE_ATTRIBUTES]
        # We should add as hidden the Simulator State attribute.
        result.append({self.KEY_NAME: 'simulation_state', self.KEY_TYPE: SimulationState,
                       self.KEY_LABEL: "Continuation of", self.KEY_REQUIRED: False, self.KEY_UI_HIDE: True})
        return result


    def get_output(self):
        """
        :returns: list of classes for possible results of the Simulator.
        """
        return [time_series.TimeSeries]


    def configure(self, model, model_parameters, integrator, integrator_parameters, connectivity,
                  monitors, monitors_parameters=None, surface=None, surface_parameters=None, stimulus=None,
                  coupling=None, coupling_parameters=None, initial_conditions=None,
                  conduction_speed=None, simulation_length=0, simulation_state=None):
        """
        Make preparations for the adapter launch.
        """
        self.log.debug("available_couplings: %s..." % str(self.available_couplings))
        self.log.debug("coupling: %s..." % str(coupling))
        self.log.debug("coupling_parameters: %s..." % str(coupling_parameters))

        self.log.debug("%s: Initializing Model..." % str(self))
        noise_framework.build_noise(model_parameters)
        model_instance = self.available_models[str(model)](**model_parameters)
        self._validate_model_parameters(model_instance, connectivity, surface)

        self.log.debug("%s: Initializing Integration scheme..." % str(self))
        noise_framework.build_noise(integrator_parameters)
        integr = self.available_integrators[integrator](**integrator_parameters)

        self.log.debug("%s: Instantiating Monitors..." % str(self))
        monitors_list = []
        for monitor_name in monitors:
            if (monitors_parameters is not None) and (str(monitor_name) in monitors_parameters):
                current_monitor_parameters = monitors_parameters[str(monitor_name)]
                HRFKernelEquation.build_equation_from_dict('hrf_kernel', current_monitor_parameters, True)
                monitors_list.append(self.available_monitors[str(monitor_name)](**current_monitor_parameters))
            else:
                ### We have monitors without any UI settable parameter.
                monitors_list.append(self.available_monitors[str(monitor_name)]())

        if len(monitors) < 1:
            raise LaunchException("Can not launch operation without monitors selected !!!")

        self.log.debug("%s: Initializing Coupling..." % str(self))
        coupling_inst = self.available_couplings[str(coupling)](**coupling_parameters)

        self.log.debug("Initializing Cortex...")
        if self._is_surface_simulation(surface, surface_parameters):
            cortex_entity = Cortex(use_storage=False).populate_cortex(surface, surface_parameters)
            if cortex_entity.region_mapping_data.connectivity.number_of_regions != connectivity.number_of_regions:
                raise LaunchException("Incompatible RegionMapping -- Connectivity !!")
            if cortex_entity.region_mapping_data.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible RegionMapping -- Surface !!")
            select_loc_conn = cortex_entity.local_connectivity
            if select_loc_conn is not None and select_loc_conn.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible LocalConnectivity -- Surface !!")
        else:
            cortex_entity = None

        self.log.debug("%s: Instantiating requested simulator..." % str(self))
        connectivity.configure()
        self.algorithm = Simulator(connectivity=connectivity, coupling=coupling_inst, surface=cortex_entity,
                                   stimulus=stimulus, model=model_instance, integrator=integr,
                                   monitors=monitors_list, initial_conditions=initial_conditions,
                                   conduction_speed=conduction_speed)
        self.simulation_length = simulation_length
        self.log.debug("%s: Initializing storage..." % str(self))
        try:
            self.algorithm.configure()
            if simulation_state is not None:
                simulation_state.fill_into(self.algorithm)
        except ValueError, err:
            raise LaunchException("Failed to configure simulator due to invalid Input Values. It could be because "
                                  "of an incompatibility between different version of TVB code.", err)
    def _prepare_simulator_from_view_model(self, view_model):
        simulator = Simulator()
        simulator.gid = view_model.gid

        conn = self.load_traited_by_gid(view_model.connectivity)
        simulator.connectivity = conn

        simulator.conduction_speed = view_model.conduction_speed
        simulator.coupling = view_model.coupling

        rm_surface = None

        if view_model.surface:
            simulator.surface = Cortex()
            rm_index = self.load_entity_by_gid(
                view_model.surface.region_mapping_data.hex)
            rm = h5.load_from_index(rm_index)

            rm_surface_index = self.load_entity_by_gid(rm_index.fk_surface_gid)
            rm_surface = h5.load_from_index(rm_surface_index, CorticalSurface)
            rm.surface = rm_surface
            rm.connectivity = conn

            simulator.surface.region_mapping_data = rm
            if simulator.surface.local_connectivity:
                lc = self.load_traited_by_gid(
                    view_model.surface.local_connectivity)
                assert lc.surface.gid == rm_index.fk_surface_gid
                lc.surface = rm_surface
                simulator.surface.local_connectivity = lc

        if view_model.stimulus:
            stimulus_index = self.load_entity_by_gid(view_model.stimulus.hex)
            stimulus = h5.load_from_index(stimulus_index)
            simulator.stimulus = stimulus

            if isinstance(stimulus, StimuliSurface):
                simulator.stimulus.surface = rm_surface
            else:
                simulator.stimulus.connectivity = simulator.connectivity

        simulator.model = view_model.model
        simulator.integrator = view_model.integrator
        simulator.initial_conditions = view_model.initial_conditions
        simulator.monitors = view_model.monitors
        simulator.simulation_length = view_model.simulation_length

        # TODO: why not load history here?
        # if view_model.history:
        #     history_index = dao.get_datatype_by_gid(view_model.history.hex)
        #     history = h5.load_from_index(history_index)
        #     assert isinstance(history, SimulationHistory)
        #     history.fill_into(self.algorithm)
        return simulator
 def get_traited_datatype(self):
     return Simulator()
Example #30
0
 def build(connectivity=None, simulation_length=100):
     if not connectivity:
         connectivity = connectivity_factory(2)
     return Simulator(connectivity=connectivity,
                      surface=None,
                      simulation_length=simulation_length)
class SimulatorAdapter(ABCAsynchronous):
    """
    Interface between the Simulator and the Framework.
    """
    _ui_name = "Simulation Core"

    algorithm = None

    available_models = get_traited_subclasses(Model)
    available_monitors = get_traited_subclasses(Monitor)
    available_integrators = get_traited_subclasses(Integrator)
    available_couplings = get_traited_subclasses(Coupling)

    # This is a list with the monitors that actually return multi dimensions for the state variable dimension.
    # We exclude from this for example EEG, MEG or Bold which return 
    HAVE_STATE_VARIABLES = ["GlobalAverage", "SpatialAverage", "Raw", "SubSample", "TemporalAverage"]


    def __init__(self):
        super(SimulatorAdapter, self).__init__()
        self.log.debug("%s: Initialized..." % str(self))

    def get_input_tree2(self):
        sim = Simulator()
        sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
        result = sim.interface_experimental
        return result

    def get_input_tree(self):
        """
        Return a list of lists describing the interface to the simulator. This
        is used by the GUI to generate the menus and fields necessary for
        defining a simulation.
        """
        sim = Simulator()
        sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
        result = sim.interface[self.INTERFACE_ATTRIBUTES]
        # We should add as hidden the Simulator State attribute.
        result.append({self.KEY_NAME: 'simulation_state',
                       self.KEY_TYPE: 'tvb.datatypes.simulation_state.SimulationState',
                       self.KEY_LABEL: "Continuation of", self.KEY_REQUIRED: False, self.KEY_UI_HIDE: True})
        return result


    def get_output(self):
        """
        :returns: list of classes for possible results of the Simulator.
        """
        return [time_series.TimeSeries]


    def configure(self, model, model_parameters, integrator, integrator_parameters, connectivity,
                  monitors, monitors_parameters=None, surface=None, surface_parameters=None, stimulus=None,
                  coupling=None, coupling_parameters=None, initial_conditions=None,
                  conduction_speed=None, simulation_length=0, simulation_state=None):
        """
        Make preparations for the adapter launch.
        """
        self.log.debug("available_couplings: %s..." % str(self.available_couplings))
        self.log.debug("coupling: %s..." % str(coupling))
        self.log.debug("coupling_parameters: %s..." % str(coupling_parameters))

        self.log.debug("%s: Initializing Model..." % str(self))
        noise_framework.build_noise(model_parameters)
        model_instance = self.available_models[str(model)](**model_parameters)
        self._validate_model_parameters(model_instance, connectivity, surface)

        self.log.debug("%s: Initializing Integration scheme..." % str(self))
        noise_framework.build_noise(integrator_parameters)
        integr = self.available_integrators[integrator](**integrator_parameters)

        self.log.debug("%s: Instantiating Monitors..." % str(self))
        monitors_list = []
        for monitor_name in monitors:
            if (monitors_parameters is not None) and (str(monitor_name) in monitors_parameters):
                current_monitor_parameters = monitors_parameters[str(monitor_name)]
                HRFKernelEquation.build_equation_from_dict('hrf_kernel', current_monitor_parameters, True)
                monitors_list.append(self.available_monitors[str(monitor_name)](**current_monitor_parameters))
            else:
                ### We have monitors without any UI settable parameter.
                monitors_list.append(self.available_monitors[str(monitor_name)]())

        if len(monitors) < 1:
            raise LaunchException("Can not launch operation without monitors selected !!!")

        self.log.debug("%s: Initializing Coupling..." % str(self))
        coupling_inst = self.available_couplings[str(coupling)](**coupling_parameters)

        self.log.debug("Initializing Cortex...")
        if self._is_surface_simulation(surface, surface_parameters):
            cortex_entity = Cortex(use_storage=False).populate_cortex(surface, surface_parameters)
            if cortex_entity.region_mapping_data.connectivity.number_of_regions != connectivity.number_of_regions:
                raise LaunchException("Incompatible RegionMapping -- Connectivity !!")
            if cortex_entity.region_mapping_data.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible RegionMapping -- Surface !!")
            select_loc_conn = cortex_entity.local_connectivity
            if select_loc_conn is not None and select_loc_conn.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible LocalConnectivity -- Surface !!")
        else:
            cortex_entity = None

        self.log.debug("%s: Instantiating requested simulator..." % str(self))

        if conduction_speed not in (0.0, None):
            connectivity.speed = numpy.array([conduction_speed])
        else:
            raise LaunchException("conduction speed cannot be 0 or missing")

        self.algorithm = Simulator(connectivity=connectivity, coupling=coupling_inst, surface=cortex_entity,
                                   stimulus=stimulus, model=model_instance, integrator=integr,
                                   monitors=monitors_list, initial_conditions=initial_conditions,
                                   conduction_speed=conduction_speed)
        self.simulation_length = simulation_length
        self.log.debug("%s: Initializing storage..." % str(self))
        try:
            self.algorithm.preconfigure()
        except ValueError as err:
            raise LaunchException("Failed to configure simulator due to invalid Input Values. It could be because "
                                  "of an incompatibility between different version of TVB code.", err)


    def get_required_memory_size(self, **kwargs):
        """
        Return the required memory to run this algorithm.
        """
        return self.algorithm.memory_requirement()


    def get_required_disk_size(self, **kwargs):
        """
        Return the required disk size this algorithm estimates it will take. (in kB)
        """
        return self.algorithm.storage_requirement(self.simulation_length) / 2 ** 10
    
    
    def get_execution_time_approximation(self, **kwargs):
        """
        Method should approximate based on input arguments, the time it will take for the operation 
        to finish (in seconds).
        """
        # This is just a brute approx so cluster nodes won't kill operation before
        # it's finished. This should be done with a higher grade of sensitivity
        # Magic number connecting simulation length to simulation computation time
        # This number should as big as possible, as long as it is still realistic, to
        magic_number = 6.57e-06     # seconds
        approx_number_of_nodes = 500
        approx_nvar = 15
        approx_modes = 15

        simulation_length = int(float(kwargs['simulation_length']))
        approx_integrator_dt = float(kwargs['integrator_parameters']['dt'])

        if approx_integrator_dt == 0.0:
            approx_integrator_dt = 1.0

        if 'surface' in kwargs and kwargs['surface'] is not None and kwargs['surface'] != '':
            approx_number_of_nodes *= approx_number_of_nodes

        estimation = magic_number * approx_number_of_nodes * approx_nvar * approx_modes * simulation_length \
            / approx_integrator_dt

        return max(int(estimation), 1)


    def _try_find_mapping(self, mapping_class, connectivity_gid):
        """
        Try to find a DataType instance of class "mapping_class", linked to the given Connectivity.
        Entities in the current project will have priority.

        :param mapping_class: DT class, with field "_connectivity" on it
        :param connectivity_gid: GUID
        :return: None or instance of "mapping_class"
        """

        dts_list = dao.get_generic_entity(mapping_class, connectivity_gid, '_connectivity')
        if len(dts_list) < 1:
            return None

        for dt in dts_list:
            dt_operation = dao.get_operation_by_id(dt.fk_from_operation)
            if dt_operation.fk_launched_in == self.current_project_id:
                return dt
        return dts_list[0]



    def launch(self, model, model_parameters, integrator, integrator_parameters, connectivity,
               monitors, monitors_parameters=None, surface=None, surface_parameters=None, stimulus=None,
               coupling=None, coupling_parameters=None, initial_conditions=None,
               conduction_speed=None, simulation_length=0, simulation_state=None):
        """
        Called from the GUI to launch a simulation.
          *: string class name of chosen model, etc...
          *_parameters: dictionary of parameters for chosen model, etc...
          connectivity: tvb.datatypes.connectivity.Connectivity object.
          surface: tvb.datatypes.surfaces.CorticalSurface: or None.
          stimulus: tvb.datatypes.patters.* object
        """
        result_datatypes = dict()
        start_time = self.algorithm.current_step * self.algorithm.integrator.dt

        self.algorithm.configure(full_configure=False)
        if simulation_state is not None:
            simulation_state.fill_into(self.algorithm)

        region_map = self._try_find_mapping(region_mapping.RegionMapping, connectivity.gid)
        region_volume_map = self._try_find_mapping(region_mapping.RegionVolumeMapping, connectivity.gid)

        for monitor in self.algorithm.monitors:
            m_name = monitor.__class__.__name__
            ts = monitor.create_time_series(self.storage_path, connectivity, surface, region_map, region_volume_map)
            self.log.debug("Monitor %s created the TS %s" % (m_name, ts))
            # Now check if the monitor will return results for each state variable, in which case store
            # the labels for these state variables.
            # todo move these into monitors as well
            #   and replace check if ts.user_tag_1 with something better (e.g. pre_ex & post)
            state_variable_dimension_name = ts.labels_ordering[1]
            if ts.user_tag_1:
                ts.labels_dimensions[state_variable_dimension_name] = ts.user_tag_1.split(';')

            elif m_name in self.HAVE_STATE_VARIABLES:
                selected_vois = [self.algorithm.model.variables_of_interest[idx] for idx in monitor.voi]
                ts.labels_dimensions[state_variable_dimension_name] = selected_vois

            ts.start_time = start_time
            result_datatypes[m_name] = ts

        #### Create Simulator State entity and persist it in DB. H5 file will be empty now.
        if not self._is_group_launch():
            simulation_state = SimulationState(storage_path=self.storage_path)
            self._capture_operation_results([simulation_state])

        ### Run simulation
        self.log.debug("%s: Starting simulation..." % str(self))
        for result in self.algorithm(simulation_length=simulation_length):
            for j, monitor in enumerate(monitors):
                if result[j] is not None:
                    result_datatypes[monitor].write_time_slice([result[j][0]])
                    result_datatypes[monitor].write_data_slice([result[j][1]])

        self.log.debug("%s: Completed simulation, starting to store simulation state " % str(self))
        ### Populate H5 file for simulator state. This step could also be done while running sim, in background.
        if not self._is_group_launch():
            simulation_state.populate_from(self.algorithm)
            self._capture_operation_results([simulation_state])

        self.log.debug("%s: Simulation state persisted, returning results " % str(self))
        final_results = []
        for result in result_datatypes.values():
            result.close_file()
            final_results.append(result)
        self.log.info("%s: Adapter simulation finished!!" % str(self))
        return final_results


    def _validate_model_parameters(self, model_instance, connectivity, surface):
        """
        Checks if the size of the model parameters is set correctly.
        """
        ui_configurable_params = model_instance.ui_configurable_parameters
        for param in ui_configurable_params:
            param_value = eval('model_instance.' + param)
            if isinstance(param_value, numpy.ndarray):
                if len(param_value) == 1 or connectivity is None:
                    continue
                if surface is not None:
                    if (len(param_value) != surface.number_of_vertices
                            and len(param_value) != connectivity.number_of_regions):
                        msg = str(surface.number_of_vertices) + ' or ' + str(connectivity.number_of_regions)
                        msg = self._get_exception_message(param, msg, len(param_value))
                        self.log.error(msg)
                        raise LaunchException(msg)
                elif len(param_value) != connectivity.number_of_regions:
                    msg = self._get_exception_message(param, connectivity.number_of_regions, len(param_value))
                    self.log.error(msg)
                    raise LaunchException(msg)


    @staticmethod
    def _get_exception_message(param_name, expected_size, actual_size):
        """
        Creates the message that will be displayed to the user when the size of a model parameter is incorrect.
        """
        msg = "The length of the parameter '" + param_name + "' is not correct."
        msg += " It is expected to be an array of length " + str(expected_size) + "."
        msg += " It is an array of length " + str(actual_size) + "."
        return msg

    @staticmethod
    def _is_surface_simulation(surface, surface_parameters):
        """
        Is this a surface simulation?
        """
        return surface is not None and surface_parameters is not None
    def configure(self, model, model_parameters, integrator, integrator_parameters, connectivity,
                  monitors, monitors_parameters=None, surface=None, surface_parameters=None, stimulus=None,
                  coupling=None, coupling_parameters=None, initial_conditions=None,
                  conduction_speed=None, simulation_length=0, simulation_state=None):
        """
        Make preparations for the adapter launch.
        """
        self.log.debug("available_couplings: %s..." % str(self.available_couplings))
        self.log.debug("coupling: %s..." % str(coupling))
        self.log.debug("coupling_parameters: %s..." % str(coupling_parameters))

        self.log.debug("%s: Initializing Model..." % str(self))
        noise_framework.build_noise(model_parameters)
        model_instance = self.available_models[str(model)](**model_parameters)
        self._validate_model_parameters(model_instance, connectivity, surface)

        self.log.debug("%s: Initializing Integration scheme..." % str(self))
        noise_framework.build_noise(integrator_parameters)
        integr = self.available_integrators[integrator](**integrator_parameters)

        self.log.debug("%s: Instantiating Monitors..." % str(self))
        monitors_list = []
        for monitor_name in monitors:
            if (monitors_parameters is not None) and (str(monitor_name) in monitors_parameters):
                current_monitor_parameters = monitors_parameters[str(monitor_name)]
                HRFKernelEquation.build_equation_from_dict('hrf_kernel', current_monitor_parameters, True)
                monitors_list.append(self.available_monitors[str(monitor_name)](**current_monitor_parameters))
            else:
                ### We have monitors without any UI settable parameter.
                monitors_list.append(self.available_monitors[str(monitor_name)]())

        if len(monitors) < 1:
            raise LaunchException("Can not launch operation without monitors selected !!!")

        self.log.debug("%s: Initializing Coupling..." % str(self))
        coupling_inst = self.available_couplings[str(coupling)](**coupling_parameters)

        self.log.debug("Initializing Cortex...")
        if self._is_surface_simulation(surface, surface_parameters):
            cortex_entity = Cortex(use_storage=False).populate_cortex(surface, surface_parameters)
            if cortex_entity.region_mapping_data.connectivity.number_of_regions != connectivity.number_of_regions:
                raise LaunchException("Incompatible RegionMapping -- Connectivity !!")
            if cortex_entity.region_mapping_data.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible RegionMapping -- Surface !!")
            select_loc_conn = cortex_entity.local_connectivity
            if select_loc_conn is not None and select_loc_conn.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible LocalConnectivity -- Surface !!")
        else:
            cortex_entity = None

        self.log.debug("%s: Instantiating requested simulator..." % str(self))

        if conduction_speed not in (0.0, None):
            connectivity.speed = numpy.array([conduction_speed])
        else:
            raise LaunchException("conduction speed cannot be 0 or missing")

        self.algorithm = Simulator(connectivity=connectivity, coupling=coupling_inst, surface=cortex_entity,
                                   stimulus=stimulus, model=model_instance, integrator=integr,
                                   monitors=monitors_list, initial_conditions=initial_conditions,
                                   conduction_speed=conduction_speed)
        self.simulation_length = simulation_length
        self.log.debug("%s: Initializing storage..." % str(self))
        try:
            self.algorithm.preconfigure()
        except ValueError as err:
            raise LaunchException("Failed to configure simulator due to invalid Input Values. It could be because "
                                  "of an incompatibility between different version of TVB code.", err)
Example #33
0
 def get_input_tree2(self):
     sim = Simulator()
     sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
     result = sim.interface_experimental
     return result
class SimulatorAdapter(ABCAsynchronous):
    """
    Interface between the Simulator and the Framework.
    """
    _ui_name = "Simulation Core"

    algorithm = None

    available_models = get_traited_subclasses(Model)
    available_monitors = get_traited_subclasses(Monitor)
    available_integrators = get_traited_subclasses(Integrator)
    available_couplings = get_traited_subclasses(Coupling)

    # This is a list with the monitors that actually return multi dimensions for the state variable dimension.
    # We exclude from this for example EEG, MEG or Bold which return 
    HAVE_STATE_VARIABLES = ["GlobalAverage", "SpatialAverage", "Raw", "SubSample", "TemporalAverage"]


    def __init__(self):
        super(SimulatorAdapter, self).__init__()
        self.log.debug("%s: Initialized..." % str(self))


    def get_input_tree(self):
        """
        Return a list of lists describing the interface to the simulator. This
        is used by the GUI to generate the menus and fields necessary for
        defining a simulation.
        """
        sim = Simulator()
        sim.trait.bound = self.INTERFACE_ATTRIBUTES_ONLY
        result = sim.interface[self.INTERFACE_ATTRIBUTES]
        # We should add as hidden the Simulator State attribute.
        result.append({self.KEY_NAME: 'simulation_state', self.KEY_TYPE: SimulationState,
                       self.KEY_LABEL: "Continuation of", self.KEY_REQUIRED: False, self.KEY_UI_HIDE: True})
        return result


    def get_output(self):
        """
        :returns: list of classes for possible results of the Simulator.
        """
        return [time_series.TimeSeries]


    def configure(self, model, model_parameters, integrator, integrator_parameters, connectivity,
                  monitors, monitors_parameters=None, surface=None, surface_parameters=None, stimulus=None,
                  coupling=None, coupling_parameters=None, initial_conditions=None,
                  conduction_speed=None, simulation_length=0, simulation_state=None):
        """
        Make preparations for the adapter launch.
        """
        self.log.debug("available_couplings: %s..." % str(self.available_couplings))
        self.log.debug("coupling: %s..." % str(coupling))
        self.log.debug("coupling_parameters: %s..." % str(coupling_parameters))

        self.log.debug("%s: Initializing Model..." % str(self))
        noise_framework.build_noise(model_parameters)
        model_instance = self.available_models[str(model)](**model_parameters)
        self._validate_model_parameters(model_instance, connectivity, surface)

        self.log.debug("%s: Initializing Integration scheme..." % str(self))
        noise_framework.build_noise(integrator_parameters)
        integr = self.available_integrators[integrator](**integrator_parameters)

        self.log.debug("%s: Instantiating Monitors..." % str(self))
        monitors_list = []
        for monitor_name in monitors:
            if (monitors_parameters is not None) and (str(monitor_name) in monitors_parameters):
                current_monitor_parameters = monitors_parameters[str(monitor_name)]
                HRFKernelEquation.build_equation_from_dict('hrf_kernel', current_monitor_parameters, True)
                monitors_list.append(self.available_monitors[str(monitor_name)](**current_monitor_parameters))
            else:
                ### We have monitors without any UI settable parameter.
                monitors_list.append(self.available_monitors[str(monitor_name)]())

        if len(monitors) < 1:
            raise LaunchException("Can not launch operation without monitors selected !!!")

        self.log.debug("%s: Initializing Coupling..." % str(self))
        coupling_inst = self.available_couplings[str(coupling)](**coupling_parameters)

        self.log.debug("Initializing Cortex...")
        if self._is_surface_simulation(surface, surface_parameters):
            cortex_entity = Cortex(use_storage=False).populate_cortex(surface, surface_parameters)
            if cortex_entity.region_mapping_data.connectivity.number_of_regions != connectivity.number_of_regions:
                raise LaunchException("Incompatible RegionMapping -- Connectivity !!")
            if cortex_entity.region_mapping_data.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible RegionMapping -- Surface !!")
            select_loc_conn = cortex_entity.local_connectivity
            if select_loc_conn is not None and select_loc_conn.surface.number_of_vertices != surface.number_of_vertices:
                raise LaunchException("Incompatible LocalConnectivity -- Surface !!")
        else:
            cortex_entity = None

        self.log.debug("%s: Instantiating requested simulator..." % str(self))

        if conduction_speed not in (0.0, None):
            connectivity.speed = numpy.array([conduction_speed])
        else:
            raise LaunchException("conduction speed cannot be 0 or missing")

        self.algorithm = Simulator(connectivity=connectivity, coupling=coupling_inst, surface=cortex_entity,
                                   stimulus=stimulus, model=model_instance, integrator=integr,
                                   monitors=monitors_list, initial_conditions=initial_conditions,
                                   conduction_speed=conduction_speed)
        self.simulation_length = simulation_length
        self.log.debug("%s: Initializing storage..." % str(self))
        try:
            self.algorithm.preconfigure()
        except ValueError, err:
            raise LaunchException("Failed to configure simulator due to invalid Input Values. It could be because "
                                  "of an incompatibility between different version of TVB code.", err)