コード例 #1
0
    def index(self):
        current_user_id = common.get_logged_user().id
        # In case the number of dynamics gets big we should add a filter in the ui.
        dynamics = dao.get_dynamics_for_user(current_user_id)

        if not dynamics:
            return self.no_dynamics_page()

        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        des = SerializationManager(burst_config)

        connectivity = des.get_connectivity()
        params = ConnectivityViewer.get_connectivity_parameters(connectivity)

        params.update({
            'title':
            'Model parameters',
            'mainContent':
            'burst/model_param_region',
            'isSingleMode':
            True,
            'submit_parameters_url':
            '/burst/modelparameters/regions/submit_model_parameters',
            'dynamics':
            dynamics,
            'dynamics_json':
            self._dynamics_json(dynamics),
            'initial_dynamic_ids':
            json.dumps(burst_config.dynamic_ids)
        })

        return self.fill_default_attributes(params, 'regionmodel')
    def index(self):
        current_user_id = common.get_logged_user().id
        # In case the number of dynamics gets big we should add a filter in the ui.
        dynamics = dao.get_dynamics_for_user(current_user_id)

        if not dynamics:
            return self.no_dynamics_page()

        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        des = SerializationManager(burst_config)

        connectivity = des.get_connectivity()

        if connectivity is None:
            msg = 'You have to select a connectivity before setting up the region Model. '
            common.set_error_message(msg)
            raise ValueError(msg)

        params = ConnectivityViewer.get_connectivity_parameters(connectivity)

        params.update({
            'title': 'Model parameters',
            'mainContent': 'burst/model_param_region',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters',
            'dynamics': dynamics,
            'dynamics_json': self._dynamics_json(dynamics),
            'initial_dynamic_ids': json.dumps(burst_config.dynamic_ids)
        })

        return self.fill_default_attributes(params, 'regionmodel')
コード例 #3
0
    def index(self):
        current_user_id = common.get_logged_user().id
        # In case the number of dynamics gets big we should add a filter in the ui.
        dynamics = dao.get_dynamics_for_user(current_user_id)

        if not dynamics:
            return self.no_dynamics_page()

        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        des = SerializationManager(burst_config)

        connectivity = des.get_connectivity()

        if connectivity is None:
            msg = 'You have to select a connectivity before setting up the region Model. '
            common.set_error_message(msg)
            raise ValueError(msg)

        current_project = common.get_current_project()
        file_handler = FilesHelper()
        conn_path = file_handler.get_project_folder(current_project, str(connectivity.fk_from_operation))

        params = ConnectivityViewer.get_connectivity_parameters(connectivity, conn_path)

        params.update({
            'title': 'Model parameters',
            'mainContent': 'burst/model_param_region',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters',
            'dynamics': dynamics,
            'dynamics_json': self._dynamics_json(dynamics),
            'initial_dynamic_ids': json.dumps(burst_config.dynamic_ids)
        })

        return self.fill_default_attributes(params, 'regionmodel')
コード例 #4
0
    def get_data_from_burst_configuration(self):
        """
        Returns the model and surface instances from the burst configuration.
        """
        des = SerializationManager(
            common.get_from_session(common.KEY_BURST_CONFIG))
        ### Read from session current burst-configuration
        if des.conf is None:
            return None, None
        if des.has_model_pse_ranges():
            common.set_error_message(
                "When configuring model parameters you are not allowed to specify range values."
            )
            raise cherrypy.HTTPRedirect("/burst/")

        try:
            model, integrator = des.make_model_and_integrator()
        except Exception:
            self.logger.exception(
                "Some of the provided parameters have an invalid value.")
            common.set_error_message(
                "Some of the provided parameters have an invalid value.")
            raise cherrypy.HTTPRedirect("/burst/")

        surface = des.get_surface()
        return model, surface
コード例 #5
0
    def submit_model_parameters(self, node_values):
        """
        Collects the model parameters values from all the models used for the connectivity nodes.
        Assumes that the array indices are consistent with the node order.
        """
        dynamic_ids = json.loads(node_values)
        dynamics = [dao.get_dynamic(did) for did in dynamic_ids]

        for dynamic in dynamics[1:]:
            if dynamic.model_class != dynamics[0].model_class:
                raise Exception("All dynamics must have the same model type")

        model_name = dynamics[0].model_class
        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        simulator_config = common.get_from_session(common.KEY_SIMULATOR_CONFIG)

        # update model parameters in burst config
        des = SerializationManager(simulator_config)
        model_parameters = [
            dict(json.loads(d.model_parameters)) for d in dynamics
        ]
        des.write_model_parameters(model_name, model_parameters)

        # update dynamic ids in burst config
        burst_config.dynamic_ids = json.dumps(dynamic_ids)

        # Update in session the simulator configuration and the current form URL in wizzard for burst-page.
        common.add2session(common.KEY_BURST_CONFIG, burst_config)
        common.add2session(common.KEY_LAST_LOADED_FORM_URL,
                           SimulatorWizzardURLs.SET_INTEGRATOR_URL)
        raise cherrypy.HTTPRedirect("/burst/")
コード例 #6
0
    def submit_model_parameters(self, node_values):
        """
        Collects the model parameters values from all the models used for the connectivity nodes.
        Assumes that the array indices are consistent with the node order.
        """
        dynamic_ids = json.loads(node_values)
        dynamics = [dao.get_dynamic(did) for did in dynamic_ids]

        for dynamic in dynamics[1:]:
            if dynamic.model_class != dynamics[0].model_class:
                raise Exception("All dynamics must have the same model type")

        model_name = dynamics[0].model_class
        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)

        # update model parameters in burst config
        des = SerializationManager(burst_config)
        model_parameters = [dict(json.loads(d.model_parameters)) for d in dynamics]
        des.write_model_parameters(model_name, model_parameters)

        # update dynamic ids in burst config
        burst_config.dynamic_ids = dynamic_ids

        # Update in session BURST configuration for burst-page.
        # todo was this needed? as the burst config in session has already been changed
        # common.add2session(common.KEY_BURST_CONFIG, burst_config.clone())
        raise cherrypy.HTTPRedirect("/burst/")
コード例 #7
0
    def submit_model_parameters(self, node_values):
        """
        Collects the model parameters values from all the models used for the connectivity nodes.
        Assumes that the array indices are consistent with the node order.
        """
        dynamic_ids = json.loads(node_values)
        dynamics = [dao.get_dynamic(did) for did in dynamic_ids]

        for dynamic in dynamics[1:]:
            if dynamic.model_class != dynamics[0].model_class:
                raise Exception("All dynamics must have the same model type")

        model_name = dynamics[0].model_class
        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)

        # update model parameters in burst config
        des = SerializationManager(burst_config)
        model_parameters = [
            dict(json.loads(d.model_parameters)) for d in dynamics
        ]
        des.write_model_parameters(model_name, model_parameters)

        # update dynamic ids in burst config
        burst_config.dynamic_ids = dynamic_ids

        # Update in session BURST configuration for burst-page.
        # todo was this needed? as the burst config in session has already been changed
        #common.add2session(common.KEY_BURST_CONFIG, burst_config.clone())
        raise cherrypy.HTTPRedirect("/burst/")
コード例 #8
0
    def index(self):
        current_user_id = common.get_logged_user().id
        # In case the number of dynamics gets big we should add a filter in the ui.
        dynamics = dao.get_dynamics_for_user(current_user_id)

        if not dynamics:
            return self.no_dynamics_page()

        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        des = SerializationManager(burst_config)

        connectivity = des.get_connectivity()
        params = ConnectivityViewer.get_connectivity_parameters(connectivity)

        params.update(
            {
                "title": "Model parameters",
                "mainContent": "burst/model_param_region",
                "isSingleMode": True,
                "submit_parameters_url": "/burst/modelparameters/regions/submit_model_parameters",
                "dynamics": dynamics,
                "dynamics_json": self._dynamics_json(dynamics),
                "initial_dynamic_ids": json.dumps(burst_config.dynamic_ids),
            }
        )

        return self.fill_default_attributes(params, "regionmodel")
コード例 #9
0
    def index(self):
        des = SerializationManager(
            common.get_from_session(common.KEY_BURST_CONFIG))
        connectivity = des.get_connectivity()
        model, integrator = des.make_model_and_integrator()

        state_vars = model.state_variables
        noise_values = self.init_noise_config_values(model, integrator,
                                                     connectivity)
        initial_noise = self.group_noise_array_by_state_var(
            noise_values, state_vars, connectivity.number_of_regions)

        current_project = common.get_current_project()
        file_handler = FilesHelper()
        conn_path = file_handler.get_project_folder(
            current_project, str(connectivity.fk_from_operation))

        params = ConnectivityViewer.get_connectivity_parameters(
            connectivity, conn_path)
        params.update({
            'title': 'Noise configuration',
            'mainContent': 'burst/noise',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/noise/submit',
            'stateVars': state_vars,
            'stateVarsJson': json.dumps(state_vars),
            'noiseInputValues': initial_noise[0],
            'initialNoiseValues': json.dumps(initial_noise)
        })
        return self.fill_default_attributes(params, 'regionmodel')
コード例 #10
0
 def submit(self, node_values):
     """
     Submit noise dispersions
     :param node_values: A map from state variable names to noise dispersion arrays. Ex {'V': [1,2...74]}
     """
     des = SerializationManager(common.get_from_session(common.KEY_BURST_CONFIG))
     des.write_noise_parameters(json.loads(node_values))
     raise cherrypy.HTTPRedirect("/burst/")
コード例 #11
0
 def submit(self, node_values):
     """
     Submit noise dispersions
     :param node_values: A map from state variable names to noise dispersion arrays. Ex {'V': [1,2...74]}
     """
     des = SerializationManager(self.simulator_context.simulator)
     des.write_noise_parameters(json.loads(node_values))
     self.simulator_context.add_last_loaded_form_url_to_session(SimulatorWizzardURLs.SET_NOISE_PARAMS_URL)
     raise cherrypy.HTTPRedirect("/burst/")
コード例 #12
0
 def submit(self, node_values):
     """
     Submit noise dispersions
     :param node_values: A map from state variable names to noise dispersion arrays. Ex {'V': [1,2...74]}
     """
     des = SerializationManager(
         common.get_from_session(common.KEY_BURST_CONFIG))
     des.write_noise_parameters(json.loads(node_values))
     raise cherrypy.HTTPRedirect("/burst/")
コード例 #13
0
 def submit(self, node_values):
     """
     Submit noise dispersions
     :param node_values: A map from state variable names to noise dispersion arrays. Ex {'V': [1,2...74]}
     """
     des = SerializationManager(common.get_from_session(common.KEY_SIMULATOR_CONFIG))
     des.write_noise_parameters(json.loads(node_values))
     common.add2session(common.KEY_LAST_LOADED_FORM_URL, SimulatorWizzardURLs.SET_NOISE_PARAMS_URL)
     raise cherrypy.HTTPRedirect("/burst/")
コード例 #14
0
    def setUp(self):
        _, self.connectivity = DatatypesFactory().create_connectivity()
        self.test_user = TestFactory.create_user(username="******")
        self.test_project = TestFactory.create_project(self.test_user, "Test")

        burst_conf = BurstConfiguration(self.test_project.id)
        burst_conf._simulator_configuration = self.CONF_HOPFIELD_HEUN_STOCH_RANGES
        burst_conf.prepare_after_load()
        burst_conf.simulator_configuration['connectivity'] = {'value': self.connectivity.gid}

        self.s_manager = SerializationManager(burst_conf)
        self.empty_manager = SerializationManager(BurstConfiguration(None))
コード例 #15
0
    def transactional_setup_method(self):
        _, self.connectivity = DatatypesFactory().create_connectivity()
        self.test_user = TestFactory.create_user(username="******")
        self.test_project = TestFactory.create_project(self.test_user, "Test")

        burst_conf = BurstConfiguration(self.test_project.id)
        burst_conf._simulator_configuration = self.CONF_HOPFIELD_HEUN_STOCH_RANGES
        burst_conf.prepare_after_load()
        burst_conf.simulator_configuration['connectivity'] = {'value': self.connectivity.gid}

        self.s_manager = SerializationManager(burst_conf)
        self.empty_manager = SerializationManager(BurstConfiguration(None))
コード例 #16
0
    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)
コード例 #17
0
    def index(self):
        des = SerializationManager(self.simulator_context.simulator)
        conn_idx = load.load_entity_by_gid(des.conf.connectivity)
        model = des.conf.model
        integrator = des.conf.integrator

        state_vars = model.state_variables
        noise_values = self.init_noise_config_values(model, integrator, conn_idx)
        initial_noise = self.group_noise_array_by_state_var(noise_values, state_vars, conn_idx.number_of_regions)

        current_project = common.get_current_project()

        params = ConnectivityViewer.get_connectivity_parameters(conn_idx, current_project.name,
                                                                str(conn_idx.fk_from_operation))
        params.update({
            'title': 'Noise configuration',
            'mainContent': 'burst/noise',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/noise/submit',
            'stateVars': state_vars,
            'stateVarsJson': json.dumps(state_vars),
            'noiseInputValues': initial_noise[0],
            'initialNoiseValues': json.dumps(initial_noise)
        })
        return self.fill_default_attributes(params, 'regionmodel')
コード例 #18
0
 def test_group_parameter_values_by_name(self):
     gp = SerializationManager.group_parameter_values_by_name([{
         "a": 2.0,
         'b': 1.0
     }, {
         "a": 3.0,
         'b': 7.0
     }])
     assert {'a': [2.0, 3.0], 'b': [1.0, 7.0]} == gp
    def get_data_from_burst_configuration(self):
        """
        Returns the model and surface instances from the burst configuration.
        """
        des = SerializationManager(common.get_from_session(common.KEY_BURST_CONFIG))
        ### Read from session current burst-configuration
        if des.conf is None:
            return None, None
        if des.has_model_pse_ranges():
            common.set_error_message("When configuring model parameters you are not allowed to specify range values.")
            raise cherrypy.HTTPRedirect("/burst/")

        try:
            model, integrator = des.make_model_and_integrator()
        except Exception:
            self.logger.exception("Some of the provided parameters have an invalid value.")
            common.set_error_message("Some of the provided parameters have an invalid value.")
            raise cherrypy.HTTPRedirect("/burst/")

        surface = des.get_surface()
        return model, surface
コード例 #20
0
    def index(self):
        des = SerializationManager(common.get_from_session(common.KEY_BURST_CONFIG))
        connectivity = des.get_connectivity()
        model, integrator = des.make_model_and_integrator()

        state_vars = model.state_variables
        noise_values = self.init_noise_config_values(model, integrator, connectivity)
        initial_noise = self.group_noise_array_by_state_var(noise_values, state_vars, connectivity.number_of_regions)

        params = ConnectivityViewer.get_connectivity_parameters(connectivity)
        params.update({
            'title': 'Noise configuration',
            'mainContent': 'burst/noise',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/noise/submit',
            'stateVars': state_vars,
            'stateVarsJson' : json.dumps(state_vars),
            'noiseInputValues' : initial_noise[0],
            'initialNoiseValues': json.dumps(initial_noise)
        })
        return self.fill_default_attributes(params, 'regionmodel')
コード例 #21
0
    def get_data_from_burst_configuration(self):
        """
        Returns the model and surface instances from the burst configuration.
        """
        des = SerializationManager(self.simulator_context.simulator)
        ### Read from session current burst-configuration
        if des.conf is None:
            return None, None
        # if des.has_model_pse_ranges():
        #     common.set_error_message("When configuring model parameters you are not allowed to specify range values.")
        #     raise cherrypy.HTTPRedirect("/burst/")

        try:
            model = des.conf.model
        except Exception:
            self.logger.exception(
                "Some of the provided parameters have an invalid value.")
            common.set_error_message(
                "Some of the provided parameters have an invalid value.")
            raise cherrypy.HTTPRedirect("/burst/")

        cortex = des.conf.surface
        return model, cortex
コード例 #22
0
class SerializationManagerTest(TransactionalTestCase):
    CONF_HOPFIELD_HEUN_STOCH_RANGES = r"""
    {"": {"value": "0.1"},
    "model_parameters_option_Hopfield_noise_parameters_option_Noise_random_stream": {"value": "RandomStream"},
     "model_parameters_option_Hopfield_state_variable_range_parameters_theta": {"value": "[ 0.  1.]"},
     "integrator": {"value": "HeunStochastic"},
     "model_parameters_option_Hopfield_variables_of_interest": {"value": ["x"]},
     "surface": {"value": ""},
     "simulation_length": {"value": "100.0"},
     "monitors_parameters_option_TemporalAverage_period": {"value": "0.9765625"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_nsig": {"value": "[0.00123]"},
     "monitors": {"value": ["TemporalAverage"]},
     "model_parameters_option_Hopfield_noise_parameters_option_Noise_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"},
     "conduction_speed": {"value": "3.0"},
     "model_parameters_option_Hopfield_noise_parameters_option_Noise_ntau": {"value": "0.0"},
     "currentAlgoId": {"value": 64},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Multiplicative_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_random_stream": {"value": "RandomStream"},
     "connectivity": {"value": "be827732-1655-11e4-ae16-c860002c3492"},
     "model_parameters_option_Hopfield_noise": {"value": "Noise"},
     "range_1": {"value": "model_parameters_option_Hopfield_taux"},
     "model_parameters_option_Hopfield_taux": {"value": "{\"minValue\":0.7,\"maxValue\":1,\"step\":0.1}"},
     "range_2": {"value": "0"},
     "coupling_parameters_option_Linear_b": {"value": "[0.0]"},
     "coupling_parameters_option_Linear_a": {"value": "[0.00390625]"},
     "coupling": {"value": "Linear"},
     "model_parameters_option_Hopfield_state_variable_range_parameters_x": {"value": "[-1.  2.]"},
     "stimulus": {"value": ""},
     "integrator_parameters_option_HeunStochastic_dt": {"value": "0.09765625"},
     "model_parameters_option_Hopfield_dynamic": {"value": "[0]"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_ntau": {"value": "0.0"},
     "model_parameters_option_Hopfield_tauT": {"value": "[5.0]"},
     "integrator_parameters_option_HeunStochastic_noise": {"value": "Additive"},
     "model": {"value": "Hopfield"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"}
     }
    """

    def setUp(self):
        _, self.connectivity = DatatypesFactory().create_connectivity()
        self.test_user = TestFactory.create_user(username="******")
        self.test_project = TestFactory.create_project(self.test_user, "Test")

        burst_conf = BurstConfiguration(self.test_project.id)
        burst_conf._simulator_configuration = self.CONF_HOPFIELD_HEUN_STOCH_RANGES
        burst_conf.prepare_after_load()
        burst_conf.simulator_configuration['connectivity'] = {
            'value': self.connectivity.gid
        }

        self.s_manager = SerializationManager(burst_conf)
        self.empty_manager = SerializationManager(BurstConfiguration(None))

    def test_has_model_pse_ranges(self):
        self.assertTrue(self.s_manager.has_model_pse_ranges())
        self.assertFalse(self.empty_manager.has_model_pse_ranges())

    def test_get_params_dict(self):
        d = self.s_manager._get_params_dict()
        mp = d[MODEL_PARAMETERS]
        ip = d[INTEGRATOR_PARAMETERS]
        # test model param deserialization
        self.assertEqual([5], mp['tauT'].tolist())
        self.assertEqual([{
            'step': 0.1,
            'maxValue': 1,
            'minValue': 0.7
        }], mp['taux'].tolist())
        # test integrator param deserialization
        self.assertEqual(0.09765625, ip['dt'])
        self.assertEqual([0.00123], ip['noise_parameters']['nsig'].tolist())

    def test_make_model_and_integrator(self):
        m, i = self.s_manager.make_model_and_integrator()
        self.assertIsInstance(m, Hopfield)
        self.assertIsInstance(i, HeunStochastic)

    def test_group_parameter_values_by_name(self):
        gp = SerializationManager.group_parameter_values_by_name([{
            "a": 2.0,
            'b': 1.0
        }, {
            "a": 3.0,
            'b': 7.0
        }])
        self.assertEqual({'a': [2.0, 3.0], 'b': [1.0, 7.0]}, gp)

    def test_write_model_parameters_one_dynamic(self):
        m_name = Generic2dOscillator.__name__
        m_parms = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -10.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }

        self.s_manager.write_model_parameters(m_name, [
            m_parms.copy() for _ in range(self.connectivity.number_of_regions)
        ])

        sc = self.s_manager.conf.simulator_configuration
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        self.assertEqual(Generic2dOscillator.__name__, sc['model']['value'])

        # a modified parameter
        expected = [1.75
                    ]  # we expect same value arrays to contract to 1 element
        actual = json.loads(
            sc['model_parameters_option_Generic2dOscillator_a']['value'])
        self.assertEqual(expected, actual)
        # one with the same value as the default
        expected = [-10.0]
        actual = json.loads(
            sc['model_parameters_option_Generic2dOscillator_b']['value'])
        self.assertEqual(expected, actual)

    def test_write_model_parameters_two_dynamics(self):
        m_name = Generic2dOscillator.__name__
        m_parms_1 = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -10.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }
        m_parms_2 = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -5.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }
        # all nodes except the first have dynamic 1
        model_parameter_list = [
            m_parms_1.copy()
            for _ in range(self.connectivity.number_of_regions)
        ]
        model_parameter_list[0] = m_parms_2

        self.s_manager.write_model_parameters(m_name, model_parameter_list)

        sc = self.s_manager.conf.simulator_configuration
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        self.assertEqual(Generic2dOscillator.__name__, sc['model']['value'])

        expected = [1.75]  # array contracted to one value
        actual = json.loads(
            sc['model_parameters_option_Generic2dOscillator_a']['value'])
        self.assertEqual(expected, actual)

        # b is not the same across models. We will have a full array
        expected = [-10.0 for _ in range(self.connectivity.number_of_regions)]
        expected[0] = -5.0
        actual = json.loads(
            sc['model_parameters_option_Generic2dOscillator_b']['value'])
        self.assertEqual(expected, actual)

    def test_write_noise_parameters(self):
        disp = [{
            "x": 4,
            "theta": 2
        } for _ in range(self.connectivity.number_of_regions)]
        self.s_manager.write_noise_parameters(disp)

        sc = self.s_manager.conf.simulator_configuration
        self.assertEqual(HeunStochastic.__name__, sc['integrator']['value'])
        nodes_nr = self.connectivity.number_of_regions
        expected = [[4] * nodes_nr, [2] * nodes_nr]
        actual = json.loads(sc[
            'integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_nsig']
                            ['value'])
        self.assertEqual(expected, actual)
コード例 #23
0
 def test_group_parameter_values_by_name(self):
     gp = SerializationManager.group_parameter_values_by_name(
         [{"a": 2.0, 'b': 1.0},
          {"a": 3.0, 'b': 7.0}])
     assert {'a': [2.0, 3.0], 'b': [1.0, 7.0]} == gp
コード例 #24
0
class TestSerializationManager(TransactionalTestCase):
    CONF_HOPFIELD_HEUN_STOCH_RANGES = r"""
    {"": {"value": "0.1"},
    "model_parameters_option_Hopfield_noise_parameters_option_Noise_random_stream": {"value": "RandomStream"},
     "model_parameters_option_Hopfield_state_variable_range_parameters_theta": {"value": "[ 0.  1.]"},
     "integrator": {"value": "HeunStochastic"},
     "model_parameters_option_Hopfield_variables_of_interest": {"value": ["x"]},
     "surface": {"value": ""},
     "simulation_length": {"value": "100.0"},
     "monitors_parameters_option_TemporalAverage_period": {"value": "0.9765625"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_nsig": {"value": "[0.00123]"},
     "monitors": {"value": ["TemporalAverage"]},
     "model_parameters_option_Hopfield_noise_parameters_option_Noise_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"},
     "conduction_speed": {"value": "3.0"},
     "model_parameters_option_Hopfield_noise_parameters_option_Noise_ntau": {"value": "0.0"},
     "currentAlgoId": {"value": 64},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Multiplicative_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_random_stream": {"value": "RandomStream"},
     "connectivity": {"value": "be827732-1655-11e4-ae16-c860002c3492"},
     "model_parameters_option_Hopfield_noise": {"value": "Noise"},
     "range_1": {"value": "model_parameters_option_Hopfield_taux"},
     "model_parameters_option_Hopfield_taux": {"value": "{\"minValue\":0.7,\"maxValue\":1,\"step\":0.1}"},
     "range_2": {"value": "0"},
     "coupling_parameters_option_Linear_b": {"value": "[0.0]"},
     "coupling_parameters_option_Linear_a": {"value": "[0.00390625]"},
     "coupling": {"value": "Linear"},
     "model_parameters_option_Hopfield_state_variable_range_parameters_x": {"value": "[-1.  2.]"},
     "stimulus": {"value": ""},
     "integrator_parameters_option_HeunStochastic_dt": {"value": "0.09765625"},
     "model_parameters_option_Hopfield_dynamic": {"value": "[0]"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_ntau": {"value": "0.0"},
     "model_parameters_option_Hopfield_tauT": {"value": "[5.0]"},
     "integrator_parameters_option_HeunStochastic_noise": {"value": "Additive"},
     "model": {"value": "Hopfield"},
     "integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_random_stream_parameters_option_RandomStream_init_seed": {"value": "42"}
     }
    """

    def transactional_setup_method(self):
        _, self.connectivity = DatatypesFactory().create_connectivity()
        self.test_user = TestFactory.create_user(username="******")
        self.test_project = TestFactory.create_project(self.test_user, "Test")

        burst_conf = BurstConfiguration(self.test_project.id)
        burst_conf._simulator_configuration = self.CONF_HOPFIELD_HEUN_STOCH_RANGES
        burst_conf.prepare_after_load()
        burst_conf.simulator_configuration['connectivity'] = {'value': self.connectivity.gid}

        self.s_manager = SerializationManager(burst_conf)
        self.empty_manager = SerializationManager(BurstConfiguration(None))


    def test_has_model_pse_ranges(self):
        assert self.s_manager.has_model_pse_ranges()
        assert not self.empty_manager.has_model_pse_ranges()


    def test_get_params_dict(self):
        d = self.s_manager._get_params_dict()
        mp = d[MODEL_PARAMETERS]
        ip = d[INTEGRATOR_PARAMETERS]
        # test model param deserialization
        assert [5] == mp['tauT'].tolist()
        assert [{'step': 0.1, 'maxValue': 1, 'minValue': 0.7}] == mp['taux'].tolist()
        # test integrator param deserialization
        assert 0.09765625 == ip['dt']
        assert [ 0.00123] == ip['noise_parameters']['nsig'].tolist()


    def test_make_model_and_integrator(self):
        m ,i = self.s_manager.make_model_and_integrator()
        assert isinstance(m,Hopfield)
        assert isinstance(i, HeunStochastic)


    def test_group_parameter_values_by_name(self):
        gp = SerializationManager.group_parameter_values_by_name(
            [{"a": 2.0, 'b': 1.0},
             {"a": 3.0, 'b': 7.0}])
        assert {'a': [2.0, 3.0], 'b': [1.0, 7.0]} == gp


    def test_write_model_parameters_one_dynamic(self):
        m_name = Generic2dOscillator.__name__
        m_parms = {'I': 0.0, 'a': 1.75, 'alpha': 1.0, 'b': -10.0, 'beta': 1.0, 'c': 0.0,
               'd': 0.02, 'e': 3.0, 'f': 1.0, 'g': 0.0, 'gamma': 1.0, 'tau': 1.47}

        self.s_manager.write_model_parameters(m_name, [m_parms.copy() for _ in range(self.connectivity.number_of_regions)])

        sc = self.s_manager.conf.simulator_configuration
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        assert Generic2dOscillator.__name__ == sc['model']['value']

        # a modified parameter
        expected = [1.75]  # we expect same value arrays to contract to 1 element
        actual = json.loads(sc['model_parameters_option_Generic2dOscillator_a']['value'])
        assert expected == actual
        # one with the same value as the default
        expected = [-10.0]
        actual = json.loads(sc['model_parameters_option_Generic2dOscillator_b']['value'])
        assert expected == actual


    def test_write_model_parameters_two_dynamics(self):
        m_name = Generic2dOscillator.__name__
        m_parms_1 = {'I': 0.0, 'a': 1.75, 'alpha': 1.0, 'b': -10.0, 'beta': 1.0, 'c': 0.0,
               'd': 0.02, 'e': 3.0, 'f': 1.0, 'g': 0.0, 'gamma': 1.0, 'tau': 1.47}
        m_parms_2 = {'I': 0.0, 'a': 1.75, 'alpha': 1.0, 'b': -5.0, 'beta': 1.0, 'c': 0.0,
               'd': 0.02, 'e': 3.0, 'f': 1.0, 'g': 0.0, 'gamma': 1.0, 'tau': 1.47}
        # all nodes except the first have dynamic 1
        model_parameter_list = [m_parms_1.copy() for _ in range(self.connectivity.number_of_regions)]
        model_parameter_list[0] = m_parms_2

        self.s_manager.write_model_parameters(m_name, model_parameter_list)

        sc = self.s_manager.conf.simulator_configuration
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        assert Generic2dOscillator.__name__ == sc['model']['value']

        expected = [1.75]  # array contracted to one value
        actual = json.loads(sc['model_parameters_option_Generic2dOscillator_a']['value'])
        assert expected == actual

        # b is not the same across models. We will have a full array
        expected = [-10.0 for _ in range(self.connectivity.number_of_regions)]
        expected[0] = -5.0
        actual = json.loads(sc['model_parameters_option_Generic2dOscillator_b']['value'])
        assert expected == actual


    def test_write_noise_parameters(self):
        disp = [{"x":4,"theta":2} for _ in range(self.connectivity.number_of_regions)]
        self.s_manager.write_noise_parameters(disp)

        sc = self.s_manager.conf.simulator_configuration
        assert HeunStochastic.__name__ == sc['integrator']['value']
        nodes_nr = self.connectivity.number_of_regions
        expected = [[4] * nodes_nr , [2] * nodes_nr]
        actual = json.loads(sc['integrator_parameters_option_HeunStochastic_noise_parameters_option_Additive_nsig']['value'])
        assert expected == actual
コード例 #25
0
class TestSerializationManager(TransactionalTestCase):
    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)

    def test_group_parameter_values_by_name(self):
        gp = SerializationManager.group_parameter_values_by_name([{
            "a": 2.0,
            'b': 1.0
        }, {
            "a": 3.0,
            'b': 7.0
        }])
        assert {'a': [2.0, 3.0], 'b': [1.0, 7.0]} == gp

    def test_write_model_parameters_one_dynamic(self, connectivity_factory):
        connectivity = connectivity_factory()
        m_name = ModelsEnum.GENERIC_2D_OSCILLATOR.get_class().__name__
        m_parms = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -10.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }

        self.s_manager.write_model_parameters(
            m_name,
            [m_parms.copy() for _ in range(connectivity.number_of_regions)])

        sc = self.s_manager.conf
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        assert isinstance(sc.model,
                          ModelsEnum.GENERIC_2D_OSCILLATOR.get_class())

        # a modified parameter
        expected = [1.75
                    ]  # we expect same value arrays to contract to 1 element
        actual = sc.model.a
        assert expected == actual
        # one with the same value as the default
        expected = [-10.0]
        actual = sc.model.b
        assert expected == actual

    def test_write_model_parameters_two_dynamics(self, connectivity_factory):
        connectivity = connectivity_factory()
        m_name = ModelsEnum.GENERIC_2D_OSCILLATOR.get_class().__name__
        m_parms_1 = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -10.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }
        m_parms_2 = {
            'I': 0.0,
            'a': 1.75,
            'alpha': 1.0,
            'b': -5.0,
            'beta': 1.0,
            'c': 0.0,
            'd': 0.02,
            'e': 3.0,
            'f': 1.0,
            'g': 0.0,
            'gamma': 1.0,
            'tau': 1.47
        }
        # all nodes except the first have dynamic 1
        model_parameter_list = [
            m_parms_1.copy() for _ in range(connectivity.number_of_regions)
        ]
        model_parameter_list[0] = m_parms_2

        self.s_manager.write_model_parameters(m_name, model_parameter_list)

        sc = self.s_manager.conf
        # Default model in these tests is Hopfield. Test if the model was changed to Generic2dOscillator
        assert isinstance(sc.model,
                          ModelsEnum.GENERIC_2D_OSCILLATOR.get_class())

        expected = [1.75]  # array contracted to one value
        actual = sc.model.a
        assert expected == actual

        # b is not the same across models. We will have a full array
        expected = [-10.0 for _ in range(connectivity.number_of_regions)]
        expected[0] = -5.0
        actual = sc.model.b
        assert expected == actual.tolist()

    def test_write_noise_parameters(self, connectivity_factory):
        connectivity = connectivity_factory()
        disp = [{
            "x": 4,
            "theta": 2
        } for _ in range(connectivity.number_of_regions)]
        self.s_manager.write_noise_parameters(disp)

        assert isinstance(self.s_manager.conf.integrator, HeunStochastic)
        nodes_nr = connectivity.number_of_regions
        expected = [[4] * nodes_nr, [2] * nodes_nr]
        actual = self.s_manager.conf.integrator.noise.nsig
        assert expected == actual.tolist()