Beispiel #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, {})
Beispiel #2
0
    def build_equation_from_dict(equation_field_name,
                                 submitted_data_dict,
                                 alter_submitted_dictionary=False):
        """
        Builds from the given data dictionary the equation for the specified field name.
        The dictionary should have the data collapsed.
        """
        if equation_field_name not in submitted_data_dict:
            return None

        eq_param_str = equation_field_name + '_parameters'
        eq = submitted_data_dict.get(eq_param_str)

        equation_parameters = {}
        if eq:
            if 'parameters' in eq:
                equation_parameters = eq['parameters']
            if 'parameters_parameters' in eq:
                equation_parameters = eq['parameters_parameters']

        for k in equation_parameters:
            equation_parameters[k] = float(equation_parameters[k])

        equation_type = submitted_data_dict[equation_field_name]
        equation = parameters_factory.get_traited_instance_for_name(
            equation_type, Equation, {'parameters': equation_parameters})
        if alter_submitted_dictionary:
            del submitted_data_dict[eq_param_str]
            submitted_data_dict[equation_field_name] = equation

        return equation
    def build_equation_from_dict(equation_field_name,
                                 submitted_data_dict,
                                 alter_submitted_dictionary=False):
        """
        Builds from the given data dictionary the equation for the specified field name.
        The dictionary should have the data collapsed.
        """
        equation = None
        if equation_field_name in submitted_data_dict:
            equation_type = submitted_data_dict[equation_field_name]
            equation_parameters = {}
            eq_param_str = equation_field_name + '_parameters'

            if eq_param_str in submitted_data_dict and 'parameters' in submitted_data_dict[
                    eq_param_str]:
                equation_parameters = submitted_data_dict[eq_param_str][
                    'parameters']
            if eq_param_str in submitted_data_dict and 'parameters_parameters' in submitted_data_dict[
                    eq_param_str]:
                equation_parameters = submitted_data_dict[eq_param_str][
                    'parameters_parameters']
            equation = parameters_factory.get_traited_instance_for_name(
                equation_type, equations_data.EquationData,
                {'parameters': equation_parameters})
            if alter_submitted_dictionary:
                del submitted_data_dict[eq_param_str]
                submitted_data_dict[equation_field_name] = equation

        return equation
 def get_lconn_equation(self, kwargs):
     """
     Get the equation for the local connectivity from a dictionary of arguments.
     """
     return parameters_factory.get_traited_instance_for_name(
         kwargs['equation'], equations_data.EquationData, {
             'parameters': kwargs['equation_parameters'].get(
                 'parameters', {})
         })
    def launch(self, **kwargs):
        """
        Used for creating a StimuliRegion instance
        """
        stimuli_region = StimuliRegion(storage_path=self.storage_path)
        stimuli_region.connectivity = kwargs['connectivity']
        stimuli_region.weight = kwargs['weight']
        #spatial_eq = parameters_factory.get_traited_instance_for_name(kwargs['spatial'], equations_data.EquationData,
        #                                                                {'parameters': kwargs['spatial_parameters'].get('parameters', {})})
        temporal_eq = parameters_factory.get_traited_instance_for_name(kwargs['temporal'], equations_data.EquationData,
                                                                        {'parameters': kwargs['temporal_parameters'].get('parameters', {})})
        #stimuli_region.spatial = spatial_eq
        stimuli_region.temporal = temporal_eq

        return stimuli_region
Beispiel #6
0
 def _compute_equation(parameters):
     """
     This method will return an equation and the model parameter on
     which should be applied the equation.
     The equation is constructed based on the parameters collected from the UI.
     """
     model_param = parameters[MODEL_PARAM]
     equation = parameters[MODEL_PARAM + PARAM_SUFFIX][MODEL_PARAM_EQUATION]
     equation_params = parameters[MODEL_PARAM + PARAM_SUFFIX][MODEL_PARAM_EQUATION + PARAM_SUFFIX][equation]
     equation_params = collapse_params(equation_params, [])
     if PARAMETERS + PARAM_SUFFIX in equation_params:
         equation_params = equation_params[PARAMETERS + PARAM_SUFFIX]
     else:
         equation_params = {}
     for param in equation_params:
         equation_params[param] = float(equation_params[param])
     selected_equation = get_traited_instance_for_name(equation, equations.Equation, {PARAMETERS: equation_params})
     return model_param, selected_equation
    def get_data_for_param_sliders(self, connectivity_node_index):
        """
        NOTE: This method may throw 'ValueError' exception.

        Return a dict which contains all the needed information for
        drawing the sliders for the model parameters of the selected connectivity node.
        """
        connectivity_node_index = int(connectivity_node_index)
        current_model = self._get_model_for_region(connectivity_node_index)
        #we have to obtain the model with its default values(the one submitted from burst may have some
        # parameters values changed); the step is computed based on the number of decimals of the default values
        default_model_for_node = parameters_factory.get_traited_instance_for_name(
            self.model_name, models_module.Model, {})
        param_sliders_data = dict()
        for param_name in self.model_parameter_names:
            current_value = getattr(current_model, param_name)
            ### Convert to list to avoid having non-serializable values numpy.int32
            if isinstance(current_value, numpy.ndarray):
                current_value = current_value.tolist()[0]
            else:
                #check if the current_value represents a valid number
                #handle the exception in the place where you call this method
                float(current_value)
            ranger = default_model_for_node.trait[
                param_name].trait.range_interval

            if current_value > ranger.hi:
                current_value = ranger.hi
                self.update_model_parameter(connectivity_node_index,
                                            param_name, current_value)
            if current_value < ranger.lo:
                current_value = ranger.lo
                self.update_model_parameter(connectivity_node_index,
                                            param_name, current_value)

            param_sliders_data[param_name] = {
                'min': ranger.lo,
                'max': ranger.hi,
                'default': current_value,
                'step': ranger.step
            }
        param_sliders_data['all_param_names'] = self.model_parameter_names
        return param_sliders_data
    def build_equation_from_dict(equation_field_name, submitted_data_dict, alter_submitted_dictionary=False):
        """
        Builds from the given data dictionary the equation for the specified field name.
        The dictionary should have the data collapsed.
        """
        equation = None
        if equation_field_name in submitted_data_dict:
            equation_type = submitted_data_dict[equation_field_name]
            equation_parameters = {}
            eq_param_str = equation_field_name + '_parameters'

            if eq_param_str in submitted_data_dict and 'parameters' in submitted_data_dict[eq_param_str]:
                equation_parameters = submitted_data_dict[eq_param_str]['parameters']
            if eq_param_str in submitted_data_dict and 'parameters_parameters' in submitted_data_dict[eq_param_str]:
                equation_parameters = submitted_data_dict[eq_param_str]['parameters_parameters']
            equation = parameters_factory.get_traited_instance_for_name(equation_type, equations_data.EquationData,
                                                                        {'parameters': equation_parameters})
            if alter_submitted_dictionary:
                del submitted_data_dict[eq_param_str]
                submitted_data_dict[equation_field_name] = equation

        return equation
    def get_data_for_param_sliders(self, connectivity_node_index):
        """
        NOTE: This method may throw 'ValueError' exception.

        Return a dict which contains all the needed information for
        drawing the sliders for the model parameters of the selected connectivity node.
        """
        connectivity_node_index = int(connectivity_node_index)
        current_model = self._get_model_for_region(connectivity_node_index)
        #we have to obtain the model with its default values(the one submitted from burst may have some
        # parameters values changed); the step is computed based on the number of decimals of the default values
        default_model_for_node = parameters_factory.get_traited_instance_for_name(self.model_name,
                                                                                  models_module.Model, {})
        param_sliders_data = dict()
        for param_name in self.model_parameter_names:
            current_value = getattr(current_model, param_name)
            ### Convert to list to avoid having non-serializable values numpy.int32
            if isinstance(current_value, numpy.ndarray):
                current_value = current_value.tolist()[0]
            else:
                #check if the current_value represents a valid number
                #handle the exception in the place where you call this method
                float(current_value)
            ranger = default_model_for_node.trait[param_name].trait.range_interval

            if current_value > ranger.hi:
                current_value = ranger.hi
                self.update_model_parameter(connectivity_node_index, param_name, current_value)
            if current_value < ranger.lo:
                current_value = ranger.lo
                self.update_model_parameter(connectivity_node_index, param_name, current_value)

            param_sliders_data[param_name] = {'min': ranger.lo, 'max': ranger.hi,
                                              'default': current_value, 'step': ranger.step}
        param_sliders_data['all_param_names'] = self.model_parameter_names
        return param_sliders_data
 def get_temporal_equation(self, kwargs):
     """
     From a dictionary of arguments build the temporal equation.
     """
     return parameters_factory.get_traited_instance_for_name(kwargs['temporal'], equations_data.EquationData,
                                                                     {'parameters': kwargs['temporal_parameters'].get('parameters', {})})
 def __make_shallow_model(self):
     from tvb.basic.traits.parameters_factory import get_traited_instance_for_name
     """ Creates a model of the type present in the config without setting any parameters on it """
     class_name = self.conf.get_simulation_parameter_value(PARAM_MODEL)
     return get_traited_instance_for_name(class_name, Model, {})
Beispiel #12
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, {})
Beispiel #13
0
     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)
 ### Prepare Surface
 surface_gid = burst_configuration.get_simulation_parameter_value(
     PARAM_SURFACE)
 def test_get_traited_instance(self):
     """
     Try to create an instance of a class using the traited method.
     """
     inst = get_traited_instance_for_name("StringArray", Array, {})
     assert isinstance(inst, arrays.StringArray)
 def __make_shallow_model(self):
     """ Creates a model of the type present in the config without setting any parameters on it """
     class_name = self.conf.get_simulation_parameter_value(PARAM_MODEL)
     return get_traited_instance_for_name(class_name, Model, {})