def step_1(self): """ Generate the required template dictionary for the first step. """ current_stimuli_region = common.get_from_session(KEY_REGION_STIMULUS) selected_stimulus_gid = current_stimuli_region.gid.hex region_stim_selector_form = StimulusRegionSelectorForm(common.get_current_project().id) region_stim_selector_form.region_stimulus.data = selected_stimulus_gid region_stim_selector_form.display_name.data = common.get_from_session(KEY_REGION_STIMULUS_NAME) region_stim_creator_form = RegionStimulusCreatorForm(self.equation_choices, common.get_current_project().id) if not hasattr(current_stimuli_region, 'connectivity') or not current_stimuli_region.connectivity: current_connectivity_in_form = region_stim_creator_form.connectivity._get_values_from_db()[0] region_stim_creator_form.connectivity.data = current_connectivity_in_form[2] current_stimuli_region.connectivity = uuid.UUID(region_stim_creator_form.connectivity.value) region_stim_creator_form.fill_from_trait(current_stimuli_region) template_specification = dict(title="Spatio temporal - Region stimulus") template_specification['mainContent'] = 'spatial/stimulus_region_step1_main' template_specification['isSingleMode'] = True template_specification['regionStimSelectorForm'] = self.get_template_dict(region_stim_selector_form) template_specification['regionStimCreatorForm'] = self.get_template_dict(region_stim_creator_form) template_specification['baseUrl'] = '/spatial/stimulus/region' self.plotted_equation_prefixes = { self.CONNECTIVITY_FIELD: region_stim_creator_form.connectivity.name, self.TEMPORAL_FIELD: region_stim_creator_form.temporal.name, self.TEMPORAL_PARAMS_FIELD: region_stim_creator_form.temporal_params.name[1:], self.DISPLAY_NAME_FIELD: region_stim_selector_form.display_name.name } template_specification['fieldsWithEvents'] = json.dumps(self.plotted_equation_prefixes) template_specification['next_step_url'] = '/spatial/stimulus/region/step_1_submit' template_specification['anyScaling'] = 0 template_specification = self._add_extra_fields_to_interface(template_specification) return self.fill_default_attributes(template_specification)
def step_1(self): """ Used for generating the interface which allows the user to define a stimulus. """ current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_stim_selector_form = StimulusSurfaceSelectorForm(common.get_current_project().id) surface_stim_selector_form.surface_stimulus.data = current_surface_stim.gid.hex surface_stim_creator_form = SurfaceStimulusCreatorForm(self.possible_spatial_equations, self.possible_temporal_equations, common.get_current_project().id) if not hasattr(current_surface_stim, 'surface') or not current_surface_stim.surface: current_surface_in_form = surface_stim_creator_form.surface._get_values_from_db()[0] surface_stim_creator_form.surface.data = current_surface_in_form[2] current_surface_stim.surface = uuid.UUID(surface_stim_creator_form.surface.value) surface_stim_creator_form.fill_from_trait(current_surface_stim) surface_stim_selector_form.display_name.data = common.get_from_session(KEY_SURFACE_STIMULI_NAME) template_specification = dict(title="Spatio temporal - Surface stimulus") template_specification['surfaceStimulusSelectForm'] = surface_stim_selector_form template_specification['surfaceStimulusCreateForm'] = surface_stim_creator_form self.plotted_equation_prefixes = { self.SURFACE_FIELD: surface_stim_creator_form.surface.name, self.SPATIAL_FIELD: surface_stim_creator_form.spatial.name, self.SPATIAL_PARAMS_FIELD: surface_stim_creator_form.spatial_params.name[1:], self.TEMPORAL_FIELD: surface_stim_creator_form.temporal.name, self.TEMPORAL_PARAMS_FIELD: surface_stim_creator_form.temporal_params.name[1:], self.DISPLAY_NAME_FIELD: surface_stim_selector_form.display_name.name } template_specification['mainContent'] = 'spatial/stimulus_surface_step1_main' template_specification['baseUrl'] = '/spatial/stimulus/surface' template_specification['spatialFieldsPrefixes'] = json.dumps(self.plotted_equation_prefixes) template_specification['next_step_url'] = '/spatial/stimulus/surface/step_1_submit' template_specification['definedFocalPoints'] = current_surface_stim.focal_points_triangles.tolist() template_specification = self._add_extra_fields_to_interface(template_specification) return self.fill_default_attributes(template_specification)
def get_creator_and_interface(self, creator_module, creator_class, datatype_instance, lock_midpoint_for_eq=None): """ Returns a Tuple: a creator instance and a dictionary for the creator interface. The interface is prepared for rendering, it is populated with existent data, in case of a parameter of type DataType. The name of the attributes are also prefixed to identify groups. """ algo_group = self.flow_service.get_algorithm_by_module_and_class( creator_module, creator_class)[1] group, _ = self.flow_service.prepare_adapter( common.get_current_project().id, algo_group) #I didn't use the interface(from the above line) returned by the method 'prepare_adapter' from flow service # because the selects that display dataTypes will also have the 'All' entry. datatype_instance.trait.bound = traited_interface.INTERFACE_ATTRIBUTES_ONLY input_list = datatype_instance.interface[ traited_interface.INTERFACE_ATTRIBUTES] if lock_midpoint_for_eq is not None: for idx in lock_midpoint_for_eq: input_list[idx] = self._lock_midpoints(input_list[idx]) category = self.flow_service.get_visualisers_category() input_list = self.flow_service.prepare_parameters( input_list, common.get_current_project().id, category.id) input_list = ABCAdapter.prepare_param_names(input_list) return self.flow_service.build_adapter_instance(group), input_list
def index(self): """Get on burst main page""" # todo : reuse load_burst here for consistency. template_specification = dict( mainContent="burst/main_burst", title="Simulation Cockpit", baseUrl=TvbProfile.current.web.BASE_URL, includedResources='project/included_resources') portlets_list = self.burst_service.get_available_portlets() session_stored_burst = common.get_from_session(common.KEY_BURST_CONFIG) if session_stored_burst is None or session_stored_burst.id is None: if session_stored_burst is None: session_stored_burst = self.burst_service.new_burst_configuration( common.get_current_project().id) common.add2session(common.KEY_BURST_CONFIG, session_stored_burst) adapter_interface = self.cached_simulator_input_tree if session_stored_burst is not None: current_data = session_stored_burst.get_all_simulator_values( )[0] adapter_interface = InputTreeManager.fill_defaults( adapter_interface, current_data, True) ### Add simulator tree to session to be available in filters self.context.add_adapter_to_session( self.cached_simulator_algorithm, adapter_interface, current_data) template_specification['inputList'] = adapter_interface selected_portlets = session_stored_burst.update_selected_portlets() template_specification[ 'burst_list'] = self.burst_service.get_available_bursts( common.get_current_project().id) template_specification['portletList'] = portlets_list template_specification['selectedPortlets'] = json.dumps( selected_portlets) template_specification['draw_hidden_ranges'] = True template_specification['burstConfig'] = session_stored_burst ### Prepare PSE available metrics ### We put here all available algorithms, because the metrics select area is a generic one, ### and not loaded with every Burst Group change in history. algorithm = self.flow_service.get_algorithm_by_module_and_class( IntrospectionRegistry.MEASURE_METRICS_MODULE, IntrospectionRegistry.MEASURE_METRICS_CLASS) adapter_instance = ABCAdapter.build_adapter(algorithm) if adapter_instance is not None and hasattr(adapter_instance, 'available_algorithms'): template_specification['available_metrics'] = [ metric_name for metric_name in adapter_instance.available_algorithms ] else: template_specification['available_metrics'] = [] template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification[common.KEY_SECTION] = 'burst' return self.fill_default_attributes(template_specification)
def step_1(self): """ Used for generating the interface which allows the user to define a stimulus. """ current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) project_id = common.get_current_project().id surface_stim_selector_form = self.algorithm_service.prepare_adapter_form( form_instance=StimulusSurfaceSelectorForm(), project_id=common.get_current_project().id) surface_stim_selector_form.surface_stimulus.data = current_surface_stim.gid.hex surface_stim_creator_form = self.algorithm_service.prepare_adapter_form( form_instance=SurfaceStimulusCreatorForm(), project_id=common.get_current_project().id) if not hasattr(current_surface_stim, 'surface') or not current_surface_stim.surface: default_surface_index = try_get_last_datatype( project_id, SurfaceIndex, SurfaceStimulusCreatorForm.get_filters()) if default_surface_index is None: common.set_error_message(self.MSG_MISSING_SURFACE) current_surface_stim.surface = uuid.uuid4() else: current_surface_stim.surface = uuid.UUID( default_surface_index.gid) surface_stim_creator_form.fill_from_trait(current_surface_stim) surface_stim_selector_form.display_name.data = current_surface_stim.display_name template_specification = dict( title="Spatio temporal - Surface stimulus") template_specification[ 'surfaceStimulusSelectForm'] = self.render_spatial_form( surface_stim_selector_form) template_specification[ 'surfaceStimulusCreateForm'] = self.render_spatial_form( surface_stim_creator_form) self.plotted_equation_prefixes = { self.SURFACE_FIELD: surface_stim_creator_form.surface.name, self.DISPLAY_NAME_FIELD: surface_stim_selector_form.display_name.name } template_specification[ 'mainContent'] = 'spatial/stimulus_surface_step1_main' template_specification['baseUrl'] = self.base_url template_specification['spatialFieldsPrefixes'] = json.dumps( self.plotted_equation_prefixes) template_specification[ 'next_step_url'] = '/spatial/stimulus/surface/step_1_submit' template_specification[ 'definedFocalPoints'] = current_surface_stim.focal_points_triangles.tolist( ) template_specification = self._add_extra_fields_to_interface( template_specification) return self.fill_default_attributes(template_specification)
def step_1(self): """ Generate the required template dictionary for the first step. """ current_stimuli_region = common.get_from_session(KEY_REGION_STIMULUS) selected_stimulus_gid = current_stimuli_region.gid.hex project_id = common.get_current_project().id region_stim_selector_form = self.algorithm_service.prepare_adapter_form( form_instance=StimulusRegionSelectorForm(), project_id=common.get_current_project().id) region_stim_selector_form.region_stimulus.data = selected_stimulus_gid region_stim_selector_form.display_name.data = current_stimuli_region.display_name region_stim_creator_form = self.algorithm_service.prepare_adapter_form( form_instance=RegionStimulusCreatorForm(), project_id=common.get_current_project().id) if not hasattr( current_stimuli_region, 'connectivity') or not current_stimuli_region.connectivity: conn = try_get_last_datatype(project_id, ConnectivityIndex) if conn is None: current_stimuli_region.connectivity = uuid.uuid4() common.set_error_message(self.MSG_MISSING_CONNECTIVITY) else: current_stimuli_region.connectivity = uuid.UUID(conn.gid) region_stim_creator_form.fill_from_trait(current_stimuli_region) template_specification = dict( title="Spatio temporal - Region stimulus") template_specification[ 'mainContent'] = 'spatial/stimulus_region_step1_main' template_specification['isSingleMode'] = True template_specification[ 'regionStimSelectorForm'] = self.render_spatial_form( region_stim_selector_form) template_specification[ 'regionStimCreatorForm'] = self.render_spatial_form( region_stim_creator_form) template_specification['baseUrl'] = self.base_url self.plotted_equation_prefixes = { self.CONNECTIVITY_FIELD: region_stim_creator_form.connectivity.name, self.DISPLAY_NAME_FIELD: region_stim_selector_form.display_name.name } template_specification['fieldsWithEvents'] = json.dumps( self.plotted_equation_prefixes) template_specification[ 'next_step_url'] = '/spatial/stimulus/region/step_1_submit' template_specification['anyScaling'] = 0 template_specification = self._add_extra_fields_to_interface( template_specification) return self.fill_default_attributes(template_specification)
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 prepare_group_launch(self, group_gid, step_key, algorithm_id, **data): """ Receives as input a group gid and an algorithm given by category and id, along with data that gives the name of the required input parameter for the algorithm. Having these generate a range of GID's for all the DataTypes in the group and launch a new operation group. """ dt_group = self.project_service.get_datatypegroup_by_gid(group_gid) datatypes = self.project_service.get_datatypes_from_datatype_group(dt_group.id) range_param_name = data.pop('range_param_name') data[RANGE_PARAMETER_1] = range_param_name data[range_param_name] = ','.join(dt.gid for dt in datatypes) self.operation_services.group_operation_launch(common.get_logged_user().id, common.get_current_project(), int(algorithm_id), int(step_key), **data) redirect_url = self._compute_back_link('operations', common.get_current_project()) raise cherrypy.HTTPRedirect(redirect_url)
def readjsonstructure(self, project_id, visibility_filter=StaticFiltersFactory.FULL_VIEW, first_level=None, second_level=None, filter_value=None): """ AJAX exposed method. Will return the complete JSON for Project's structure, or filtered tree (filter only Relevant entities or Burst only Data). """ if first_level is None or second_level is None: first_level, second_level = self.get_project_structure_grouping() else: self.set_project_structure_grouping(first_level, second_level) selected_filter = StaticFiltersFactory.build_datatype_filters( single_filter=visibility_filter) if project_id == 'undefined': project_id = common.get_current_project().id project = self.project_service.find_project(project_id) json_structure = self.project_service.get_project_structure( project, selected_filter, first_level, second_level, filter_value) # This JSON encoding is necessary, otherwise we will get an error # from JSTree library while trying to load with AJAX # the content of the tree. encoder = JSONEncoder() return encoder.iterencode(json_structure)
def set_connectivity(self, **param): current_region_stim = common.get_from_session(KEY_REGION_STIMULUS) connectivity_form_field = RegionStimulusCreatorForm(common.get_current_project().id).connectivity connectivity_form_field.fill_from_post(param) current_region_stim.connectivity = connectivity_form_field.value conn_index = ABCAdapter.load_entity_by_gid(connectivity_form_field.value.hex) current_region_stim.weight = StimuliRegion.get_default_weights(conn_index.number_of_regions)
def set_display_name(self, **param): display_name_form_field = StimulusRegionSelectorForm( common.get_current_project().id).display_name display_name_form_field.fill_from_post(param) if display_name_form_field.value is not None: common.add2session(KEY_REGION_STIMULUS_NAME, display_name_form_field.value)
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. """ current_lconn = common.get_from_session(KEY_LCONN) left_side_form = LocalConnectivitySelectorForm( project_id=common.get_current_project().id) left_side_form.existentEntitiesSelect.data = current_lconn.gid.hex template_specification = dict(title="Surface - Local Connectivity") template_specification[ 'mainContent'] = 'spatial/local_connectivity_step2_main' template_specification[ 'existentEntitiesInputList'] = self.render_adapter_form( left_side_form) 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 if current_lconn is not None: selected_local_conn = load_entity_by_gid(current_lconn.gid) template_specification.update( self.display_surface(selected_local_conn.fk_surface_gid)) template_specification['no_local_connectivity'] = False template_specification[ 'minValue'] = selected_local_conn.matrix_non_zero_min template_specification[ 'maxValue'] = selected_local_conn.matrix_non_zero_max else: template_specification['no_local_connectivity'] = True template_specification[common.KEY_PARAMETERS_CONFIG] = False return self.fill_default_attributes(template_specification)
def invokeadaptermethod(self, adapter_id, method_name, **data): """ Public web method, to be used when invoking specific methods from external Adapters/Algorithms. """ algo_group = self.flow_service.get_algo_group_by_identifier(adapter_id) try: adapter_instance = self.flow_service.build_adapter_instance(algo_group) result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), common.get_current_project().id, method_name, **data) common.set_info_message("Submit OK!") if isinstance(adapter_instance, ABCDisplayer) and isinstance(result, dict): common.pop_message_from_session() result[ABCDisplayer.KEY_IS_ADAPTER] = True result[common.KEY_DISPLAY_MENU] = True result[common.KEY_OPERATION_ID] = adapter_instance.operation_id result[common.KEY_ADAPTER] = adapter_id if KEY_CONTROLLS not in result: result[KEY_CONTROLLS] = None self._populate_section(algo_group, result) return self.fill_default_attributes(result, algo_group.displayname) except OperationException, excep: common.set_warning_message('Problem when submitting data!') self.logger.error("Invalid method, or wrong parameters when invoking external method on post!") self.logger.exception(excep)
def _mark_selected(self, project): """ Set the project passed as parameter as the selected project. """ previous_project = common.get_current_project() # Update project stored in selection, with latest Project entity from DB. members = self.user_service.get_users_for_project("", project.id)[1] project.members = members if previous_project is None or previous_project.id != project.id: # Clean Burst selection from session in case of a different project. SimulatorContext().clean_project_data_from_session() # Store in DB new project selection user = common.get_from_session(common.KEY_USER) if user is not None: self.user_service.save_project_to_user(user.id, project.id) # Display info message about project change self.logger.debug("Selected project is now " + project.name) common.set_info_message("Your current working project is: " + str(project.name)) linked_dt = self.project_service.get_linked_datatypes_storage_path( project) storage_interface = StorageInterface() storage_interface.set_project_active(project, linked_dt) if previous_project is not None: storage_interface.set_project_inactive(previous_project) # Add the project entity to session every time, as it might be changed (e.g. after edit) common.add2session(common.KEY_PROJECT, project)
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() sim_config = common.get_from_session(common.KEY_SIMULATOR_CONFIG) connectivity = sim_config.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_idx = dao.get_datatype_by_gid(connectivity.hex) conn_path = file_handler.get_project_folder(current_project, str(conn_idx.fk_from_operation)) params = ConnectivityViewer.get_connectivity_parameters(conn_idx, conn_path) burst_config = common.get_from_session(common.KEY_BURST_CONFIG) 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': burst_config.dynamic_ids }) return self.fill_default_attributes(params, 'regionmodel')
def invokeadaptermethod(self, adapter_id, method_name, **data): """ Public web method, to be used when invoking specific methods from external Adapters/Algorithms. """ algo_group = self.flow_service.get_algo_group_by_identifier(adapter_id) try: adapter_instance = self.flow_service.build_adapter_instance( algo_group) result = self.flow_service.fire_operation( adapter_instance, common.get_logged_user(), common.get_current_project().id, method_name, **data) common.set_info_message("Submit OK!") if isinstance(adapter_instance, ABCDisplayer) and isinstance( result, dict): common.pop_message_from_session() result[ABCDisplayer.KEY_IS_ADAPTER] = True result[common.KEY_DISPLAY_MENU] = True result[common.KEY_OPERATION_ID] = adapter_instance.operation_id result[common.KEY_ADAPTER] = adapter_id if KEY_CONTROLLS not in result: result[KEY_CONTROLLS] = None self._populate_section(algo_group, result) return self.fill_default_attributes(result, algo_group.displayname) except OperationException, excep: common.set_warning_message('Problem when submitting data!') self.logger.error( "Invalid method, or wrong parameters when invoking external method on post!" ) self.logger.exception(excep)
def load_burst_from_json(self, **data): """Upload Burst from previously exported JSON file""" self.logger.debug("Uploading ..." + str(data)) try: upload_param = "uploadedfile" if upload_param in data and data[upload_param]: upload_param = data[upload_param] if isinstance(upload_param, FieldStorage) or isinstance( upload_param, Part): if not upload_param.file: raise BurstServiceException( "Please select a valid JSON file.") upload_param = upload_param.file.read() upload_param = json.loads(upload_param) prj_id = common.get_current_project().id importer = ImportService() burst_entity = importer.load_burst_entity(upload_param, prj_id) common.add2session(common.KEY_BURST_CONFIG, burst_entity) except Exception as excep: self.logger.warning(excep.message) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/burst/')
def store_exploration_section(self, val_range, step, dt_group_guid): """ Launching method for further simulations. """ range_list = [float(num) for num in val_range.split(",")] step_list = [float(num) for num in step.split(",")] datatype_group_ob = ProjectService().get_datatypegroup_by_gid(dt_group_guid) operation_grp = datatype_group_ob.parent_operation_group operation_obj = self.flow_service.load_operation(datatype_group_ob.fk_from_operation) parameters = json.loads(operation_obj.parameters) range1name, range1_dict = json.loads(operation_grp.range1) range2name, range2_dict = json.loads(operation_grp.range2) parameters[RANGE_PARAMETER_1] = range1name parameters[RANGE_PARAMETER_2] = range2name ##change the existing simulator parameters to be min max step types range1_dict = {constants.ATT_MINVALUE: range_list[0], constants.ATT_MAXVALUE: range_list[1], constants.ATT_STEP: step_list[0]} range2_dict = {constants.ATT_MINVALUE: range_list[2], constants.ATT_MAXVALUE: range_list[3], constants.ATT_STEP: step_list[1]} parameters[range1name] = json.dumps(range1_dict) # this is for the x axis parameter parameters[range2name] = json.dumps(range2_dict) # this is for the y axis parameter OperationService().group_operation_launch(common.get_logged_user().id, common.get_current_project().id, operation_obj.algorithm.id, operation_obj.algorithm.fk_category, datatype_group_ob, **parameters) return [True, 'Stored the exploration material successfully']
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 set_surface(self, **param): current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_form_field = SurfaceStimulusCreatorForm( 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 create_stimulus(self): """ Creates a stimulus from the given data. """ try: current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_stimulus_creator = ABCAdapter.build_adapter_from_class( SurfaceStimulusCreator) self.operation_service.fire_operation( surface_stimulus_creator, common.get_logged_user(), common.get_current_project().id, view_model=current_surface_stim) common.set_important_message( "The operation for creating the stimulus was successfully launched." ) except (NameError, ValueError, SyntaxError): common.set_error_message( "The operation failed due to invalid parameter input.") return False except Exception as ex: common.set_error_message(ex) return False return True
def step_2(self): """ Used for generating the interface which allows the user to define a stimulus. """ current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) template_specification = dict( title="Spatio temporal - Surface stimulus") surface_stim_selector_form = StimulusSurfaceSelectorForm( common.get_current_project().id) surface_stim_selector_form.display_name.data = current_surface_stim.display_name surface_stim_selector_form.surface_stimulus.data = current_surface_stim.gid.hex template_specification[ 'surfaceStimulusSelectForm'] = self.render_adapter_form( surface_stim_selector_form) template_specification[ 'mainContent'] = 'spatial/stimulus_surface_step2_main' template_specification[ 'next_step_url'] = '/spatial/stimulus/surface/step_2_submit' template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification['surfaceGID'] = current_surface_stim.surface.hex template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification[ 'definedFocalPoints'] = current_surface_stim.focal_points_triangles.tolist( ) plotted_equation_prefixes = { self.DISPLAY_NAME_FIELD: surface_stim_selector_form.display_name.name } template_specification['baseUrl'] = self.base_url template_specification['spatialFieldsPrefixes'] = json.dumps( plotted_equation_prefixes) template_specification.update( self.display_surface(current_surface_stim.surface.hex)) return self.fill_default_attributes(template_specification)
def get_portlet_configurable_interface(self, index_in_tab): """ From the position given by the tab index and the index from that tab, get the portlet configuration and build the configurable interface for that portlet. """ burst_config = common.get_from_session(common.KEY_BURST_CONFIG) tab_index = burst_config.selected_tab portlet_config = burst_config.tabs[tab_index].portlets[int( index_in_tab)] portlet_interface = self.burst_service.build_portlet_interface( portlet_config, common.get_current_project().id) full_portlet_input_tree = [] for entry in portlet_interface: full_portlet_input_tree.extend(entry.interface) self.context.add_portlet_to_session(full_portlet_input_tree) portlet_interface = { "adapters_list": portlet_interface, common.KEY_PARAMETERS_CONFIG: False, common.KEY_SESSION_TREE: self.context.KEY_PORTLET_CONFIGURATION } return self.fill_default_attributes(portlet_interface)
def _compute_operation_details(self, entity_gid, is_group=False): """ Returns a dictionary which contains the details for the given operation. """ selected_project = common.get_current_project() op_details = self.project_service.get_operation_details(entity_gid, is_group) operation_id = op_details.operation_id display_reload_btn = True operation = self.flow_service.load_operation(operation_id) if (operation.fk_operation_group is not None) or (operation.burst is not None): display_reload_btn = False else: op_categ_id = operation.algorithm.algo_group.fk_category raw_categories = self.flow_service.get_raw_categories() for category in raw_categories: if category.id == op_categ_id: display_reload_btn = False break template_specification = {"entity_gid": entity_gid, "nodeFields": op_details.get_ui_fields(), "operationId": operation_id, "displayReloadBtn": display_reload_btn, "project": selected_project, "isRelevant": operation.visible} return template_specification
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 as e: self.logger.exception("Could not launch burst!") return {'error': e.message}
def _compute_operation_details(self, entity_gid, is_group=False): """ Returns a dictionary which contains the details for the given operation. """ selected_project = common.get_current_project() op_details = self.project_service.get_operation_details( entity_gid, is_group) operation_id = op_details.operation_id display_reload_btn = True operation = OperationService.load_operation(operation_id) if (operation.fk_operation_group is not None) or (operation.burst is not None): display_reload_btn = False else: op_categ_id = operation.algorithm.fk_category raw_categories = self.algorithm_service.get_raw_categories() for category in raw_categories: if category.id == op_categ_id: display_reload_btn = False break template_specification = { "entity_gid": entity_gid, "nodeFields": op_details.get_ui_fields(), "operationId": operation_id, "displayReloadBtn": display_reload_btn, "project": selected_project, "isRelevant": operation.visible } return template_specification
def show_group_of_algorithms(self, step_key, algorithm_ids): project = common.get_current_project() category = self.algorithm_service.get_category_by_id(step_key) algorithms = [] for i in algorithm_ids.split(','): algorithm_id = int(i) algorithm = self.algorithm_service.get_algorithm_by_identifier( algorithm_id) algorithm.link = self.get_url_adapter(step_key, algorithm_id) adapter_instance = self.algorithm_service.prepare_adapter( algorithm) adapter_form = self.algorithm_service.prepare_adapter_form( adapter_instance, project.id) algorithm.form = self.render_adapter_form(adapter_form) algorithms.append(algorithm) template_specification = dict( mainContent="flow/algorithms_list", algorithms=algorithms, title="Select an algorithm", section_name=category.displayname.lower()) self._populate_section(algorithms[0], template_specification) self.fill_default_attributes(template_specification, algorithms[0].group_name) return template_specification
def step_2(self): """ Generate the required template dictionary for the second step. """ current_region_stimulus = common.get_from_session(KEY_REGION_STIMULUS) region_stim_selector_form = StimulusRegionSelectorForm(common.get_current_project().id) region_stim_selector_form.region_stimulus.data = current_region_stimulus.gid.hex region_stim_selector_form.display_name.data = common.get_from_session(KEY_REGION_STIMULUS_NAME) template_specification = dict(title="Spatio temporal - Region stimulus") template_specification['mainContent'] = 'spatial/stimulus_region_step2_main' template_specification['next_step_url'] = '/spatial/stimulus/region/step_2_submit' template_specification['regionStimSelectorForm'] = self.render_adapter_form(region_stim_selector_form) default_weights = current_region_stimulus.weight if len(default_weights) == 0: selected_connectivity = ABCAdapter.load_entity_by_gid(current_region_stimulus.connectivity.hex) if selected_connectivity is None: common.set_error_message(self.MSG_MISSING_CONNECTIVITY) default_weights = numpy.array([]) else: default_weights = StimuliRegion.get_default_weights(selected_connectivity.number_of_regions) template_specification['baseUrl'] = self.base_url self.plotted_equation_prefixes = { self.DISPLAY_NAME_FIELD: region_stim_selector_form.display_name.name } template_specification['fieldsWithEvents'] = json.dumps(self.plotted_equation_prefixes) template_specification['node_weights'] = json.dumps(default_weights.tolist()) template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification.update(self.display_connectivity(current_region_stimulus.connectivity.hex)) return self.fill_default_attributes(template_specification)
def step_2(self): """ Generate the required template dictionary for the second step. """ current_region_stimulus = common.get_from_session(KEY_REGION_STIMULUS) region_stim_selector_form = StimulusRegionSelectorForm( common.get_current_project().id) region_stim_selector_form.region_stimulus.data = current_region_stimulus.gid.hex region_stim_selector_form.display_name.data = common.get_from_session( KEY_REGION_STIMULUS_NAME) template_specification = dict( title="Spatio temporal - Region stimulus") template_specification[ 'mainContent'] = 'spatial/stimulus_region_step2_main' template_specification[ 'next_step_url'] = '/spatial/stimulus/region/step_2_submit' template_specification[ 'regionStimSelectorForm'] = region_stim_selector_form default_weights = current_region_stimulus.weight if len(default_weights) == 0: selected_connectivity = ABCAdapter.load_entity_by_gid( current_region_stimulus.connectivity.hex) default_weights = StimuliRegion.get_default_weights( selected_connectivity.number_of_regions) template_specification['node_weights'] = json.dumps( default_weights.tolist()) template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification.update( self.display_connectivity( current_region_stimulus.connectivity.hex)) return self.fill_default_attributes(template_specification)
def set_display_name(self, **param): display_name_form_field = StimulusSurfaceSelectorForm( common.get_current_project().id).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 load_burst_from_json(self, **data): """Upload Burst from previously exported JSON file""" self.logger.debug("Uploading ..." + str(data)) try: upload_param = "uploadedfile" if upload_param in data and data[upload_param]: upload_param = data[upload_param] if isinstance(upload_param, FieldStorage) or isinstance(upload_param, Part): if not upload_param.file: raise BurstServiceException("Please select a valid JSON file.") upload_param = upload_param.file.read() upload_param = json.loads(upload_param) prj_id = common.get_current_project().id importer = ImportService() burst_entity = importer.load_burst_entity(upload_param, prj_id) common.add2session(common.KEY_BURST_CONFIG, burst_entity) except Exception as excep: self.logger.warning(excep.message) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/burst/')
def get_filtered_datatypes(self, dt_module, dt_class, filters, has_all_option, has_none_option): """ Given the name from the input tree, the dataType required and a number of filters, return the available dataType that satisfy the conditions imposed. """ index_class = getattr(sys.modules[dt_module], dt_class)() filters_dict = json.loads(filters) fields = [] operations = [] values = [] for idx in range(len(filters_dict['fields'])): fields.append(filters_dict['fields'][idx]) operations.append(filters_dict['operations'][idx]) values.append(filters_dict['values'][idx]) filter = FilterChain(fields=fields, operations=operations, values=values) project = common.get_current_project() form = Form(project_id=project.id, draw_ranges=True) data_type_gid_attr = DataTypeGidAttr( linked_datatype=REGISTRY.get_datatype_for_index(index_class)) data_type_gid_attr.required = not string2bool(has_none_option) select_field = TraitDataTypeSelectField( data_type_gid_attr, form, conditions=filter, has_all_option=string2bool(has_all_option)) return {'options': select_field.options()}
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() file_handler = FilesHelper() conn_path = file_handler.get_project_folder( current_project, str(conn_idx.fk_from_operation)) params = ConnectivityViewer.get_connectivity_parameters( conn_idx, 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')
def storeresultfigure(self, img_type, **kwargs): """Create preview for current displayed canvas and store image in current session, for future comparison.""" project = common.get_current_project() user = common.get_logged_user() suggested_name = kwargs.get("suggestedName") self.figure_service.store_result_figure(project, user, img_type, kwargs['export_data'], suggested_name)
def getfiltereddatatypes(self, name, parent_div, tree_session_key, filters): """ Given the name from the input tree, the dataType required and a number of filters, return the available dataType that satisfy the conditions imposed. """ previous_tree = self.context.get_session_tree_for_key(tree_session_key) if previous_tree is None: common.set_error_message("Adapter Interface not in session for filtering!") raise cherrypy.HTTPRedirect("/tvb?error=True") current_node = self._get_node(previous_tree, name) if current_node is None: raise Exception("Could not find node :" + name) datatype = current_node[ABCAdapter.KEY_DATATYPE] filters = json.loads(filters) availablefilter = json.loads(FilterChain.get_filters_for_type(datatype)) for i, filter_ in enumerate(filters[FILTER_FIELDS]): #Check for filter input of type 'date' as these need to be converted if filter_ in availablefilter and availablefilter[filter_][FILTER_TYPE] == 'date': try: temp_date = string2date(filters[FILTER_VALUES][i], False) filters[FILTER_VALUES][i] = temp_date except ValueError: raise #In order for the filter object not to "stack up" on multiple calls to #this method, create a deepCopy to work with if ABCAdapter.KEY_CONDITION in current_node: new_filter = copy.deepcopy(current_node[ABCAdapter.KEY_CONDITION]) else: new_filter = FilterChain() new_filter.fields.extend(filters[FILTER_FIELDS]) new_filter.operations.extend(filters[FILTER_OPERATIONS]) new_filter.values.extend(filters[FILTER_VALUES]) #Get dataTypes that match the filters from DB then populate with values values, total_count = InputTreeManager().populate_option_values_for_dtype( common.get_current_project().id, datatype, new_filter, self.context.get_current_step() ) #Create a dictionary that matches what the template expects parameters = {ABCAdapter.KEY_NAME: name, ABCAdapter.KEY_FILTERABLE: availablefilter, ABCAdapter.KEY_TYPE: ABCAdapter.TYPE_SELECT, ABCAdapter.KEY_OPTIONS: values, ABCAdapter.KEY_DATATYPE: datatype} if total_count > MAXIMUM_DATA_TYPES_DISPLAYED: parameters[KEY_WARNING] = WARNING_OVERFLOW if ABCAdapter.KEY_REQUIRED in current_node: parameters[ABCAdapter.KEY_REQUIRED] = current_node[ABCAdapter.KEY_REQUIRED] if len(values) > 0 and string2bool(str(parameters[ABCAdapter.KEY_REQUIRED])): parameters[ABCAdapter.KEY_DEFAULT] = str(values[-1][ABCAdapter.KEY_VALUE]) previous_selected = self.context.get_current_default(name) if previous_selected in [str(vv['value']) for vv in values]: parameters[ABCAdapter.KEY_DEFAULT] = previous_selected template_specification = {"inputRow": parameters, "disabled": False, "parentDivId": parent_div, common.KEY_SESSION_TREE: tree_session_key} return self.fill_default_attributes(template_specification)
def reset_burst(self): """ Called when click on "New Burst" entry happens from UI. This will generate an empty new Burst Configuration. """ common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE) new_burst = self.burst_service.new_burst_configuration(common.get_current_project().id) common.add2session(common.KEY_BURST_CONFIG, new_burst)
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 prepare_group_launch(self, group_gid, step_key, algorithm_id, **data): """ Receives as input a group gid and an algorithm given by category and id, along with data that gives the name of the required input parameter for the algorithm. Having these generate a range of GID's for all the DataTypes in the group and launch a new operation group. """ prj_service = ProjectService() dt_group = prj_service.get_datatypegroup_by_gid(group_gid) datatypes = prj_service.get_datatypes_from_datatype_group(dt_group.id) range_param_name = data.pop('range_param_name') data[RANGE_PARAMETER_1] = range_param_name data[range_param_name] = ','.join(dt.gid for dt in datatypes) OperationService().group_operation_launch(common.get_logged_user().id, common.get_current_project().id, int(algorithm_id), int(step_key), **data) redirect_url = self._compute_back_link('operations', common.get_current_project()) raise cherrypy.HTTPRedirect(redirect_url)
def storeresultfigure(self, img_type, **kwargs): """Create preview for current displayed canvas and store image in current session, for future comparison.""" project = common.get_current_project() user = common.get_logged_user() operation_id = kwargs.get("operationId") suggested_name = kwargs.get("suggestedName") self.figure_service.store_result_figure(project, user, img_type, kwargs['export_data'], image_name=suggested_name, operation_id=operation_id)
def index(self): """ Display project main-menu. Choose one project to work with. """ current_project = common.get_current_project() if current_project is None: raise cherrypy.HTTPRedirect("/project/viewall") template_specification = dict(mainContent="project_submenu", title="TVB Project Menu") return self.fill_default_attributes(template_specification)
def _persist_project(self, data, project_id, is_create, current_user): """Private method to persist""" data = EditForm().to_python(data) saved_project = self.project_service.store_project(current_user, is_create, project_id, **data) selected_project = common.get_current_project() if len(self.project_service.retrieve_projects_for_user(current_user.id, 1)) == 1: selected_project = saved_project if selected_project is None or (saved_project.id == selected_project.id): self._mark_selected(saved_project)
def get_simple_adapter_interface(self, algorithm_id, parent_div='', is_uploader=False): """ AJAX exposed method. Will return only the interface for a adapter, to be used when tabs are needed. """ curent_project = common.get_current_project() is_uploader = string2bool(is_uploader) template_specification = self.get_adapter_template(curent_project.id, algorithm_id, is_uploader) template_specification[common.KEY_PARENT_DIV] = parent_div return self.fill_default_attributes(template_specification)
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 editresultfigures(self, remove_figure=False, rename_session=False, remove_session=False, **data): """ This method knows how to handle the following actions: remove figure, update figure, remove session and update session. """ project = common.get_current_project() user = common.get_logged_user() redirect_url = '/project/figure/displayresultfigures' if "selected_session" in data and data["selected_session"] is not None and len(data["selected_session"]): redirect_url += '/' + data["selected_session"] del data["selected_session"] figure_id = None if "figure_id" in data: figure_id = data["figure_id"] del data["figure_id"] if cherrypy.request.method == 'POST' and rename_session: successfully_updated = True if "old_session_name" in data and "new_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures(project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: new_data = {"name": figure.name, "session_name": data["new_session_name"]} success = self._update_figure(figure.id, **new_data) if not success: successfully_updated = False if successfully_updated: common.set_info_message("The session was successfully updated!") else: common.set_error_message("The session was not successfully updated! " "There could be some figures that still refer to the old session.") elif cherrypy.request.method == 'POST' and remove_session: successfully_removed = True if "old_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures(project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: success = self.figure_service.remove_result_figure(figure.id) if not success: successfully_removed = False if successfully_removed: common.set_info_message("The session was removed successfully!") else: common.set_error_message("The session was not entirely removed!") elif cherrypy.request.method == 'POST' and remove_figure and figure_id is not None: success = self.figure_service.remove_result_figure(figure_id) if success: common.set_info_message("Figure removed successfully!") else: common.set_error_message("Figure could not be removed!") elif figure_id is not None: self._update_figure(figure_id, **data) raise cherrypy.HTTPRedirect(redirect_url)
def get_creator_and_interface(self, creator_module, creator_class, datatype_instance, lock_midpoint_for_eq=None): """ Returns a Tuple: a creator instance and a dictionary for the creator interface. The interface is prepared for rendering, it is populated with existent data, in case of a parameter of type DataType. The name of the attributes are also prefixed to identify groups. """ algo_group = self.flow_service.get_algorithm_by_module_and_class(creator_module, creator_class)[1] group, _ = self.flow_service.prepare_adapter(common.get_current_project().id, algo_group) #I didn't use the interface(from the above line) returned by the method 'prepare_adapter' from flow service # because the selects that display dataTypes will also have the 'All' entry. datatype_instance.trait.bound = traited_interface.INTERFACE_ATTRIBUTES_ONLY input_list = datatype_instance.interface[traited_interface.INTERFACE_ATTRIBUTES] if lock_midpoint_for_eq is not None: for idx in lock_midpoint_for_eq: input_list[idx] = self._lock_midpoints(input_list[idx]) category = self.flow_service.get_visualisers_category() input_list = self.flow_service.prepare_parameters(input_list, common.get_current_project().id, category.id) input_list = ABCAdapter.prepare_param_names(input_list) return self.flow_service.build_adapter_instance(group), input_list
def create_local_connectivity(self, **kwargs): """ Used for creating and storing a local connectivity. """ context = common.get_from_session(KEY_LCONN_CONTEXT) local_connectivity_creator = self.get_creator_and_interface(LOCAL_CONN_CREATOR_MODULE, LOCAL_CONN_CREATOR_CLASS, LocalConnectivity())[0] self.flow_service.fire_operation(local_connectivity_creator, common.get_logged_user(), common.get_current_project().id, **kwargs) common.set_important_message("The operation for creating the local connectivity was successfully launched.") context.reset() return self.step_1()
def cached_simulator_input_tree(self): """ Cache Simulator's input tree, for performance issues. Anyway, without restart, the introspected tree will not be different on multiple executions. :returns: Simulator's Input Tree (copy from cache or just loaded) """ cached_simulator_tree = common.get_from_session(common.KEY_CACHED_SIMULATOR_TREE) if cached_simulator_tree is None: cached_simulator_tree = self.flow_service.prepare_adapter(common.get_current_project().id, self.cached_simulator_algorithm) common.add2session(common.KEY_CACHED_SIMULATOR_TREE, cached_simulator_tree) return copy.deepcopy(cached_simulator_tree)
def _get_available_selections(self, datatype_gid): """ selection retrieval common to selection component and connectivity selection """ curent_project = common.get_current_project() selections = self.flow_service.get_selections_for_project(curent_project.id, datatype_gid) names, sel_values = [], [] for selection in selections: names.append(selection.ui_name) sel_values.append(selection.selected_nodes) return names, sel_values
def displayresultfigures(self, selected_session='all_sessions'): """ Collect and display saved previews, grouped by session.""" project = common.get_current_project() user = common.get_logged_user() data, all_sessions_info = self.figure_service.retrieve_result_figures(project, user, selected_session) manage_figure_title = "Figures for " + str(selected_session) + " category" if selected_session == 'all_sessions': manage_figure_title = "Figures for all categories" template_specification = dict(mainContent="project/figures_display", title="Stored Visualizer Previews", controlPage=None, displayControl=False, selected_sessions_data=data, all_sessions_info=all_sessions_info, selected_session=selected_session, manageFigureTitle=manage_figure_title) template_specification = self.fill_default_attributes(template_specification, subsection='figures') return template_specification
def _populate_user_and_project(self, template_dictionary, escape_db_operations=False): """ Populate the template dictionary with current logged user (from session). """ logged_user = common.get_logged_user() template_dictionary[common.KEY_USER] = logged_user show_help = logged_user is not None and logged_user.is_online_help_active() template_dictionary[common.KEY_SHOW_ONLINE_HELP] = show_help project = common.get_current_project() template_dictionary[common.KEY_PROJECT] = project if project is not None and not escape_db_operations: self.update_operations_count() return template_dictionary
def downloaddata(self, data_gid, export_module): """ Export the data to a default path of TVB_STORAGE/PROJECTS/project_name """ current_prj = common.get_current_project() # Load data by GID entity = ABCAdapter.load_entity_by_gid(data_gid) # Do real export export_mng = ExportManager() file_name, file_path, delete_file = export_mng.export_data(entity, export_module, current_prj) if delete_file: # We force parent folder deletion because export process generated it. self.mark_file_for_delete(file_path, True) self.logger.debug("Data exported in file: " + str(file_path)) return serve_file(file_path, "application/x-download", "attachment", file_name)
def default(self, step_key, adapter_key, cancel=False, back_page=None, not_reset=False, **data): """ Render a specific adapter. 'data' are arguments for POST """ project = common.get_current_project() algo_group = self.flow_service.get_algo_group_by_identifier(adapter_key) back_page_link = self._compute_back_link(back_page, project) if algo_group is None: raise cherrypy.HTTPRedirect("/tvb?error=True") if cherrypy.request.method == 'POST' and cancel: raise cherrypy.HTTPRedirect(back_page_link) submit_link = self.get_url_adapter(step_key, adapter_key, back_page) is_burst = back_page not in ['operations', 'data'] if cherrypy.request.method == 'POST': data[common.KEY_ADAPTER] = adapter_key template_specification = self.execute_post(project.id, submit_link, step_key, algo_group, **data) self._populate_section(algo_group, template_specification, is_burst) else: if (('Referer' not in cherrypy.request.headers or ('Referer' in cherrypy.request.headers and 'step' not in cherrypy.request.headers['Referer'])) and 'View' in algo_group.group_category.displayname): # Avoid reset in case of Visualizers, as a supplementary GET # might be enforced by MPLH5 on FF. not_reset = True template_specification = self.get_template_for_adapter(project.id, step_key, algo_group, submit_link, not not_reset, is_burst=is_burst) if template_specification is None: raise cherrypy.HTTPRedirect('/tvb') if KEY_CONTROLLS not in template_specification: template_specification[KEY_CONTROLLS] = None if common.KEY_SUBMIT_LINK not in template_specification: template_specification[common.KEY_SUBMIT_LINK] = submit_link if KEY_CONTENT not in template_specification: template_specification[KEY_CONTENT] = "flow/full_adapter_interface" template_specification[common.KEY_DISPLAY_MENU] = False else: template_specification[common.KEY_DISPLAY_MENU] = True template_specification[common.KEY_BACK_PAGE] = back_page_link template_specification[common.KEY_ADAPTER] = adapter_key template_specification[ABCDisplayer.KEY_IS_ADAPTER] = True self.fill_default_attributes(template_specification, algo_group.displayname) return template_specification
def store_measure_points_selection(self, ui_name, **data): """ Save a MeasurePoints selection (new or update existing entity). """ if ui_name and ui_name != self.NEW_SELECTION_NAME: sel_project_id = common.get_current_project().id # client sends integers as strings: selection = json.dumps([int(s) for s in json.loads(data['selection'])]) datatype_gid = data['datatype_gid'] self.flow_service.save_measure_points_selection(ui_name, selection, datatype_gid, sel_project_id) return [True, 'Selection saved successfully.'] else: error_msg = self.NEW_SELECTION_NAME + " or empty name are not valid as selection names." return [False, error_msg]
def get_select_existent_entities(self, label, entity_type, entity_gid=None): """ Returns the dictionary needed for drawing the select which display all the created entities of the specified type. """ project_id = common.get_current_project().id category = self.flow_service.get_visualisers_category() interface = [{'name': 'existentEntitiesSelect', 'label': label, 'type': entity_type}] if entity_gid is not None: interface[0]['default'] = entity_gid interface = self.flow_service.prepare_parameters(interface, project_id, category.id) interface = ABCAdapter.prepare_param_names(interface) return interface
def create_stimulus(self): """ Creates a stimulus from the given data. """ try: context = common.get_from_session(KEY_SURFACE_CONTEXT) surface_stimulus_creator = self.get_creator_and_interface(SURFACE_STIMULUS_CREATOR_MODULE, SURFACE_STIMULUS_CREATOR_CLASS, StimuliSurface())[0] self.flow_service.fire_operation(surface_stimulus_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.") context.selected_stimulus = None except (NameError, ValueError, SyntaxError), _: common.set_error_message("The operation failed due to invalid parameter input.") return False
def show_group_of_algorithms(self, step_key, algorithm_ids): project = common.get_current_project() category = self.flow_service.get_category_by_id(step_key) algorithms = [] for i in algorithm_ids.split(','): algorithm_id = int(i) algorithm = self.flow_service.get_algorithm_by_identifier(algorithm_id) algorithm.link = self.get_url_adapter(step_key, algorithm_id) algorithm.input_tree = self.flow_service.prepare_adapter(project.id, algorithm) algorithms.append(algorithm) template_specification = dict(mainContent="flow/algorithms_list", algorithms=algorithms, title="Select an algorithm", section_name=category.displayname.lower()) self._populate_section(algorithms[0], template_specification) self.fill_default_attributes(template_specification, algorithms[0].group_name) return template_specification
def update_operations_count(self): """ If a project is selected, update Operation Numbers in call-out. """ project = common.get_current_project() if project is not None: fns, sta, err, canceled, pending = self.flow_service.get_operation_numbers(project.id) project.operations_finished = fns project.operations_started = sta project.operations_error = err project.operations_canceled = canceled project.operations_pending = pending common.add2session(common.KEY_PROJECT, project)
def index(self): """Get on burst main page""" # todo : reuse load_burst here for consistency. template_specification = dict(mainContent="burst/main_burst", title="Simulation Cockpit", baseUrl=TvbProfile.current.web.BASE_URL, includedResources='project/included_resources') portlets_list = self.burst_service.get_available_portlets() session_stored_burst = common.get_from_session(common.KEY_BURST_CONFIG) if session_stored_burst is None or session_stored_burst.id is None: if session_stored_burst is None: session_stored_burst = self.burst_service.new_burst_configuration(common.get_current_project().id) common.add2session(common.KEY_BURST_CONFIG, session_stored_burst) adapter_interface = self.cached_simulator_input_tree if session_stored_burst is not None: current_data = session_stored_burst.get_all_simulator_values()[0] adapter_interface = ABCAdapter.fill_defaults(adapter_interface, current_data, True) ### Add simulator tree to session to be available in filters self.context.add_adapter_to_session(self.cached_simulator_algo_group, adapter_interface, current_data) template_specification['inputList'] = adapter_interface selected_portlets = session_stored_burst.update_selected_portlets() template_specification['burst_list'] = self.burst_service.get_available_bursts(common.get_current_project().id) template_specification['portletList'] = portlets_list template_specification['selectedPortlets'] = json.dumps(selected_portlets) template_specification['draw_hidden_ranges'] = True template_specification['burstConfig'] = session_stored_burst ### Prepare PSE available metrics ### We put here all available algorithms, because the metrics select area is a generic one, ### and not loaded with every Burst Group change in history. algo_group = self.flow_service.get_algorithm_by_module_and_class(MEASURE_METRICS_MODULE, MEASURE_METRICS_CLASS)[1] adapter_instance = ABCAdapter.build_adapter(algo_group) if adapter_instance is not None and hasattr(adapter_instance, 'available_algorithms'): template_specification['available_metrics'] = [metric_name for metric_name in adapter_instance.available_algorithms.keys()] else: template_specification['available_metrics'] = [] template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification[common.KEY_SECTION] = 'burst' return self.fill_default_attributes(template_specification)
def _mark_selected(self, project): """ Set the project passed as parameter as the selected project. """ previous_project = common.get_current_project() ### Update project stored in selection, with latest Project entity from DB. members = self.user_service.get_users_for_project("", project.id)[1] project.members = members common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE) common.add2session(common.KEY_PROJECT, project) if previous_project is None or previous_project.id != project.id: ### Clean Burst selection from session in case of a different project. common.remove_from_session(common.KEY_BURST_CONFIG) ### Store in DB new project selection user = common.get_from_session(common.KEY_USER) if user is not None: self.user_service.save_project_to_user(user.id, project.id) ### Display info message about project change self.logger.debug("Selected project is now " + project.name) common.set_info_message("Your current working project is: " + str(project.name))