예제 #1
0
 def __make_instance_from_burst_config(self, params_dict, parent_class, class_name_key, params_key):
     """ This is used internally to create a model or an integrator based on the burst config """
     class_name = self.conf.get_simulation_parameter_value(class_name_key)
     parameters = params_dict[params_key]
     noise_framework.build_noise(parameters)
     try:
         return get_traited_instance_for_name(class_name, parent_class, parameters)
     except Exception:
         self.logger.exception("Could not create an instance of %s with the given parameters. "
                               "A new instance will be created with the default values." % class_name)
         return get_traited_instance_for_name(class_name, parent_class, {})
    def integrator_changed(self, dynamic_gid, **kwargs):
        adapter = _IntegratorFragmentAdapter()
        tree = adapter.convert_ui_inputs(kwargs, validation_required=False)
        integrator_name = tree['integrator']
        integrator_parameters = tree['integrator_parameters']

        noise_framework.build_noise(integrator_parameters)
        integrator = self.available_integrators[integrator_name](**integrator_parameters)

        dynamic = self.get_cached_dynamic(dynamic_gid)
        dynamic.integrator = integrator
        dynamic.model.integrator = integrator
        dynamic.model.configure()
        self._configure_integrator_noise(integrator, dynamic.model)

        dynamic.phase_plane = phase_space_d3(dynamic.model, dynamic.integrator)
예제 #3
0
    def integrator_changed(self, dynamic_gid, **kwargs):
        adapter = _IntegratorFragmentAdapter()
        tree = adapter.convert_ui_inputs(kwargs, validation_required=False)
        integrator_name = tree['integrator']
        integrator_parameters = tree['integrator_parameters']

        noise_framework.build_noise(integrator_parameters)
        integrator = self.available_integrators[integrator_name](
            **integrator_parameters)

        dynamic = self.get_cached_dynamic(dynamic_gid)
        dynamic.integrator = integrator
        dynamic.model.integrator = integrator
        dynamic.model.configure()
        self._configure_integrator_noise(integrator, dynamic.model)

        dynamic.phase_plane = phase_space_d3(dynamic.model, dynamic.integrator)
    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)
예제 #5
0
    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)
예제 #6
0
class SpatioTemporalController(base.BaseController):
    """
    Base class which contains methods related to spatio-temporal actions.
    """
    def __init__(self):
        base.BaseController.__init__(self)
        self.flow_service = FlowService()
        self.logger = get_logger(__name__)
        editable_entities = [
            dict(link='/spatial/stimulus/region/step_1_submit/1/1',
                 title='Region Stimulus',
                 subsection='regionstim',
                 description='Create a new Stimulus on Region level'),
            dict(link='/spatial/stimulus/surface/step_1_submit/1/1',
                 title='Surface Stimulus',
                 subsection='surfacestim',
                 description='Create a new Stimulus on Surface level')
        ]
        self.submenu_list = editable_entities

    @cherrypy.expose
    @using_template('base_template')
    @logged()
    @settings()
    def index(self, **data):
        """
        Displays the main page for the spatio temporal section.
        """
        template_specification = dict(title="Spatio temporal", data=data)
        template_specification['mainContent'] = 'header_menu'
        return self.fill_default_attributes(template_specification)

    @staticmethod
    def get_connectivity_parameters(input_connectivity, surface_data=None):
        """
        Returns a dictionary which contains all the needed data for drawing a connectivity.
        """
        viewer = ConnectivityViewer()
        global_params, global_pages = viewer.compute_connectivity_global_params(
            input_connectivity, surface_data)
        global_params.update(global_pages)
        global_params['selectedConnectivityGid'] = input_connectivity.gid
        return global_params

    def get_data_from_burst_configuration(self):
        """
        Returns the model, integrator, connectivity and surface instances from the burst configuration.
        """
        ### Read from session current burst-configuration
        burst_configuration = base.get_from_session(base.KEY_BURST_CONFIG)
        if burst_configuration is None:
            return None, None, None
        first_range = burst_configuration.get_simulation_parameter_value(
            'first_range')
        second_range = burst_configuration.get_simulation_parameter_value(
            'second_range')
        if ((first_range is not None
             and str(first_range).startswith(MODEL_PARAMETERS))
                or (second_range is not None
                    and str(second_range).startswith(MODEL_PARAMETERS))):
            base.set_error_message(
                "When configuring model parameters you are not allowed to specify range values."
            )
            raise cherrypy.HTTPRedirect("/burst/")
        group = self.flow_service.get_algorithm_by_module_and_class(
            SIMULATOR_MODULE, SIMULATOR_CLASS)[1]
        simulator_adapter = self.flow_service.build_adapter_instance(group)
        try:
            params_dict = simulator_adapter.convert_ui_inputs(
                burst_configuration.get_all_simulator_values()[0], False)
        except Exception, excep:
            self.logger.exception(excep)
            base.set_error_message(
                "Some of the provided parameters have an invalid value.")
            raise cherrypy.HTTPRedirect("/burst/")
        ### Prepare Model instance
        model = burst_configuration.get_simulation_parameter_value(PARAM_MODEL)
        model_parameters = params_dict[MODEL_PARAMETERS]
        noise_framework.build_noise(model_parameters)
        try:
            model = get_traited_instance_for_name(model, Model,
                                                  model_parameters)
        except Exception, ex:
            self.logger.exception(ex)
            self.logger.info(
                "Could not create the model instance with the given parameters. "
                "A new model instance will be created with the default values."
            )
            model = get_traited_instance_for_name(model, Model, {})
예제 #7
0
 noise_framework.build_noise(model_parameters)
 try:
     model = get_traited_instance_for_name(model, Model,
                                           model_parameters)
 except Exception, ex:
     self.logger.exception(ex)
     self.logger.info(
         "Could not create the model instance with the given parameters. "
         "A new model instance will be created with the default values."
     )
     model = get_traited_instance_for_name(model, Model, {})
 ### Prepare Integrator instance
 integrator = burst_configuration.get_simulation_parameter_value(
     PARAM_INTEGRATOR)
 integrator_parameters = params_dict[INTEGRATOR_PARAMETERS]
 noise_framework.build_noise(integrator_parameters)
 try:
     integrator = get_traited_instance_for_name(integrator, Integrator,
                                                integrator_parameters)
 except Exception, ex:
     self.logger.exception(ex)
     self.logger.info(
         "Could not create the integrator instance with the given parameters. "
         "A new integrator instance will be created with the default values."
     )
     integrator = get_traited_instance_for_name(integrator, Integrator,
                                                {})
 ### Prepare Connectivity
 connectivity_gid = burst_configuration.get_simulation_parameter_value(
     PARAM_CONNECTIVITY)
 connectivity = ABCAdapter.load_entity_by_gid(connectivity_gid)