code
stringlengths
1
18.2k
def file_put_contents(self, path, data): """ Put passed contents into file located at 'path' """ path = self.get_full_file_path(path) # if file exists, create a temp copy to allow rollback if os.path.isfile(path): tmp_path = self.new_tmp() self.do_action({ 'do' : ['copy', path, tmp_path], 'undo' : ['move', tmp_path, pa...
def move_file(self, src, dst): """ Move file from src to dst """ src = self.get_full_file_path(src); dst = self.get_full_file_path(dst) # record where file moved if os.path.isfile(src): # if destination file exists, copy it to tmp first if os.path.isfile(dst): tmp_path = self.new_tmp() self.do_action({ 'do' : ['copy', ...
def delete_file(self, path): """ delete a file """ path = self.get_full_file_path(path) # if file exists, create a temp copy to allow rollback if os.path.isfile(path): tmp_path = self.new_tmp() self.do_action({ 'do' : ['move', path, tmp_path], 'undo' : ['move', tmp_path, path]}) else: raise OSError(errno.ENOENT, 'No su...
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' result = {} try: # get labels from filesystem for entry in os.scandir(diskdir): if entry.name.startswith('.'): continue if islink(entry.path): target = os.readlink(entry.path) else: target = entry.path result[target] = entry....
def get_diskinfo(opts, show_all=False, debug=False, local_only=False): ''' Returns a list holding the current disk info, stats divided by the ouptut unit. ''' outunit = opts.outunit disks = [] try: label_map = get_label_map(opts) lines = run(diskcmd).splitlines()[1:] # dump header for line in lines: tokens = line.split...
outunit disk.mntp = mntp.decode('utf8') disk.label = label_map.get(disk.mntp) disk.ismntd = bool(disk.mntp) disk.isnet = ':' in dev # cheesy but may work? (macos) if local_only and disk.isnet: continue if disk.ismntd: if disk.mntp == '/': disk.rw = True else: disk.rw = os.access(disk.mntp, os.W_OK) # ~ disk.isopt = Non...
def get_meminfo(opts): ''' Returns a dictionary holding the current memory info, divided by the ouptut unit. If mem info can't be read, returns None. For Darwin / Mac OS X, interrogates the output of the sysctl and vm_stat utilities rather than /proc/meminfo ''' outunit = opts.outunit meminfo = MemInfo() sysinf = parse...
meminfo.swapused = (meminfo.swaptotal - meminfo.swapcached - #~ meminfo.swapfree) if opts.debug: print('meminfo:', meminfo) return meminfo
def parse_sysctl(text): ''' Parse sysctl output. ''' lines = text.splitlines() results = {} for line in lines: key, _, value = line.decode('ascii').partition(': ') if key == 'hw.memsize': value = int(value) elif key == 'vm.swapusage': values = value.split()[2::3] # every third token su_unit = values[0][-1].lower() # ge...
def parse_vmstat(text): ''' Parse vmstat output. ''' lines = text.splitlines() results = Info() # TODO use MemInfo try: PAGESIZE = int(lines[0].split()[-2]) except IndexError: PAGESIZE = 4096 for line in lines[1:]: # dump header if not line[0] == 80: # b'P' startswith Page... break tokens = line.split() name, value = t...
def get_base_url(html: str) -> str: """ Search for login url from VK login page """ forms = BeautifulSoup(html, 'html.parser').find_all('form') if not forms: raise VVKBaseUrlException('Form for login not found') elif len(forms) > 1: raise VVKBaseUrlException('More than one login form found') login_url = forms[0].get('a...
def get_url_params(url: str, fragment: bool = False) -> dict: """ Parse URL params """ parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_query = parse_qsl(parsed_url.query) return dict(url_query)
def check_page_for_warnings(html: str) -> None: """ Checks if is any warnings on page if so raises an exception """ soup = BeautifulSoup(html, 'html.parser') warnings = soup.find_all('div', {'class': 'service_msg_warning'}) if warnings: exception_msg = '; '.join((warning.get_text() for warning in warnings)) raise VVKPa...
def result_to_dict(res): """ :param res: :any:`sqlalchemy.engine.ResultProxy` :return: a list of dicts where each dict represents a row in the query where the key \ is the column name and the value is the value of that column. """ keys = res.keys() return [dict(itertools.izip(keys, row)) for row in res]
def get_bind_processor(column_type, dialect): """ Returns a bind processor for a column type and dialect, with special handling for JSON/JSONB column types to return dictionaries instead of serialized JSON strings. NOTE: This is a workaround for https://github.com/NerdWalletOSS/savage/issues/8 :param column_type: :py:c...
wrapped_bind_processor(value): json_deserializer = dialect._json_deserializer or json.loads return json_deserializer(column_type.bind_processor(dialect)(value)) return wrapped_bind_processor
def get_column_attribute(row, col_name, use_dirty=True, dialect=None): """ :param row: the row object :param col_name: the column name :param use_dirty: whether to return the dirty value of the column :param dialect: if not None, should be a :py:class:`~sqlalchemy.engine.interfaces.Dialect`. If \ specified, this functi...
return current_value elif hist.deleted: return bind_processor(hist.deleted[0]) return None
def get_column_keys_and_names(table): """ Return a generator of tuples k, c such that k is the name of the python attribute for the column and c is the name of the column in the sql table. """ ins = inspect(table) return ((k, c.name) for k, c in ins.mapper.c.items())
def has_constraint(model, engine, *col_names): # pragma: no cover """ :param model: model class to check :param engine: SQLAlchemy engine :param col_names: the name of columns which the unique constraint should contain :rtype: bool :return: True if the given columns are part of a unique constraint on model """ table_na...
def is_modified(row, dialect): """ Has the row data been modified? This method inspects the row, and iterates over all columns looking for changes to the (processed) data, skipping over unmodified columns. :param row: SQLAlchemy model instance :param dialect: :py:class:`~sqlalchemy.engine.interfaces.Dialect` :return: T...
def registerLoggers(info, error, debug): """ Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message, kwargs will be interpolated. """ g...
def background(cl, proto=EchoProcess, **kw): """ Use the reactor to run a process in the background. Keep the pid around. ``proto'' may be any callable which returns an instance of ProcessProtocol """ if isinstance(cl, basestring): cl = shlex.split(cl) if not cl[0].startswith('/'): path = which(cl[0]) assert path, '%s ...
def runner(Options, buffering=True): """ Return a standard "run" function that wraps an Options class If buffering=False, turn off stdout/stderr buffering for this process """ def run(argv=None): if not buffering: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0) if...
def killall(self): """ Kill all children """ for pid in set(self): try: os.kill(pid, signal.SIGTERM) except OSError, e: # pragma: nocover if e.errno == errno.ESRCH: "Process previously died on its own" self.remove(pid)
def processEnded(self, reason): """ Connected process shut down """ log_debug("{name} process exited", name=self.name) if self.deferred: if reason.type == ProcessDone: self.deferred.callback(reason.value.exitCode) elif reason.type == ProcessTerminated: self.deferred.errback(reason) return self.deferred
def errReceived(self, data): """ Connected process wrote to stderr """ lines = data.splitlines() for line in lines: log_error("*** {name} stderr *** {line}", name=self.name, line=self.errFilter(line))
def outLineReceived(self, line): """ Handle data via stdout linewise. This is useful if you turned off buffering. In your subclass, override this if you want to handle the line as a protocol line in addition to logging it. (You may upcall this function safely.) """ log_debug('<<< {name} stdout >>> {line}', name=self.na...
def write(self, *a, **kw): """ Write to both files If either one has an error, try writing the error to the other one. """ fl = None try: self.file1.write(*a, **kw) self.file1.flush() except IOError: badFile, fl = 1, failure.Failure() try: self.file2.write(*a, **kw) self.file2.flush() except IOError: badFile, fl = 2, f...
def item_completed(self, results, item, info): ''' 在正常图片本地化处理管道业务执行完毕后,使用缩略图路径替换原 ``result[path]`` 路径, 从而使最终打包时使用缩略图,并根据配置,对缩略图进行灰度处理 :param item: 爬取到的数据模型 :type item: :class:`.MoearPackageMobiItem` or dict ''' # 处理 results 中的 path 使用缩略图路径替代 for ok, result in results: if not ok: continue path = result['path'] path = re...
def process_item(self, item, spider): ''' 将从图片处理管道流过的数据模型中的缩略图链接更新到文章中的相应图片 URL 上, 并对其中的,已删除图片 ``item['image_urls_removed']`` 进行处理, 使其显示内建的删除图标。 最终使用文章模板,对数据模型中的数据进行渲染并输出到指定路径中,完成本地化, 等待最终 ``mobi`` 打包 :param item: 爬取到的数据模型 :type item: :class:`.MoearPackageMobiItem` or dict :param spider: 当前爬虫对象 :type spider: :class:`.M...
item['url_local'] = os.path.join('html', html_name) page_store = os.path.join(spider.build_source_dir, item['url_local']) # 将item中的生成字段添加到post中 idx = 0 post = None for section in spider.data.items(): for p in section[1]: idx += 1 if p.get('origin_url') == item.get('url'): post = p p['idx'] = 'post_{:0>3}'.format(idx) p...
def from_etree( el, node=None, node_cls=None, tagsub=functools.partial(re.sub, r'\{.+?\}', ''), Node=Node): '''Convert the element tree to a tater tree. ''' node_cls = node_cls or Node if node is None: node = node_cls() tag = tagsub(el.tag) attrib = dict((tagsub(k), v) for (k, v) in el.attrib.items()) node.update(attri...
def from_dict(cls, raw_data, **kwargs): """ This factory for :class:`Model` creates a Model from a dict object. """ instance = cls() instance.populate(raw_data, **kwargs) instance.validate(**kwargs) return instance
def secure(view): """ Authentication decorator for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator. """ auth_decorator = import_class(settings.AUTH...
def getOpenFileName(*args): """ Normalizes the getOpenFileName method between the different Qt wrappers. :return (<str> filename, <bool> accepted) """ result = QtGui.QFileDialog.getOpenFileName(*args) # PyQt4 returns just a string if type(result) is not tuple: return result, bool(result) # PySide returns a tuple of str...
def getDirectory(*args): """ Normalizes the getDirectory method between the different Qt wrappers. :return (<str> filename, <bool> accepted) """ result = QtGui.QFileDialog.getDirectory(*args) # PyQt4 returns just a string if type(result) is not tuple: return result, bool(result) # PySide returns a tuple of str, bool el...
def getSaveFileName(*args): """ Normalizes the getSaveFileName method between the different Qt wrappers. :return (<str> filename, <bool> accepted) """ result = QtGui.QFileDialog.getSaveFileName(*args) # PyQt4 returns just a string if type(result) is not tuple: return result, bool(result) # PySide returns a tuple of str...
def get_netid_categories(netid, category_codes): """ Return a list of uwnetid.models Category objects corresponding to the netid and category code or list provided """ url = _netid_category_url(netid, category_codes) response = get_resource(url) return _json_to_categories(response)
def update_catagory(netid, category_code, status): """ Post a subscriptionfor the given netid and category_code """ url = "{0}/category".format(url_version()) body = { "categoryCode": category_code, "status": status, "categoryList": [{"netid": netid}] } response = post_resource(url, json.dumps(body)) return json.loads(...
def _netid_category_url(netid, category_codes): """ Return UWNetId resource for provided netid and category code or code list """ return "{0}/{1}/category/{2}".format( url_base(), netid, (','.join([str(n) for n in category_codes]) if isinstance(category_codes, (list, tuple)) else category_codes))
def _json_to_categories(response_body): """ Returns a list of Category objects """ data = json.loads(response_body) categories = [] for category_data in data.get("categoryList", []): categories.append(Category().from_json( data.get('uwNetID'), category_data)) return categories
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in globals_map, locals_map return locals_map
def activate(ctx): """Activate the given ParseContext.""" if hasattr(ctx, '_on_context_exit'): raise ContextError( 'Context actions registered outside this ' 'parse context are active') try: ParseContext._active.append(ctx) ctx._on_context_exit = [] yield finally: for func, args, kwargs in ctx._on_context_exit: func(*a...
def parse(self, **global_args): """Entry point to parsing a BUILD file. Args: **global_args: Variables to include in the parsing environment. """ if self.build_file not in ParseContext._parsed: # http://en.wikipedia.org/wiki/Abstract_syntax_tree # http://martinfowler.com/books/dsl.html butcher_context = {} for str_to_e...
def instantiate_client(self, config): """ :param config: The config object. :type config: dict :return: The instantiated class. :rtype: :class:`revision.client.Client` """ modules = config.module.split('.') class_name = modules.pop() module_path = '.'.join(modules) client_instance = getattr( __import__(module_path, {},...
def add_client(self, client): """ Adds the specified client to this manager. :param client: The client to add into this manager. :type client: :class:`revision.client.Client` :return: The ClientManager instance (method chaining) :rtype: :class:`revision.client_manager.ClientManager` """ if not isinstance(client, Client...
def generate_conf_file(argv: List[str]) -> bool: """ Convert a set of FHIR resources into their corresponding i2b2 counterparts. :param argv: Command line arguments. See: create_parser for details :return: """ parser = ArgumentParser(description="Generate SQL db_conf file template") parser.add_argument("-f", "--configf...
def compute(self, *args, **kwargs)->[Any, None]: """Compose and evaluate the function. """ return super().compute( self.compose, *args, **kwargs )
def copy(self, klass=None): """Create a new instance of the current chain. """ chain = ( klass if klass else self.__class__ )(*self._args, **self._kwargs) chain._tokens = self._tokens.copy() return chain
def call(self, tokens, *args, **kwargs): """Add args and kwargs to the tokens. """ tokens.append([evaluate, [args, kwargs], {}]) return tokens
def copy(self, klass=_x): """A new chain beginning with the current chain tokens and argument. """ chain = super().copy() new_chain = klass(chain._args[0]) new_chain._tokens = [[ chain.compose, [], {}, ]] return new_chain
def prefix(filename): ''' strips common fMRI dataset suffixes from filenames ''' return os.path.split(re.sub(_afni_suffix_regex,"",str(filename)))[1]
def suffix(filename,suffix): ''' returns a filenames with ``suffix`` inserted before the dataset suffix ''' return os.path.split(re.sub(_afni_suffix_regex,"%s\g<1>" % suffix,str(filename)))[1]
def afni_copy(filename): ''' creates a ``+orig`` copy of the given dataset and returns the filename as a string ''' if nl.pkg_available('afni',True): afni_filename = "%s+orig" % nl.prefix(filename) if not os.path.exists(afni_filename + ".HEAD"): nl.calc(filename,'a',prefix=nl.prefix(filename)) return afni_filename
def nifti_copy(filename,prefix=None,gzip=True): ''' creates a ``.nii`` copy of the given dataset and returns the filename as a string''' # I know, my argument ``prefix`` clobbers the global method... but it makes my arguments look nice and clean if prefix==None: prefix = filename nifti_filename = globals()['prefix'](pr...
def dset_copy(dset,to_dir): '''robust way to copy a dataset (including AFNI briks)''' if nl.is_afni(dset): dset_strip = re.sub(r'\.(HEAD|BRIK)?(\.(gz|bz))?','',dset) for dset_file in [dset_strip + '.HEAD'] + glob.glob(dset_strip + '.BRIK*'): if os.path.exists(dset_file): shutil.copy(dset_file,to_dir) else: if os.path.e...
def _dset_info_afni(dset): ''' returns raw output from running ``3dinfo`` ''' info = DsetInfo() try: raw_info = subprocess.check_output(['3dinfo','-verb',str(dset)],stderr=subprocess.STDOUT) except: return None if raw_info==None: return None # Subbrick info: sub_pattern = r'At sub-brick #(\d+) \'([^\']+)\' datum type i...
info.slice_timing = slice_timing[0] TR = re.findall('Time step = ([0-9.]+)s',raw_info) if len(TR): info.TR = float(TR[0]) # Other info.. details_regex = { 'identifier': r'Identifier Code:\s+(.*)', 'filetype': r'Storage Mode:\s+(.*)', 'space': r'Template Space:\s+(.*)' } for d in details_regex: m = re.search(details_reg...
def dset_info(dset): '''returns a :class:`DsetInfo` object containing the meta-data from ``dset``''' if nl.pkg_available('afni'): return _dset_info_afni(dset) nl.notify('Error: no packages available to get dset info',level=nl.level.error) return None
def subbrick(dset,label,coef=False,tstat=False,fstat=False,rstat=False,number_only=False): ''' returns a string referencing the given subbrick within a dset This method reads the header of the dataset ``dset``, finds the subbrick whose label matches ``label`` and returns a string of type ``dataset[X]``, which can be us...
coef is True: coef = 0 label += "#%d_Coef" % coef elif tstat != False: if tstat==True: tstat = 0 label += "#%d_Tstat" % tstat elif fstat: label += "_Fstat" elif rstat: label += "_R^2" info = nl.dset_info(dset) if info==None: nl.notify('Error: Couldn\'t get info from dset "%s"'%dset,level=nl.level.error) return None i =...
def dset_grids_equal(dsets): '''Tests if each dataset in the ``list`` ``dsets`` has the same number of voxels and voxel-widths''' infos = [dset_info(dset) for dset in dsets] for i in xrange(3): if len(set([x.voxel_size[i] for x in infos]))>1 or len(set([x.voxel_dims[i] for x in infos]))>1: return False return True
def resample_dset(dset,template,prefix=None,resam='NN'): '''Resamples ``dset`` to the grid of ``template`` using resampling mode ``resam``. Default prefix is to suffix ``_resam`` at the end of ``dset`` Available resampling modes: :NN: Nearest Neighbor :Li: Linear :Cu: Cubic :Bk: Blocky ''' if prefix==None: prefix = nl....
def ijk_to_xyz(dset,ijk): '''convert the dset indices ``ijk`` to RAI coordinates ``xyz``''' i = nl.dset_info(dset) orient_codes = [int(x) for x in nl.run(['@AfniOrient2RAImap',i.orient]).output.split()] orient_is = [abs(x)-1 for x in orient_codes] rai = [] for rai_i in xrange(3): ijk_i = orient_is[rai_i] if orient_code...
def bounding_box(dset): '''return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset``''' o = nl.run(["3dAutobox","-input",dset]) ijk_coords = re.findall(r'[xyz]=(\d+)\.\.(\d+)',o.output) from_rai = ijk_to_xyz(dset,[float(x[0]) for x in ijk_coords]) to_rai = ijk_to_xyz(dset,[float(x[1]) for x...
def value_at_coord(dset,coords): '''returns value at specified coordinate in ``dset``''' return nl.numberize(nl.run(['3dmaskave','-q','-dbox'] + list(coords) + [dset],stderr=None).output)
def do_printActivities(self,args): """Print scaling activities""" parser = CommandArgumentParser("printActivities") parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh'); args = vars(parser.parse_args(args)) refresh = args['refresh'] or not self.activities if refresh: response = self.c...
def do_printActivity(self,args): """Print scaling activity details""" parser = CommandArgumentParser("printActivity") parser.add_argument(dest='index',type=int,help='refresh'); args = vars(parser.parse_args(args)) index = args['index'] activity = self.activities[index] pprint(activity)
def do_printInstances(self,args): """Print the list of instances in this auto scaling group. printInstances -h for detailed help""" parser = CommandArgumentParser("printInstances") parser.add_argument(dest='filters',nargs='*',default=["*"],help='Filter instances'); parser.add_argument('-a','--addresses',action='store_t...
= 0 print " Network Interfaces:" for interface in networkInterfaces: print " * {0:3d} {1}".format(number, interface['PrivateIpAddress']) number +=1 if tags: tags = description['Reservations'][0]['Instances'][0]['Tags'] print " Tags:" for tag in tags: print " * {0} {1}".format(tag['Key'],tag['Value']) if details: pprint...
def do_printPolicy(self,args): """Print the autoscaling policy""" parser = CommandArgumentParser("printPolicy") args = vars(parser.parse_args(args)) policy = self.client.describe_policies(AutoScalingGroupName=self.scalingGroup) pprint(policy)
def do_rebootInstance(self,args): """Restart specified instance""" parser = CommandArgumentParser("rebootInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] try: index = int(instanceId) instances = self.scalingGroupDescription...
def do_setDesiredCapacity(self,args): """Set the desired capacity""" parser = CommandArgumentParser("setDesiredCapacity") parser.add_argument(dest='value',type=int,help='new value'); args = vars(parser.parse_args(args)) value = int(args['value']) print "Setting desired capacity to {}".format(value) client = AwsConnecti...
def do_run(self,args): """SSH to each instance in turn and run specified command""" parser = CommandArgumentParser("run") parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you've seen before.") parser...
instances = instances[skip:] # if replaceKey or keyscan: # for instance in instances: # stdplus.resetKnownHost(instance) if args['macro']: if len(args['command']) > 1: print("Only one macro may be specified with the -m switch.") return else: macro = args['command'][0] print("Macro:{}".format(macro)) command = Config.co...
def do_ssh(self,args): """SSH to an instance. ssh -h for detailed help""" parser = CommandArgumentParser("ssh") parser.add_argument(dest='instance',help='instance index or name'); parser.add_argument('-a','--address-number',default='0',dest='interface-number',help='instance id of the instance to ssh to'); parser.add_ar...
vars(parser.parse_args(args)) interfaceNumber = int(args['interface-number']) forwarding = args['forwarding'] replaceKey = args['replaceKey'] keyscan = args['keyscan'] background = args['background'] verbosity = args['verbosity'] ignoreHostKey = args['ignore-host-key'] noEcho = args['no-echo'] # Figure out the host to ...
def do_startInstance(self,args): """Start specified instance""" parser = CommandArgumentParser("startInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] force = args['force'] try: index = int(instanceId) instances = self.scali...
def do_stopInstance(self,args): """Stop specified instance""" parser = CommandArgumentParser("stopInstance") parser.add_argument(dest='instance',help='instance index or name'); parser.add_argument('-f','--force',action='store_true',dest='force',help='instance index or name'); args = vars(parser.parse_args(args)) instan...
def do_terminateInstance(self,args): """Terminate an EC2 instance""" parser = CommandArgumentParser("terminateInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] try: index = int(instanceId) instances = self.scalingGroupDescri...
def do_updateCapacity(self,args): """Set the desired capacity""" parser = CommandArgumentParser("updateMinMax") parser.add_argument('-m','--min',dest='min',type=int,help='new values'); parser.add_argument('-M','--max',dest='max',type=int,help='new values'); parser.add_argument('-d','--desired',dest='desired',type=int,h...
def main(sequencepath, report, refseq_database, num_threads=12, start=time.time()): """ Run the appropriate functions in order :param sequencepath: path of folder containing FASTA genomes :param report: boolean to determine whether a report is to be created :param refseq_database: Path to reduced refseq database sketch...
find_l75(contig_len_dict, genome_length_dict) l90_dict = find_l90(contig_len_dict, genome_length_dict) printtime('Using prodigal to calculate number of ORFs in each sample', start) orf_file_dict = predict_orfs(file_dict, num_threads=num_threads) orf_dist_dict = find_orf_distribution(orf_file_dict) if report: reporter(g...
def find_files(sequencepath): """ Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as .fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported :param sequencepath: path of folder containing FASTA genomes :return: list of FASTA files ""...
def filer(filelist): """ Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension) :param filelist: list of files to parse :return filedict: dictionary of stain name: /sequencepath/strain_name.extension """ # Initialise the dictionary filedict = dict() for seqfile in filelist: # Sp...
def fasta_records(files): """ Use SeqIO to create dictionaries of all records for each FASTA file :param files: dictionary of stain name: /sequencepath/strain_name.extension :return: file_records: dictionary of all contig records for all strains """ # Initialise the dictionary file_records = dict() for file_name, fasta...
def find_genus(files, database, threads=12): """ Uses MASH to find the genus of fasta files. :param files: File dictionary returned by filer method. :param database: Path to reduced refseq database sketch. :param threads: Number of threads to run mash with. :return: genus_dict: Dictionary of genus for each sample. Will...
def fasta_stats(files, records): """ Parse the lengths of all contigs for each sample, as well as the total GC% :param files: dictionary of stain name: /sequencepath/strain_name.extension :param records: Dictionary of strain name: SeqIO records :return: contig_len_dict, gc_dict: dictionaries of list of all contig lengt...
# Calculate the GC% of the total genome sequence using GC - format to have two decimal places gc_dict[file_name] = float('{:0.2f}'.format(GC(fasta_sequence))) return contig_len_dict, gc_dict
def find_contig_distribution(contig_lengths_dict): """ Determine the frequency of different contig size ranges for each strain :param contig_lengths_dict: :return: contig_len_dist_dict: dictionary of strain name: tuple of contig size range frequencies """ # Initialise the dictionary contig_len_dist_dict = dict() for fi...
1 elif contig_length > 5000: over_5000 += 1 else: other += 1 # Populate the dictionary with a tuple of each of the size range frequencies contig_len_dist_dict[file_name] = (over_1000000, over_500000, over_100000, over_50000, over_10000, over_5000, other) return contig_len_dist_dict
def find_largest_contig(contig_lengths_dict): """ Determine the largest contig for each strain :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :return: longest_contig_dict: dictionary of strain name: longest contig """ # Initialise the dictionary longest_contig_dict = di...
def find_genome_length(contig_lengths_dict): """ Determine the total length of all the contigs for each strain :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :return: genome_length_dict: dictionary of strain name: total genome length """ # Initialise the dictionary geno...
def find_num_contigs(contig_lengths_dict): """ Count the total number of contigs for each strain :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :return: num_contigs_dict: dictionary of strain name: total number of contigs """ # Initialise the dictionary num_contigs_dict...
def find_n50(contig_lengths_dict, genome_length_dict): """ Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of al...
current contig length is the N50 if currentlength >= genome_length_dict[file_name] * 0.5: # Populate the dictionary, and break the loop n50_dict[file_name] = contig_length break return n50_dict
def find_n75(contig_lengths_dict, genome_length_dict): """ Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all...
def find_n90(contig_lengths_dict, genome_length_dict): """ Calculate the N90 for each strain. N90 is defined as the largest contig such that at least 9/10 of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of al...
def find_l50(contig_lengths_dict, genome_length_dict): """ Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50 :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :param genome_length_dict: dictionary of strain name: total g...