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/")
Example #2
0
    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 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 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 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)
Example #6
0
 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)
Example #7
0
 def copy_burst(self, burst_id):
     """
     When currently selected entry is a valid Burst, create a clone of that Burst.
     """
     common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
     base_burst = self.burst_service.load_burst(burst_id)[0]
     if (base_burst is None) or (base_burst.id is None):
         return self.reset_burst()
     common.add2session(common.KEY_BURST_CONFIG, base_burst.clone())
     return base_burst.name
Example #8
0
 def copy_burst(self, burst_id):
     """
     When currently selected entry is a valid Burst, create a clone of that Burst.
     """
     common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
     base_burst = self.burst_service.load_burst(burst_id)[0]
     if (base_burst is None) or (base_burst.id is None):
         return self.reset_burst()
     common.add2session(common.KEY_BURST_CONFIG, base_burst.clone())
     return base_burst.name
 def _remove_project(self, project_id):
     """Private method for removing project."""
     try:
         self.project_service.remove_project(project_id)
     except ServicesBaseException as exc:
         self.logger.error("Could not delete project!")
         self.logger.exception(exc)
         common.set_error_message(exc.message)
     prj = common.get_current_project()
     if prj is not None and prj.id == int(project_id):
         common.remove_from_session(common.KEY_PROJECT)
Example #10
0
 def tvb(self, error=False, **data):
     """
     /tvb URL
     Returns the home page with the messages stored in the user's session.
     """
     self.logger.debug("Unused submit attributes:" + str(data))
     template_dictionary = dict(mainContent="index", title="The Virtual Brain Project")
     template_dictionary = self._fill_user_specific_attributes(template_dictionary)
     if common.get_from_session(common.KEY_IS_RESTART):
         template_dictionary[common.KEY_IS_RESTART] = True
         common.remove_from_session(common.KEY_IS_RESTART)
     return self.fill_default_attributes(template_dictionary, error)
 def tvb(self, error=False, **data):
     """
     /tvb URL
     Returns the home page with the messages stored in the user's session.
     """
     self.logger.debug("Unused submit attributes:" + str(data))
     template_dictionary = dict(mainContent="../index", title="The Virtual Brain Project")
     template_dictionary = self._fill_user_specific_attributes(template_dictionary)
     if common.get_from_session(common.KEY_IS_RESTART):
         template_dictionary[common.KEY_IS_RESTART] = True
         common.remove_from_session(common.KEY_IS_RESTART)
     return self.fill_default_attributes(template_dictionary, error)
Example #12
0
    def editone(self, project_id=None, cancel=False, save=False, delete=False, **data):
        """
        Create or change Project. When project_id is empty we create a 
        new entity, otherwise we are to edit and existent one.
        """
        if cherrypy.request.method == 'POST' and cancel:
            raise cherrypy.HTTPRedirect('/project')
        if cherrypy.request.method == 'POST' and delete:
            self._remove_project(project_id)
            raise cherrypy.HTTPRedirect('/project/viewall')

        current_user = common.get_logged_user()
        is_create = False
        if project_id is None or not int(project_id):
            is_create = True
            data["administrator"] = current_user.display_name
            admin_username = current_user.username
        else:
            current_project = self.project_service.find_project(project_id)
            if not save:
                # Only when we do not have submitted data,
                # populate fields with initial values for edit.
                data = dict(name=current_project.name, description=current_project.description)
            data["administrator"] = current_project.administrator.display_name
            admin_username = current_project.administrator.username
            self._mark_selected(current_project)
        data["project_id"] = project_id

        template_specification = dict(mainContent="project/editone", data=data, isCreate=is_create,
                                      title="Create new project" if is_create else "Edit " + data["name"],
                                      editUsersEnabled=(current_user.username == admin_username))
        try:
            if cherrypy.request.method == 'POST' and save:
                common.remove_from_session(common.KEY_PROJECT)
                common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
                self._persist_project(data, project_id, is_create, current_user)
                raise cherrypy.HTTPRedirect('/project/viewall')
        except formencode.Invalid as excep:
            self.logger.debug(str(excep))
            template_specification[common.KEY_ERRORS] = excep.unpack_errors()
        except ProjectServiceException as excep:
            self.logger.debug(str(excep))
            common.set_error_message(excep.message)
            raise cherrypy.HTTPRedirect('/project/viewall')

        all_users, members, pages = self.user_service.get_users_for_project(current_user.username, project_id)
        template_specification['usersList'] = all_users
        template_specification['usersMembers'] = [m.id for m in members]
        template_specification['usersPages'] = pages
        template_specification['usersCurrentPage'] = 1
        return self.fill_default_attributes(template_specification, 'properties')
Example #13
0
 def clean_project_data_from_session(self, remove_project=True):
     common.remove_from_session(self.KEY_SIMULATOR_CONFIG)
     common.remove_from_session(self.KEY_LAST_LOADED_FORM_URL)
     common.remove_from_session(self.KEY_BURST_CONFIG)
     common.remove_from_session(self.KEY_IS_SIMULATOR_BRANCH)
     common.add2session(self.KEY_IS_SIMULATOR_LOAD, False)
     if remove_project:
         common.remove_project_from_session()
Example #14
0
    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))
Example #15
0
    def load_burst(self, burst_id):
        """
        Given a burst id return its running status, weather it was a operation group and the selected tab.
        This is called when a burst is selected in the history,
        when returning from a burst config page (model param or noise)
        and when the status of running simulations is polled.
        Besides returning these values it updates the session stored burst.

        A burst configuration has 2 meanings.
        It is a staging configuration for a new burst (stored in transients in the session).
        It is the configuration used to launch a simulation and it's running status (stored in the db).
        This method has to merge the two meanings.
        If the requested burst_id is different from the one held in the session,
        then the burst config is loaded from the db, discarding any session stored config.
        If the id is the same then the session config is kept.
        """
        try:
            burst_id = int(burst_id)
            old_burst = common.get_from_session(common.KEY_BURST_CONFIG)
            burst, group_gid = self.burst_service.load_burst(burst_id)

            if old_burst and old_burst.id == burst_id:
                # This function was called to reload the current burst.
                # Merge session config into the db config. Overwrite all transient fields
                burst.simulator_configuration = old_burst.simulator_configuration
                burst.dynamic_ids = old_burst.dynamic_ids

            burst.selected_tab = old_burst.selected_tab
            common.add2session(common.KEY_BURST_CONFIG, burst)
            return {
                'status': burst.status,
                'group_gid': group_gid,
                'selected_tab': burst.selected_tab
            }
        except Exception:
            ### Most probably Burst was removed. Delete it from session, so that client
            ### has a good chance to get a good response on refresh
            self.logger.exception("Error loading burst")
            common.remove_from_session(common.KEY_BURST_CONFIG)
            raise
    def logout(self):
        """
        Logging out user and clean session
        """
        user = common.remove_from_session(common.KEY_USER)
        if user is not None:
            self.logger.debug("User " + user.username +
                              " is just logging out!")
        common.clean_project_data_from_session()
        common.set_info_message("Thank you for using The Virtual Brain!")

        common.expire_session()
        raise cherrypy.HTTPRedirect("/user")
Example #17
0
    def cancel_or_remove_operation(self,
                                   operation_id,
                                   is_group,
                                   remove_after_stop=False):
        """
        Stop the operation given by operation_id. If is_group is true stop all the
        operations from that group.
        """
        operation_id = int(operation_id)
        is_group = int(is_group) != 0
        # Load before we remove, to have its data in memory here
        burst_config = BurstService.get_burst_for_operation_id(operation_id)

        result = OperationService.stop_operation(operation_id, is_group,
                                                 remove_after_stop)
        if remove_after_stop:
            current_burst = common.get_from_session(common.KEY_BURST_CONFIG)
            if current_burst is not None and burst_config is not None and current_burst.id == burst_config.id:
                common.remove_from_session(common.KEY_BURST_CONFIG)
                common.add2session(common.KEY_BURST_CONFIG,
                                   BurstConfiguration(burst_config.project.id))
        return result
Example #18
0
    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)
            simulator = self.simulator_context.simulator

            for param_name in self.model_params_dict.values():
                param_data = context_model_parameters.get_data_for_model_param(
                    param_name)
                if param_data is None:
                    continue
                setattr(simulator.model, param_name, param_data)
            ### Update in session the last loaded URL for burst-page.
            self.simulator_context.add_last_loaded_form_url_to_session(
                SimulatorWizzardURLs.SET_INTEGRATOR_URL)

        ### Clean from session drawing context
        common.remove_from_session(KEY_CONTEXT_MPS)
        raise cherrypy.HTTPRedirect("/burst/")
    def editone(self, project_id=None, cancel=False, save=False, delete=False, **data):
        """
        Create or change Project. When project_id is empty we create a 
        new entity, otherwise we are to edit and existent one.
        """
        if cherrypy.request.method == 'POST' and cancel:
            raise cherrypy.HTTPRedirect('/project')
        if cherrypy.request.method == 'POST' and delete:
            self._remove_project(project_id)
            raise cherrypy.HTTPRedirect('/project/viewall')

        current_user = common.get_logged_user()
        is_create = False
        if project_id is None or not int(project_id):
            is_create = True
            data["administrator"] = current_user.username
        else:
            current_project = self.project_service.find_project(project_id)
            if not save:
                # Only when we do not have submitted data,
                # populate fields with initial values for edit.
                data = dict(name=current_project.name, description=current_project.description)
            data["administrator"] = current_project.administrator.username
            self._mark_selected(current_project)
        data["project_id"] = project_id

        template_specification = dict(mainContent="project/editone", data=data, isCreate=is_create,
                                      title="Create new project" if is_create else "Edit " + data["name"],
                                      editUsersEnabled=(current_user.username == data['administrator']))
        try:
            if cherrypy.request.method == 'POST' and save:
                common.remove_from_session(common.KEY_PROJECT)
                common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
                self._persist_project(data, project_id, is_create, current_user)
                raise cherrypy.HTTPRedirect('/project/viewall')
        except formencode.Invalid, excep:
            self.logger.debug(str(excep))
            template_specification[common.KEY_ERRORS] = excep.unpack_errors()
Example #20
0
    def logout(self):
        """
        Logging out user and clean session
        """
        user = common.remove_from_session(common.KEY_USER)
        if user is not None:
            self.logger.debug("User " + user.username + " is just logging out!")
        current_project = common.get_current_project()
        if current_project is not None and encryption_handler.encryption_enabled():
            encryption_handler.set_project_inactive(current_project)
        SimulatorContext().clean_project_data_from_session()
        common.set_info_message("Thank you for using The Virtual Brain!")

        common.expire_session()
        raise cherrypy.HTTPRedirect("/user")
Example #21
0
    def load_burst(self, burst_id):
        """
        Given a burst id return its running status, weather it was a operation group and the selected tab.
        This is called when a burst is selected in the history,
        when returning from a burst config page (model param or noise)
        and when the status of running simulations is polled.
        Besides returning these values it updates the session stored burst.

        A burst configuration has 2 meanings.
        It is a staging configuration for a new burst (stored in transients in the session).
        It is the configuration used to launch a simulation and it's running status (stored in the db).
        This method has to merge the two meanings.
        If the requested burst_id is different from the one held in the session,
        then the burst config is loaded from the db, discarding any session stored config.
        If the id is the same then the session config is kept.
        """
        try:
            burst_id = int(burst_id)
            old_burst = common.get_from_session(common.KEY_BURST_CONFIG)
            burst, group_gid = self.burst_service.load_burst(burst_id)

            if old_burst and old_burst.id == burst_id:
                # This function was called to reload the current burst.
                # Merge session config into the db config. Overwrite all transient fields
                burst.simulator_configuration = old_burst.simulator_configuration
                burst.dynamic_ids = old_burst.dynamic_ids

            burst.selected_tab = old_burst.selected_tab
            common.add2session(common.KEY_BURST_CONFIG, burst)
            return {'status': burst.status, 'group_gid': group_gid, 'selected_tab': burst.selected_tab}
        except Exception:
            ### Most probably Burst was removed. Delete it from session, so that client 
            ### has a good chance to get a good response on refresh
            self.logger.exception("Error loading burst")
            common.remove_from_session(common.KEY_BURST_CONFIG)
            raise
    def logout(self):
        """
        Logging out user and clean session
        """
        user = common.remove_from_session(common.KEY_USER)
        if user is not None:
            self.logger.debug("User " + user.username + " is just logging out!")
        common.remove_from_session(common.KEY_PROJECT)
        common.remove_from_session(common.KEY_BURST_CONFIG)
        common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
        common.set_info_message("Thank you for using The Virtual Brain!")

        common.expire_session()
        raise cherrypy.HTTPRedirect("/user")
Example #23
0
    def logout(self):
        """
        Logging out user and clean session
        """
        user = common.remove_from_session(common.KEY_USER)
        if user is not None:
            self.logger.debug("User " + user.username + " is just logging out!")
        common.remove_from_session(common.KEY_PROJECT)
        common.remove_from_session(common.KEY_BURST_CONFIG)
        common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE)
        common.set_info_message("Thank you for using The Virtual Brain!")

        common.expire_session()
        raise cherrypy.HTTPRedirect("/user")
Example #24
0
 def clean_from_session(self):
     """
     Remove info about selected algo from session
     """
     common.remove_from_session(self.KEY_VIEW_MODEL)
        except ServicesBaseException, excep:
            self.logger.warning(excep.message)
            common.set_error_message(excep.message)
        raise cherrypy.HTTPRedirect('/project/viewall')

    def _remove_project(self, project_id):
        """Private method for removing project."""
        try:
            self.project_service.remove_project(project_id)
        except ServicesBaseException, exc:
            self.logger.error("Could not delete project!")
            self.logger.exception(exc)
            common.set_error_message(exc.message)
        prj = common.get_current_project()
        if prj is not None and prj.id == int(project_id):
            common.remove_from_session(common.KEY_PROJECT)

    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 clean_from_session(self):
     """
     Remove info about selected algo from session
     """
     common.remove_from_session(self.KEY_CURRENT_ADAPTER_INFO)
Example #27
0
 def remove_burst_config_from_session(self):
     common.remove_from_session(self.KEY_BURST_CONFIG)
            self.logger.warning(excep.message)
            common.set_error_message(excep.message)
        raise cherrypy.HTTPRedirect('/project/viewall')


    def _remove_project(self, project_id):
        """Private method for removing project."""
        try:
            self.project_service.remove_project(project_id)
        except ServicesBaseException, exc:
            self.logger.error("Could not delete project!")
            self.logger.exception(exc)
            common.set_error_message(exc.message)
        prj = common.get_current_project()
        if prj is not None and prj.id == int(project_id):
            common.remove_from_session(common.KEY_PROJECT)


    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)


    @expose_page
    @settings
Example #29
0
 def clean_from_session(self):
     """
     Remove info about selected algo from session
     """
     common.remove_from_session(self.KEY_CURRENT_ADAPTER_INFO)