Best Python code snippet using grail_python
00_amrfinder_filter.py
Source:00_amrfinder_filter.py
1#!/usr/bin/env python2'''Filter AMRFinder Plus results for high confidence matches.3This script filters AMRFinder output tables for matches, with4default criteria focused on high quality & complete matches.5e.g. >90% identity, >90% match length.6Script options also allow filtering for just AMR determinants,7or conversely, only non-AMR results (e.g. virulence/stress).8'''9import argparse10def dict_writer(protein_id, sequence_name, HMM_id, 11 method_type, d, line, duplicates):12 if sequence_name in d.values():13 duplicates += 1 14 elif HMM_id in d.values():15 duplicates += 116 else:17 d[protein_id] = line18 return d, duplicates19def method_filter(infile, outfile, method, just_AMR, no_AMR):20 d = {} # initialize dictionary for writing matches21 d_amr = {} # initialize dictionary for writing just AMR matches22 d_no_amr = {} # initialize dictionary for writing just non-AMR matches23 total = 0 # counter for number of AMRFinder lines/matches24 method_match = 0 # counter for number of genes matching method criteria25 method_fail = 0 # counter for number of genes failing method criteria filter26 duplicates = 0 # counter for number of duplicate genes27 just_AMR_count = 028 no_AMR_count = 029 if method == "complete":30 methods = ["ALLELE", "EXACT", "BLAST", "HMM"]31 elif method == "add_partial_end":32 methods = ["ALLELE", "EXACT", "BLAST", "HMM", "PARTIAL_CONTIG_END"]33 with open(infile, 'r') as file:34 for line in file:35 total += 136 X = line.rstrip().split('\t')37 protein_id = X[0] # protein id (with contig)38 gene_symbol = X[1] # gene symbol39 sequence_name = X[2] # sequence name40 scope = X[3] # core / plus41 element_type = X[4] # AMR, STRESS, etc.42 element_subtype = X[5] # AMR, Metal, Acid, etc.43 amr_class = X[6] # e.g. glycopeptide, aminoglycoside, etc.44 amr_subclass = X[7] # e.g. vancomycin, streptomycin, etc.45 method_type = X[8] # e.g. PARTIALP, HMM, EXACTP, etc.46 target_l = X[9] # target length47 ref_l = X[10] # ref length48 cov_pct = X[11] # coverage percent [breadth]49 pct_ident = X[12] # percent identity to reference50 align_l = X[13] # alignment length51 accession = X[14] # NCBI accession for closest sequence52 ref_name = X[15] # name of closest sequence53 HMM_id = X[16] # id of closest HMM54 HMM_desc = X[17] # description of closest HMM55# print(line)56 # print(method_type, element_type)57 if method_type.startswith(tuple(methods)):58 # add option to filter just AMR results59 if just_AMR:60 if element_type == 'AMR':61 d_amr, duplicates = dict_writer(protein_id, sequence_name,62 HMM_id, method_type, d_amr, line, duplicates)63 just_AMR_count += 164 if no_AMR:65 if element_type != 'AMR':66 d_no_amr, duplicates = dict_writer(protein_id, sequence_name,67 HMM_id, method_type, d_no_amr, line, duplicates)68 no_AMR_count += 169 d, duplicates = dict_writer(protein_id, sequence_name,70 HMM_id, method_type, d, line, duplicates)71 method_match += 172 else:73 method_fail += 174 print('Writing output file(s)...')75 with open(f"{outfile}.tsv", 'w') as file:76 for key, value in d.items():77 file.write(value)78 if no_AMR:79 with open(f"{outfile}_noAMR.tsv", 'w') as noAMR_file:80 for key, value in d_no_amr.items():81 noAMR_file.write(value)82 if just_AMR:83 with open(f"{outfile}_justAMR.tsv", 'w') as file:84 for key, value in d_amr.items():85 file.write(value)86 87 print('Done.')88 print('')89 print('Filter statistics:')90 print(' - total hits in unfiltered AMRFinder table: ', total)91 print(' - lines passing filter:', method_match, "(", round((method_match/total * 100), 1), "% ).")92 print(' - lines failing filter:', method_fail, "(", round((method_fail/total * 100), 1), "% ).")93 if just_AMR:94 print(' - just AMR results:', just_AMR_count)95 if no_AMR:96 print(' - non-AMR results:', no_AMR_count)97 print(' - duplicate HMM ids:', duplicates, "(", round((duplicates/total * 100), 1), "% ).")98def main():99 # configure argparse arguments & pass to method_filter100 parser = argparse.ArgumentParser(101 description=__doc__,102 formatter_class = argparse.RawDescriptionHelpFormatter103 )104 parser.add_argument(105 '-i', '--input',106 help = 'Please specify AMRFinder input tsv file name & path.',107 metavar = '',108 type=str,109 required=True110 )111 parser.add_argument(112 '-o', '--output',113 help = 'Please specify AMRFinder filtered prefix & path for output tsv.',114 metavar = '',115 type=str,116 required=True117 )118 parser.add_argument(119 '-m', '--method',120 help = 'Please specify filtered AMRFinder output tsv file name & path.\121 Select from: complete -or- add_partial_end',122 metavar = '',123 type=str,124 default = 'complete',125 choices=['complete', 'add_partial_end']126 )127 parser.add_argument(128 '-j', '--just_AMR',129 help = 'Flag to write tsv with just AMR results',130 required=False,131 action='store_true'132 )133 parser.add_argument(134 '-v', '--virulence_stress',135 help = 'Flag to write tsv without AMR results (e.g. filter only virulence, stress)',136 required=False,137 action='store_true'138 )139 args=vars(parser.parse_args())140 print('')141 print("File:", args['input'])142 print("Method:", args['method'])143 print('Filtering results...')144 method_filter(args['input'], args['output'], 145 args['method'], args['just_AMR'], args['virulence_stress'])146if __name__ == "__main__":...
test_direct_exception_handling.py
Source:test_direct_exception_handling.py
...12 raise failure_exception13@step14def error_step():15 raise error_exception16def method_fail():17 passed_step()18 failed_step()19 raise Exception('we should not reach this')20@step(step_group=True)21def failed_group():22 passed_step()23 failed_step()24 raise Exception('we should not reach this too')25def method_fail_group():26 failed_group()27 raise Exception('we should not reach this even here')28def method_error():29 passed_step()30 error_step()31 raise Exception('we should not reach this')32@step(step_group=True)33def error_group():34 passed_step()35 error_step()36 raise Exception('we should not reach this too')37def method_error_group():38 error_group()39 raise Exception('we should not reach this even here')40class TestDirectHandling(TestCase):41 def test_method_fail(self):42 try:43 validate_method_output(method_fail, 'PASSED passed step\n'44 'FAILED failed step')45 except Exception as inst:46 eq_(inst, failure_exception)47 def test_group_fail(self):48 try:49 validate_method_output(method_fail_group, 'FAILED failed group\n'50 ' PASSED passed step\n'51 ' FAILED failed step')52 except Exception as inst:53 eq_(inst, failure_exception)54 def test_method_error(self):55 try:...
conditions.py
Source:conditions.py
...9 def function(arg): # ordinary function10 pass11 class C(object):12 @post_condition(lambda ret: ret > 0)13 def method_fail(self):14 return 015 @post_condition(lambda ret: ret > 0)16 def method_success(self):17 return 118 """19 def decorator(func):20 @functools.wraps(func) # presever name, docstring, etc21 def wrapper(*args, **kwargs): # NOTE: no self22 if pre_condition is not None:23 assert pre_condition(*args, **kwargs), "Pre-Condition was not met!"24 retval = func(*args, **kwargs) # call original function or method25 if post_condition is not None:26 assert post_condition(retval), "Post-Condition was not met!"27 return retval...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!