def test_undefined_drug_within_a_drug_class(self): """DLV drug is missing from NNRTI drug class (the drug is associated with no drug class)""" try: transformer = XmlAsiTransformer(False) fd = open( os.path.join( self.module_path, "test/data/HIVDB_undefinedDrugWithinDrugClass.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("testUndefinedDrugWithinADrugClass:\n\t%s" % str(e)) try: actual_err_message = str(e).index( "The following drugs have not been associated with a drug class" ) except ValueError as v: raise Exception( "The following error message was expected: " + "The following drugs have not been associated with a drug class\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("testUndefinedDrugWithinADrugClass ex:%s" % str(exc)) raise exc finally: fd.close()
def test_result_out_of_range(self): """for ETR drug, drug class NNRTI, for the second rule, which is a boolean condition the actions contain a SCORERANGE action""" gene_dict = dict() transformer = None try: transformer = XmlAsiTransformer(False) fd = open( os.path.join( self.module_path, "test/data/HIVDB_evaluationExceptionScoreRangeAction.xml"), "r") gene_dict = transformer.transform(fd) except AsiParsingException as e: print("testInvalidRuleActionType AsiParsingException:" + str(e)) raise e except Exception as exc: print("testInvalidRuleActionType Exception:" + str(exc)) raise exc gene = gene_dict.get(self.gene_name) try: evaluated_gene = gene.evaluate(self.mutations, self.mutation_comparator) except AsiEvaluationException as e: print("No score range has been defined for a score of\n\t" + str(e)) actual_err_message = str(e).index( "No score range has been defined for a score of:") assert True == (actual_err_message > -1)
def test_defined_drug_within_different_drug_classes_alg_info(self): """DLV drug defined in NNRTI and NRTI drug classes. Using get_algorithm_info""" try: transformer = XmlAsiTransformer(False) fd = open( os.path.join( self.module_path, "test/data/HIVDB_definedDrugWithinDifferentDrugClasses.xml" ), "r") transformer.get_algorithm_info(fd) except AsiParsingException as e: print("testDefinedDrugWithinDifferentDrugClasses:\n\t%s" % str(e)) try: actual_err_message = str(e).index( "has been defined for more than one drug class") except ValueError as v: raise Exception( "The following error message was expected: " + "has been defined for more than one drug class\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("testDefinedDrugWithinDifferentDrugClasses ex:%s" % str(exc)) raise exc finally: fd.close()
def summarize_hivdb(hivdb_file): """Output genes and conditions covered in HIVdb XML output. """ res_genes = XmlAsiTransformer(True).transform(open(hivdb_file, "r")) with open("hivdb_summary.txt", "w") as out_handle: for gene in res_genes.values(): for drug_class in gene.get_drug_classes(): for drug in drug_class.get_drugs(): for rule in drug.get_drug_rules(): out_handle.write("%s %s %s %s\n" % (gene.name, drug_class.name, drug.name, rule.condition.statement))
def test_float_result_rule_action_type(self): """for ETR drug, drug class NNRTI, for the rule, which is a score condition, the actions contain a COMMENT action""" gene_dict = dict() transformer = None try: transformer = XmlAsiTransformer(False) fd = open( os.path.join( self.module_path, "test/data/HIVDB_invalidFloatResultActionType.xml"), "r") gene_dict = transformer.transform(fd) except AsiParsingException as e: print("testInvalidRuleActionType AsiParsingException:" + str(e)) raise e except Exception as exc: print("testInvalidRuleActionType Exception:" + str(exc)) raise exc # get Gene gene = gene_dict.get(self.gene_name) # get set of DrugClass objects drug_classes = gene.get_drug_classes() # get DrugClass drug_class = None for item in drug_classes: if item.get_class_name() == "NNRTI": drug_class = item break # get Drug drug = None for item in drug_class.get_drugs(): if item.get_drug_name() == "ETR": drug = item break # get Rule drug_rule = drug.get_drug_rules()[0] drug_rule.get_actions().append( CommentAction(CommentDefinition("test", "used in Python tests", 1))) try: evaluated_gene = gene.evaluate(self.mutations, self.mutation_comparator) except AsiEvaluationException as e: print("the action does not support a result of type:\n\t" + str(e)) actual_err_message = str(e).index( "does not support a result of type:") assert True == (actual_err_message > -1)
def test_drug_without_any_rule(self): """DLV drug does not have defined any rule""" try: transformer = XmlAsiTransformer(False) fd = open( os.path.join(self.module_path, "test/data/HIVDB_drugWithoutAnyRule.xml"), "r") gene_dict = transformer.transform(fd) gene = gene_dict.get(self.gene_name) evaluated_gene = gene.evaluate(self.mutations, self.mutation_comparator) print("evaluated gene:" + str(evaluated_gene)) except AsiEvaluationException as e: print("no rules for this drug\n\t" + str(e)) raise e except Exception as exc: print("testDrugWtihoutAnyRule ex:" + str(exc)) raise exc
def test_missing_drug_class_name(self): """Test missing drug class name""" try: transformer = XmlAsiTransformer(self.validate_xml) fd = open(os.path.join(self.module_path,"test/data/HIVDB_missingDrugClassName.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("test_missing_drug_class_name:\n\t%s" % str(e)) try: actual_err_message = str(e).index("Not a Stanford resistance analysis XML file") except ValueError as v: raise Exception("The following error message was expected: " + "Not a Stanford resistance analysis XML file\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def test_overlapping_ranges(self): """Test overlapping ranges""" try: transformer = XmlAsiTransformer(False) fd = open(os.path.join(self.module_path,"test/data/HIVDB_overlappingRanges.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("test_overLapping_ranges:\n\t%s" % str(e)) try: actual_err_message = str(e).index("Score range values overlap") except ValueError as v: raise Exception("The following error message was expected: " + "Score range values overlap\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def test_missing_level_definition_sir_alg_info(self): """Test missing_level_definition_sir. Using get_algorithm_info""" try: transformer = XmlAsiTransformer(self.validate_xml) fd = open(os.path.join(self.module_path,"test/data/HIVDB_missingLevelDefinitionSIR.xml"), "r") transformer.get_algorithm_info(fd) except AsiParsingException as e: print("test_missing_level_definition_sir:\n\t%s" % str(e)) try: actual_err_message = str(e).index("Not a Stanford resistance analysis XML file") except ValueError as v: raise Exception("The following error message was expected: " + "Not a Stanford resistance analysis XML file\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def test_multiple_comment_definition_tags(self): """Test multiple comment definition tags""" try: transformer = XmlAsiTransformer(self.validate_xml) fd = open(os.path.join(self.module_path,"test/data/HIVDB_multipleCommentDefinitionTags.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("test_multiple_comment_definition_tags:\n\t%s" % str(e)) try: actual_err_message = str(e).index("Not a Stanford resistance analysis XML file") except ValueError as v: raise Exception("The following error message was expected: " + "Not a Stanford resistance analysis XML file\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def test_undefined_drug_alg_info(self): """DLV drug is not defined under a DRUG tag. Using get_algorithm_info""" try: transformer = XmlAsiTransformer(False) fd = open( os.path.join(self.module_path, "test/data/HIVDB_undefinedDrug.xml"), "r") transformer.get_algorithm_info(fd) except AsiParsingException as e: print("testUndefinedDrug\n\t" + str(e)) try: actual_err_message = str(e).index( "has not been defined as a drug") except ValueError as v: raise Exception("The following error message was expected: " + "has not been defined as a drug\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:" + str(exc)) raise exc finally: fd.close()
def test_required_global_range(self): try: transformer = XmlAsiTransformer(False) fd = open( os.path.join(self.module_path, "test/data/HIVDB_missingRequiredGlobalRange.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print( "GLOBALRANGE tag is a required element (some rules are using USE_GLOBALRANGE tag):\n\t" + str(e)) try: actual_err_message = str(e).index( "required global range does not exist") except ValueError as v: raise Exception("The following error message was expected: " + "required global range does not exist\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def test_missing_required_rule_elements(self): """Test when a rule is missing the condition for DLV drug""" try: transformer = XmlAsiTransformer(self.validate_xml) fd = open( os.path.join(self.module_path, "test/data/HIVDB_missingCondition.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("CONDITION tag is a required element:\n\t%s" % str(e)) try: actual_err_message = str(e).index( "Not a Stanford resistance analysis XML file") except ValueError as v: raise Exception( "The following error message was expected: " + "Not a Stanford resistance analysis XML file\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close() try: transformer = XmlAsiTransformer(self.validate_xml) fd = open( os.path.join(self.module_path, "test/data/HIVDB_missingActions.xml"), "r") transformer.transform(fd) except AsiParsingException as e: print("ACTIONS tag is a required element:\n\t%s" % str(e)) try: actual_err_message = str(e).index( "Not a Stanford resistance analysis XML file") except ValueError as v: raise Exception( "The following error message was expected: " + "Not a Stanford resistance analysis XML file\n" + "Instead received:%s" % (str(e))) except Exception as exc: print("ex:%s" % str(exc)) raise exc finally: fd.close()
def output_resistance_levels(aavf_file, xml_file, output_path): """ Parse aavf file to AAVF object. Create XmlAsiTransformer. Use transformer to evaluate drug resistance levels in the AAVF object mutations. Output drug resistance. """ records = list(parser.Reader(aavf_file).read_records()) mutations = defaultdict(list) # parse mutations from records genes = XmlAsiTransformer(True).transform(open(xml_file, "r")) output_file = output_path # handles the case where the output_path was passed from somewhere # other than to click, from the command line, # e.g. from a test file if isinstance(output_path, str): output_file = open(output_path, "w+") output_string = "#gene,drug class,drug,resistance level" # create mutations list for record in records: if record.ALT[0] != "*": mutations[record.GENE].append("%s%s" % (record.POS, record.ALT[0])) for gene in mutations: evaluated_gene = genes[gene].evaluate(mutations[gene], StringMutationComparator(True)) for drug_class in evaluated_gene.get_evaluated_drug_classes(): for drug in drug_class.get_evaluated_drugs(): for condition in drug.get_evaluated_conditions(): definition = next(iter(condition.get_definitions())) output_string += ("\n%s,%s,%s,%s" % (gene, drug_class.get_drug_class().name, drug.get_drug().name, definition.get_text())) output_file.write(output_string) output_file.close() return output_string
def annotate_aavf(in_file, hivdb_file, out_file): """Annotate an AAVF input file with drug resistance changes. """ res_genes = XmlAsiTransformer(True).transform(open(hivdb_file, "r")) reader = parser.Reader(in_file) aavf_obj = reader.read_records() aavf_obj.infos["CAT"] = model.Info("CAT", ".", "String", "Drug resistance category", None, None) aavf_obj.infos["DRUG"] = model.Info("DRUG", ".", "String", "Drug reistances", None, None) with open(out_file, "w") as out_handle: writer = parser.Writer(out_handle, aavf_obj) for rec in aavf_obj: if rec.POS not in rec.ALT: rmuts = evaluate_resistance([rec], res_genes) k = (rec.GENE, "%s%s%s" % (rec.REF, rec.POS, rec.ALT[0])) if rmuts.get(k): cats = [] drugs = [] for cat in rmuts.get(k).keys(): cats.append(cat) drugs.extend(rmuts[k][cat]) rec.INFO["CAT"] = cats rec.INFO["DRUG"] = drugs writer.write_record(rec)
def test_bool_result_rule_action_type(self): """for ETR drug, drug class NNRTI, for the rule, which is a bool condition, the actions contain as SCORERANGE action""" gene_dict = dict() transformer = None try: transformer = XmlAsiTransformer(False) fd = open( os.path.join(self.module_path, "test/data/HIVDB_invalidRuleActionType.xml"), "r") gene_dict = transformer.transform(fd) except AsiParsingException as e: print("testInvalidRuleActionType AsiParsingException:" + str(e)) raise e except Exception as exc: print("testInvalidRuleActionType Exception:" + str(exc)) raise exc try: # get Gene gene = gene_dict.get(self.gene_name) # get set drug_classes = gene.get_drug_classes() # get DrugClass drug_class = None for item in drug_classes: if item.get_class_name() == "NNRTI": drug_class = item break # get Drug drug = None for item in drug_class.get_drugs(): if item.get_drug_name() == "ETR": drug = item break levels = dict() levels["1"] = LevelDefinition(1, "level 1", "S") levels["2"] = LevelDefinition(1, "level 1", "S") score_range_str = "(-INF TO 10 => 1, 11 TO INF => 2)" score_range = transformer.parse_score_range( score_range_str, levels) drug_rule = drug.get_drug_rules()[0] drug_rule.get_actions().append(ScoreRangeAction(score_range)) try: evaluatedGene = gene.evaluate(self.mutations, self.mutation_comparator) except AsiEvaluationException as e: print("the action does not support a result of type:\n\t" + str(e)) try: actual_err_message = str(e).index( "does not support a result of type") except ValueError as v: raise Exception( "The following error message was expected: " + "does not support a result of type\n" + "Instead received:%s" % (str(e))) except AsiParsingException as ape: print("testInvalidRuleActionType AsiParsingException (evaluate):" + str(ape)) raise ape