code
stringlengths
1
18.2k
def get_composition_search_session_for_repository(self, repository_id): """Gets a composition search session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository return: (osid.repository.CompositionSearchSession) - a ``CompositionSearchSession`` raise: NotFound - ``repository_id`` not...
def get_composition_admin_session(self): """Gets a composition administration session for creating, updating and deleting compositions. return: (osid.repository.CompositionAdminSession) - a ``CompositionAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_composition_admi...
def get_repository_lookup_session(self): """Gets the repository lookup session. return: (osid.repository.RepositoryLookupSession) - a ``RepositoryLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_repository_lookup()`` is ``false`` *compliance: optional -- This method ...
def get_repository_query_session(self): """Gets the repository query session. return: (osid.repository.RepositoryQuerySession) - a ``RepositoryQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_repository_query()`` is ``false`` *compliance: optional -- This method must ...
def get_repository_admin_session(self): """Gets the repository administrative session for creating, updating and deleteing repositories. return: (osid.repository.RepositoryAdminSession) - a ``RepositoryAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_repository_admin(...
def get_repository_hierarchy_session(self): """Gets the repository hierarchy traversal session. return: (osid.repository.RepositoryHierarchySession) - ``a RepositoryHierarchySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_repository_hierarchy()`` is ``false`` *compliance:...
def get_repository_hierarchy_design_session(self): """Gets the repository hierarchy design session. return: (osid.repository.RepositoryHierarchyDesignSession) - a ``RepostoryHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_repository_hierarchy_design()`` is ...
def get_asset_search_session_for_repository(self, repository_id, proxy): """Gets an asset search session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSearchSession) - an ``AssetSearchSession`` raise: NotFound...
def get_asset_admin_session(self, proxy): """Gets an asset administration session for creating, updating and deleting assets. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetAdminSession) - an ``AssetAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to compl...
def get_asset_admin_session_for_repository(self, repository_id, proxy): """Gets an asset administration session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetAdminSession) - an ``AssetAdminSession`` raise: Not...
def get_asset_composition_design_session(self, proxy): """Gets the session for creating asset compositions. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetCompositionDesignSession) - an ``AssetCompositionDesignSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to...
def get_composition_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the composition lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionLookupSession) - the new ``CompositionLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed...
def get_composition_lookup_session_for_repository(self, repository_id, proxy): """Gets the ``OsidSession`` associated with the composition lookup service for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionLoo...
def get_composition_admin_session_for_repository(self, repository_id, proxy): """Gets a composiiton administrative session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionAdminSession) - a ``CompositionAdm...
def get_composition_repository_session(self, proxy): """Gets the session for retrieving composition to repository mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionRepositorySession) - a ``CompositionRepositorySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFaile...
def get_composition_repository_assignment_session(self, proxy): """Gets the session for assigning composition to repository mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionRepositoryAssignmentSession) - a ``CompositionRepositoryAssignmentSession`` raise: NullArgument - ``proxy`` is ...
def get_assessment_id(self): """Gets the assessment ``Id`` associated with this learning objective. return: (osid.id.Id) - the assessment ``Id`` raise: IllegalState - ``has_assessment()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource....
def get_knowledge_category_id(self): """Gets the grade ``Id`` associated with the knowledge dimension. return: (osid.id.Id) - the grade ``Id`` raise: IllegalState - ``has_knowledge_category()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Res...
def get_cognitive_process_id(self): """Gets the grade ``Id`` associated with the cognitive process. return: (osid.id.Id) - the grade ``Id`` raise: IllegalState - ``has_cognitive_process()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resourc...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._cognitive_process_default = self._mdata['cognitive_process']['default_id_values'][0] self._assessment_default = self._mdata['assessment']['default_id_values'][0] self._knowledge_category_d...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedObjectiveBankIds'] = [str(kwargs['objective_bank_id'])] self._my_map['cognitiveProcessId'] = self._cognitive_process_default self._my_map['assessmentId...
def get_assessment_metadata(self): """Gets the metadata for an assessment. return: (osid.Metadata) - metadata for the assessment *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['assessment'...
def set_assessment(self, assessment_id): """Sets the assessment. arg: assessment_id (osid.id.Id): the new assessment raise: InvalidArgument - ``assessment_id`` is invalid raise: NoAccess - ``assessment_id`` cannot be modified raise: NullArgument - ``assessment_id`` is ``null`` *compliance: mandatory -- This method must...
def clear_assessment(self): """Clears the assessment. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_assessment_metadata().i...
def get_knowledge_category_metadata(self): """Gets the metadata for a knowledge category. return: (osid.Metadata) - metadata for the knowledge category *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(s...
def set_knowledge_category(self, grade_id): """Sets the knowledge category. arg: grade_id (osid.id.Id): the new knowledge category raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``grade_id`` cannot be modified raise: NullArgument - ``grade_id`` is ``null`` *compliance: mandatory -- This method must ...
def clear_knowledge_category(self): """Clears the knowledge category. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_knowled...
def get_cognitive_process_metadata(self): """Gets the metadata for a cognitive process. return: (osid.Metadata) - metadata for the cognitive process *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self...
def set_cognitive_process(self, grade_id): """Sets the cognitive process. arg: grade_id (osid.id.Id): the new cognitive process raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``grade_id`` cannot be modified raise: NullArgument - ``grade_id`` is ``null`` *compliance: mandatory -- This method must be ...
def clear_cognitive_process(self): """Clears the cognitive process. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_cognitive...
def get_objective_id(self): """Gets the ``Id`` of the related objective. return: (osid.id.Id) - the objective ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bool(self._my_map['objectiveId']): raise errors.IllegalState...
def get_objective(self): """Gets the related objective. return: (osid.learning.Objective) - the related objective raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective if not bool(self._my_...
def get_assets(self): """Gets any assets associated with this activity. return: (osid.repository.AssetList) - list of assets raise: IllegalState - ``is_asset_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented ...
def get_courses(self): """Gets any courses associated with this activity. return: (osid.course.CourseList) - list of courses raise: IllegalState - ``is_course_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented...
def get_assessments(self): """Gets any assessments associated with this activity. return: (osid.assessment.AssessmentList) - list of assessments raise: IllegalState - ``is_assessment_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be impleme...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._courses_default = self._mdata['courses']['default_id_values'] self._assessments_default = self._mdata['assessments']['default_id_values'] self._assets_default = self._mdata['assets']['defa...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedObjectiveBankIds'] = [str(kwargs['objective_bank_id'])] self._my_map['courseIds'] = self._courses_default self._my_map['assessmentIds'] = self._assessm...
def get_assets_metadata(self): """Gets the metadata for the assets. return: (osid.Metadata) - metadata for the assets *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template metadata = dict(self._mdata['assets']) metadata.up...
def set_assets(self, asset_ids): """Sets the assets. arg: asset_ids (osid.id.Id[]): the asset ``Ids`` raise: InvalidArgument - ``asset_ids`` is invalid raise: NullArgument - ``asset_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ ...
def clear_assets(self): """Clears the assets. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear_assets_template if (self.get_assets_metadata().is_read_only(...
def get_courses_metadata(self): """Gets the metadata for the courses. return: (osid.Metadata) - metadata for the courses *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template metadata = dict(self._mdata['courses']) metadat...
def set_courses(self, course_ids): """Sets the courses. arg: course_ids (osid.id.Id[]): the course ``Ids`` raise: InvalidArgument - ``course_ids`` is invalid raise: NullArgument - ``course_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented...
def clear_courses(self): """Clears the courses. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear_assets_template if (self.get_courses_metadata().is_read_on...
def get_assessments_metadata(self): """Gets the metadata for the assessments. return: (osid.Metadata) - metadata for the assessments *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template metadata = dict(self._mdata['assess...
def set_assessments(self, assessment_ids): """Sets the assessments. arg: assessment_ids (osid.id.Id[]): the assessment ``Ids`` raise: InvalidArgument - ``assessment_ids`` is invalid raise: NullArgument - ``assessment_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- Thi...
def clear_assessments(self): """Clears the assessments. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear_assets_template if (self.get_assessments_metadata(...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidRelationshipForm._init_metadata(self, **kwargs) self._completion_default = self._mdata['completion']['default_decimal_values'][0] self._level_default = self._mdata['level']['default_id_values'][0]
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidRelationshipForm._init_map(self, record_types=record_types) self._my_map['assignedObjectiveBankIds'] = [str(kwargs['objective_bank_id'])] self._my_map['completion'] = self._completion_default self._my_map['objectiveId'] = str(k...
def get_completion_metadata(self): """Gets the metadata for completion percentage. return: (osid.Metadata) - metadata for the completion percentage *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self....
def set_completion(self, completion): """Sets the completion percentage. arg: completion (decimal): the completion percentage raise: InvalidArgument - ``completion`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from temp...
def clear_completion(self): """Clears the completion. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score if (self.get_completion_metad...
def clear_level(self): """Clears the level. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_level_metadata().is_read_only() or self.get_level_metadata().is_required()): raise errors.NoAccess() self._my_map[...
def get_objective_bank(self): """Gets the ``ObjectiveBank`` at this node. return: (osid.learning.ObjectiveBank) - the objective bank represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('LEARNING', runtime=self._runtime, pro...
def get_parent_objective_bank_nodes(self): """Gets the parents of this objective bank. return: (osid.learning.ObjectiveBankNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_objective_bank_nodes = [] for node in self._my_map['parentNodes']: parent_objective_bank...
def get_objectives_by_search(self, objective_query, objective_search): """Pass through to provider ObjectiveSearchSession.get_objectives_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() retur...
def get_activities_by_search(self, activity_query, activitiesearch): """Pass through to provider ActivitySearchSession.get_activities_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return s...
def get_proficiencies_for_resource_on_date(self, resource_id, from_, to): """Pass through to provider ProficiencyLookupSession.get_proficiencies_for_resource_on_date""" # Implemented from azosid template for - # osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template if self._can('look...
def get_proficiencies_by_search(self, proficiency_query, proficiency_search): """Pass through to provider ProficiencySearchSession.get_proficiencies_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDe...
def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False): "Compute the edges for the histogram bins to keep it the same for all nodes." if use_orig_distr: print('Using original distribution (without histogram) to compute edge weights!') edges=None return edges if edge_...
def extract(features, groups, weight_method=default_weight_method, num_bins=default_num_bins, edge_range=default_edge_range, trim_outliers=default_trim_behaviour, trim_percentile=default_trim_percentile, use_original_distribution=False, relative_to_all=False, asymmetric=False, return_networkx_graph=default_return_netwo...
values) specifying which element belongs to which cortical patch. Grouping with numerical values (contiguous from 1 to num_patches) is strongly recommended for simplicity, but this could also be a list of strings of length p, in which case a tuple is returned, identifying which weight belongs to which pair of patches. ...
'manhattan' - 'minowski' - 'noelle_1' - 'noelle_2' - 'noelle_3' - 'noelle_4' - 'noelle_5' - 'relative_bin_deviation' - 'relative_deviation' Note only the following are *metrics*: - 'manhattan' - 'minowski' - 'euclidean' - 'noelle_2' - 'noelle_4' - 'noelle_5' The following are *semi- or quasi-metrics*: - 'kullback_leibl...
'diff_means_abs' Please note this can lead to adjacency matrices that may not be symmetric e.g. difference metric on two scalars is not symmetric). In this case, be sure to use the flag: allow_non_symmetric=True If weight_method is a callable, it must two accept two arrays as input and return one scalar as output. Exam...
number of bins (esp with fewer bins in the range of 3-20), and hence the features extracted based on them vary also. 3) It is recommended to study the impact of this parameter on the final results of the experiment. This could also be optimized within an inner cross-validation loop if desired. edge_range : tuple or Non...
not possible trim the tails (e.g. using the parameters ``trim_outliers`` and ``trim_percentile``) for the current set of features using its own range. trim_outliers : bool, optional Whether to trim a small percentile of outliers at the edges of feature range, when features are expected to contain extreme outliers (like...
directly. Example: ``diff_in_medians = lambda x, y: abs(np.median(x)-np.median(y))`` This option is valid only when weight_method is a valid callable, which must take two inputs (possibly of different lengths) and return a single scalar. relative_to_all : bool Flag to instruct the computation of a grand histogram (dist...
graph populated with weights computed. Default: False. out_weights_path : str, optional Where to save the extracted weight matrix. If networkx output is returned, it would be saved in GraphML format. Default: nothing saved unless instructed. Returns ------- edge_weights : ndarray numpy 2d array of pair-wise edge-weight...
edge_range, trim_outliers, trim_percentile) weight_func, use_orig_distr, non_symmetric = check_weight_method(weight_method, use_original_distribution, asymmetric) # using the same bin edges for all nodes/groups to ensure correspondence # NOTE: common bin edges is important for the disances to be any meaningful edges = ...
def pairwise_extract(features, groups, edges, weight_func, use_orig_distr, group_ids, num_groups, num_links, non_symmetric, return_networkx_graph, out_weights_path): """ Core function to compute the pair-wise histogram distance between all ROIs. Parameters ---------- features groups edges weight_func use_orig_distr gro...
1, num_groups, 1) for dest in target_list: # skipping edge between self if src == dest: continue index2 = groups == group_ids[dest] hist_two = compute_histogram(features[index2], edges, use_orig_distr) try: edge_value = weight_func(hist_one, hist_two) if return_networkx_graph: graph.add_edge(group_ids[src], group_ids[d...
graph else: if out_weights_path is not None: np.savetxt(out_weights_path, edge_weights, delimiter=',', fmt='%.9f') return edge_weights
def identify_groups(groups): """ To compute number of unique elements in a given membership specification. Parameters ---------- groups : numpy 1d array of length p, each value specifying which group that particular node belongs to. For examlpe, if you have a cortical thickness values for 1000 vertices belonging to 100...
ValueError('There must be atleast two nodes or groups in data, for pair-wise edge-weight calculations.') return group_ids, num_groups
def check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile): """Ensuring the parameters are in valid ranges.""" if num_bins < minimum_num_bins: raise ValueError('Too few bins! The number of bins must be >= 5') if num_values < num_groups: raise ValueError('Insufficient number of values in fe...
def type_cast_params(num_bins, edge_range_spec, features, groups): """Casting inputs to required types.""" if isinstance(num_bins, str): # possible when called from CLI num_bins = np.float(num_bins) # rounding it to ensure it is int num_bins = np.rint(num_bins) if np.isnan(num_bins) or np.isinf(num_bins): raise ValueEr...
two values (min, max)') if not isinstance(features, np.ndarray): features = np.array(features) if not isinstance(groups, np.ndarray): groups = np.array(groups) return num_bins, edge_range, features, groups
def make_random_histogram(length=100, num_bins=10): "Returns a sequence of histogram density values that sum to 1.0" hist, bin_edges = np.histogram(np.random.random(length), bins=num_bins, density=True) # to ensure they sum to 1.0 hist = hist / sum(hist) if len(hist) < 2: raise ValueError('Invalid histogram') return hi...
def check_weight_method(weight_method_spec, use_orig_distr=False, allow_non_symmetric=False): "Check if weight_method is recognized and implemented, or ensure it is callable." if not isinstance(use_orig_distr, bool): raise TypeError('use_original_distribution flag must be boolean!') if not isinstance(allow_non_symmetri...
is symmetric. Ignoring asymmetric=False flag.') allow_non_symmetric=False else: raise NotImplementedError('Chosen histogram distance/metric not implemented or invalid.') elif callable(weight_method_spec): # ensure 1) takes two ndarrays try: dummy_weight = weight_method_spec(make_random_histogram(), make_random_histogra...
def check_params(features_spec, groups_spec, num_bins, edge_range_spec, trim_outliers, trim_percentile): """Necessary check on values, ranges, and types.""" if isinstance(features_spec, str) and isinstance(groups_spec, str): features, groups = read_features_and_groups(features_spec, groups_spec) else: features, groups ...
def run_cli(): "Command line interface to hiwenet." features_path, groups_path, weight_method, num_bins, edge_range, \ trim_outliers, trim_percentile, return_networkx_graph, out_weights_path = parse_args() # TODO add the possibility to process multiple combinations of parameters: diff subjects, diff metrics # for featu...
def read_features_and_groups(features_path, groups_path): "Reader for data and groups" try: if not pexists(features_path): raise ValueError('non-existent features file') if not pexists(groups_path): raise ValueError('non-existent groups file') if isinstance(features_path, str): features = np.genfromtxt(features_path, d...
def get_parser(): "Specifies the arguments and defaults, and returns the parser." parser = argparse.ArgumentParser(prog="hiwenet") parser.add_argument("-f", "--in_features_path", action="store", dest="in_features_path", required=True, help="Abs. path to file containing features for a given subject") parser.add_argument...
bin the given values e.g. --edge_range 1 6 " "This can be helpful to ensure correspondence across multiple invocations of hiwenet (for different subjects)," " in terms of range across all bins as well as individual bin edges. " "Default : {}, to automatically compute from the given values.".format(default_edge_range)) ...
def parse_args(): """Parser/validator for the cmd line args.""" parser = get_parser() if len(sys.argv) < 2: parser.print_help() warnings.warn('Too few arguments!', UserWarning) parser.exit(1) # parsing try: params = parser.parse_args() except Exception as exc: print(exc) raise ValueError('Unable to parse command-line a...
def _init(board, project_dir): """ Initialize an OpenAg-based project. Internal function we use for both init and flash commands. """ project_dir = os.path.abspath(project_dir) # Initialize the platformio project pio_config_path = os.path.join(project_dir, "platformio.ini") if not os.path.isfile(pio_config_path): click...
def _run( categories, param_file, project_dir, plugin, target, status_update_interval ): """ Generate code for this project and run it. Internal function we use for both run and flash commands. """ project_dir = os.path.abspath(project_dir) # Make sure the project has been initialized pio_config = os.path.join(project_...
for record in firmware_type_params ] firmware = [ FirmwareModule(record) for record in firmware_params ] # Check for working modules in the lib folder # Do this second so project-local values overwrite values from the server lib_path = os.path.join(project_dir, "lib") for dir_name in os.listdir(lib_path): dir_path = os...
categories modules = prune_unspecified_categories(modules, categories) # Generate src.ino src_dir = os.path.join(project_dir, "src") src_file_path = os.path.join(src_dir, "src.ino") # Load the plugins plugin_fns = (load_plugin(plugin_name) for plugin_name in plugin) # Run modules through each plugin plugins = [plugin_f...
target: command.append("-t") command.append(target) env = os.environ.copy() build_flags = [] for c in categories: build_flags.append("-DOPENAG_CATEGORY_{}".format(c.upper())) env["PLATFORMIO_BUILD_FLAGS"] = " ".join(build_flags) if subprocess.call(command, cwd=project_dir, env=env): raise click.ClickException("Compilat...
def run( categories, param_file, project_dir, plugin, target, status_update_interval ): """ Generate code for this project and run it """ return _run( categories, param_file, project_dir, plugin, target, status_update_interval )
def run_module( ctx, arguments, project_dir, board, **kwargs ): """ Run a single instance of this module. [ARGUMENTS] specifies a list of implementation-specific arguments to the module (for example, configuring Arduino pin numbers for the module). Example: \b openag firmware run_module -t upload 4 This command fetches...
found") # Create the build directory build_path = os.path.join(here, "_build") if not os.path.isdir(build_path): os.mkdir(build_path) kwargs["project_dir"] = build_path # Initialize an openag project in the build directory ctx.invoke(init, board=board, **kwargs) # Link the source files into the lib directory lib_path =...
= float(val) elif arg_info["type"] == "bool": if val.lower() == "true": val = True elif val.lower() == "false": val = False else: raise click.BadParameter( "Argument number {} should be a boolean value " '("true" or "false")'.format(i) ) real_args.append(val) # Write the modules.json file modules = { FIRMWARE_MODULE: [...
def flash( categories, param_file, project_dir, plugin, target, status_update_interval, board ): """ Flashes firmware to device (init + run). Initializes a pio project and runs the result, flashing it to the device. """ _init(board, project_dir) _run( categories, param_file, project_dir, plugin, target, status_update_i...
def prune_unspecified_categories(modules, categories): """ Removes unspecified module categories. Mutates dictionary and returns it. """ res = {} for mod_name, mod_info in modules.items(): mod_categories = mod_info.get("categories", all_categories) for category in categories: if category in mod_categories: break else: ...
def load_plugin(plugin_name): """ Given a plugin name, load plugin cls from plugin directory. Will throw an exception if no plugin can be found. """ plugin_cls = plugin_map.get(plugin_name, None) if not plugin_cls: try: plugin_module_name, plugin_cls_name = plugin_name.split(":") plugin_module = import_module(plugin_mo...
def lengths_offsets(value): """Split the given comma separated value to multiple integer values. """ values = [] for item in value.split(','): item = int(item) values.append(item) return values
def open_pysam_file(fname, ftype): """Open a BAM or FASTA file with pysam (for use with "with" statement)""" try: if ftype == 'bam': fpysam = pysam.AlignmentFile(fname, 'rb') elif ftype == 'fasta': fpysam = pysam.FastaFile(fname) yield fpysam except: raise else: fpysam.close()
def is_bam_valid(bam_file): """Check if bam file is valid. Raises a ValueError if pysam cannot read the file. #TODO: pysam does not differentiate between BAM and SAM """ try: f = pysam.AlignmentFile(bam_file) except ValueError: raise except: raise else: f.close() return True