code
stringlengths
1
18.2k
def create_single_poll_session(self, poll_id, poll_sessions_course_id, poll_sessions_course_section_id=None, poll_sessions_has_public_results=None): """ Create a single poll session. Create a new poll session for this poll """ path = {} data = {} params = {} # REQUIRED - PATH - poll_id """ID""" path["poll_id"] = poll_i...
def _invoke(self, *params): """ Run the self.exe command in-process with the supplied params. """ cmd = [self.exe, '-R', self.location] + list(params) with reentry.in_process_context(cmd) as result: sys.modules['mercurial.dispatch'].run() stdout = result.stdio.stdout.getvalue() stderr = result.stdio.stderr.getvalue() i...
def removeFromRegistery(obj) : """Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory taken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects, cascades to free the registeries of related rabali...
def getDctDescription(self) : "returns a dict describing the object" return {'type' : RabaFields.RABA_FIELD_TYPE_IS_RABA_OBJECT, 'className' : self._rabaClass.__name__, 'raba_id' : self.raba_id, 'raba_namespace' : self._raba_namespace}
def unreference(self) : "explicit deletes the object from the singleton reference dictionary. This is mandatory to be able to delete the object using del(). Also, any attempt to reload an object with the same parameters will result un a new instance being created" try : del(self.__class__._instances[makeRabaObjectSingl...
def ensureIndex(cls, fields, where = '', whereValues = []) : """Add an index for field, indexes take place and slow down saves and deletes but they speed up a lot everything else. If you are going to do a lot of saves/deletes drop the indexes first re-add them afterwards Fields can be a list of fields for Multi-Column ...
where, whereValues = ww) con.commit()
def dropIndex(cls, fields) : "removes an index created with ensureIndex " con = RabaConnection(cls._raba_namespace) rlf, ff = cls._parseIndex(fields) for name in rlf : con.dropIndex(name, 'anchor_raba_id') con.dropIndex(cls.__name__, ff) con.commit()
def getIndexes(cls) : "returns a list of the indexes of a class" con = RabaConnection(cls._raba_namespace) idxs = [] for idx in con.getIndexes(rabaOnly = True) : if idx[2] == cls.__name__ : idxs.append(idx) else : for k in cls.columns : if RabaFields.isRabaListField(getattr(cls, k)) and idx[2] == con.makeRabaListTableN...
def flushIndexes(cls) : "drops all indexes for a class" con = RabaConnection(cls._raba_namespace) for idx in cls.getIndexes() : con.dropIndexByName(idx[1])
def set(self, **args) : "set multiple values quickly, ex : name = woopy" for k, v in args.items() : setattr(self, k, v)
def getFields(cls) : """returns a set of the available fields. In order to be able ti securely loop of the fields, "raba_id" and "json" are not included in the set""" s = set(cls.columns.keys()) s.remove('json') s.remove('raba_id') return s
def _attachToObject(self, anchorObj, relationName) : "dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
def pupatizeElements(self) : """Transform all raba object into pupas""" for i in range(len(self)) : self[i] = self[i].pupa()
def _save(self) : """saves the RabaList into it's own table. This a private function that should be called directly Before saving the entire list corresponding to the anchorObj is wiped out before being rewritten. The alternative would be to keep the sync between the list and the table in real time (remove in both). If...
: if isRabaObject(e) : e.save() objDct = e.getDctDescription() values.append((self.anchorObj.raba_id, None, RabaFields.RABA_FIELD_TYPE_IS_RABA_OBJECT, e._rabaClass.__name__, e.raba_id, e._raba_namespace)) elif isPythonPrimitive(e) : values.append((self.anchorObj.raba_id, e, RabaFields.RABA_FIELD_TYPE_IS_PRIMITIVE, None...
def _attachToObject(self, anchorObj, relationName) : "Attaches the rabalist to a raba object. Only attached rabalists can be saved" if self.anchorObj == None : self.relationName = relationName self.anchorObj = anchorObj self._setNamespaceConAndConf(anchorObj._rabaClass._raba_namespace) self.tableName = self.connection....
def list_files_courses(self, course_id, content_types=None, include=None, only=None, order=None, search_term=None, sort=None): """ List files. Returns the paginated list of files for the folder or course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL...
file (see UsageRights)""" if include is not None: self._validate_enum(include, ["user"]) params["include"] = include # OPTIONAL - only """Array of information to restrict to. Overrides include[] "names":: only returns file name information""" if only is not None: params["only"] = only # OPTIONAL - sort """Sort results ...
def get_public_inline_preview_url(self, id, submission_id=None): """ Get public inline preview url. Determine the URL that should be used for inline preview of the file. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - submission_id """The id of the submission the file is...
def get_file_courses(self, id, course_id, include=None): """ Get file. Returns the standard attachment json object """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - include """Array of additional informat...
def update_file(self, id, hidden=None, lock_at=None, locked=None, name=None, on_duplicate=None, parent_folder_id=None, unlock_at=None): """ Update file. Update some settings on the specified file """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - name """The new display nam...
renamed to a name matching an existing file, the API call will fail unless this parameter is supplied. "overwrite":: Replace the existing file with the same name "rename":: Add a qualifier to make the new filename unique""" if on_duplicate is not None: self._validate_enum(on_duplicate, ["overwrite", "rename"]) data["on...
data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/files/{id}".format(**path), data=data, params=params, single_item=True)
def delete_file(self, id): """ Delete file. Remove the specified file curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \ -H 'Authorization: Bearer <token>' """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id self.logger.debug("DELETE /api/v1/files/{id} with query params: {params} ...
def get_folder_groups(self, id, group_id): """ Get folder. Returns the details for a folder You can get the root folder from a context by using 'root' as the :id. For example, you could get the root folder for a course like: """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = gr...
def update_folder(self, id, hidden=None, lock_at=None, locked=None, name=None, parent_folder_id=None, position=None, unlock_at=None): """ Update folder. Updates a folder """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - name """The new name of the folder""" if name is not ...
# OPTIONAL - locked """Flag the folder as locked""" if locked is not None: data["locked"] = locked # OPTIONAL - hidden """Flag the folder as hidden""" if hidden is not None: data["hidden"] = hidden # OPTIONAL - position """Set an explicit sort position for the folder""" if position is not None: data["position"] = posit...
def create_folder_courses(self, name, course_id, hidden=None, lock_at=None, locked=None, parent_folder_id=None, parent_folder_path=None, position=None, unlock_at=None): """ Create folder. Creates a folder in the specified context """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id...
created if it does not already exist. This parameter only applies to new folders in a context that has folders, such as a user, a course, or a group. If this and parent_folder_id are sent an error will be returned. If neither is given, a default folder will be used.""" if parent_folder_path is not None: data["parent_fo...
= hidden # OPTIONAL - position """Set an explicit sort position for the folder""" if position is not None: data["position"] = position self.logger.debug("POST /api/v1/courses/{course_id}/folders with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POS...
def delete_folder(self, id, force=None): """ Delete folder. Remove the specified folder. You can only delete empty folders unless you set the 'force' flag """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - force """Set to 'true' to allow deleting a non-empty folder""" if fo...
def copy_file(self, dest_folder_id, source_file_id, on_duplicate=None): """ Copy a file. Copy a file from elsewhere in Canvas into a folder. Copying a file across contexts (between courses and users) is permitted, but the source and destination must belong to the same institution. """ path = {} data = {} params = {} # ...
on_duplicate is not None: self._validate_enum(on_duplicate, ["overwrite", "rename"]) data["on_duplicate"] = on_duplicate self.logger.debug("POST /api/v1/folders/{dest_folder_id}/copy_file with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/a...
def copy_folder(self, dest_folder_id, source_folder_id): """ Copy a folder. Copy a folder (and its contents) from elsewhere in Canvas into a folder. Copying a folder across contexts (between courses and users) is permitted, but the source and destination must belong to the same institution. If the source and destinatio...
data=data, params=params, single_item=True)
def set_usage_rights_courses(self, file_ids, course_id, usage_rights_use_justification, folder_ids=None, publish=None, usage_rights_legal_copyright=None, usage_rights_license=None): """ Set usage rights. Sets copyright and license information for one or more files """ path = {} data = {} params = {} # REQUIRED - PATH -...
if publish is not None: data["publish"] = publish # REQUIRED - usage_rights[use_justification] """The intellectual property justification for using the files in Canvas""" self._validate_enum(usage_rights_use_justification, ["own_copyright", "used_by_permission", "fair_use", "public_domain", "creative_commons"]) data["u...
def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None): """ Remove usage rights. Removes copyright and license information associated with one or more files """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - file_ids """List of ids ...
def remove_usage_rights_groups(self, group_id, file_ids, folder_ids=None): """ Remove usage rights. Removes copyright and license information associated with one or more files """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - file_ids """List of ids of fi...
def remove_usage_rights_users(self, user_id, file_ids, folder_ids=None): """ Remove usage rights. Removes copyright and license information associated with one or more files """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - file_ids """List of ids of files t...
def today_as_utc_datetime(): """Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date.""" now = today() if not isinstance(now, datetime) and isinstance(now, date): now = datetime.combine(now, datetime.min.time()) now = now.replace(tzinfo=tz.gettz('UTC')) return now
def import_class(name): """Load class from fully-qualified python module name. ex: import_class('bulbs.content.models.Content') """ module, _, klass = name.rpartition('.') mod = import_module(module) return getattr(mod, klass)
def get_valid_managers(cls, location): """ Get the valid RepoManagers for this location. """ def by_priority_attr(c): return getattr(c, 'priority', 0) classes = sorted( iter_subclasses(cls), key=by_priority_attr, reverse=True) all_managers = (c(location) for c in classes) return (mgr for mgr in all_managers if mgr.is_v...
def get_parent_tags(self, rev=None): """ Return the tags for the parent revision (or None if no single parent can be identified). """ try: parent_rev = one(self.get_parent_revs(rev)) except Exception: return None return self.get_tags(parent_rev)
def find_all_files(self): """ Find files including those in subrepositories. """ files = self.find_files() subrepo_files = ( posixpath.join(subrepo.location, filename) for subrepo in self.subrepos() for filename in subrepo.find_files() ) return itertools.chain(files, subrepo_files)
def get_cmd_out(command): '''Get the output of a command. Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command. Args: command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`). Note: If ``command`` is a ``str``, it will be e...
def get_name(): '''Get desktop environment or OS. Get the OS name or desktop environment. **List of Possible Values** +-------------------------+---------------+ | Windows | windows | +-------------------------+---------------+ | Mac OS X | mac | +-------------------------+---------------+ | GNOME 3+ | gnome | +-------...
| +-------------------------+---------------+ | AfterStep | afterstep | +-------------------------+---------------+ | WindowMaker | windowmaker | +-------------------------+---------------+ | [Other] | unknown | +-------------------------+---------------+ Returns: str: The name of the desktop environment or OS. ''' if ...
desktop environments. elif 'xfce' in desktop_session: return 'xfce4' elif desktop_session.startswith('ubuntu'): return 'unity' elif desktop_session.startswith('xubuntu'): return 'xfce4' elif desktop_session.startswith('lubuntu'): return 'lxde' elif desktop_session.startswith('kubuntu'): return 'kde' elif desktop_sessio...
def is_in_path(program): ''' Check if a program is in the system ``PATH``. Checks if a given program is in the user's ``PATH`` or not. Args: program (str): The program to try to find in ``PATH``. Returns: bool: Is the program in ``PATH``? ''' if sys.version_info.major == 2: path = os.getenv('PATH') if os.name == 'nt': ...
def is_running(process): ''' Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running? ''' if os.name == 'nt': process_list = get_cmd_...
in ps, return True return True return False
def parse_datetime(value): """Returns a datetime object for a given argument This helps to convert strings, dates and datetimes to proper tz-enabled datetime objects.""" if isinstance(value, (string_types, text_type, binary_type)): value = dateutil.parser.parse(value) value.replace(tzinfo=dateutil.tz.tzutc()) return va...
def NegateQueryFilter(es_query): # noqa """ Return a filter removing the contents of the provided query. """ query = es_query.to_dict().get("query", {}) filtered = query.get("filtered", {}) negated_filter = filtered.get("filter", {}) return Not(**negated_filter)
def set_deserializer_by_mime_type(self, mime_type): """ :param mime_type: :return: Used by content_type_set to set get a reference to the serializer object """ for deserializer in self._deserializers: if deserializer.content_type() == mime_type: self._selected_deserializer = deserializer return raise exception.Unsuppor...
def body_template(self, value): """ Must be an instance of a prestans.types.DataCollection subclass; this is generally set during the RequestHandler lifecycle. Setting this spwans the parsing process of the body. If the HTTP verb is GET an AssertionError is thrown. Use with extreme caution. """ if self.method == VERB.G...
def get_response_attribute_filter(self, template_filter, template_model=None): """ Prestans-Response-Attribute-List can contain a client's requested definition for attributes required in the response. This should match the response_attribute_filter_template? :param template_filter: :param template_model: the expected m...
def add(self, parent, obj_type, **attributes): """ IXN API add command @param parent: object parent - object will be created under this parent. @param object_type: object type. @param attributes: additional attributes. @return: IXN object reference. """ return self.ixn.add(parent.obj_ref(), obj_type, *self._get_args_li...
def version(self): """ Return the underlying version """ lines = iter(self._invoke('version').splitlines()) version = next(lines).strip() return self._parse_version(version)
def find_files(self): """ Find versioned files in self.location """ all_files = self._invoke('locate', '-I', '.').splitlines() # now we have a list of all files in self.location relative to # self.find_root() # Remove the parent dirs from them. from_root = os.path.relpath(self.location, self.find_root()) loc_rel_paths ...
def get_tags(self, rev=None): """ Get the tags for the given revision specifier (or the current revision if not specified). """ rev_num = self._get_rev_num(rev) # rev_num might end with '+', indicating local modifications. return ( set(self._read_tags_for_rev(rev_num)) if not rev_num.endswith('+') else set([]) )
def _read_tags_for_revset(self, spec): """ Return TaggedRevision for each tag/rev combination in the revset spec """ cmd = [ 'log', '--style', 'default', '--config', 'defaults.log=', '-r', spec] res = self._invoke(*cmd) header_pattern = re.compile(r'(?P<header>\w+?):\s+(?P<value>.*)') match_res = map(header_pattern.mat...
def _get_rev_num(self, rev=None): """ Determine the revision number for a given revision specifier. """ # first, determine the numeric ID cmd = ['identify', '--num'] # workaround for #4 cmd.extend(['--config', 'defaults.identify=']) if rev: cmd.extend(['--rev', rev]) res = self._invoke(*cmd) return res.strip()
def _get_tags_by_num(self): """ Return a dictionary mapping revision number to tags for that number. """ by_revision = operator.attrgetter('revision') tags = sorted(self.get_tags(), key=by_revision) revision_tags = itertools.groupby(tags, key=by_revision) def get_id(rev): return rev.split(':', 1)[0] return dict( (get_i...
def get_tags(self, rev=None): """ Return the tags for the current revision as a set """ rev = rev or 'HEAD' return set(self._invoke('tag', '--points-at', rev).splitlines())
def validate_template_name(self, key, value): """Validate template name. :param key: The template path. :param value: The template name. :raises ValueError: If template name is wrong. """ if value not in dict(current_app.config['PAGES_TEMPLATES']): raise ValueError( 'Template "{0}" does not exist.'.format(value)) retur...
def classify(self, n_jobs=-1, configure=None): """ Returns input-output behaviors for the list of logical networks in the attribute :attr:`networks` Example:: >>> from caspo import core, classify >>> networks = core.LogicalNetworkList.from_csv('networks.csv') >>> setup = core.Setup.from_json('setup.json') >>> classifie...
for part in parts) networks = core.LogicalNetworkList.from_hypergraph(networks.hg) for behavior in behaviors_parts: networks = networks.concat(behavior) behaviors = __learn_io__(networks, self.setup, configure) self.stats['time_io'] = timeit.default_timer() - start self._logger.info("%s input-output logical behaviors f...
def add_observee_with_credentials(self, user_id, access_token=None, observee_password=None, observee_unique_id=None): """ Add an observee with credentials. Register the given user to observe another user, given the observee's credentials. *Note:* all users are allowed to add their own observees, given the observee's cr...
access_token """The access token for the user to observe. Required if <tt>observee[unique_id]</tt> or <tt>observee[password]</tt> are omitted.""" if access_token is not None: data["access_token"] = access_token self.logger.debug("POST /api/v1/users/{user_id}/observees with query params: {params} and form data: {data}"....
def show_observee(self, user_id, observee_id): """ Show an observee. Gets information about an observed user. *Note:* all users are allowed to view their own observees. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - observee_id """ID""" path["obser...
def add_item(name, command, system_wide=False): '''Adds a program to startup. Adds a program to user startup. Args: name (str) : The name of the startup entry. command (str) : The command to run. system_wide (bool): Add to system-wide startup. Note: ``system_wide`` requires superuser/admin privileges. ''' desktop_env =...
as root # which will auto-happen if current process is root. else: # Linux/Unix if desktop_env == 'unknown': # CLI if system_wide: login_file = '/etc/profile' else: login_file = os.path.expanduser('~/.profile') with open(login_file, 'a') as f: f.write(command) else: try: desktop_file_name = name + '.desktop' startup_fi...
def list_items(system_wide=False): '''List startup programs. List the programs set to run at startup. Args: system_wide (bool): Gets the programs that run at system-wide startup. Returns: list: A list of dictionaries in this format: .. code-block:: python { 'name': 'The name of the entry.', 'command': 'The command used...
path in launchd_plist_paths: if item + '.plist' in os.listdir(path): plist_file = os.path.join(path, item + '.plist') # Parse the plist if sys.version_info.major == 2: plist_parsed = plistlib.readPlist(plist_file) else: with open(plist_file) as f: plist_parsed = plistlib.load(f) if 'Program' in plist_parsed: cmd = plis...
file_path = os.path.join('/etc/profile.d', file) result.append({ 'name': file, 'command': 'sh %s' % file_path }) # GUI try: startup_dir = directories.get_config_dir('autostart', system_wide=system_wide)[0] for file in os.listdir(startup_dir): file_parsed = desktopfile.parse(os.path.join(startup_dir, file)) if 'Name' in...
def remove_item(name, system_wide=False): '''Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` requires superuser/admin pri...
f: login_file_contents = f.read() final_login_file_contents = '' for line in login_file_contents.split('\n'): if line.split(' ')[0] != name: final_login_file_contents += line with open(login_file, 'w') as f: f.write(final_login_file_contents) else: try: desktop_file_name = name + '.desktop' startup_file = os.path.join(...
def get_current_user(self): """ Override get_current_user for Google AppEngine Checks for oauth capable request first, if this fails fall back to standard users API """ from google.appengine.api import users if _IS_DEVELOPMENT_SERVER: return users.get_current_user() else: from google.appengine.api import oauth try: use...
def bam2es( bam_fn, es_fo, allowed_delta, ): """Convert BAM file to ES file. Args: bam_fn (str): File name of the BAM file. bam_fo (file): File object of the ES file. allowed_delta (int): Maximal allowed coordinates difference for correct reads. """ es_fo.write("# RN: read name" + os.linesep) es_fo.write("# Q: is mappe...
os.linesep) es_fo.write("# u segment is unmapped and should be mapped" + os.linesep) es_fo.write("# Segs: number of segments" + os.linesep) es_fo.write("# " + os.linesep) es_fo.write("# RN\tQ\tChr\tD\tL\tR\tCat\tSegs" + os.linesep) with pysam.AlignmentFile(bam_fn, "rb") as sam: references_dict = {} for i in range(len(s...
0 or abs(segment.left - left) <= allowed_delta) and (segment.right == 0 or abs(segment.right - right) <= allowed_delta) and (segment.left != 0 or segment.right == 0) and (chrom_id == 0 or chrom_id == segment.chr_id) ): exists_corresponding_segment = True segment = str(j + 1) break # read was mapped to correct location ...
+ os.linesep )
def create_es(self): """Create an ES (intermediate) file for this BAM file. This is the function which asses if an alignment is correct """ with (gzip.open(self._es_fn, "tw+") if self.compress_intermediate_files else open(self._es_fn, "w+")) as es_fo: self.bam2es( bam_fn=self._bam_fn, es_fo=es_fo, allowed_delta=self.re...
def _vector_of_categories(srs, read_tuple_name, parts): """Create vector of categories (voc[q] ... assigned category for given quality level) srs ... single read statistics ... for every q ... dictionary read_tuple_name ... read name parts ... number of segments """ # default value vec = ["x" for i in range(rnftools.la...
str((q, srs[q])) vec[q] = "w" ##### # m # - at least one segment was aligned but should not be aligned ##### if srs[q]["w"] == 0 and srs[q]["m"] > 0: assert vec[q] == "x", str((q, srs[q])) vec[q] = "m" ##### # U # - all segments should be unaligned but are unaligned ##### if srs[q]["U"] > 0 and srs[q]["u"] == 0 and srs...
len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q][ "u"] == 0 and srs[q]["t"] > 0: assert vec[q] == "x", str((q, srs[q])) vec[q] = "t" ##### # T # - at least one segment was thresholded ##### if len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[...
def es2et( es_fo, et_fo, ): """Convert ES to ET. Args: es_fo (file): File object for the ES file. et_fo (file): File object for the ET file. """ et_fo.write("# Mapping information for read tuples" + os.linesep) et_fo.write("#" + os.linesep) et_fo.write("# RN: read name" + os.linesep) et_fo.write("# I: intervals with as...
"m": 0, "w": 0, "T": 0, "t": 0, } for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1) ] last_rname = rname #################### # Unmapped segment # #################### ##### # U # ##### if category == "U": for q in range(len(single_reads_statistics)): single_reads_statistics[q]["U"] += 1 ##### # u # ##### e...
range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1): single_reads_statistics[q]["t"] += 1 ##### # M # ##### else: assert category[0] == "M", category segment_id = int(category.replace("M_", "")) for q in range(mapping_quality + 1): single_reads_statistics[q]["M"].append(segment_id) for q in range(...
def create_et(self): """Create a et file for this BAM file (mapping information about read tuples). raises: ValueError """ with (gzip.open(self._es_fn, "tr") if self.compress_intermediate_files else open(self._es_fn, "r")) as es_fo: with (gzip.open(self._et_fn, "tw+") if self.compress_intermediate_files else open(self....
def et2roc(et_fo, roc_fo): """ET to ROC conversion. Args: et_fo (file): File object for the ET file. roc_fo (file): File object for the ROC file. raises: ValueError """ stats_dicts = [ { "q": q, "M": 0, "w": 0, "m": 0, "P": 0, "U": 0, "u": 0, "T": 0, "t": 0, "x": 0 } for q in range(rnftools.lavender.MAXIMAL_MAPPING_QUA...
+ os.linesep) roc_fo.write("# Categories:" + os.linesep) roc_fo.write("# M: Mapped correctly." + os.linesep) roc_fo.write("# w: Mapped to a wrong position." + os.linesep) roc_fo.write("# m: Mapped but should be unmapped." + os.linesep) roc_fo.write("# P: Multimapped." + os.linesep) roc_fo.write("# U: Unmapped and shoul...
def create_roc(self): """Create a ROC file for this BAM file. raises: ValueError """ with (gzip.open(self._et_fn, "tr") if self.compress_intermediate_files else open(self._et_fn, "r")) as et_fo: with open(self._roc_fn, "w+") as roc_fo: self.et2roc( et_fo=et_fo, roc_fo=roc_fo, )
def create_gp(self): """Create a GnuPlot file for this BAM file.""" categories_order = [ ("{U}", "#ee82ee", 'Unmapped correctly'), ("{u}", "#ff0000", 'Unmapped incorrectly'), ("{T}", "#00ff00", 'Thresholded correctly'), ("{t}", "#008800", 'Thresholded incorrectly'), ("{P}", "#ffff00", 'Multimapped'), ("{w}+{x}", "#7f7f...
unset xtics set ylab "Part of all reads (%)" set format y "%g %%" set yran [{yran}] set y2ran [{yran}] set pointsize 1.5 set grid ytics lc rgb "#777777" lw 1 lt 0 front set grid x2tics lc rgb "#777777" lw 1 lt 0 front set datafile separator "\\t" set palette negative set termin svg size {svg_size} enhanced set out "{sv...
def create_graphics(self): """Create images related to this BAM file using GnuPlot.""" rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: svg_fn = self._svg_fn pdf_fn = self._pdf_fn svg42pdf(svg_fn, pdf_fn, method=self.render_pdf_method)
def create_html(self): """Create a HTML page for this BAM file.""" roc_dicts = [] with open(self._roc_fn, "r") as roc: for line in roc: line = line.strip() if line != "" and line[0] != "#": (q, M, w, m, P, U, u, T, t, x, a) = map(int, line.split("\t")) roc_dict = { "q": q, "M": M, "w": w, "m": m, "P": P, "U": U, "u": u...
<td><small> {P_proc:.2f} </small></td> <td> {unmapped} </td> <td><small> {unmapped_proc:.2f} </small></td> <td> {U} </td> <td><small> {U_proc:.2f} </small></td> <td> {u} </td> <td><small> {u_proc:.2f} </small></td> <td> {T} </td> <td><small> {T_proc:.2f} </small></td> <td> {t} </td> <td><small> {t_proc:.2f} </small></t...