code stringlengths 1 18.2k |
|---|
de_novo_nonchimeras_f = open(output_fp_de_novo_nonchimeras, "U") reference_nonchimeras_f = open(output_fp_ref_nonchimeras, "U") # Save a list of already-written labels labels_written = [] for label, seq in parse_fasta(de_novo_nonchimeras_f): if label in all_non_chimeras: if label not in labels_written: output_combined_... |
def assign_reads_to_otus(original_fasta, filtered_fasta, output_filepath=None, log_name="assign_reads_to_otus.log", perc_id_blast=0.97, global_alignment=True, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None): """ Uses original fasta file, blasts to assign reads to filtered fa... |
ids.... if not output_filepath: _, output_filepath = mkstemp(prefix='assign_reads_to_otus', suffix='.uc') log_filepath = join(working_dir, log_name) params = {'--id': perc_id_blast, '--global': global_alignment} app = Usearch(params, WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) data = {'--query': original_fasta, '--db'... |
def usearch_qf( fasta_filepath, refseqs_fp=None, output_dir=None, percent_id=0.97, percent_id_err=0.97, minsize=4, abundance_skew=2.0, db_filepath=None, rev=False, label_prefix="", label_suffix="", retain_label_as_comment=False, count_start=0, perc_id_blast=0.97, save_intermediate_files=False, HALT_EXEC=False, global_a... |
minsize = Minimum size of cluster for retention after chimera removal. abundance_skew = threshold setting for chimera removal with de novo chimera detection. db_filepath = filepath of reference fasta sequence set for ref based chimera detection. rev = search plus and minus strands of sequences, used in ref based chimer... |
= not defined in usearch helpstring w = Word length for U-sorting slots = Size of compressed index table. Should be prime, e.g. 40000003. Should also specify --w, typical is --w 16 or --w 32. maxrejects = Max rejected targets, 0=ignore, default 32. save_intermediate_files = retain all the intermediate files created dur... |
usearch call. usersort = Used for specifying custom sorting (i.e., non-length based sorting) with usearch/uclust. suppress_new_clusters = with reference based OTU picking, if enabled, will prevent new clusters that do not match the reference from being clustered. chimeras_retention = accepts either 'intersection' or 'u... |
usearch_fasta_sort_from_filepath(fasta_filepath, output_filepath= join( output_dir, 'len_sorted.fasta'), save_intermediate_files=save_intermediate_files, remove_usearch_logs=remove_usearch_logs, working_dir=output_dir, HALT_EXEC=HALT_EXEC) intermediate_files.append(output_filepath_len_sorted) if verbose: print "Derepli... |
are selected, do not matter. if de_novo_chimera_detection: if verbose: print "Performing de novo chimera detection..." app_result, output_fp_de_novo_nonchimeras =\ usearch_chimera_filter_de_novo(error_clustered_output_fp, abundance_skew=abundance_skew, output_chimera_filepath= join( output_dir, 'de_novo_chimeras.fasta'... |
size..." # chimera detection was not performed, use output file of step 4 as input # to filtering by cluster size if not (reference_chimera_detection and de_novo_chimera_detection): output_fp = error_clustered_output_fp app_result, output_fp =\ usearch_sort_by_abundance(output_fp, output_filepath= join(output_dir, 'abu... |
'clustered_seqs.fasta'), percent_id=percent_id, sizein=sizein, sizeout=sizeout, w=w, slots=slots, maxrejects=maxrejects, save_intermediate_files=save_intermediate_files, remove_usearch_logs=remove_usearch_logs, working_dir=output_dir, HALT_EXEC=HALT_EXEC) intermediate_files.append(output_filepath) # Enumerate the OTUs ... |
closed reference OTU picking if suppress_new_clusters: otu_id_field = 9 else: otu_id_field = 1 clusters, failures = clusters_from_blast_uc_file(open(clusters_file, "U"), otu_id_field) # Remove temp files unless user specifies output filepath if not save_intermediate_files: remove_files(intermediate_files) return cluste... |
def usearch61_ref_cluster(seq_path, refseqs_fp, percent_id=0.97, rev=False, save_intermediate_files=True, minlen=64, output_dir='.', remove_usearch_logs=False, verbose=False, wordlength=8, usearch_fast_cluster=False, usearch61_sort_method='abundance', otu_prefix="denovo", usearch61_maxrejects=32, usearch61_maxaccepts=1... |
reverse strand matching. usearch61_sort_method: Sort sequences by abundance or length by using functionality provided by usearch61, or do not sort by using None option. otu_prefix: label to place in front of OTU IDs, used to prevent duplicate IDs from appearing with reference based OTU picking. usearch61_maxrejects: Nu... |
mapping and failures file. open-reference approach: dereplicate sequences first, do reference based clustering, parse failures, sort failures fasta according to chosen method, cluster failures, merge reference clustering results/de novo results/dereplicated data, write OTU mapping file. Dereplication should save proces... |
failures =\ parse_usearch61_clusters(open(clusters_fp, "U"), otu_prefix="", ref_clustered=True) dereplicated_clusters =\ parse_dereplicated_uc(open(dereplicated_uc, "U")) clusters = merge_clusters_dereplicated_seqs(clusters, dereplicated_clusters) failures = merge_failures_dereplicated_seqs(failures, dereplicated_clust... |
def usearch61_denovo_cluster(seq_path, percent_id=0.97, rev=False, save_intermediate_files=True, minlen=64, output_dir='.', remove_usearch_logs=False, verbose=False, wordlength=8, usearch_fast_cluster=False, usearch61_sort_method='abundance', otu_prefix="denovo", usearch61_maxrejects=32, usearch61_maxaccepts=1, sizeord... |
length by using functionality provided by usearch61, or do not sort by using None option. otu_prefix: label to place in front of OTU IDs, used to prevent duplicate IDs from appearing with reference based OTU picking. usearch61_maxrejects: Number of rejects allowed by usearch61 usearch61_maxaccepts: Number of accepts al... |
if usearch61_sort_method == 'abundance' and not usearch_fast_cluster: intermediate_fasta, dereplicated_uc, app_result =\ sort_by_abundance_usearch61(seq_path, output_dir, rev, minlen, remove_usearch_logs, HALT_EXEC, output_fna_filepath=join( output_dir, file_prefix + 'abundance_sorted.fna'), output_uc_filepath=join(out... |
version is usearch ' + 'v6.1.544) is installed or improperly formatted input file was ' + 'provided') except ApplicationNotFoundError: remove_files(files_to_remove) raise ApplicationNotFoundError('usearch61 not found, is it properly ' + 'installed?') if usearch61_sort_method == 'abundance' and not usearch_fast_cluster:... |
def sort_by_abundance_usearch61(seq_path, output_dir='.', rev=False, minlen=64, remove_usearch_logs=False, HALT_EXEC=False, output_fna_filepath=None, output_uc_filepath=None, log_name="abundance_sorted.log", threads=1.0): """ usearch61 application call to sort fasta file by abundance. seq_path: fasta filepath to be clu... |
'--threads': threads } if rev: params['--strand'] = 'both' if not remove_usearch_logs: params['--log'] = log_filepath app = Usearch61(params, WorkingDir=output_dir, HALT_EXEC=HALT_EXEC) app_result = app() return output_fna_filepath, output_uc_filepath, app_result |
def sort_by_length_usearch61(seq_path, output_dir=".", minlen=64, remove_usearch_logs=False, HALT_EXEC=False, output_fna_filepath=None, log_name="length_sorted.log"): """ usearch61 application call to sort fasta file by length. seq_path: fasta filepath to be clustered with usearch61 output_dir: directory to output log,... |
def usearch61_cluster_ref(intermediate_fasta, refseqs_fp, percent_id=0.97, rev=False, minlen=64, output_dir=".", remove_usearch_logs=False, wordlength=8, usearch61_maxrejects=32, usearch61_maxaccepts=1, HALT_EXEC=False, output_uc_filepath=None, log_filepath="ref_clustered.log", threads=1.0 ): """ Cluster input fasta se... |
intermediate_fasta, '--db': refseqs_fp, '--minseqlength': minlen, '--id': percent_id, '--uc': output_uc_filepath, '--wordlength': wordlength, '--maxrejects': usearch61_maxrejects, '--maxaccepts': usearch61_maxaccepts, '--threads': threads } if not remove_usearch_logs: params['--log'] = log_filepath if rev: params['--st... |
def usearch61_fast_cluster(intermediate_fasta, percent_id=0.97, minlen=64, output_dir=".", remove_usearch_logs=False, wordlength=8, usearch61_maxrejects=8, usearch61_maxaccepts=1, HALT_EXEC=False, output_uc_filepath=None, log_name="fast_clustered.log", threads=1.0): """ Performs usearch61 de novo fast clustering via cl... |
threads: Specify number of threads used per core per CPU """ log_filepath = join(output_dir, log_name) params = {'--minseqlength': minlen, '--cluster_fast': intermediate_fasta, '--id': percent_id, '--uc': output_uc_filepath, '--wordlength': wordlength, '--maxrejects': usearch61_maxrejects, '--maxaccepts': usearch61_max... |
def usearch61_smallmem_cluster(intermediate_fasta, percent_id=0.97, minlen=64, rev=False, output_dir=".", remove_usearch_logs=False, wordlength=8, usearch61_maxrejects=32, usearch61_maxaccepts=1, sizeorder=False, HALT_EXEC=False, output_uc_filepath=None, log_name="smallmem_clustered.log", sizeout=False, consout_filepat... |
(.uc) file. log_name: filepath to write usearch61 generated log file sizeout: If True, will save abundance data in output fasta labels. consout_filepath: Needs to be set to save clustered consensus fasta filepath used for chimera checking. """ log_filepath = join(output_dir, log_name) params = {'--minseqlength': minlen... |
def usearch61_chimera_check_denovo(abundance_fp, uchime_denovo_fp, minlen=64, output_dir=".", remove_usearch_logs=False, uchime_denovo_log_fp="uchime_denovo.log", usearch61_minh=0.28, usearch61_xn=8.0, usearch61_dn=1.4, usearch61_mindiffs=3, usearch61_mindiv=0.8, usearch61_abundance_skew=2.0, HALT_EXEC=False): """ Does... |
number of diffs in a segment. Increasing this value tends to reduce the number of false positives while reducing sensitivity to very low-divergence chimeras. usearch61_mindiv: Minimum divergence, i.e. 100% - identity between the query and closest reference database sequence. Expressed as a percentage, so the default is... |
def usearch61_chimera_check_ref(abundance_fp, uchime_ref_fp, reference_seqs_fp, minlen=64, output_dir=".", remove_usearch_logs=False, uchime_ref_log_fp="uchime_ref.log", usearch61_minh=0.28, usearch61_xn=8.0, usearch61_dn=1.4, usearch61_mindiffs=3, usearch61_mindiv=0.8, threads=1.0, HALT_EXEC=False): """ Does reference... |
positives (and also sensitivity). usearch61_mindiffs: Minimum number of diffs in a segment. Increasing this value tends to reduce the number of false positives while reducing sensitivity to very low-divergence chimeras. usearch61_mindiv: Minimum divergence, i.e. 100% - identity between the query and closest reference d... |
app = Usearch61(params, WorkingDir=output_dir, HALT_EXEC=HALT_EXEC) app_result = app() return uchime_ref_fp, app_result |
def parse_dereplicated_uc(dereplicated_uc_lines): """ Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from usearch61 (i.e. open file of abundance sorted .uc data) """ dereplicated_clusters = {} seed_hit_ix = 0 seq_id_ix = 8 s... |
def parse_usearch61_clusters(clustered_uc_lines, otu_prefix='denovo', ref_clustered=False): """ Returns dict of cluster ID:seq IDs clustered_uc_lines: lines from .uc file resulting from de novo clustering otu_prefix: string added to beginning of OTU ID. ref_clustered: If True, will attempt to create dict keys for clust... |
+ curr_line[ref_id_ix]] = [curr_id] else: clusters[otu_prefix + curr_line[otu_id_ix]].append(curr_id) if curr_line[seed_hit_ix] == "N": failures.append(curr_line[seq_id_ix].split(';')[0]) return clusters, failures |
def merge_clusters_dereplicated_seqs(de_novo_clusters, dereplicated_clusters): """ combines de novo clusters and dereplicated seqs to OTU id:seqs dict de_novo_clusters: dict of OTU ID:clustered sequences dereplicated_clusters: dict of seq IDs: dereplicated seq IDs """ clusters = {} for curr_denovo_key in de_novo_cluste... |
def merge_failures_dereplicated_seqs(failures, dereplicated_clusters): """ Appends failures from dereplicated seqs to failures list failures: list of failures dereplicated_clusters: dict of seq IDs: dereplicated seq IDs """ curr_failures = set(failures) dereplicated_ids = set(dereplicated_clusters) for curr_failure in ... |
def parse_usearch61_failures(seq_path, failures, output_fasta_fp): """ Parses seq IDs from failures list, writes to output_fasta_fp seq_path: filepath of original input fasta file. failures: list/set of failure seq IDs output_fasta_fp: path to write parsed sequences """ parsed_out = open(output_fasta_fp, "w") for label... |
def _on_error_page_write_error(self, status_code, **kwargs): """Replaces the default Tornado error page with a Django-styled one""" if oz.settings.get('debug'): exception_type, exception_value, tback = sys.exc_info() is_breakpoint = isinstance(exception_value, oz.error_pages.DebugBreakException) frames = oz.error_pages... |
def get_blink_cookie(self, name): """Gets a blink cookie value""" value = self.get_cookie(name) if value != None: self.clear_cookie(name) return escape.url_unescape(value) |
def set_blink(self, message, type="info"): """ Sets the blink, a one-time transactional message that is shown on the next page load """ self.set_cookie("blink_message", escape.url_escape(message), httponly=True) self.set_cookie("blink_type", escape.url_escape(type), httponly=True) |
def cdhit_clusters_from_seqs(seqs, moltype=DNA, params=None): """Returns the CD-HIT clusters given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA, and raise if any ot... |
= CD_HIT(WorkingDir=working_dir, params=params) elif moltype is RNA: app = CD_HIT_EST(WorkingDir=working_dir, params=params) elif moltype is DNA: app = CD_HIT_EST(WorkingDir=working_dir, params=params) else: raise ValueError, "Moltype must be either PROTEIN, RNA, or DNA" # grab result res = app(int_map.toFasta()) clust... |
def cdhit_from_seqs(seqs, moltype, params=None): """Returns the CD-HIT results given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA, and raise if any other moltype is... |
else: raise ValueError, "Moltype must be either PROTEIN, RNA, or DNA" # grab result res = app(seqs.toFasta()) new_seqs = dict(parse_fasta(res['FASTA'])) # perform cleanup res.cleanUp() shutil.rmtree(working_dir) remove(params['-o'] + '.bak.clstr') return SequenceCollection(new_seqs, MolType=moltype) |
def parse_cdhit_clstr_file(lines): """Returns a list of list of sequence ids representing clusters""" clusters = [] curr_cluster = [] for l in lines: if l.startswith('>Cluster'): if not curr_cluster: continue clusters.append(curr_cluster) curr_cluster = [] else: curr_cluster.append(clean_cluster_seq_id(l.split()[2])) i... |
def _input_as_multiline_string(self, data): """Writes data to tempfile and sets -i parameter data -- list of lines """ if data: self.Parameters['-i']\ .on(super(CD_HIT,self)._input_as_multiline_string(data)) return '' |
def _input_as_lines(self, data): """Writes data to tempfile and sets -i parameter data -- list of lines, ready to be written to file """ if data: self.Parameters['-i']\ .on(super(CD_HIT,self)._input_as_lines(data)) return '' |
def _get_clstr_outfile(self): """Returns the absolute path to the clstr outfile""" if self.Parameters['-o'].isOn(): return ''.join([self.Parameters['-o'].Value, '.clstr']) else: raise ValueError, "No output file specified" |
def _get_result_paths(self, data): """Return dict of {key: ResultPath}""" result = {} result['FASTA'] = ResultPath(Path=self._get_seqs_outfile()) result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile()) return result |
def segment(self, tokens): """ Segments a sequence of tokens into a sequence of segments. :Parameters: tokens : `list` ( :class:`~deltas.Token` ) """ look_ahead = LookAhead(tokens) segments = Segment() while not look_ahead.empty(): if look_ahead.peek().type not in self.whitespace: # Paragraph! paragraph = MatchableSegm... |
for s in sentence) if non_whitespace >= self.min_sentence: break paragraph.append(sentence) else: # look_ahead.peek().type in self.whitespace whitespace = Segment(look_ahead.i, [next(look_ahead)]) paragraph.append(whitespace) segments.append(paragraph) else: # look_ahead.peek().type in self.whitespace whitespace = Segm... |
def send(self, payload, token, expiration=None, priority=None, identifier=None): """ Attempts to send a push message. On network failures, progagates the exception. It is advised to make all text in the payload dictionary unicode objects and not mix unicode objects and str objects. If str objects are used, they must be... |
body is too long and cannot be truncated to fit """ # we only use one conn at a time currently but we may as well do this... created_conn = False while not created_conn: if len(self.conns) == 0: self.conns.append(PushConnection(self, self.address, self.certfile, self.keyfile)) created_conn = True conn = random.choice(s... |
def get_all_feedback(self): """ Connects to the feedback service and returns any feedback that is sent as a list of FeedbackItem objects. Blocks the current greenlet until all feedback is returned. If a network error occurs before any feedback is received, it is propagated to the caller. Otherwise, it is ignored and th... |
def _parse_xml(self, response): """ Run our XML parser (lxml in this case) over our response text. Lxml doesn't enjoy having xml/encoding information in the header so we strip that out if necessary. We return a parsed XML object that can be used by the calling API method and massaged into a more appropriate format. """... |
def _handle_api_error(self, error): """ New Relic cheerfully provides expected API error codes depending on your API call deficiencies so we convert these to exceptions and raise them for the user to handle as they see fit. """ status_code = error.response.status_code message = error.message if 403 == status_code: rais... |
def _api_rate_limit_exceeded(self, api_call, window=60): """ We want to keep track of the last time we sent a request to the NewRelic API, but only for certain operations. This method will dynamically add an attribute to the Client class with a unix timestamp with the name of the API api_call we make so that we can che... |
+ "_window", current) else: timeout = window - (current - previous).seconds raise NewRelicApiRateLimitException(str(timeout)) |
def view_applications(self): """ Requires: account ID (taken from Client object) Returns: a list of Application objects Endpoint: rpm.newrelic.com Errors: 403 Invalid API Key Method: Get """ endpoint = "https://rpm.newrelic.com" uri = "{endpoint}/accounts/{id}/applications.xml".format(endpoint=endpoint, id=self.account... |
def delete_applications(self, applications): """ Requires: account ID, application ID (or name). Input should be a dictionary { 'app_id': 1234 , 'app': 'My Application'} Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: None Explicit, failed deletions will be in XML Method: Post """ endpoint... |
def notify_deployment(self, application_id=None, application_name=None, description=None, revision=None, changelog=None, user=None): """ Notify NewRelic of a deployment. http://newrelic.github.io/newrelic_api/NewRelicApi/Deployment.html :param description: :param revision: :param changelog: :param user: :return: A dict... |
def get_metric_names(self, agent_id, re=None, limit=5000): """ Requires: application ID Optional: Regex to filter metric names, limit of results Returns: A dictionary, key: metric name, value: list of fields available for a given metric Method: Get Restrictions: Rate limit to 1x per minute Errors: 403 Invalid API Key, ... |
a list of metric objects. It might be more # consistent with the retrieval of metric data to make them objects but # since the attributes in each type of metric object are different # (and we aren't going to make heavyweight objects) we don't want to. metrics = {} for metric in response.findall('.//metric'): fields = [... |
def get_metric_data(self, applications, metrics, field, begin, end, summary=False): """ Requires: account ID, list of application IDs, list of metrics, metric fields, begin, end Method: Get Endpoint: api.newrelic.com Restrictions: Rate limit to 1x per minute Errors: 403 Invalid API key, 422 Invalid Parameters Returns: ... |
{} # Figure out what we were passed and set our parameter correctly # TODO: allow querying by something other than an application name/id, # such as server id or agent id try: int(applications[0]) except ValueError: app_string = "app" else: app_string = "app_id" if len(applications) > 1: app_string = app_string + "[]" ... |
# there should be no overlaps in time. metrics = [] for metric in response.findall('.//metric'): metrics.append(Metric(metric)) return metrics |
def get_threshold_values(self, application_id): """ Requires: account ID, list of application ID Method: Get Endpoint: api.newrelic.com Restrictions: ??? Errors: 403 Invalid API key, 422 Invalid Parameters Returns: A list of threshold_value objects, each will have information about its start/end time, metric name, metr... |
def view_servers(self): """ Requires: account ID (taken from Client object) Returns: a list of Server objects Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Get """ endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{id}/servers.xml".format(endpoint=endpoint, id=self.account_id) res... |
def delete_servers(self, server_id): """ Requires: account ID, server ID Input should be server id Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Delete """ endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{account_id}/servers/{server_id}... |
def join_paired_end_reads_fastqjoin( reads1_infile_path, reads2_infile_path, perc_max_diff=None, # typical default is 8 min_overlap=None, # typical default is 6 outfile_label='fastqjoin', params={}, working_dir=tempfile.gettempdir(), SuppressStderr=True, SuppressStdout=True, HALT_EXEC=False): """ Runs fastq-join, with ... |
values # set to None by default. This way we do not have to worry # about changes in default behaviour of the wrapped # application if perc_max_diff is not None: if isinstance(perc_max_diff, int) and 0 <= perc_max_diff <= 100: fastq_join_app.Parameters['-p'].on(perc_max_diff) else: raise ValueError("perc_max_diff must ... |
path in path_dict.values(): if not os.path.exists(path): raise IOError('Output file not found at: %s' % path) # fastq-join automatically appends: 'join', 'un1', or 'un2' # to the end of the file names. But we want to rename them so # they end in '.fastq'. So, we iterate through path_dict to # rename the files and overw... |
def _get_output_path(self): """Checks if a base file label / path is set. Returns absolute path.""" if self.Parameters['-o'].isOn(): output_path = self._absolute(str(self.Parameters['-o'].Value)) else: raise ValueError("No output path specified.") return output_path |
def _get_stitch_report_path(self): """Checks if stitch report label / path is set. Returns absolute path.""" if self.Parameters['-r'].isOn(): stitch_path = self._absolute(str(self.Parameters['-r'].Value)) return stitch_path elif self.Parameters['-r'].isOff(): return None |
def _get_result_paths(self, data): """Capture fastq-join output. Three output files are produced, in the form of outputjoin : assembled paired reads outputun1 : unassembled reads_1 outputun2 : unassembled reads_2 If a barcode / mate-pairs file is also provided then the following additional files are output: outputjoin2... |
need to check this way becuase there are no infile parameters. mate_path_string = output_path + 'join2' mate_unassembled_path_string = output_path + 'un3' if os.path.exists(mate_path_string) and \ os.path.exists(mate_unassembled_path_string): result['Mate'] = ResultPath(Path=mate_path_string, IsWritten=True) result['Ma... |
def parse_fields(fields, as_dict=False): ''' Given a list of fields (or several other variants of the same), return back a consistent, normalized form of the same. To forms are currently supported: dictionary form: dict 'key' is the field name and dict 'value' is either 1 (include) or 0 (exclude). list form (other): li... |
int(v) for k, v in fields.iteritems()}) elif isinstance(fields, basestring): _fields.update({unicode(s).strip(): 1 for s in fields.split(',')}) elif isinstance(fields, (list, tuple)): _fields.update({unicode(s).strip(): 1 for s in fields}) else: raise ValueError("invalid fields value") if as_dict: return _fields else: ... |
def date_range(date, func='date'): ''' Return back start and end dates given date string :param date: metrique date (range) to apply to pql query The tilde '~' symbol is used as a date range separated. A tilde by itself will mean 'all dates ranges possible' and will therefore search all objects irrelevant of it's _end ... |
provided. ie, from beginning of known time -> date. A date on both the left and right will be a simple date range query where the date range starts from the date on the left and ends on the date on the right. ie, from date to date. ''' if isinstance(date, basestring): date = date.strip() if not date: return '_end == No... |
if d else None) split = date.split('~') # replace all occurances of 'T' with ' ' # this is used for when datetime is passed in # like YYYY-MM-DDTHH:MM:SS instead of # YYYY-MM-DD HH:MM:SS as expected # and drop all occurances of 'timezone' like substring # FIXME: need to adjust (to UTC) for the timezone info we're dropp... |
def parse(table, query=None, date=None, fields=None, distinct=False, limit=None, alias=None): ''' Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metrique date range query :param date: m... |
table column objects themselves to ensure # our bind / result processors are mapped properly fields = fields if fields else table.columns msg = 'parse(query=%s, fields=%s)' % (query, fields) #msg = re.sub(' in \[[^\]]+\]', ' in [...]', msg) logger.debug(msg) kwargs = {} if query: interpreter = MQLInterpreter(table) que... |
def enqueue_sync(self, func, *func_args): ''' Enqueue an arbitrary synchronous function. Deprecated: Use async version instead ''' worker = self.pick_sticky(0) # just pick first always args = (func,) + func_args coro = worker.enqueue(enums.Task.FUNC, args) asyncio.ensure_future(coro) |
async def async_enqueue_sync(self, func, *func_args): ''' Enqueue an arbitrary synchronous function. ''' worker = self.pick_sticky(0) # just pick first always args = (func,) + func_args await worker.enqueue(enums.Task.FUNC, args) |
def enqueue_download(self, resource): ''' Enqueue the download of the given foreign resource. Deprecated: Use async version instead ''' worker = self.pick_sticky(resource.url_string) coro = worker.enqueue(enums.Task.DOWNLOAD, (resource,)) asyncio.ensure_future(coro) |
async def async_enqueue_download(self, resource): ''' Enqueue the download of the given foreign resource. ''' worker = self.pick_sticky(resource.url_string) await worker.enqueue(enums.Task.DOWNLOAD, (resource,)) |
def enqueue_convert(self, converter, from_resource, to_resource): ''' Enqueue use of the given converter to convert to given resources. Deprecated: Use async version instead ''' worker = self.pick_sticky(from_resource.url_string) args = (converter, from_resource, to_resource) coro = worker.enqueue(enums.Task.CONVERT, a... |
async def async_enqueue_convert(self, converter, from_, to): ''' Enqueue use of the given converter to convert to given from and to resources. ''' worker = self.pick_sticky(from_.url_string) args = (converter, from_, to) await worker.enqueue(enums.Task.CONVERT, args) |
async def async_enqueue_multiconvert(self, url_string, to_type): ''' Enqueue a multi-step conversion process, from the given URL string (which is assumed to have been downloaded / resolved) ''' worker = self.pick_sticky(url_string) args = (url_string, to_type) await worker.enqueue(enums.Task.MULTICONVERT, args) |
def strain_in_plane(self, **kwargs): ''' Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain. ''' if self._strain_out_of_plane is not None: return ((self._strain_out_of_plane / -2.) * (self.unstrained.c11(**kwargs) / self.unstrained.c12(**... |
def strain_out_of_plane(self, **kwargs): ''' Returns the out-of-plane strain assuming no lattice relaxation, which is negative for tensile strain and positive for compressive strain. This is the strain measured by X-ray diffraction (XRD) symmetric omega-2theta scans. ''' if self._strain_out_of_plane is not None: return... |
def substrate_a(self, **kwargs): ''' Returns the substrate's lattice parameter. ''' if self.substrate is not None: return self.substrate.a(**kwargs) else: return (self.unstrained.a(**kwargs) / (1. - self.strain_in_plane(**kwargs))) |
def CBO(self, **kwargs): ''' Returns the strain-shifted conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return self.unstrained.CBO(**kwargs) + self.CBO_strain_shift(**kwargs) |
def CBO_Gamma(self, **kwargs): ''' Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_Gamma(**kwargs) + self.CBO_strain_shift(**kwargs)) |
def CBO_L(self, **kwargs): ''' Returns the strain-shifted L-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_L(**kwargs) + self.CBO_strain_shift(**kwargs)) |
def CBO_X(self, **kwargs): ''' Returns the strain-shifted X-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_X(**kwargs) + self.CBO_strain_shift(**kwargs)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.