当前位置: 首页>>代码示例>>Python>>正文


Python FlowService.get_algorithm_by_module_and_class方法代码示例

本文整理汇总了Python中tvb.core.services.flow_service.FlowService.get_algorithm_by_module_and_class方法的典型用法代码示例。如果您正苦于以下问题:Python FlowService.get_algorithm_by_module_and_class方法的具体用法?Python FlowService.get_algorithm_by_module_and_class怎么用?Python FlowService.get_algorithm_by_module_and_class使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tvb.core.services.flow_service.FlowService的用法示例。


在下文中一共展示了FlowService.get_algorithm_by_module_and_class方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fire_simulation

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
def fire_simulation(project_id=1, **kwargs):
    project = dao.get_project_by_id(project_id)
    flow_service = FlowService()

    # below the holy procedure to launch with the correct parameters taken from the defaults
    stored_adapter = flow_service.get_algorithm_by_module_and_class(SIMULATOR_MODULE, SIMULATOR_CLASS)
    simulator_adapter = ABCAdapter.build_adapter(stored_adapter)
    flatten_interface = simulator_adapter.flaten_input_interface()
    itree_mngr = flow_service.input_tree_manager
    prepared_flatten_interface = itree_mngr.fill_input_tree_with_options(flatten_interface, project.id,
                                                                         stored_adapter.fk_category)
    launch_args = {}
    for entry in prepared_flatten_interface:
        value = entry['default']
        if isinstance(value, dict):
            value = str(value)
        if hasattr(value, 'tolist'):
            value = value.tolist()
        launch_args[entry['name']] = value
    launch_args.update(**kwargs)
    # end of magic

    launched_operation = flow_service.fire_operation(simulator_adapter, project.administrator,
                                                     project.id, **launch_args)[0]
    return launched_operation
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:27,代码来源:lab.py

示例2: launch_simulation_workflow

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
def launch_simulation_workflow(json_path, prj_id):
    """

    :param json_path: Path towards a local JSON file exported from GUI
    :param prj_id: This ID of a project needs to exists in DB, and it can be taken from the WebInterface
    """
    project = dao.get_project_by_id(prj_id)

    with open(json_path, 'rb') as input_file:
        simulation_json = input_file.read()
        simulation_json = json.loads(simulation_json)
        LOG.info("Simulation JSON loaded from file '%s': \n  %s", json_path, simulation_json)

        importer = ImportService()
        simulation_config = importer.load_burst_entity(simulation_json, prj_id)
        LOG.info("Simulation Workflow configuration object loaded: \n  %s", simulation_config)

        flow_service = FlowService()
        simulator_algorithm, _ = flow_service.get_algorithm_by_module_and_class(SIMULATOR_MODULE, SIMULATOR_CLASS)
        LOG.info("Found Simulation algorithm in local DB: \n   %s", simulator_algorithm)

        burst_service = BurstService()
        burst_service.launch_burst(simulation_config, 0, simulator_algorithm.id, project.administrator.id, LAUNCH_NEW)
        LOG.info("Check in the web GUI for your operation. It should be starting now ...")
开发者ID:amitsaroj001,项目名称:tvb-framework,代码行数:26,代码来源:run_workflow.py

示例3: ModelValidator

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
class ModelValidator(object):
    overwrites = {}


    def __init__(self, overwrites=None, settings_file=None):
        """ Parameters can be overwritten either from a settigns file or from a dictionary. """
        if overwrites is not None:
            self.overwrites.update(overwrites)
        if settings_file is not None:
            settings = open(sys.argv[1]).read()
            for line in settings.split('\n'):
                key, value = line.split('=')
                self.overwrites[key.strip()] = value.strip()
        if KEY_PROJECT not in self.overwrites:
            raise Exception("Settings file should contain the id of the project: %s=1" % KEY_PROJECT)
        self.project = dao.get_project_by_id(self.overwrites[KEY_PROJECT])
        self.flow_service = FlowService()
        self.operation_service = OperationService()


    def launch_validation(self):
        """
        Prepare the arguments to be submitted and launch actual operations group.
        TODO: Now get the results and check if any errors
        """
        stored_adapter = self.flow_service.get_algorithm_by_module_and_class(SIMULATOR_MODULE, SIMULATOR_CLASS)
        simulator_adapter = ABCAdapter.build_adapter(stored_adapter)
        launch_args = {}
        flatten_interface = simulator_adapter.flaten_input_interface()
        itree_mngr = self.flow_service.input_tree_manager
        prepared_flatten_interface = itree_mngr.fill_input_tree_with_options(flatten_interface, self.project.id,
                                                                             stored_adapter.fk_category)
        for entry in prepared_flatten_interface:
            value = entry['default']
            if isinstance(value, dict):
                value = str(value)
            if hasattr(value, 'tolist'):
                value = value.tolist()
            launch_args[entry['name']] = value
        launch_args.update(self.overwrites)
        
        nr_of_operations = 1
        for key in self.overwrites:
            if key.startswith(PARAM_RANGE_PREFIX):
                range_values = self.operation_service.get_range_values(launch_args, key)
                nr_of_operations *= len(range_values)
        do_launch = False
        print "Warning! This will launch %s operations. Do you agree? (yes/no)" % nr_of_operations
        while 1:
            accept = raw_input()
            if accept.lower() == 'yes':
                do_launch = True
                break
            if accept.lower() == 'no':
                do_launch = False
                break
            print "Please type either yes or no"
        
        if do_launch:
            self.launched_operations = self.flow_service.fire_operation(simulator_adapter, self.project.administrator,
                                                                        self.project.id, **launch_args)
            return self.validate_results(0)
        else:
            return "Operation canceled by user."


    def validate_results(self, last_verified_index):
        error_count = 0
        while last_verified_index < len(self.launched_operations):
            operation_to_check = self.launched_operations[last_verified_index]
            operation = dao.get_operation_by_id(operation_to_check.id)
            if not operation.has_finished:
                sleep(10)
            if operation.status == STATUS_ERROR:
                sys.stdout.write("E(" + str(operation_to_check.id) + ")")
                error_count += 1
                last_verified_index += 1
                sys.stdout.flush()
            if operation.status == STATUS_FINISHED:
                last_verified_index += 1
                sys.stdout.write('.')
                sys.stdout.flush()
        if error_count:
            return "%s operations in error; %s operations successfully." % (error_count,
                                                                            len(self.launched_operations) - error_count)
        return "All operations finished successfully!"
开发者ID:gummadhav,项目名称:tvb-framework,代码行数:88,代码来源:model_validations.py

示例4: test_reduce_dimension_component

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
    def test_reduce_dimension_component(self):
        """
        Tests the generation of the component which allows the user
        to select one dimension from a multi dimension array
        """
        flow_service = FlowService()
        array_count = self.count_all_entities(MappedArray)
        assert 0 == array_count, "Expected to find no data"
        adapter_instance = NDimensionArrayAdapter()
        PARAMS = {}
        OperationService().initiate_prelaunch(self.operation, adapter_instance, {}, **PARAMS)
        inserted_arrays, array_count = flow_service.get_available_datatypes(self.test_project.id, MappedArray)
        assert 1 == array_count, "Problems when inserting data"

        algorithm = flow_service.get_algorithm_by_module_and_class(
            'tvb.tests.framework.adapters.ndimensionarrayadapter', 'NDimensionArrayAdapter')
        interface = flow_service.prepare_adapter(self.test_project.id, algorithm)
        self.template_specification['inputList'] = interface
        resulted_html = _template2string(self.template_specification)
        self.soup = BeautifulSoup(resulted_html)

        found_divs = self.soup.find_all('p', attrs=dict(id="dimensionsDiv_input_data"))
        assert len(found_divs) == 1, "Data generated incorrect"

        gid = inserted_arrays[0][2]
        cherrypy.session = {'user': self.test_user}
        entity = dao.get_datatype_by_gid(gid)
        component_content = FlowController().gettemplatefordimensionselect(gid, "input_data")
        self.soup = BeautifulSoup(component_content)

        #check dimensions
        found_selects_0 = self.soup.find_all('select', attrs=dict(id="dimId_input_data_dimensions_0"))
        found_selects_1 = self.soup.find_all('select', attrs=dict(id="dimId_input_data_dimensions_1"))
        found_selects_2 = self.soup.find_all('select', attrs=dict(id="dimId_input_data_dimensions_2"))
        assert len(found_selects_0) == 1, "select not found"
        assert len(found_selects_1) == 1, "select not found"
        assert len(found_selects_2) == 1, "select not found"

        #check the aggregation functions selects
        agg_selects_0 = self.soup.find_all('select', attrs=dict(id="funcId_input_data_dimensions_0"))
        agg_selects_1 = self.soup.find_all('select', attrs=dict(id="funcId_input_data_dimensions_1"))
        agg_selects_2 = self.soup.find_all('select', attrs=dict(id="funcId_input_data_dimensions_2"))
        assert len(agg_selects_0), 1 == "incorrect first dim"
        assert len(agg_selects_1), 1 == "incorrect second dim"
        assert len(agg_selects_2), 1 == "incorrect third dim."

        data_shape = entity.shape
        assert len(data_shape) == 3, "Shape of the array is incorrect"
        for i in range(data_shape[0]):
            options = self.soup.find_all('option', attrs=dict(value=gid + "_0_" + str(i)))
            assert len(options) == 1, "Generated option is incorrect"
            assert options[0].text == "Time " + str(i), "The label of the option is not correct"
            assert options[0].parent["name"] == "input_data_dimensions_0"
        for i in range(data_shape[1]):
            options = self.soup.find_all('option', attrs=dict(value=gid + "_1_" + str(i)))
            assert len(options) == 1, "Generated option is incorrect"
            assert options[0].text == "Channel " + str(i), "Option's label incorrect"
            assert options[0].parent["name"] == "input_data_dimensions_1", "incorrect parent"
        for i in range(data_shape[2]):
            options = self.soup.find_all('option', attrs=dict(value=gid + "_2_" + str(i)))
            assert len(options) == 1, "Generated option is incorrect"
            assert options[0].text == "Line " + str(i), "The label of the option is not correct"
            assert options[0].parent["name"] == "input_data_dimensions_2"

        #check the expected hidden fields
        expected_shape = self.soup.find_all('input', attrs=dict(id="input_data_expected_shape"))
        assert len(expected_shape) == 1, "The generated option is not correct"
        assert expected_shape[0]["value"] == "expected_shape_", "The generated option is not correct"
        input_hidden_op = self.soup.find_all('input', attrs=dict(id="input_data_operations"))
        assert len(input_hidden_op) == 1, "The generated option is not correct"
        assert input_hidden_op[0]["value"] == "operations_", "The generated option is not correct"
        input_hidden_dim = self.soup.find_all('input', attrs=dict(id="input_data_expected_dim"))
        assert len(input_hidden_dim) == 1, "The generated option is not correct"
        assert input_hidden_dim[0]["value"] == "requiredDim_1", "The generated option is not correct"
        input_hidden_shape = self.soup.find_all('input', attrs=dict(id="input_data_array_shape"))
        assert len(input_hidden_shape) == 1, "The generated option is not correct"
        assert input_hidden_shape[0]["value"] == "[5, 1, 3]", "The generated option is not correct"

        #check only the first option from the aggregations functions selects
        options = self.soup.find_all('option', attrs=dict(value="func_none"))
        assert len(options) == 3, "The generated option is not correct"
开发者ID:the-virtual-brain,项目名称:tvb-framework,代码行数:83,代码来源:genshi_test.py

示例5: SpatioTemporalController

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
class SpatioTemporalController(BaseController):
    """
    Base class which contains methods related to spatio-temporal actions.
    """

    def __init__(self):
        BaseController.__init__(self)
        self.flow_service = FlowService()
        self.logger = get_logger(__name__)
        editable_entities = [dict(link='/spatial/stimulus/region/step_1_submit/1/1', title='Region Stimulus',
                                  subsection='regionstim', description='Create a new Stimulus on Region level'),
                             dict(link='/spatial/stimulus/surface/step_1_submit/1/1', title='Surface Stimulus',
                                  subsection='surfacestim', description='Create a new Stimulus on Surface level')]
        self.submenu_list = editable_entities


    @expose_page
    @settings
    def index(self, **data):
        """
        Displays the main page for the spatio temporal section.
        """
        template_specification = {'title': "Spatio temporal", 'data': data, 'mainContent': 'header_menu'}
        return self.fill_default_attributes(template_specification)



    @staticmethod
    def display_surface(surface_gid):
        """
        Generates the HTML for displaying the surface with the given ID.
        """
        surface = ABCAdapter.load_entity_by_gid(surface_gid)
        common.add2session(PARAM_SURFACE, surface_gid)
        url_vertices_pick, url_normals_pick, url_triangles_pick = surface.get_urls_for_pick_rendering()
        url_vertices, url_normals, _, url_triangles = surface.get_urls_for_rendering()

        return {
            'urlVerticesPick': json.dumps(url_vertices_pick),
            'urlTrianglesPick': json.dumps(url_triangles_pick),
            'urlNormalsPick': json.dumps(url_normals_pick),
            'urlVertices': json.dumps(url_vertices),
            'urlTriangles': json.dumps(url_triangles),
            'urlNormals': json.dumps(url_normals),
            'brainCenter': json.dumps(surface.center())
        }


    @staticmethod
    def prepare_entity_interface(input_list):
        """
        Prepares the input tree obtained from a creator.
        """
        return {'inputList': input_list,
                common.KEY_PARAMETERS_CONFIG: False}


    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


    @staticmethod
    def get_series_json(data, label):
        """ For each data point entry, build the FLOT specific JSON. """
        return '{"data": %s, "label": "%s"}' % (json.dumps(data), label)


    @staticmethod
    def build_final_json(list_of_series):
        """ Given a list with all the data points, build the final FLOT json. """
        return '[' + ','.join(list_of_series) + ']'


    @staticmethod
    def get_ui_message(list_of_equation_names):
        """
        The message returned by this method should be displayed if
        the equation with the given name couldn't be evaluated in all points.
        """
        if list_of_equation_names:
            return ("Could not evaluate the " + ", ".join(list_of_equation_names) + " equation(s) "
#.........这里部分代码省略.........
开发者ID:amitsaroj001,项目名称:tvb-framework,代码行数:103,代码来源:base_spatio_temporal_controller.py

示例6: TestWorkflow

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
class TestWorkflow(TransactionalTestCase):
    """
    Test that workflow conversion methods are valid.
    """


    def transactional_setup_method(self):
        """
        Sets up the testing environment;
        saves config file;
        creates a test user, a test project;
        creates burst, operation, flow and workflow services
        """
        self.test_user = TestFactory.create_user()
        self.test_project = TestFactory.create_project(self.test_user)
        self.workflow_service = WorkflowService()
        self.burst_service = BurstService()
        self.operation_service = OperationService()
        self.flow_service = FlowService()


    def transactional_teardown_method(self):
        """
        Remove project folders and clean up database.
        """
        FilesHelper().remove_project_structure(self.test_project.name)
        self.delete_project_folders()


    def __create_complex_workflow(self, workflow_step_list):
        """
        Creates a burst with a complex workflow with a given list of workflow steps.
        :param workflow_step_list: a list of workflow steps that will be used in the
            creation of a new workflow for a new burst
        """
        burst_config = TestFactory.store_burst(self.test_project.id)

        stored_dt = datatypes_factory.DatatypesFactory()._store_datatype(Datatype1())

        first_step_algorithm = self.flow_service.get_algorithm_by_module_and_class("tvb.tests.framework.adapters.testadapter1",
                                                                                   "TestAdapterDatatypeInput")
        metadata = {DataTypeMetaData.KEY_BURST: burst_config.id}
        kwargs = {"test_dt_input": stored_dt.gid, 'test_non_dt_input': '0'}
        operations, group = self.operation_service.prepare_operations(self.test_user.id, self.test_project.id,
                                                                      first_step_algorithm,
                                                                      first_step_algorithm.algorithm_category,
                                                                      metadata, **kwargs)

        workflows = self.workflow_service.create_and_store_workflow(project_id=self.test_project.id,
                                                                    burst_id=burst_config.id,
                                                                    simulator_index=0,
                                                                    simulator_id=first_step_algorithm.id,
                                                                    operations=operations)
        self.operation_service.prepare_operations_for_workflowsteps(workflow_step_list, workflows, self.test_user.id,
                                                                    burst_config.id, self.test_project.id, group,
                                                                    operations)
        #fire the first op
        if len(operations) > 0:
            self.operation_service.launch_operation(operations[0].id, False)
        return burst_config.id


    def test_workflow_generation(self):
        """
        A simple test just for the fact that a workflow is created an ran, 
        no dynamic parameters are passed. In this case we create a two steps
        workflow: step1 - tvb.tests.framework.adapters.testadapter2.TestAdapter2
                  step2 - tvb.tests.framework.adapters.testadapter1.TestAdapter1
        The first adapter doesn't return anything and the second returns one
        tvb.datatypes.datatype1.Datatype1 instance. We check that the steps
        are actually ran by checking that two operations are created and that
        one dataType is stored.
        """
        workflow_step_list = [TestFactory.create_workflow_step("tvb.tests.framework.adapters.testadapter2",
                                                               "TestAdapter2", step_index=1,
                                                               static_kwargs={"test2": 2}),
                              TestFactory.create_workflow_step("tvb.tests.framework.adapters.testadapter1",
                                                               "TestAdapter1", step_index=2,
                                                               static_kwargs={"test1_val1": 1, "test1_val2": 1})]
        self.__create_complex_workflow(workflow_step_list)
        stored_datatypes = dao.get_datatypes_in_project(self.test_project.id)
        assert  len(stored_datatypes) == 2, "DataType from second step was not stored."
        assert  stored_datatypes[0].type == 'Datatype1', "Wrong type was stored."
        assert  stored_datatypes[1].type == 'Datatype1', "Wrong type was stored."

        finished, started, error, _, _ = dao.get_operation_numbers(self.test_project.id)
        assert  finished == 3, "Didnt start operations for both adapters in workflow."
        assert  started == 0, "Some operations from workflow didnt finish."
        assert  error == 0, "Some operations finished with error status."


    def test_workflow_dynamic_params(self):
        """
        A simple test just for the fact that dynamic parameters are passed properly
        between two workflow steps: 
                  step1 - tvb.tests.framework.adapters.testadapter1.TestAdapter1
                  step2 - tvb.tests.framework.adapters.testadapter3.TestAdapter3
        The first adapter returns a tvb.datatypes.datatype1.Datatype1 instance. 
        The second adapter has this passed as a dynamic workflow parameter.
        We check that the steps are actually ran by checking that two operations 
#.........这里部分代码省略.........
开发者ID:maedoc,项目名称:tvb-framework,代码行数:103,代码来源:workflow_service_test.py

示例7: BaseController

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
class BaseController(object):
    """
    This class contains the methods served at the root of the Web site.
    """


    def __init__(self):
        self.logger = get_logger(self.__class__.__module__)

        self.user_service = UserService()
        self.flow_service = FlowService()

        analyze_category = self.flow_service.get_launchable_non_viewers()
        self.analyze_category_link = '/flow/step/' + str(analyze_category.id)
        self.analyze_adapters = None

        self.connectivity_tab_link = '/flow/step_connectivity'
        view_category = self.flow_service.get_visualisers_category()
        conn_id = self.flow_service.get_algorithm_by_module_and_class(CONNECTIVITY_MODULE, CONNECTIVITY_CLASS)[1].id
        connectivity_link = self.get_url_adapter(view_category.id, conn_id)

        self.connectivity_submenu = [dict(title="Large Scale Connectivity", subsection="connectivity",
                                          description="View Connectivity Regions. Perform Connectivity lesions",
                                          link=connectivity_link),
                                     dict(title="Local Connectivity", subsection="local",
                                          link='/spatial/localconnectivity/step_1/1',
                                          description="Create or view existent Local Connectivity entities.")]
        self.burst_submenu = [dict(link='/burst', subsection='burst',
                                   title='Simulation Cockpit', description='Manage simulations'),
                              dict(link='/burst/dynamic', subsection='dynamic',
                                   title='Phase plane', description='Configure model dynamics')]


    @staticmethod
    def mark_file_for_delete(file_name, delete_parent_folder=False):
        """
        This method stores provided file name in session, 
        and later on when request is done, all these files/folders
        are deleted
        
        :param file_name: name of the file or folder to be deleted
        :param delete_parent_folder: specify if the parent folder of the file should be removed too.
        """
        # No processing if no file specified
        if file_name is None:
            return

        files_list = common.get_from_session(FILES_TO_DELETE_ATTR)
        if files_list is None:
            files_list = []
            common.add2session(FILES_TO_DELETE_ATTR, files_list)

        # Now add file/folder to list
        if delete_parent_folder:
            folder_name = os.path.split(file_name)[0]
            files_list.append(folder_name)
        else:
            files_list.append(file_name)


    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))


    @staticmethod
    def get_url_adapter(step_key, adapter_id, back_page=None):
        """
        Compute the URLs for a given adapter. 
        Same URL is used both for GET and POST.
        """
        result_url = '/flow/' + str(step_key) + '/' + str(adapter_id)
        if back_page is not None:
            result_url = result_url + "?back_page=" + str(back_page)
        return result_url


    @cherrypy.expose
    def index(self):
        """
        / Path response
        Redirects to /tvb
#.........这里部分代码省略.........
开发者ID:amitsaroj001,项目名称:tvb-framework,代码行数:103,代码来源:base_controller.py

示例8: SerializationManager

# 需要导入模块: from tvb.core.services.flow_service import FlowService [as 别名]
# 或者: from tvb.core.services.flow_service.FlowService import get_algorithm_by_module_and_class [as 别名]
class SerializationManager(object):
    """
    Constructs data types based on a burst configuration.
    Updates the burst configuration.
    """
    def __init__(self, conf):
        """
        :param conf: burst configuration entity
        """
        self.logger = get_logger(__name__)
        self.flow_service = FlowService()
        self.conf = conf


    def _build_simulator_adapter(self):
        _, group = self.flow_service.get_algorithm_by_module_and_class(SIMULATOR_MODULE, SIMULATOR_CLASS)
        return self.flow_service.build_adapter_instance(group)


    def has_model_pse_ranges(self):
        """ Returns True if the burst configuration describes a range on a model parameter """
        first_range = self.conf.get_simulation_parameter_value(RANGE_PARAMETER_1)
        second_range = self.conf.get_simulation_parameter_value(RANGE_PARAMETER_2)
        first_range_on = first_range is not None and str(first_range).startswith(MODEL_PARAMETERS)
        second_range_on = second_range is not None and str(second_range).startswith(MODEL_PARAMETERS)
        return first_range_on or second_range_on


    def _get_params_dict(self):
        """ Convert ui inputs from the configuration to python types """
        simulator_adapter = self._build_simulator_adapter()
        return simulator_adapter.convert_ui_inputs(self.conf.get_all_simulator_values()[0], False)


    def __make_instance_from_burst_config(self, params_dict, parent_class, class_name_key, params_key):
        """ This is used internally to create a model or an integrator based on the burst config """
        class_name = self.conf.get_simulation_parameter_value(class_name_key)
        parameters = params_dict[params_key]
        noise_framework.build_noise(parameters)
        try:
            return get_traited_instance_for_name(class_name, parent_class, parameters)
        except Exception:
            self.logger.exception("Could not create an instance of %s with the given parameters. "
                                  "A new instance will be created with the default values." % class_name)
            return get_traited_instance_for_name(class_name, parent_class, {})


    def __make_shallow_model(self):
        """ Creates a model of the type present in the config without setting any parameters on it """
        class_name = self.conf.get_simulation_parameter_value(PARAM_MODEL)
        return get_traited_instance_for_name(class_name, Model, {})


    def make_model_and_integrator(self):
        """
        :return: A model and an integrator.
        :rtype: Model, Integrator
        """
        params_dict = self._get_params_dict()
        model = self.__make_instance_from_burst_config(params_dict, Model, PARAM_MODEL, MODEL_PARAMETERS)
        integrator = self.__make_instance_from_burst_config(params_dict, Integrator,
                                                            PARAM_INTEGRATOR, INTEGRATOR_PARAMETERS)
        return model, integrator


    def get_connectivity(self):
        """ Prepare Connectivity """
        connectivity_gid = self.conf.get_simulation_parameter_value(PARAM_CONNECTIVITY)
        return ABCAdapter.load_entity_by_gid(connectivity_gid)


    def get_surface(self):
        """ Prepare Surface """
        surface_gid = self.conf.get_simulation_parameter_value(PARAM_SURFACE)
        if surface_gid:
            return ABCAdapter.load_entity_by_gid(surface_gid)
        return None

    @staticmethod
    def group_parameter_values_by_name(model_parameters_list):
        """
        @:param model_parameters_list: Given a list of model parameters like this:
                [{"a": 2.0, 'b': 1.0},
                 {"a": 3.0, 'b': 7.0}])

        @:return: This method will group them by param name to get:
                {'a': [2.0, 3.0], 'b': [1.0, 7.0]}
        """
        ret = {}
        for model_parameters in model_parameters_list:
            for param_name, param_val in model_parameters.iteritems():
                if param_name not in ret:
                    ret[param_name] = []
                ret[param_name].append(param_val)
        return ret


    def write_model_parameters(self, model_name, model_parameters_list):
        """
        Update model parameters in burst config.
#.........这里部分代码省略.........
开发者ID:amitsaroj001,项目名称:tvb-framework,代码行数:103,代码来源:burst_config_serialization.py


注:本文中的tvb.core.services.flow_service.FlowService.get_algorithm_by_module_and_class方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。