def step_2(self, **kwargs): """ Generate the html for the second step of the local connectivity page. :param kwargs: not actually used, but parameters are still submitted from UI since we just\ use the same js function for this. TODO: do this in a smarter way """ context = common.get_from_session(KEY_LCONN_CONTEXT) left_side_interface = self.get_select_existent_entities('Load Local Connectivity:', LocalConnectivity, context.selected_entity) template_specification = dict(title="Surface - Local Connectivity") template_specification['mainContent'] = 'spatial/local_connectivity_step2_main' template_specification['existentEntitiesInputList'] = left_side_interface template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification['next_step_url'] = '/spatial/localconnectivity/step_1' msg, _ = common.get_message_from_session() template_specification['displayedMessage'] = msg context = common.get_from_session(KEY_LCONN_CONTEXT) if context.selected_entity is not None: selected_local_conn = ABCAdapter.load_entity_by_gid(context.selected_entity) template_specification.update(self.display_surface(selected_local_conn.surface.gid)) template_specification['no_local_connectivity'] = False min_value, max_value = selected_local_conn.get_min_max_values() template_specification['minValue'] = min_value template_specification['maxValue'] = max_value else: template_specification['no_local_connectivity'] = True template_specification[common.KEY_PARAMETERS_CONFIG] = False return self.fill_default_attributes(template_specification)
def submit_model_parameters(self, submit_action="cancel_action"): """ Collects the model parameters values from all the models used for the surface vertices. @:param submit_action: a post parameter. It distinguishes if this request is a cancel or a submit """ if submit_action == "submit_action": context_model_parameters = common.get_from_session(KEY_CONTEXT_MPS) burst_configuration = common.get_from_session(common.KEY_BURST_CONFIG) for original_param, modified_param in context_model_parameters.prepared_model_parameter_names.items(): full_name = PARAMS_MODEL_PATTERN % (context_model_parameters.model_name, original_param) param_data = context_model_parameters.get_data_for_model_param(original_param, modified_param) if isinstance(param_data, dict): equation = param_data[KEY_EQUATION] focal_points = param_data[KEY_FOCAL_POINTS] # if focal points or the equation are missing do not update this model parameter if not focal_points or not equation: continue param_data[KEY_EQUATION] = equation.to_json(equation) param_data[KEY_FOCAL_POINTS] = json.dumps(focal_points) param_data = json.dumps(param_data) burst_configuration.update_simulation_parameter(full_name, param_data) ### Update in session BURST configuration for burst-page. common.add2session(common.KEY_BURST_CONFIG, burst_configuration.clone()) ### Clean from session drawing context common.remove_from_session(KEY_CONTEXT_MPS) raise cherrypy.HTTPRedirect("/burst/")
def get_stimulus_chunk(self, chunk_idx): """ Get the next chunk of the stimulus data. """ stimulus = common.get_from_session(KEY_STIMULUS) surface_gid = common.get_from_session(PARAM_SURFACE) chunk_idx = int(chunk_idx) if stimulus.surface.gid != surface_gid: raise Exception("TODO: Surface changed while visualizing stimulus. See how to handle this.") data = [] for idx in range(chunk_idx * CHUNK_SIZE, min((chunk_idx + 1) * CHUNK_SIZE, stimulus.temporal_pattern.shape[1]), 1): data.append(stimulus(idx).tolist()) return data
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 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/")
def launch_burst(self, launch_mode, burst_name, **data): """ Do the actual burst launch, using the configuration saved in current session. :param launch_mode: new/branch/continue :param burst_name: user-given burst name. It can be empty (case in which we will fill with simulation_x) :param data: kwargs for simulation input parameters. """ data = json.loads(data['simulator_parameters']) burst_config = common.get_from_session(common.KEY_BURST_CONFIG) ## Validate new burst-name if launch_mode == LAUNCH_NEW and burst_name != 'none_undefined': validation_result = self._is_burst_name_ok(burst_name) if validation_result is True: burst_config.name = burst_name else: return {'error': validation_result} ## Fill all parameters user_id = common.get_logged_user().id data[common.KEY_ADAPTER] = self.cached_simulator_algorithm_id burst_config.update_simulator_configuration(data) burst_config.fk_project = common.get_current_project().id ## Do the asynchronous launch try: burst_id, burst_name = self.burst_service.launch_burst(burst_config, 0, self.cached_simulator_algorithm_id, user_id, launch_mode) return {'id': burst_id, 'name': burst_name} except BurstServiceException, e: self.logger.exception("Could not launch burst!") return {'error': e.message}
def stop_burst_operation(self, operation_id, is_group, remove_after_stop=False): """ For a given operation id that is part of a burst just stop the given burst. :returns True when stopped operation was successfully. """ operation_id = int(operation_id) if int(is_group) == 0: operation = self.flow_service.load_operation(operation_id) else: op_group = ProjectService.get_operation_group_by_id(operation_id) first_op = ProjectService.get_operations_in_group(op_group)[0] operation = self.flow_service.load_operation(int(first_op.id)) try: burst_service = BurstService() result = burst_service.stop_burst(operation.burst) if remove_after_stop: current_burst = common.get_from_session(common.KEY_BURST_CONFIG) if current_burst and current_burst.id == operation.burst.id: common.remove_from_session(common.KEY_BURST_CONFIG) result = burst_service.cancel_or_remove_burst(operation.burst.id) or result return result except Exception, ex: self.logger.exception(ex) return False
def _add_extra_fields_to_interface(input_list): """ The fields that have to be added to the existent adapter interface should be added in this method. """ context = common.get_from_session(KEY_SURFACE_CONTEXT) temporal_iface = [] min_tmp_x = {'name': 'min_tmp_x', 'label': 'Temporal Start Time(ms)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('min_tmp_x', 0), "description": "The minimum value of the x-axis for temporal equation plot. " "Not persisted, used only for visualization."} max_tmp_x = {'name': 'max_tmp_x', 'label': 'Temporal End Time(ms)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('max_tmp_x', 100), "description": "The maximum value of the x-axis for temporal equation plot. " "Not persisted, used only for visualization."} temporal_iface.append(min_tmp_x) temporal_iface.append(max_tmp_x) spatial_iface = [] min_space_x = {'name': 'min_space_x', 'label': 'Spatial Start Distance(mm)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('min_space_x', 0), "description": "The minimum value of the x-axis for spatial equation plot."} max_space_x = {'name': 'max_space_x', 'label': 'Spatial End Distance(mm)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('max_space_x', 100), "description": "The maximum value of the x-axis for spatial equation plot."} spatial_iface.append(min_space_x) spatial_iface.append(max_space_x) input_list['spatialPlotInputList'] = spatial_iface input_list['temporalPlotInputList'] = temporal_iface return input_list
def step_1(self, do_reset=0, **kwargs): """ Generate the html for the first step of the local connectivity page. :param do_reset: Boolean telling to start from empty page or not :param kwargs: not actually used, but parameters are still submitted from UI since we just\ use the same js function for this. TODO: do this in a smarter way """ if int(do_reset) == 1: new_context = ContextLocalConnectivity() common.add2session(KEY_LCONN_CONTEXT, new_context) context = common.get_from_session(KEY_LCONN_CONTEXT) right_side_interface = self._get_lconn_interface() left_side_interface = self.get_select_existent_entities('Load Local Connectivity', LocalConnectivity, context.selected_entity) # add interface to session, needed for filters self.add_interface_to_session(left_side_interface, right_side_interface['inputList']) template_specification = dict(title="Surface - Local Connectivity") template_specification['mainContent'] = 'spatial/local_connectivity_step1_main' template_specification.update(right_side_interface) template_specification['displayCreateLocalConnectivityBtn'] = True template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification['existentEntitiesInputList'] = left_side_interface template_specification['submit_parameters_url'] = '/spatial/localconnectivity/create_local_connectivity' template_specification['equationViewerUrl'] = '/spatial/localconnectivity/get_equation_chart' template_specification['equationsPrefixes'] = json.dumps(self.plotted_equations_prefixes) template_specification['next_step_url'] = '/spatial/localconnectivity/step_2' msg, msg_type = common.get_message_from_session() template_specification['displayedMessage'] = msg return self.fill_default_attributes(template_specification)
def save_parameters(self, index_in_tab, **data): """ Save parameters :param tab_nr: the index of the selected tab :param index_in_tab: the index of the configured portlet in the selected tab :param data: the {"portlet_parameters": json_string} Where json_string is a Jsonified dictionary {"name": value}, representing the configuration of the current portlet Having these inputs, current method updated the configuration of the portlet in the corresponding tab position form the burst configuration in session. """ burst_config = common.get_from_session(common.KEY_BURST_CONFIG) tab_nr = burst_config.selected_tab old_portlet_config = burst_config.tabs[int(tab_nr)].portlets[int(index_in_tab)] data = json.loads(data['portlet_parameters']) # Replace all void entries with 'None' for entry in data: if data[entry] == '': data[entry] = None need_relaunch = self.burst_service.update_portlet_configuration(old_portlet_config, data) if need_relaunch: #### Reset Burst Configuration into an entity not persisted (id = None for all) common.add2session(common.KEY_BURST_CONFIG, burst_config.clone()) return "relaunchView" else: self.workflow_service.store_workflow_step(old_portlet_config.visualizer) return "noRelaunch"
def get_surface_model_parameters_data(self, default_selected_model_param=None): """ Returns a dictionary which contains all the data needed for drawing the model parameters. """ context_model_parameters = common.get_from_session(KEY_CONTEXT_MPS) if default_selected_model_param is None: default_selected_model_param = context_model_parameters.prepared_model_parameter_names.values()[0] equation_displayer = EquationDisplayer() equation_displayer.trait.bound = interface.INTERFACE_ATTRIBUTES_ONLY input_list = equation_displayer.interface[interface.INTERFACE_ATTRIBUTES] input_list[0] = self._lock_midpoints(input_list[0]) options = [] for original_param, modified_param in context_model_parameters.prepared_model_parameter_names.items(): attributes = deepcopy(input_list) self._fill_default_values(attributes, modified_param) option = {'name': original_param, 'value': modified_param, 'attributes': attributes} options.append(option) input_list = [{'name': 'model_param', 'type': 'select', 'default': default_selected_model_param, 'label': 'Model param', 'required': True, 'options': options}] input_list = InputTreeManager.prepare_param_names(input_list) return {common.KEY_PARAMETERS_CONFIG: False, 'inputList': input_list, 'applied_equations': context_model_parameters.get_configure_info()}
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')
def save_simulator_configuration(self, exclude_ranges, **data): """ :param exclude_ranges: should be a boolean value. If it is True than the ranges will be excluded from the simulation parameters. Data is a dictionary with pairs in one of the forms: { 'simulator_parameters' : { $name$ : { 'value' : $value$, 'is_disabled' : true/false } }, 'burstName': $burst_name} The names for the checkboxes next to the parameter with name $name$ is always $name$_checked Save this dictionary in an easy to process form from which you could rebuild either only the selected entries, or all of the simulator tree with the given default values. """ exclude_ranges = string2bool(str(exclude_ranges)) burst_config = common.get_from_session(common.KEY_BURST_CONFIG) if BURST_NAME in data: burst_config.name = data[BURST_NAME] data = json.loads(data['simulator_parameters']) for entry in data: if exclude_ranges and (entry.endswith("_checked") or entry == RANGE_PARAMETER_1 or entry == RANGE_PARAMETER_2): continue burst_config.update_simulation_parameter(entry, data[entry]) checkbox_for_entry = entry + "_checked" if checkbox_for_entry in data: burst_config.update_simulation_parameter(entry, data[checkbox_for_entry], KEY_PARAMETER_CHECKED)
def launch_full_visualizer(self, index_in_tab): """ Launch the full scale visualizer from a small preview from the burst cockpit. """ burst = common.get_from_session(common.KEY_BURST_CONFIG) selected_tab = burst.selected_tab visualizer = burst.tabs[selected_tab].portlets[int(index_in_tab)].visualizer result, input_data = self.burst_service.launch_visualization(visualizer, is_preview=False) algorithm = self.flow_service.get_algorithm_by_identifier(visualizer.fk_algorithm) if common.KEY_TITLE not in result: result[common.KEY_TITLE] = algorithm.displayname result[common.KEY_ADAPTER] = algorithm.id result[common.KEY_OPERATION_ID] = None result[common.KEY_INCLUDE_RESOURCES] = 'flow/included_resources' ## Add required field to input dictionary and return it so that it can be used ## ## for top right control. #### input_data[common.KEY_ADAPTER] = algorithm.id if common.KEY_PARENT_DIV not in result: result[common.KEY_PARENT_DIV] = '' self.context.add_adapter_to_session(algorithm, None, copy.deepcopy(input_data)) self._populate_section(algorithm, result, True) result[common.KEY_DISPLAY_MENU] = True result[common.KEY_BACK_PAGE] = "/burst" result[common.KEY_SUBMIT_LINK] = self.get_url_adapter(algorithm.fk_category, algorithm.id, 'burst') if KEY_CONTROLLS not in result: result[KEY_CONTROLLS] = '' return self.fill_default_attributes(result)
def load_region_stimulus(self, region_stimulus_gid, from_step=None): """ Loads the interface for the selected region stimulus. """ selected_region_stimulus = ABCAdapter.load_entity_by_gid(region_stimulus_gid) temporal_eq = selected_region_stimulus.temporal spatial_eq = selected_region_stimulus.spatial connectivity = selected_region_stimulus.connectivity weights = selected_region_stimulus.weight temporal_eq_type = temporal_eq.__class__.__name__ spatial_eq_type = spatial_eq.__class__.__name__ default_dict = {'temporal': temporal_eq_type, 'spatial': spatial_eq_type, 'connectivity': connectivity.gid, 'weight': json.dumps(weights)} for param in temporal_eq.parameters: prepared_name = 'temporal_parameters_option_' + str(temporal_eq_type) prepared_name = prepared_name + '_parameters_parameters_' + str(param) default_dict[prepared_name] = str(temporal_eq.parameters[param]) for param in spatial_eq.parameters: prepared_name = 'spatial_parameters_option_' + str(spatial_eq_type) + '_parameters_parameters_' + str(param) default_dict[prepared_name] = str(spatial_eq.parameters[param]) input_list = self.get_creator_and_interface(REGION_STIMULUS_CREATOR_MODULE, REGION_STIMULUS_CREATOR_CLASS, StimuliRegion())[1] input_list = InputTreeManager.fill_defaults(input_list, default_dict) context = common.get_from_session(KEY_REGION_CONTEXT) context.reset() context.update_from_interface(input_list) context.equation_kwargs[DataTypeMetaData.KEY_TAG_1] = selected_region_stimulus.user_tag_1 context.set_active_stimulus(region_stimulus_gid) return self.do_step(from_step)
def load_burst_history(self): """ Load the available burst that are stored in the database at this time. This is one alternative to 'chrome-back problem'. """ session_burst = common.get_from_session(common.KEY_BURST_CONFIG) return {'burst_list': self.burst_service.get_available_bursts(common.get_current_project().id), 'selectedBurst': session_burst.id}
def step_2_submit(self, next_step, **kwargs): """ Any submit from the second step should be handled here. Update the context and then do the next step as required. """ context = common.get_from_session(KEY_REGION_CONTEXT) context.equation_kwargs[DataTypeMetaData.KEY_TAG_1] = kwargs[DataTypeMetaData.KEY_TAG_1] return self.do_step(next_step, 2)
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/")
def get_focal_points(self, model_param): """ Returns the html which displays the list of focal points selected for the equation used for computing the values for the given model parameter. """ context_model_parameters = common.get_from_session(KEY_CONTEXT_MPS) return {'focal_points': context_model_parameters.get_focal_points_for_parameter(model_param), 'focal_points_json': json.dumps(context_model_parameters.get_focal_points_for_parameter(model_param))}
def get_portlet_session_configuration(self): """ Get the current configuration of portlets stored in session for this burst, as a json. """ burst_entity = common.get_from_session(common.KEY_BURST_CONFIG) returned_configuration = burst_entity.update_selected_portlets() return returned_configuration
def get_current_step(self): """ Get from session previously selected step (category ID). """ full_description = common.get_from_session(self.KEY_CURRENT_ADAPTER_INFO) if full_description is not None and self._KEY_CURRENT_STEP in full_description: return full_description[self._KEY_CURRENT_STEP] return None
def get_current_input_tree(self): """ Get from session previously selected InputTree. """ full_description = common.get_from_session(self.KEY_CURRENT_ADAPTER_INFO) if full_description is not None and self._KEY_INPUT_TREE in full_description: return full_description[self._KEY_INPUT_TREE] return None
def add_portlet_to_session(self, portlet_interface): """ Add a portlet configuration to the session. Used for applying filters on portlet configurations. """ full_description = common.get_from_session(self.KEY_CURRENT_ADAPTER_INFO) if full_description is None or full_description is {}: raise Exception("Should not add portlet interface to session") full_description[self.KEY_PORTLET_CONFIGURATION] = portlet_interface
def remove_focal_point(self, model_param, vertex_index): """ Removes the given focal point from the list of focal points specified for the equation used for computing the values for the specified model param. """ context_model_parameters = common.get_from_session(KEY_CONTEXT_MPS) context_model_parameters.remove_focal_point(model_param, vertex_index) return {'focal_points': context_model_parameters.get_focal_points_for_parameter(model_param), 'focal_points_json': json.dumps(context_model_parameters.get_focal_points_for_parameter(model_param))}
def get_session_tree_for_key(self, tree_session_key): """ Get from session previously selected InputTree stored under the :param tree_session_key. """ if tree_session_key == self.KEY_TREE_DEFAULT: return self.get_current_input_tree() full_description = common.get_from_session(self.KEY_CURRENT_ADAPTER_INFO) if full_description is not None and tree_session_key in full_description: return full_description[tree_session_key] return None
def get_selected_burst(self): """ Return the burst that is currently stored in session. This is one alternative to 'chrome-back problem'. """ session_burst = common.get_from_session(common.KEY_BURST_CONFIG) if session_burst.id: return str(session_burst.id) else: return 'None'
def get_previous_selected_rangers(self): """ Retrieve Rangers, if any previously selected in Burst. """ burst_config = common.get_from_session(common.KEY_BURST_CONFIG) first_range, second_range = '0', '0' if burst_config is not None: first_range = burst_config.get_simulation_parameter_value(RANGE_PARAMETER_1) or '0' second_range = burst_config.get_simulation_parameter_value(RANGE_PARAMETER_2) or '0' return [first_range, second_range]
def step_2_submit(self, next_step, **kwargs): """ Any submit from the second step should be handled here. Update the context and then do the next step as required. """ context = common.get_from_session(KEY_SURFACE_CONTEXT) submited_focal_points = kwargs['defined_focal_points'] context.set_focal_points(submited_focal_points) context.equation_kwargs[DataTypeMetaData.KEY_TAG_1] = kwargs[DataTypeMetaData.KEY_TAG_1] return self.do_step(next_step, 2)
def create_stimulus(self): """ Creates a stimulus from the given data. """ context = common.get_from_session(KEY_REGION_CONTEXT) local_connectivity_creator = self.get_creator_and_interface(REGION_STIMULUS_CREATOR_MODULE, REGION_STIMULUS_CREATOR_CLASS, StimuliRegion())[0] context.equation_kwargs.update({'weight': json.dumps(context.get_weights())}) self.flow_service.fire_operation(local_connectivity_creator, common.get_logged_user(), common.get_current_project().id, **context.equation_kwargs) common.set_important_message("The operation for creating the stimulus was successfully launched.")
def check_status_for_visualizer(self, selected_tab, index_in_tab, width='800', height='600'): """ This call is used to check on a regular basis if the data for a certain portlet is available for visualization. Should return the status and the HTML to be displayed. """ burst = common.get_from_session(common.KEY_BURST_CONFIG) target_portlet = burst.tabs[int(selected_tab)].portlets[int(index_in_tab)] target_portlet = self.__portlet_config2portlet_entity(target_portlet) template_dict = {'portlet_entity': target_portlet, 'model': tvb.core.entities.model, 'width': int(width), 'height': int(height)} return template_dict
def set_display_name(self, **param): display_name_form_field = StimulusSurfaceSelectorForm().display_name display_name_form_field.fill_from_post(param) if display_name_form_field.value is not None: current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) current_surface_stim.display_name = display_name_form_field.value
def set_surface(self, **param): current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_form_field = SurfaceStimulusCreatorForm().surface surface_form_field.fill_from_post(param) current_surface_stim.surface = surface_form_field.value self._reset_focal_points(current_surface_stim)
def set_temporal_param(self, **param): current_region_stim = common.get_from_session(KEY_REGION_STIMULUS) eq_param_form_class = get_form_for_equation(type(current_region_stim.temporal)) eq_param_form = eq_param_form_class(prefix=RegionStimulusCreatorForm.NAME_TEMPORAL_PARAMS_DIV) eq_param_form.fill_from_post(param) eq_param_form.fill_trait(current_region_stim.temporal)
def _add_extra_fields_to_interface(input_list): """ The fields that have to be added to the existent adapter interface should be added in this method. """ context = common.get_from_session(KEY_SURFACE_CONTEXT) temporal_iface = [] min_tmp_x = { 'name': 'min_tmp_x', 'label': 'Temporal Start Time(ms)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('min_tmp_x', 0), "description": "The minimum value of the x-axis for temporal equation plot. " "Not persisted, used only for visualization." } max_tmp_x = { 'name': 'max_tmp_x', 'label': 'Temporal End Time(ms)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('max_tmp_x', 100), "description": "The maximum value of the x-axis for temporal equation plot. " "Not persisted, used only for visualization." } temporal_iface.append(min_tmp_x) temporal_iface.append(max_tmp_x) spatial_iface = [] min_space_x = { 'name': 'min_space_x', 'label': 'Spatial Start Distance(mm)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('min_space_x', 0), "description": "The minimum value of the x-axis for spatial equation plot." } max_space_x = { 'name': 'max_space_x', 'label': 'Spatial End Distance(mm)', 'type': 'str', "disabled": "False", "default": context.equation_kwargs.get('max_space_x', 100), "description": "The maximum value of the x-axis for spatial equation plot." } spatial_iface.append(min_space_x) spatial_iface.append(max_space_x) input_list['spatialPlotInputList'] = spatial_iface input_list['temporalPlotInputList'] = temporal_iface return input_list
def set_temporal_param(self, **param): current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) eq_param_form_class = get_form_for_equation(type(current_surface_stim.temporal)) eq_param_form = eq_param_form_class(prefix=SurfaceStimulusCreatorForm.NAME_TEMPORAL_PARAMS_DIV) eq_param_form.fill_from_post(param) eq_param_form.fill_trait(current_surface_stim.temporal)
def get_equation_chart(self): """ Returns the html which contains the plot with the equations specified into 'plotted_equations_prefixes' field. """ try: # This should be called once at first rendering and once for any change event on form fields used # in computation: equation, equation params, surface, cutoff current_lconn = common.get_from_session(KEY_LCONN) surface_gid = current_lconn.surface.hex surface = load_entity_by_gid(surface_gid) if surface is None: raise MissingDataException(self.MSG_MISSING_SURFACE + "!!!") max_x = current_lconn.cutoff if max_x <= 0: max_x = 50 equation = current_lconn.equation # What we want ideal_case_series, _ = equation.get_series_data(0, 2 * max_x) # What we'll mostly get avg_res = 2 * int(max_x / surface.edge_mean_length) step = max_x * 2 / (avg_res - 1) average_case_series, _ = equation.get_series_data( 0, 2 * max_x, step) # It can be this bad worst_res = 2 * int(max_x / surface.edge_max_length) step = 2 * max_x / (worst_res - 1) worst_case_series, _ = equation.get_series_data(0, 2 * max_x, step) # This is as good as it gets... best_res = 2 * int(max_x / surface.edge_min_length) step = 2 * max_x / (best_res - 1) best_case_series, _ = equation.get_series_data(0, 2 * max_x, step) max_y = -1000000000 min_y = 10000000000 for case in ideal_case_series: if min_y > case[1]: min_y = case[1] if min_y > case[1]: min_y = case[1] if max_y < case[1]: max_y = case[1] if max_y < case[1]: max_y = case[1] vertical_line = [] vertical_step = (max_y - min_y) / NO_OF_CUTOFF_POINTS for i in range(NO_OF_CUTOFF_POINTS): vertical_line.append([max_x, min_y + i * vertical_step]) all_series = self.get_series_json(ideal_case_series, average_case_series, worst_case_series, best_case_series, vertical_line) return { 'allSeries': all_series, 'prefix': 'spatial', "message": None } except NameError as ex: self.logger.exception(ex) return { 'allSeries': None, 'errorMsg': "Incorrect parameters for equation passed." } except SyntaxError as ex: self.logger.exception(ex) return { 'allSeries': None, 'errorMsg': "Some of the parameters hold invalid characters." } except Exception as ex: self.logger.exception(ex) return {'allSeries': None, 'errorMsg': ex}
def get_selected_portlets(self): """ Get the selected portlets for the loaded burst. """ burst = common.get_from_session(common.KEY_BURST_CONFIG) return burst.update_selected_portlets()
def simulator(self): return common.get_from_session(self.KEY_SIMULATOR_CONFIG)
def set_surface(self, **param): current_lconn = common.get_from_session(KEY_LCONN) surface_form_field = LocalConnectivityCreatorForm().surface surface_form_field.fill_from_post(param) current_lconn.surface = surface_form_field.value
def change_selected_tab(self, tab_nr): """ Set :param tab_nr: as the currently selected tab in the stored burst configuration. """ common.get_from_session(common.KEY_BURST_CONFIG).selected_tab = int(tab_nr)
def step_1(self, do_reset=0, **kwargs): """ Generate the html for the first step of the local connectivity page. :param do_reset: Boolean telling to start from empty page or not :param kwargs: not actually used, but parameters are still submitted from UI since we just\ use the same js function for this. TODO: do this in a smarter way """ project_id = common.get_current_project().id if int(do_reset) == 1: new_lconn = LocalConnectivityCreatorModel() default_surface_index = dao.try_load_last_surface_of_type( project_id, CORTICAL) if default_surface_index: new_lconn.surface = uuid.UUID(default_surface_index.gid) else: # TODO: ok to keep a default gid here? new_lconn.surface = uuid.uuid4() common.add2session(KEY_LCONN, new_lconn) current_lconn = common.get_from_session(KEY_LCONN) existent_lcon_form = LocalConnectivitySelectorForm( project_id=project_id) existent_lcon_form.existentEntitiesSelect.data = current_lconn.gid.hex configure_lcon_form = LocalConnectivityCreatorForm( self.possible_equations, project_id=project_id) configure_lcon_form.fill_from_trait(current_lconn) current_lconn.equation = configure_lcon_form.spatial.value() template_specification = dict(title="Surface - Local Connectivity") template_specification[ 'mainContent'] = 'spatial/local_connectivity_step1_main' template_specification['inputList'] = self.get_template_dict( configure_lcon_form) template_specification['displayCreateLocalConnectivityBtn'] = True template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification[ 'existentEntitiesInputList'] = self.get_template_dict( existent_lcon_form) template_specification[ 'submit_parameters_url'] = '/spatial/localconnectivity/create_local_connectivity' template_specification[ 'equationViewerUrl'] = '/spatial/localconnectivity/get_equation_chart' template_specification[ 'localConnBaseUrl'] = '/spatial/localconnectivity' self.plotted_equation_prefixes = { self.SURFACE_FIELD: configure_lcon_form.surface.name, self.EQUATION_FIELD: configure_lcon_form.spatial.name, self.CUTOFF_FIELD: configure_lcon_form.cutoff.name, self.DISPLAY_NAME_FIELD: configure_lcon_form.display_name.name, self.EQUATION_PARAMS_FIELD: configure_lcon_form.spatial_params.name[1:] } template_specification['equationsPrefixes'] = json.dumps( self.plotted_equation_prefixes) template_specification[ 'next_step_url'] = '/spatial/localconnectivity/step_2' msg, msg_type = common.get_message_from_session() template_specification['displayedMessage'] = msg return self.fill_default_attributes(template_specification)
def burst_config(self): return common.get_from_session(self.KEY_BURST_CONFIG)
def set_display_name(self, **param): display_name_form_field = LocalConnectivityCreatorForm().display_name display_name_form_field.fill_from_post(param) if display_name_form_field.value is not None: lconn = common.get_from_session(KEY_LCONN) lconn.display_name = display_name_form_field.value
def get_view_model_from_session(self): """ Get view_model from session """ return common.get_from_session(self.KEY_VIEW_MODEL)
def set_surface(self, **param): current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_form_field = SurfaceStimulusCreatorForm(self.possible_spatial_equations, self.possible_temporal_equations, common.get_current_project().id).surface surface_form_field.fill_from_post(param) current_surface_stim.surface = surface_form_field.value self._reset_focal_points(current_surface_stim)
def set_cutoff_value(self, **param): current_lconn = common.get_from_session(KEY_LCONN) cutoff_form_field = LocalConnectivityCreatorForm().cutoff cutoff_form_field.fill_from_post(param) current_lconn.cutoff = cutoff_form_field.value
def set_equation_param(self, **param): current_lconn = common.get_from_session(KEY_LCONN) eq_param_form_class = get_form_for_equation(type(current_lconn.equation)) eq_param_form = eq_param_form_class(prefix=LocalConnectivityCreatorForm.NAME_EQUATION_PARAMS_DIV) eq_param_form.fill_from_post(param) eq_param_form.fill_trait(current_lconn.equation)
def get_equation_chart(self, **form_data): """ Returns the html which contains the plot with the equations specified into 'plotted_equations_prefixes' field. """ if len(form_data['equation'] ) > 0 and form_data['equation'] is not None: try: context = common.get_from_session(KEY_LCONN_CONTEXT) surface_gid = form_data['surface'] if context.selected_surface is None or context.selected_surface.gid != surface_gid: surface = ABCAdapter.load_entity_by_gid(surface_gid) else: surface = context.selected_surface local_connectivity_creator = self.get_creator_and_interface( LOCAL_CONN_CREATOR_MODULE, LOCAL_CONN_CREATOR_CLASS, LocalConnectivity())[0] max_x = float(form_data["cutoff"]) if max_x <= 0: max_x = 50 form_data = local_connectivity_creator.prepare_ui_inputs( form_data, validation_required=False) equation = local_connectivity_creator.get_lconn_equation( form_data) #What we want ideal_case_series, _ = equation.get_series_data(0, 2 * max_x) #What we'll mostly get avg_res = 2 * int(max_x / surface.edge_length_mean) step = max_x * 2 / (avg_res - 1) average_case_series, _ = equation.get_series_data( 0, 2 * max_x, step) #It can be this bad worst_res = 2 * int(max_x / surface.edge_length_max) step = 2 * max_x / (worst_res - 1) worst_case_series, _ = equation.get_series_data( 0, 2 * max_x, step) #This is as good as it gets... best_res = 2 * int(max_x / surface.edge_length_min) step = 2 * max_x / (best_res - 1) best_case_series, _ = equation.get_series_data( 0, 2 * max_x, step) max_y = -1000000000 min_y = 10000000000 for case in ideal_case_series: if min_y > case[1]: min_y = case[1] if min_y > case[1]: min_y = case[1] if max_y < case[1]: max_y = case[1] if max_y < case[1]: max_y = case[1] vertical_line = [] vertical_step = (max_y - min_y) / NO_OF_CUTOFF_POINTS for i in xrange(NO_OF_CUTOFF_POINTS): vertical_line.append([max_x, min_y + i * vertical_step]) all_series = self.get_series_json(ideal_case_series, average_case_series, worst_case_series, best_case_series, vertical_line) return { 'allSeries': all_series, 'prefix': self.plotted_equations_prefixes[0], "message": None } except NameError, ex: self.logger.exception(ex) return { 'allSeries': None, 'errorMsg': "Incorrect parameters for equation passed." } except SyntaxError, ex: self.logger.exception(ex) return { 'allSeries': None, 'errorMsg': "Some of the parameters hold invalid characters." }
def step_1(self, do_reset=0, **kwargs): """ Generate the html for the first step of the local connectivity page. :param do_reset: Boolean telling to start from empty page or not :param kwargs: not actually used, but parameters are still submitted from UI since we just\ use the same js function for this. """ project_id = common.get_current_project().id if int(do_reset) == 1: new_lconn = LocalConnectivityCreatorModel() default_surface_index = try_get_last_datatype( project_id, SurfaceIndex, LocalConnectivityCreatorForm.get_filters()) if default_surface_index: new_lconn.surface = uuid.UUID(default_surface_index.gid) else: # Surface is required in model and we should keep it like this, but we also want to new_lconn.surface = uuid.uuid4() common.set_error_message(self.MSG_MISSING_SURFACE) common.add2session(KEY_LCONN, new_lconn) current_lconn = common.get_from_session(KEY_LCONN) existent_lcon_form = self.algorithm_service.prepare_adapter_form( form_instance=LocalConnectivitySelectorForm(), project_id=common.get_current_project().id) existent_lcon_form.existentEntitiesSelect.data = current_lconn.gid.hex configure_lcon_form = self.algorithm_service.prepare_adapter_form( form_instance=LocalConnectivityCreatorForm(), project_id=common.get_current_project().id) configure_lcon_form.fill_from_trait(current_lconn) current_lconn.equation = configure_lcon_form.spatial.value() template_specification = dict(title="Surface - Local Connectivity") template_specification[ 'mainContent'] = 'spatial/local_connectivity_step1_main' template_specification['inputList'] = self.render_spatial_form( configure_lcon_form) template_specification['displayCreateLocalConnectivityBtn'] = True template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification[ 'existentEntitiesInputList'] = self.render_spatial_form( existent_lcon_form) template_specification[ 'submit_parameters_url'] = '/spatial/localconnectivity/create_local_connectivity' template_specification[ 'equationViewerUrl'] = '/spatial/localconnectivity/get_equation_chart' template_specification['baseUrl'] = self.base_url self.plotted_equation_prefixes = { self.SURFACE_FIELD: configure_lcon_form.surface.name, self.EQUATION_FIELD: configure_lcon_form.spatial.name, self.CUTOFF_FIELD: configure_lcon_form.cutoff.name, self.DISPLAY_NAME_FIELD: configure_lcon_form.display_name.name, self.EQUATION_PARAMS_FIELD: configure_lcon_form.spatial.subform_field.name[1:] } template_specification['equationsPrefixes'] = json.dumps( self.plotted_equation_prefixes) template_specification[ 'next_step_url'] = '/spatial/localconnectivity/step_2' return self.fill_default_attributes(template_specification)
def set_model_parameter(self, model_parameter): context = common.get_from_session(KEY_CONTEXT_MPS) context.current_model_param = model_parameter template_specification = self._prepare_reload(context) return self.fill_default_attributes(template_specification)
def _cache(self): cache = common.get_from_session(self.SESSION_KEY) if cache is None: cache = {} common.add2session(self.SESSION_KEY, cache) return cache
def last_loaded_fragment_url(self): return common.get_from_session(self.KEY_LAST_LOADED_FORM_URL)