piezo 0.3__tar.gz → 0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: piezo
3
- Version: 0.3
3
+ Version: 0.4
4
4
  Summary: Predicting the effect of an antibiotic from gene mutations
5
5
  Home-page: https://github.com/oxfordmmm/piezo
6
6
  Author: Philip W Fowler
@@ -26,32 +26,29 @@ This code was developed as part of the [CRyPTIC](http://www.crypticproject.org)
26
26
 
27
27
  ## Installation
28
28
 
29
- ### using `pip`
29
+ ### Using `pip`
30
30
 
31
31
  This will install the most recent release on PyPI.
32
32
 
33
33
  ```
34
- $ pip install piezo
35
- $ cd piezo
36
- $ py.test
34
+ pip install piezo
37
35
  ```
38
36
 
39
- ### from GitHub
37
+ ### From GitHub
40
38
 
41
39
  This will install the current version from GitHub and therefore may be ahead of the PyPI version.
42
40
 
43
41
  ```
44
- $ git clone https://github.com/oxfordmmm/piezo
45
- $ cd piezo
46
- $ pip install .
47
- $ py.test
42
+ git clone https://github.com/oxfordmmm/piezo
43
+ cd piezo
44
+ pip install .
48
45
  ```
49
46
  The pre-requisites are all fairly standard and are listed in `setup.cfg` so will be automatically installed.
50
47
 
51
48
  ## Included files
52
49
 
53
50
  ```
54
- $ $ ls tests/test-catalogue/
51
+ $ ls tests/test-catalogue/
55
52
  NC_004148.2.gbk NC_004148.2_TEST_GM1_RFUS_v1.0.csv
56
53
  ```
57
54
  NC_004148 is the reference genome of the human metapneumovirus and is used primarily for unit testing since it is small and fast to parse.
@@ -10,32 +10,29 @@ This code was developed as part of the [CRyPTIC](http://www.crypticproject.org)
10
10
 
11
11
  ## Installation
12
12
 
13
- ### using `pip`
13
+ ### Using `pip`
14
14
 
15
15
  This will install the most recent release on PyPI.
16
16
 
17
17
  ```
18
- $ pip install piezo
19
- $ cd piezo
20
- $ py.test
18
+ pip install piezo
21
19
  ```
22
20
 
23
- ### from GitHub
21
+ ### From GitHub
24
22
 
25
23
  This will install the current version from GitHub and therefore may be ahead of the PyPI version.
26
24
 
27
25
  ```
28
- $ git clone https://github.com/oxfordmmm/piezo
29
- $ cd piezo
30
- $ pip install .
31
- $ py.test
26
+ git clone https://github.com/oxfordmmm/piezo
27
+ cd piezo
28
+ pip install .
32
29
  ```
33
30
  The pre-requisites are all fairly standard and are listed in `setup.cfg` so will be automatically installed.
34
31
 
35
32
  ## Included files
36
33
 
37
34
  ```
38
- $ $ ls tests/test-catalogue/
35
+ $ ls tests/test-catalogue/
39
36
  NC_004148.2.gbk NC_004148.2_TEST_GM1_RFUS_v1.0.csv
40
37
  ```
41
38
  NC_004148 is the reference genome of the human metapneumovirus and is used primarily for unit testing since it is small and fast to parse.
piezo-0.4/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.4
@@ -0,0 +1,7 @@
1
+ '''Piezo is an AMR prediction module. Logic for handling prediction values should reside within the catalogues.
2
+ '''
3
+ #! /usr/bin/env python
4
+
5
+ # -*- coding: utf-8 -*-
6
+
7
+ from .catalogue import ResistanceCatalogue
@@ -1,12 +1,15 @@
1
1
  #! /usr/bin/env python
2
+ '''Instanciate the catalogue
3
+ '''
2
4
 
3
- import os
4
5
  import collections
6
+ import os
7
+ import warnings
5
8
 
6
- import pandas, ujson
9
+ import pandas
10
+ import ujson
7
11
 
8
- from piezo.grammar_GARC1 import predict_GARC1
9
- from piezo.grammar_GARC1 import process_catalogue_GARC1
12
+ from piezo.grammar_GARC1 import predict_GARC1, process_catalogue_GARC1
10
13
 
11
14
  # define the named tuple that will specify a resistance catalogue
12
15
  catalogue = collections.namedtuple('catalogue',
@@ -22,22 +25,49 @@ catalogue = collections.namedtuple('catalogue',
22
25
  'number_rows',
23
26
  'rules' ]
24
27
  )
28
+
29
+
25
30
  class ResistanceCatalogue:
31
+ '''Resistance catalogue loading
32
+ '''
26
33
 
27
- def __init__(self, catalogue_file, prediction_subset_only=False):
34
+ def __init__(self, catalogue_file: str, prediction_subset_only: bool=False):
35
+ '''Construct a resistance catalogue
28
36
 
37
+ Args:
38
+ catalogue_file (str): Path to the catalogue file
39
+ prediction_subset_only (bool, optional): Whether to use a subset of genes to only resistance genes. Defaults to False.
40
+ '''
29
41
  self.catalogue = load_catalogue(catalogue_file, prediction_subset_only)
30
42
 
31
- def predict(self, mutation, verbose=False):
43
+ def predict(self, mutation: str, verbose: bool=False) -> {str: str}:
44
+ '''Make a prediction of a mutation's effects based on the catalogue
32
45
 
46
+ Args:
47
+ mutation (str): Mutation in GARC
48
+ verbose (bool, optional): Whether to be verbose. Defaults to False. DEPRECIATED
49
+
50
+ Returns:
51
+ {str: str}: Dictionary mapping drug name -> prediction, or "S" if no matches
52
+ '''
53
+ if verbose:
54
+ warnings.warn("`verbose` kwarg is depreciated and will be removed in future.", UserWarning)
33
55
  return predict(self.catalogue, mutation=mutation, verbose=verbose)
34
56
 
35
- def parse_json(data):
57
+ def parse_json(data: str) -> dict:
58
+ '''Load the data within a json string to Python dict
59
+
60
+ Args:
61
+ data (str): JSON string
62
+
63
+ Returns:
64
+ dict: Dictionary of the JSON data
65
+ '''
36
66
 
37
67
  return ujson.loads(data)
38
68
 
39
69
 
40
- def load_catalogue(catalogue_file,prediction_subset_only):
70
+ def load_catalogue(catalogue_file: str, prediction_subset_only: bool) -> collections.namedtuple:
41
71
  '''
42
72
  Read in the Antimicrobial Resistance Catalogue.
43
73
 
@@ -46,10 +76,10 @@ def load_catalogue(catalogue_file,prediction_subset_only):
46
76
  prediction_subset_only (bool): whether to subset the catalogue down so it ONLY includes entities (e.g. DRUG,GENE pairs) that include at least one row predicting resistance
47
77
 
48
78
  Returns:
49
- catalogue (named_tuple): defined tuple
79
+ catalogue (collections.namedtuple): defined tuple
50
80
 
51
81
  Notes:
52
- * Applies checks to ensure the catalogue is in the right format.
82
+ * Applies checks to ensure the catalogue is in the right format. TODO: Remove assert statements as they should not be used for runtime error checking
53
83
  '''
54
84
 
55
85
 
@@ -106,13 +136,14 @@ def load_catalogue(catalogue_file,prediction_subset_only):
106
136
  number_rows,
107
137
  rules)
108
138
 
109
- def predict(catalogue,mutation,verbose):
139
+ def predict(catalogue: collections.namedtuple, mutation: str, verbose: bool=False) -> {str: str}:
110
140
  '''
111
141
  Predict the effect of the given mutation on one or more antimicrobials.
112
142
 
113
143
  Args:
144
+ catalogue (collections.namedtuple): The catalogue
114
145
  mutation (str): a genetic variant in the form GENE_MUTATION e.g. for a SNP katG_S315T, INDEL katG_315_indel.
115
- verbose (bool): if True, then a description of the rules that apply to the supplied mutation and their priority is written to STDOUT (default=False)
146
+ verbose (bool): if True, then a description of the rules that apply to the supplied mutation and their priority is written to STDOUT (default=False). DEPRECIATED
116
147
 
117
148
  Returns:
118
149
  result (dict): the drugs affected by the mutation are the keys, and the predicted phenotypes are the values. e.g. {'LEV':'R', 'MXF':'R'}
@@ -124,13 +155,7 @@ def predict(catalogue,mutation,verbose):
124
155
  * "any mutation at position S315" (i.e. a wildcard) is represented by "?" e.g. S315?
125
156
  * for more info see the walkthrough and also the NOMENCLATURE.md file
126
157
  '''
127
-
128
- if catalogue.grammar=="GARC1":
129
-
130
- result = predict_GARC1(catalogue,mutation,verbose)
131
-
132
- return(result)
133
-
134
- else:
135
-
136
- raise ValueError("Only the GENE_MUTATION GARC1 grammar is supported at present")
158
+ if verbose:
159
+ warnings.warn("`verbose` kwarg is depreciated and will be removed in future.", UserWarning)
160
+
161
+ return predict_GARC1(catalogue, mutation)
@@ -1,17 +1,40 @@
1
1
  #! /usr/bin/env python
2
+ '''All logic required to parse and generate predictions from a catalogue in GARC1
3
+ '''
4
+
5
+ import collections
2
6
 
3
7
  import pandas
4
8
 
5
- def split_mutation(row):
9
+
10
+ def split_mutation(row: pandas.Series) -> pandas.Series:
11
+ '''Take a row of the catalogue and get info about the mutation from it.
12
+ This includes the type, ref, alt, position and minor populations
13
+
14
+ Args:
15
+ row (pandas.Series): Catalogue row
16
+
17
+ Raises:
18
+ ValueError: Raised when mutations are malformed
19
+
20
+ Returns:
21
+ pandas.Series: Series about the mutation. In order: gene, mutation, position, type of position (i.e PROM/CDS), mutation type (i.e INDEL/SNP/MULTI), support for minor populations
22
+ '''
6
23
  if '&' in row['MUTATION']:
7
24
  #Multi-mutation so don't try to split it out in the same way
8
25
  gene = 'MULTI'
9
26
  #Ensure mutations are in a reproducable order
10
27
  mutation = '&'.join(sorted(list(row['MUTATION'].split('&'))))
28
+
11
29
  position = None
12
30
  mutation_affects = None
13
31
  mutation_type = 'MULTI'
14
- return pandas.Series([gene, mutation, position, mutation_affects, mutation_type])
32
+
33
+ #Check for minor populations (and remove, we'll check these separately)
34
+ minors = ','.join([mut.split(":")[-1] if ':' in mut else '' for mut in mutation.split("&")])
35
+ mutation = '&'.join([mut.split(":")[0] for mut in mutation.split("&")])
36
+
37
+ return pandas.Series([gene, mutation, position, mutation_affects, mutation_type, minors])
15
38
 
16
39
  # split the supplied mutation on _ which separates the components
17
40
  components=row['MUTATION'].split("@")
@@ -22,7 +45,16 @@ def split_mutation(row):
22
45
  # ..and the remainder is the mutation
23
46
  mutation=row['MUTATION'].split(gene+"@")[1]
24
47
 
48
+ #Check for minor populations (and remove minors, we'll check for those separately)
49
+ if ":" in mutation:
50
+ minor = mutation.split(":")[-1]
51
+ mutation = mutation.split(":")[0]
52
+ else:
53
+ minor = ''
54
+
55
+
25
56
  cols=mutation.split('_')
57
+ valid = True
26
58
 
27
59
  if len(cols)==1:
28
60
  mutation_type="SNP"
@@ -32,7 +64,7 @@ def split_mutation(row):
32
64
  if int(position)<0:
33
65
  mutation_affects="PROM"
34
66
  elif int(position)==0:
35
- raise ValueError("a position of 0 in a mutation does not make sense!")
67
+ valid = False
36
68
  except:
37
69
  position=cols[0][:-1]
38
70
  if position[0]=="-":
@@ -46,33 +78,43 @@ def split_mutation(row):
46
78
  if int(position)<0:
47
79
  mutation_affects="PROM"
48
80
  elif int(position)==0:
49
- raise ValueError("a position of 0 in a mutation does not make sense!")
81
+ valid = False
50
82
  except:
51
83
  try:
52
84
  if position[0]=="-":
53
85
  mutation_affects="PROM"
54
86
  except:
55
- pass
87
+ valid = False
56
88
 
57
89
  else:
58
- raise ValueError("badly formed mutation: "+row["MUTATION"])
59
-
60
- return(pandas.Series([gene,mutation,position,mutation_affects,mutation_type]))
90
+ raise ValueError("Badly formed mutation: "+row["MUTATION"])
91
+
92
+ if not valid:
93
+ #Valid mutation not found, so complain
94
+ raise ValueError("Badly formed mutation: "+row['MUTATION'])
95
+
96
+ return pandas.Series([gene,mutation,position,mutation_affects,mutation_type, minor])
61
97
 
62
98
 
63
- def process_catalogue_GARC1(rules,drugs,catalogue_genes_only):
99
+ def process_catalogue_GARC1(rules: pandas.DataFrame, drugs: [str], catalogue_genes_only: bool) -> (pandas.DataFrame, [str], {str: [str]}, {str: [str]}):
64
100
  '''
65
101
  For the GARC1 grammar, add some additional columns to the rules dataframe that can be inferred from the mutation.
66
102
 
67
103
  Args:
68
- rules (dataframe): Pandas dataframe of the AMR catalogue in the general form
69
- drugs (list): list of drugs in the AMR catalogue
104
+ rules (pandas.DataFrame): Pandas dataframe of the AMR catalogue in the general form
105
+ drugs ([str]): list of drugs in the AMR catalogue
70
106
  catalogue_genes_only (bool): whether to subset the catalogue down so it ONLY includes (DRUG,GENE) pairs that include at least one row predicting resistance
107
+ Returns:
108
+ (pandas.DataFrame, [str], {str: [str]}, {str: [str]}) : Tuple of values. In order:
109
+ DataFrame of the rules
110
+ List of the genes
111
+ Dictionary mapping drug name -> [gene names]
112
+ Dictionary mapping gene name -> [drug names]
71
113
 
72
114
  '''
73
115
 
74
116
  # infer these columns
75
- rules[['GENE','MUTATION','POSITION','MUTATION_AFFECTS','MUTATION_TYPE']]=rules.apply(split_mutation,axis=1)
117
+ rules[['GENE','MUTATION','POSITION','MUTATION_AFFECTS','MUTATION_TYPE', "MINOR"]] = rules.apply(split_mutation,axis=1)
76
118
 
77
119
  if catalogue_genes_only:
78
120
 
@@ -95,7 +137,7 @@ def process_catalogue_GARC1(rules,drugs,catalogue_genes_only):
95
137
  gene_lookup={}
96
138
  for gene_name in genes:
97
139
  df=rules.loc[rules.GENE==gene_name]
98
- gene_lookup[gene_name]=list(df.DRUG.unique())
140
+ gene_lookup[gene_name] = sorted(list(df.DRUG.unique()))
99
141
 
100
142
  # create a dictionary where the drugs are keys and the entries tell which genes are affected
101
143
  drug_lookup={}
@@ -103,19 +145,18 @@ def process_catalogue_GARC1(rules,drugs,catalogue_genes_only):
103
145
  df=rules.loc[rules.DRUG==drug_name]
104
146
  drug_lookup[drug_name]=list(df.GENE.unique())
105
147
 
106
- return(rules,genes,drug_lookup,gene_lookup)
148
+ return rules, genes, drug_lookup, gene_lookup
107
149
 
108
- def predict_GARC1(catalogue,gene_mutation,verbose):
150
+ def predict_GARC1(catalogue: collections.namedtuple, gene_mutation: str) -> {str: str}:
109
151
  '''
110
152
  For the GARC1 grammar, predict the effect of the supplied gene_mutation.
111
153
 
112
154
  Args:
113
- catalogue (named tuple): defines the resistance catalogue
155
+ catalogue (collections.namedtuple): defines the resistance catalogue
114
156
  gene_mutation (str): as specified by the GARC1 grammar, e.g. rpoB_S450L, fabG1_c-15t, ahpC_128_indel
115
- verbose (bool): whether to be loud
116
157
 
117
158
  Returns:
118
- result: is either a dict with the drugs as keys, or "S" if there are no hits in the catalogue
159
+ {str: str} | str: Either a dictionary mapping drug name -> predictions or "S" if no hits in the catalogue
119
160
  '''
120
161
  if '&' in gene_mutation:
121
162
  #Multi-gene so treat differently
@@ -125,8 +166,19 @@ def predict_GARC1(catalogue,gene_mutation,verbose):
125
166
  gene=components[0]
126
167
  mutation=gene_mutation.split(gene+"@")[1]
127
168
 
169
+ #Check for minors
170
+ if ":" in mutation:
171
+ try:
172
+ minor = float(mutation.split(":")[-1])
173
+ except ValueError:
174
+ assert False, "Malformed mutation! "+mutation
175
+ mutation = mutation.split(":")[0]
176
+ assert minor > 0, "Minor population given with no evidence! "+mutation
177
+ else:
178
+ minor = None
179
+
128
180
  # parse the mutation to work out what type of mutation it is, where it acts etc
129
- (position, mutation_affects, mutation_type, indel_type, indel_length, indel_bases, before, after) = parse_mutation(gene,mutation)
181
+ (position, mutation_affects, mutation_type, indel_type, indel_length, indel_bases, before, after) = parse_mutation(mutation)
130
182
 
131
183
  # if the gene isn't in the catalogue, then assume it has no effect
132
184
  if gene not in catalogue.genes:
@@ -135,14 +187,11 @@ def predict_GARC1(catalogue,gene_mutation,verbose):
135
187
  # find out the drugs to which changes in this gene can confer resistance
136
188
  drugs=catalogue.gene_lookup[gene]
137
189
 
138
- # if there aren't any just return an S again
139
- if drugs is None:
140
- return("S")
141
-
142
190
  # create the result dictionary e.g. {"RIF":'R', "RFB":'R'}
143
191
  # most of the time the predictions will be identical, but this allows them to diverge in future
144
192
  result={}
145
193
 
194
+
146
195
  # create the vectors of Booleans that will apply
147
196
  position_vector = (catalogue.rules.POSITION.isin([position,str(position), '*','-*']))
148
197
  mutation_affects_vector = (catalogue.rules.MUTATION_AFFECTS == mutation_affects)
@@ -165,34 +214,38 @@ def predict_GARC1(catalogue,gene_mutation,verbose):
165
214
 
166
215
  if mutation_type=="SNP":
167
216
  process_snp_variants(mutation_affects, predictions, before, after, mutation, subset_rules,\
168
- subset_mutation_type_vector, subset_position_vector, verbose)
217
+ subset_mutation_type_vector, subset_position_vector, minor)
169
218
  elif mutation_type=="INDEL":
170
219
  process_indel_variants(mutation_affects,
171
- predictions, before, after, subset_rules, subset_mutation_type_vector,
172
- subset_position_vector, indel_length, indel_type, indel_bases, position, verbose)
220
+ predictions, subset_rules, subset_mutation_type_vector,
221
+ subset_position_vector, indel_length, indel_type, indel_bases, position, minor)
173
222
 
174
223
  if not predictions:
175
224
  # all mutations should hit at least one of the default entries, so if this doesn't happen, something is wrong
176
- raise ValueError("No entry found in the catalogue for "+gene_mutation+compound)
225
+ raise ValueError("No entry found in the catalogue for "+gene_mutation+" "+compound)
177
226
 
178
227
  final_prediction=predictions[sorted(predictions)[-1]]
179
228
  result[compound]=final_prediction
180
229
 
181
230
  return(result)
182
231
 
183
- def predict_multi(catalogue, gene_mutation):
232
+ def predict_multi(catalogue: collections.namedtuple, gene_mutation: str) -> {str: str}:
184
233
  '''Get the predictions for a given multi-mutation.
185
234
  Mutli-mutations are (currently) a lot stricter than others, and do not support wildcards or subsets of the mutations
186
235
 
187
236
  Args:
188
- catalogue (named tuple): The resistance catalogue
237
+ catalogue (collections.namedtuple): The resistance catalogue
189
238
  gene_mutation (str): String of the mutations, each in GARC, separated by `&`
190
239
  Returns:
191
- dict | str : Either a dict with drugs as the keys, or 'S' when no predictions in catalogue
240
+ {str: str} | str : Either a dict with drugs as the keys, or 'S' when no predictions in catalogue
192
241
  '''
193
242
  #Ensure that the mutations are in a reproducable order
194
243
  sorted_mutation = '&'.join(sorted(list(gene_mutation.split('&'))))
195
244
 
245
+ #Check for minor populations (and remove, we'll check these separately)
246
+ minors = [float(mut.split(":")[-1]) if ':' in mut else None for mut in sorted_mutation.split("&")]
247
+ sorted_mutation = '&'.join([mut.split(":")[0] for mut in sorted_mutation.split("&")])
248
+
196
249
  #Get the multi rules
197
250
  multi_rules = catalogue.rules[catalogue.rules['MUTATION_TYPE']=='MULTI']
198
251
 
@@ -204,50 +257,139 @@ def predict_multi(catalogue, gene_mutation):
204
257
  drug = rule['DRUG']
205
258
  if values.index(rule['PREDICTION']) < values.index(drugs[drug]):
206
259
  #The prediction is closer to the start of the values list, so should take priority
207
- drugs[drug] = rule['PREDICTION']
260
+ #Check for minor populations first though
261
+ for (cat, minor) in zip(rule['MINOR'].split(","), minors):
262
+ if minor is None and cat == '':
263
+ #Neither are minors so add
264
+ drugs[drug] = rule['PREDICTION']
265
+ elif cat != '' and minor is not None and minor < 1 and float(cat) < 1:
266
+ #FRS
267
+ if minor >= float(cat):
268
+ #Match
269
+ drugs[drug] = rule['PREDICTION']
270
+ elif cat != '' and minor is not None and minor >=1 and float(cat) >= 1:
271
+ #COV
272
+ if minor >= float(cat):
273
+ #Match
274
+ drugs[drug] = rule['PREDICTION']
208
275
 
209
276
  #Check to ensure we have at least 1 prediction
210
277
  if len([key for key in drugs.keys() if drugs[key] != 'S']) > 0:
211
278
  return {drug: drugs[drug] for drug in drugs.keys() if drugs[drug]!='S'}
212
279
 
213
- #Nothing predicted, so default to S
214
- return 'S'
280
+ #Nothing predicted, so try each individual mutation
281
+ predictions = {}
282
+ for (mutation, minor) in zip(sorted_mutation.split("&"), minors):
283
+ #Put minor populations back into mutations as required
284
+ if minor is not None:
285
+ mutation = mutation + ":" + str(minor)
286
+
287
+ #Get the prediction for the mutation
288
+ pred = predict_GARC1(catalogue, mutation)
289
+ if isinstance(pred, str):
290
+ #We have a 'S' prediction so ignore it
291
+ continue
292
+ else:
293
+ predictions[mutation] = pred
294
+
295
+ return merge_predictions(predictions, catalogue)
296
+
215
297
 
298
+ def merge_predictions(predictions: {str: {str: str}}, catalogue: collections.namedtuple) -> {str: str}:
299
+ '''When multi-mutations do not have a hit, they are decomposed and individuals are tried instead
300
+ This merges these predictions based on the prioritisation defined for this catalogue
301
+
302
+ Args:
303
+ predictions ({str: {str: str}}): Dictionary mapping mutation -> effects for each mutation in the multi
304
+ catalogue (collections.namedtuple): The catalogue object (for finding the values)
305
+ Returns:
306
+ {str: str}: Merged effects dict mapping drug name -> prediction. Or "S" if no matches
307
+ '''
308
+ #Pull out all of the drugs which have predictions
309
+ drugs = set()
310
+ for pred in predictions:
311
+ for drug in predictions[pred].keys():
312
+ drugs.add(drug)
313
+
314
+ #Default to 'S' for now
315
+ merged = {drug: 'S' for drug in drugs}
316
+
317
+ #Look for all predictions for each drug, and report the most significant
318
+ for drug in drugs:
319
+ for mutation in predictions.keys():
320
+ #Get the prediction for this drug (if exists)
321
+ pred = predictions[mutation][drug]
322
+ if catalogue.values.index(pred) <= catalogue.values.index(merged[drug]):
323
+ #New highest priority, so set the prediction
324
+ merged[drug] = pred
325
+
326
+ #If we have >=1 non-'S' prediction, return the dict
327
+ if len([key for key in merged.keys() if merged[key] != 'S']) > 0:
328
+ return {drug: merged[drug] for drug in merged.keys() if merged[drug]!='S'}
329
+
330
+ #Else give the default 'S'
331
+ return 'S'
216
332
 
217
- def row_prediction(rows, predictions, priority, message, verbose=False):
333
+ def row_prediction(rows: pandas.DataFrame, predictions: {int: str}, priority: int, minor: float) -> None:
218
334
  '''Get the predictions from the catalogue for the applicable rows
219
335
 
220
336
  Args:
221
337
  rows (pandas.DataFrame): DataFrame of the rows within the catalogue
222
- predictions (dict): Predictions dict
223
- priority (int): Priority
224
- message (str): Message
225
- verbose (bool, optional): Whether to be verbose. Defaults to False.
338
+ predictions (dict): Predictions dict mapping priorities to predictions. This is updated for implict return
339
+ priority (int): Priority of this mutation type
340
+ minor (float | None): Reads/FRS supporting this, or None if not a minor population
226
341
  '''
227
342
  pred = None
228
343
  values = ['R', 'U', 'F', 'S', None]
229
344
  for _, row in rows.iterrows():
230
345
  if not row.empty:
231
346
  assert int(priority) in range (1,11), 'priority must be an integer in range 1,2..10'
232
- if verbose:
233
- print(str(int(priority)),str(row["PREDICTION"]), message)
234
347
  if values.index(row['PREDICTION']) < values.index(pred):
235
- #This row's prediction is more important than the current, so prioritise
236
- pred = row['PREDICTION']
348
+ #This row's prediction is more important than the current, so check for minors and prioritise
349
+ if minor is None and row['MINOR'] == '':
350
+ #Neither are minor populations so act normally
351
+ pred = row['PREDICTION']
352
+
353
+ elif row['MINOR'] != '' and minor < 1 and float(row['MINOR']) < 1:
354
+ #We have FRS
355
+ if minor >= float(row['MINOR']):
356
+ #Match
357
+ pred = row['PREDICTION']
358
+
359
+ elif row['MINOR'] != '' and minor >= 1 and float(row['MINOR']) >= 1:
360
+ #We have COV
361
+ if minor >= float(row['MINOR']):
362
+ #Match
363
+ pred = row['PREDICTION']
364
+
365
+ else:
366
+ #Mismatch, so only give a match for defaults
367
+ if "*" in row['MUTATION']:
368
+ pred = row['PREDICTION']
237
369
  if pred:
238
370
  predictions[int(priority)] = str(pred)
239
371
 
240
372
 
241
- def process_snp_variants(mutation_affects,
242
- predictions,
243
- before, after,
244
- mutation,
245
- rules,
246
- rules_mutation_type_vector,
247
- rules_position_vector,
248
- verbose):
249
- '''
250
- Apply the cascading rules for SNPs, according to the GARC1 grammar.
373
+ def process_snp_variants(mutation_affects: str,
374
+ predictions: {int: str},
375
+ before: str, after: str,
376
+ mutation: str,
377
+ rules: pandas.DataFrame,
378
+ rules_mutation_type_vector: pandas.Series,
379
+ rules_position_vector: pandas.Series,
380
+ minor: float) -> None:
381
+ '''Apply cascading rules for SNPs according to GARC
382
+
383
+ Args:
384
+ mutation_affects (str): Where this mutation affects. i.e PROM/CDS
385
+ predictions ({int: str}): Predictions dictionary mapping priority -> prediction. This is updated for implict return
386
+ before (str): Reference base/AA
387
+ after (str): Alt base/AA
388
+ mutation (str): Mutation in GARC
389
+ rules (pandas.DataFrame): Rules DataFrame
390
+ rules_mutation_type_vector (pandas.Series): Series relating to rules for this type of mutation
391
+ rules_position_vector (pandas.Series): Series relating to rules for this position
392
+ minor (float | None): Float for supporting evidence of minor populations (or None if not a minor population).
251
393
  '''
252
394
 
253
395
 
@@ -257,45 +399,55 @@ def process_snp_variants(mutation_affects,
257
399
 
258
400
  # PRIORITY=1: synonymous mutation at any position in the CDS (e.g. rpoB_*=)
259
401
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="*=")]
260
- row_prediction(row, predictions, 1, "syn SNP at any position in the CDS",verbose)
402
+ #syn SNP at any position in the CDS
403
+ row_prediction(row, predictions, 1, minor)
261
404
 
262
405
  elif before!=after:
263
406
 
264
407
  # PRIORITY=2: nonsynoymous mutation at any position in the CDS or PROM (e.g. rpoB_*? or rpoB_-*?)
265
408
  if mutation_affects=="CDS":
266
409
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="*?")]
267
- row_prediction(row, predictions, 2, "nonsyn SNP at any position in the CDS",verbose)
410
+ #nonsyn SNP at any position in the CDS
411
+ row_prediction(row, predictions, 2, minor)
268
412
  else:
269
413
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="-*?")]
270
- row_prediction(row, predictions, 2, "nonsyn SNP at any position in the PROM",verbose)
414
+ #nonsyn SNP at any position in the PROM
415
+ row_prediction(row, predictions, 2, minor)
271
416
  # PRIORITY=3: het mutation at any position in the CDS or PROM (e.g. rpoB_*Z or rpoB_-*z)
272
417
  if mutation[-1] in ['Z','z','O','o','X','x']:
273
418
  if mutation_affects=="CDS":
274
419
  if (mutation[-1]=="Z"):
275
420
  row=rules.loc[(rules_mutation_type_vector) & (rules.MUTATION=="*Z")]
276
- row_prediction(row, predictions, 3, "het SNP at any position in the CDS",verbose)
421
+ #het SNP at any position in the CDS
422
+ row_prediction(row, predictions, 3, minor)
277
423
  elif (mutation[-1]=="O"):
278
424
  row=rules.loc[(rules_mutation_type_vector) & (rules.MUTATION=="*O")]
279
- row_prediction(row, predictions, 3, "filter fail at any position in the CDS",verbose)
425
+ #filter fail at any position in the CDS
426
+ row_prediction(row, predictions, 3, minor)
280
427
  elif (mutation[-1]=="X"):
281
428
  row=rules.loc[(rules_mutation_type_vector) & (rules.MUTATION=="*X")]
282
- row_prediction(row, predictions, 3, "null at any position in the CDS",verbose)
429
+ #null at any position in the CDS
430
+ row_prediction(row, predictions, 3, minor)
283
431
  else:
284
432
  if mutation[-1]=="z":
285
433
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="-*z")]
286
- row_prediction(row, predictions, 3, "het SNP at any position in the PROM",verbose)
434
+ #het SNP at any position in the PROM
435
+ row_prediction(row, predictions, 3, minor)
287
436
  elif mutation[-1]=='o':
288
437
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="-*o")]
289
- row_prediction(row, predictions, 3, "filter fail at any position in the PROM",verbose)
438
+ #filter fail at any position in the PROM
439
+ row_prediction(row, predictions, 3, minor)
290
440
  elif mutation[-1]=='x':
291
441
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="-*x")]
292
- row_prediction(row, predictions, 3, "null at any position in the PROM",verbose)
442
+ #null at any position in the PROM
443
+ row_prediction(row, predictions, 3, minor)
293
444
 
294
445
  # PRIORITY=4: specific mutation at any position in the CDS: only Stop codons make sense for now (e.g. rpoB_*!)
295
446
  if mutation[-1] in ['!']:
296
447
  if mutation_affects=="CDS":
297
448
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="*!")]
298
- row_prediction(row, predictions, 4, "stop codon at any position in the CDS",verbose)
449
+ #stop codon at any position in the CDS
450
+ row_prediction(row, predictions, 4, minor)
299
451
 
300
452
  # PRIORITY=5: no change at specific position
301
453
  # PRIORITY=6: synonymous mutations at specific location (usually picked up by e.g. L202L, rather than L202=)
@@ -303,31 +455,43 @@ def process_snp_variants(mutation_affects,
303
455
  # PRIORITY=7: any het mutation at this specific position in the CDS or PROM (e.g. rpoB_S450Z or rpoB_c-15z)
304
456
  if mutation[-1] in ["Z","z"]:
305
457
  row=rules.loc[(rules_mutation_type_vector) & (rules_position_vector) & (rules.MUTATION.str[-1].isin(['Z','z']))]
306
- row_prediction(row, predictions, 7, "het SNP at specified position in the CDS",verbose)
458
+ #het SNP at specified position in the CDS
459
+ row_prediction(row, predictions, 7, minor)
307
460
 
308
461
  # PRIORITY=8: any nonsynoymous mutation at this specific position in the CDS or PROM (e.g. rpoB_S450? or rpoB_c-15?)
309
462
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION.str[-1]=="?")]
310
- row_prediction(row, predictions, 8, "nonsyn SNP at specified position in the CDS",verbose)
463
+ #nonsyn SNP at specified position in the CDS
464
+ row_prediction(row, predictions, 8, minor)
311
465
 
312
466
  # PRIORITY=9: an exact match
313
467
  row=rules.loc[(rules_mutation_type_vector) & (rules.MUTATION==mutation)]
314
- row_prediction(row, predictions, 9, "exact SNP match",verbose)
315
-
468
+ #exact SNP match
469
+ row_prediction(row, predictions, 9, minor)
470
+
471
+
472
+ def process_indel_variants(mutation_affects: str,
473
+ predictions: {int: str},
474
+ rules: pandas.DataFrame,
475
+ rules_mutation_type_vector: pandas.Series,
476
+ rules_position_vector: pandas.Series,
477
+ indel_length: int,
478
+ indel_type: str,
479
+ indel_bases: str,
480
+ position: int,
481
+ minor: float) -> None:
482
+ '''Apply the cascading rules for INDELs in GARC
316
483
 
317
- def process_indel_variants(mutation_affects,
318
- predictions,
319
- before, after,
320
- rules,
321
- rules_mutation_type_vector,
322
- rules_position_vector,
323
- indel_length,
324
- indel_type,
325
- indel_bases,
326
- position,
327
- verbose):
328
-
329
- '''
330
- Apply the cascading rules for INDELs, according to the GARC1 grammar.
484
+ Args:
485
+ mutation_affects (str): Which area this mutation affects. i.e PROM/CDS
486
+ predictions ({int: str}): Dictionary mapping priority -> prediction. This is updated for implict return
487
+ rules (pandas.DataFrame): Rules DataFrame
488
+ rules_mutation_type_vector (pandas.Series): Series for the rules which refer to this mutation type
489
+ rules_position_vector (pandas.Series): Series for the rules which refer to this position
490
+ indel_length (int): Length of the indel
491
+ indel_type (str): Type of the indel. i.e ins/del/fs/indel
492
+ indel_bases (str): Bases inserted/deleted (if applicable)
493
+ position (int): Position of the indel
494
+ minor (float): Float for supporting evidence of minor populations (or None if not a minor population)
331
495
  '''
332
496
 
333
497
  # PRIORITY 1: any insertion or deletion in the CDS or PROM (e.g. rpoB_*_indel or rpoB_-*_indel)
@@ -335,14 +499,16 @@ def process_indel_variants(mutation_affects,
335
499
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="*_indel")]
336
500
  else:
337
501
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="-*_indel")]
338
- row_prediction(row, predictions, 1, "any insertion or deletion in the CDS or PROM")
502
+ #any insertion or deletion in the CDS or PROM
503
+ row_prediction(row, predictions, 1, minor)
339
504
 
340
505
  # PRIORITY 2: rpoB_*_ins, rpoB_*_del any insertion (or deletion) in the CDS or PROM
341
506
  if mutation_affects == "CDS":
342
507
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION.isin(["*_ins","*_del"]))]
343
508
  else:
344
509
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION.isin(["-*_ins","-*_del"]))]
345
- row_prediction(row, predictions, 2, "any insertion (or deletion) in the CDS or PROM")
510
+ #any insertion (or deletion) in the CDS or PROM
511
+ row_prediction(row, predictions, 2, minor)
346
512
 
347
513
  # PRIORITY 3: any insertion of a specified length (or deletion) in the CDS or PROM (e.g. rpoB_*_ins_2, rpoB_*_del_3, rpoB_-*_ins_1, rpoB_-*_del_200)
348
514
  if indel_length is not None and indel_type!="indel":
@@ -350,39 +516,46 @@ def process_indel_variants(mutation_affects,
350
516
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION.isin(["*_"+indel_type+"_"+str(indel_length)]))]
351
517
  else:
352
518
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION.isin(["-*_"+indel_type+"_"+str(indel_length)]))]
353
- row_prediction(row, predictions, 3, "any insertion of a specified length (or deletion) in the CDS or PROM")
519
+ #any insertion of a specified length (or deletion) in the CDS or PROM
520
+ row_prediction(row, predictions, 3, minor)
354
521
 
355
522
  # PRIORITY=4: any frameshifting insertion or deletion in the CDS (e.g. rpoB_*_fs)
356
523
  if indel_length is not None and (indel_length%3)!=0:
357
524
  row=rules.loc[rules_mutation_type_vector & (rules.MUTATION=="*_fs")]
358
- row_prediction(row, predictions, 4, "any frameshifting insertion or deletion in the CDS")
525
+ #any frameshifting insertion or deletion in the CDS
526
+ row_prediction(row, predictions, 4, minor)
359
527
 
360
528
  # PRIORITY=5: any indel at a specific position in the CDS or PROM (e.g. rpoB_1300_indel or rpoB_-15_indel)
361
529
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION.str.contains("indel"))]
362
- row_prediction(row, predictions, 5, "any indel at a specific position in the CDS or PROM (e.g. rpoB_1300_indel or rpoB_-15_indel)")
530
+ #any indel at a specific position in the CDS or PROM (e.g. rpoB_1300_indel or rpoB_-15_indel)
531
+ row_prediction(row, predictions, 5, minor)
363
532
 
364
533
  # PRIORITY=6: an insertion (or deletion) at a specific position in the CDS or PROM (e.g. rpoB_1300_ins or rpoB_-15_del)
365
534
  if indel_type!="indel":
366
535
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION.str.contains(indel_type))]
367
- row_prediction(row, predictions, 6, "any insertion (or deletion) at a specific position in the CDS or PROM (e.g. rpoB_1300_ins or rpoB_-15_del)")
536
+ #any insertion (or deletion) at a specific position in the CDS or PROM (e.g. rpoB_1300_ins or rpoB_-15_del)
537
+ row_prediction(row, predictions, 6, minor)
368
538
 
369
539
  # PRIORITY=7: an insertion (or deletion) of a specified length at a specific position in the CDS or PROM (e.g. rpoB_1300_ins_2 or rpoB_-15_del_200)
370
540
  if indel_type!="indel" and indel_length is not None:
371
541
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION==str(position)+"_"+indel_type+"_"+str(indel_length))]
372
- row_prediction(row, predictions, 7, "an insertion (or deletion) of a specified length at a specific position in the CDS or PROM (e.g. rpoB_1300_ins_2 or rpoB_-15_del_200)")
542
+ #an insertion (or deletion) of a specified length at a specific position in the CDS or PROM (e.g. rpoB_1300_ins_2 or rpoB_-15_del_200)
543
+ row_prediction(row, predictions, 7, minor)
373
544
 
374
545
  # PRIORITY=8: a frameshifting mutation at a specific position in the CDS (e.g. rpoB_100_fs)
375
546
  if indel_length is not None and (indel_length%3)!=0 and position is not None:
376
547
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION==str(position)+"_fs")]
377
- row_prediction(row, predictions, 8, "a frameshifting mutation at a specific position in the CDS (e.g. rpoB_100_fs)")
548
+ #a frameshifting mutation at a specific position in the CDS (e.g. rpoB_100_fs)
549
+ row_prediction(row, predictions, 8, minor)
378
550
 
379
551
  # PRIORITY=9: an insertion of a specified series of nucleotides at a position in the CDS or PROM (e.g. rpoB_1300_ins_ca)
380
552
  if indel_type=="ins" and indel_length is not None and indel_bases is not None:
381
553
  row=rules.loc[rules_mutation_type_vector & rules_position_vector & (rules.MUTATION==str(position)+"_ins_"+indel_bases)]
382
- row_prediction(row, predictions, 9, "an insertion of a specified series of nucleotides at a position in the CDS or PROM (e.g. rpoB_1300_ins_ca)")
554
+ #an insertion of a specified series of nucleotides at a position in the CDS or PROM (e.g. rpoB_1300_ins_ca)
555
+ row_prediction(row, predictions, 9, minor)
383
556
 
384
557
 
385
- def parse_mutation(gene,mutation):
558
+ def parse_mutation(mutation: str) -> (str, str, str, str, int, str, str, str):
386
559
 
387
560
  """
388
561
  Take a GENE_MUTATION, and determine what type it is, what it affects etc
@@ -458,17 +631,34 @@ def parse_mutation(gene,mutation):
458
631
  if mutation_type=="SNP":
459
632
  sanity_check_snp(before,after)
460
633
 
461
- return(position, mutation_affects, mutation_type, indel_type, indel_length, indel_bases, before, after)
634
+ return position, mutation_affects, mutation_type, indel_type, indel_length, indel_bases, before, after
635
+
636
+ def infer_mutation_affects(position: int) -> str:
637
+ '''Find out which part of the gene this position affects
638
+
639
+ Args:
640
+ position (int): Gene position
462
641
 
463
- def infer_mutation_affects(position):
642
+ Returns:
643
+ str: Either "PROM" or "CDS"
644
+ '''
464
645
 
465
646
  if position<0:
466
647
  mutation_affects="PROM"
467
648
  else:
468
649
  mutation_affects="CDS"
469
- return(mutation_affects)
650
+ return mutation_affects
651
+
652
+ def sanity_check_snp(before: str, after: str) -> None:
653
+ '''Sanity check that a given SNP is valid. i.e check that the bases are valid
470
654
 
471
- def sanity_check_snp(before,after):
655
+ Args:
656
+ before (str): Reference bases/AA
657
+ after (str): Alt bases/AA
658
+
659
+ Raises:
660
+ AssertationError: Raised in cases in which the SNP is invalid.
661
+ '''
472
662
 
473
663
  assert after in ['a','c','t','g','x','z','o','?',"!",'A','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','V','W','X','Y','Z'], after+" is not a recognised amino acid or base!"
474
664
  assert before in ['a','c','t','g','?','!','A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'], before+" is not a recognised amino acid or base!"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: piezo
3
- Version: 0.3
3
+ Version: 0.4
4
4
  Summary: Predicting the effect of an antibiotic from gene mutations
5
5
  Home-page: https://github.com/oxfordmmm/piezo
6
6
  Author: Philip W Fowler
@@ -26,32 +26,29 @@ This code was developed as part of the [CRyPTIC](http://www.crypticproject.org)
26
26
 
27
27
  ## Installation
28
28
 
29
- ### using `pip`
29
+ ### Using `pip`
30
30
 
31
31
  This will install the most recent release on PyPI.
32
32
 
33
33
  ```
34
- $ pip install piezo
35
- $ cd piezo
36
- $ py.test
34
+ pip install piezo
37
35
  ```
38
36
 
39
- ### from GitHub
37
+ ### From GitHub
40
38
 
41
39
  This will install the current version from GitHub and therefore may be ahead of the PyPI version.
42
40
 
43
41
  ```
44
- $ git clone https://github.com/oxfordmmm/piezo
45
- $ cd piezo
46
- $ pip install .
47
- $ py.test
42
+ git clone https://github.com/oxfordmmm/piezo
43
+ cd piezo
44
+ pip install .
48
45
  ```
49
46
  The pre-requisites are all fairly standard and are listed in `setup.cfg` so will be automatically installed.
50
47
 
51
48
  ## Included files
52
49
 
53
50
  ```
54
- $ $ ls tests/test-catalogue/
51
+ $ ls tests/test-catalogue/
55
52
  NC_004148.2.gbk NC_004148.2_TEST_GM1_RFUS_v1.0.csv
56
53
  ```
57
54
  NC_004148 is the reference genome of the human metapneumovirus and is used primarily for unit testing since it is small and fast to parse.
@@ -1,5 +1,6 @@
1
1
  LICENSE
2
2
  README.md
3
+ VERSION
3
4
  pyproject.toml
4
5
  setup.cfg
5
6
  bin/piezo-predict.py
@@ -11,4 +12,5 @@ piezo.egg-info/SOURCES.txt
11
12
  piezo.egg-info/dependency_links.txt
12
13
  piezo.egg-info/not-zip-safe
13
14
  piezo.egg-info/requires.txt
14
- piezo.egg-info/top_level.txt
15
+ piezo.egg-info/top_level.txt
16
+ tests/test_catalogue.py
@@ -0,0 +1,272 @@
1
+ from collections import defaultdict
2
+ import pytest
3
+
4
+ import piezo
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ "test_catalogue,genes,gene_lookup",
9
+ [
10
+ (
11
+ piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv"),
12
+ ['M2', 'N', 'MULTI'],
13
+ {'M2':['DRUG_A','DRUG_B'], 'MULTI': ['DRUG_A', 'DRUG_B'], 'N': ['DRUG_A']}
14
+ ),
15
+ (
16
+ piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv", prediction_subset_only=True),
17
+ ['M2', 'MULTI'],
18
+ {'M2':['DRUG_A','DRUG_B'], 'MULTI': ['DRUG_A', 'DRUG_B']}
19
+ )
20
+ ]
21
+ )
22
+ def test_catalogue__init__(test_catalogue, genes, gene_lookup):
23
+
24
+ assert test_catalogue.catalogue.genbank_reference=="NC_004148.2"
25
+
26
+ assert test_catalogue.catalogue.name=="TEST"
27
+
28
+ assert test_catalogue.catalogue.version=="v1.0"
29
+
30
+ assert test_catalogue.catalogue.values==["R","F","U","S"]
31
+
32
+ assert test_catalogue.catalogue.grammar=="GARC1"
33
+
34
+ assert test_catalogue.catalogue.number_rows == 42
35
+
36
+ assert test_catalogue.catalogue.drugs==['DRUG_A','DRUG_B']
37
+
38
+ #Ordering of lists is annoying here, so sort both
39
+ genes = sorted(genes)
40
+ assert sorted(test_catalogue.catalogue.genes) == genes
41
+
42
+ assert test_catalogue.catalogue.gene_lookup == gene_lookup
43
+
44
+ #Convert the gene_lookup to drug_lookup
45
+ lookup = defaultdict(list)
46
+ for gene in gene_lookup.keys():
47
+ for drug in gene_lookup[gene]:
48
+ lookup[drug].append(gene)
49
+ lookup = {drug: sorted(lookup[drug]) for drug in lookup.keys()}
50
+
51
+ actual_lookup = {drug: sorted(test_catalogue.catalogue.drug_lookup[drug]) for drug in test_catalogue.catalogue.drug_lookup.keys()}
52
+ assert actual_lookup == lookup
53
+
54
+ @pytest.mark.parametrize("test_catalogue", [piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv"), piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv", prediction_subset_only=True)])
55
+ def test_catalogue_prediction_snps(test_catalogue):
56
+
57
+ # check a row in the catalogue
58
+ assert test_catalogue.predict("M2@L73P")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
59
+
60
+ # check a synonymous mutation has no effect
61
+ assert test_catalogue.predict("M2@L73L")=={'DRUG_A': 'S', 'DRUG_B': 'S'}
62
+
63
+ # check a het
64
+ assert test_catalogue.predict("M2@L73Z")=={'DRUG_A': 'F', 'DRUG_B': 'S'}
65
+
66
+ # check a filter fail that will hit the default S rule
67
+ assert test_catalogue.predict("M2@L73O")=={'DRUG_A': 'S', 'DRUG_B': 'S'}
68
+
69
+ # check a null that will hit the default S rule
70
+ assert test_catalogue.predict("M2@L73X")=={'DRUG_A': 'S', 'DRUG_B': 'S'}
71
+
72
+ # check a filter fail that hits a specific rule for DRUG_A
73
+ assert test_catalogue.predict("M2@G74O")=={'DRUG_A': 'F', 'DRUG_B': 'S'}
74
+
75
+ # check a null that hits a specific rule for DRUG_A
76
+ assert test_catalogue.predict("M2@G74X")=={'DRUG_A': 'F', 'DRUG_B': 'S'}
77
+
78
+ # check hitting a wildtype row
79
+ assert test_catalogue.predict("M2@G74I")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
80
+
81
+ assert test_catalogue.predict("M2@G74Z")=={'DRUG_A': 'R', 'DRUG_B': 'S'}
82
+
83
+ assert test_catalogue.predict("M2@G74P")=={'DRUG_A': 'R', 'DRUG_B': 'U'}
84
+
85
+ assert test_catalogue.predict("M2@G74!")=={'DRUG_A': 'S', 'DRUG_B': 'U'}
86
+
87
+ assert test_catalogue.predict("M2@t-15c")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
88
+
89
+ assert test_catalogue.predict("M2@t-15z")=={'DRUG_A': 'S', 'DRUG_B': 'S'}
90
+
91
+ assert test_catalogue.predict("M2@t-15o")=={'DRUG_A': 'F', 'DRUG_B': 'S'}
92
+
93
+ assert test_catalogue.predict("M2@t-15x")=={'DRUG_A': 'F', 'DRUG_B': 'S'}
94
+
95
+ # check that a gene not in the catalogue simply returns an "S"
96
+ assert test_catalogue.predict("N1@S2T")=="S"
97
+
98
+ # bad prediction
99
+ with pytest.raises(Exception):
100
+ assert test_catalogue.predict("M2@L73P")=={'DRUG_A': 'R', 'DRUG_B': 'R'}
101
+
102
+ # incorrect amino acid in the alt position
103
+ with pytest.raises(Exception):
104
+ assert test_catalogue.predict("M2@L73B")
105
+
106
+ # badly formed gene_mutation
107
+ with pytest.raises(Exception):
108
+ assert test_catalogue.predict("M3@K73P_3")
109
+ with pytest.raises(Exception):
110
+ assert test_catalogue.predict("M2@K73t")
111
+ with pytest.raises(Exception):
112
+ assert test_catalogue.predict("M2@a-10a")
113
+ with pytest.raises(Exception):
114
+ assert test_catalogue.predict("M2@a-10A")
115
+ with pytest.raises(Exception):
116
+ assert test_catalogue.predict("M2@T-10a")
117
+
118
+ @pytest.mark.parametrize("test_catalogue", [piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv"), piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv", prediction_subset_only=True)])
119
+ def test_catalogue_prediction_indels(test_catalogue):
120
+
121
+ # check a general indel
122
+ assert test_catalogue.predict("M2@300_indel")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
123
+
124
+ # check an insertion
125
+ assert test_catalogue.predict("M2@300_ins")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
126
+ assert test_catalogue.predict("M2@-10_ins")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
127
+ assert test_catalogue.predict("M2@-10_ins_2")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
128
+
129
+ # check a deletion
130
+ assert test_catalogue.predict("M2@300_del")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
131
+
132
+ # check numbered insertions and deletions
133
+ assert test_catalogue.predict("M2@300_ins_6")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
134
+ assert test_catalogue.predict("M2@300_del_6")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
135
+
136
+ # check a specific insertion
137
+ assert test_catalogue.predict("M2@300_ins_acc")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
138
+
139
+ assert test_catalogue.predict("M2@100_indel")=={'DRUG_A': 'R', 'DRUG_B': 'U'}
140
+ assert test_catalogue.predict("M2@100_ins")=={'DRUG_A': 'R', 'DRUG_B': 'U'}
141
+ assert test_catalogue.predict("M2@100_ins_3")=={'DRUG_A': 'R', 'DRUG_B': 'U'}
142
+ assert test_catalogue.predict("M2@100_ins_act")=={'DRUG_A': 'R', 'DRUG_B': 'U'}
143
+
144
+
145
+ # check these hit the frameshift rule
146
+ assert test_catalogue.predict("M2@100_ins_1")=={'DRUG_A': 'R', 'DRUG_B': 'R'}
147
+ assert test_catalogue.predict("M2@100_ins_acta")=={'DRUG_A': 'R', 'DRUG_B': 'R'}
148
+ assert test_catalogue.predict("M2@100_ins_400")=={'DRUG_A': 'R', 'DRUG_B': 'R'}
149
+ assert test_catalogue.predict("M2@100_ins_actgactg")=={'DRUG_A': 'R', 'DRUG_B': 'R'}
150
+ assert test_catalogue.predict("M2@300_ins_61")=={'DRUG_A': 'U', 'DRUG_B': 'R'}
151
+ assert test_catalogue.predict("M2@300_del_65")=={'DRUG_A': 'U', 'DRUG_B': 'R'}
152
+ assert test_catalogue.predict("M2@300_ins_acctt")=={'DRUG_A': 'U', 'DRUG_B': 'R'}
153
+
154
+ # badly formed INDELs
155
+ with pytest.raises(Exception):
156
+ assert test_catalogue.predict("M2@300_indel_5")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
157
+ with pytest.raises(Exception):
158
+ assert test_catalogue.predict("M2@300_indel_-5")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
159
+ with pytest.raises(Exception):
160
+ assert test_catalogue.predict("M2@300_insdel")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
161
+ with pytest.raises(Exception):
162
+ assert test_catalogue.predict("M2@300_del_ACT")=={'DRUG_A': 'U', 'DRUG_B': 'U'}
163
+
164
+ @pytest.mark.parametrize("test_catalogue", [piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv"), piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv", prediction_subset_only=True)])
165
+ def test_multi(test_catalogue):
166
+ #Exact match with 2 lines of the catalogue
167
+ assert test_catalogue.predict("M2@G74!&M2@G74X") == {"DRUG_A": "U", "DRUG_B": "R"}
168
+
169
+ #Should hit an 'S' (and 'U' default) and an 'R'
170
+ assert test_catalogue.predict("M2@F75T&M2@G74P") == {"DRUG_A": 'R', "DRUG_B": 'U'}
171
+
172
+ #Should hit an 'F' and an 'R' (and 'U' default)
173
+ assert test_catalogue.predict("M2@L73Z&M2@G74P") == {"DRUG_A": 'R', 'DRUG_B': 'U'}
174
+
175
+ #Shouldn't hit anything other than 'S'
176
+ assert test_catalogue.predict("M2@A5A&M2@K6K") == 'S'
177
+
178
+ @pytest.mark.parametrize("test_catalogue", [piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv"), piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv", prediction_subset_only=True)])
179
+ def test_minor_population(test_catalogue):
180
+ #COV
181
+ #Exact match
182
+ assert test_catalogue.predict("M2@F75V:2") == {"DRUG_A": "R", "DRUG_B": "U"}
183
+
184
+ #Greater than
185
+ assert test_catalogue.predict("M2@F75V:3") == {"DRUG_A": "R", "DRUG_B": "U"}
186
+ assert test_catalogue.predict("M2@F75V:4") == {"DRUG_A": "R", "DRUG_B": "U"}
187
+ assert test_catalogue.predict("M2@F75V:350") == {"DRUG_A": "R", "DRUG_B": "U"}
188
+ assert test_catalogue.predict("M2@F75V:123456789123456789") == {"DRUG_A": "R", "DRUG_B": "U"}
189
+
190
+ #Less than (so should just hit a default for now)
191
+ assert test_catalogue.predict("M2@F75V:1") == {"DRUG_A": "U", "DRUG_B": "U"}
192
+
193
+ #Should fail
194
+ with pytest.raises(Exception):
195
+ test_catalogue.predict("M2@F75V:0")
196
+ with pytest.raises(Exception):
197
+ test_catalogue.predict("M2@F75V:-1")
198
+
199
+ #Multi
200
+ assert test_catalogue.predict("M2@45_del_aaa:6&M2@F75V:5") == {"DRUG_A": 'R', 'DRUG_B': 'U'}
201
+ assert test_catalogue.predict("M2@45_del_a:2&M2@F75V:3") == {"DRUG_A": 'R', 'DRUG_B': 'R'}
202
+
203
+ #FRS
204
+ test_catalogue2 = piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS-FRS.csv")
205
+
206
+ #Exact match
207
+ assert test_catalogue2.predict("M2@F75V:0.03") == {"DRUG_A": "R", "DRUG_B": "U"}
208
+
209
+ #Greater than
210
+ assert test_catalogue2.predict("M2@F75V:0.04") == {"DRUG_A": "R", "DRUG_B": "U"}
211
+ assert test_catalogue2.predict("M2@F75V:0.05") == {"DRUG_A": "R", "DRUG_B": "U"}
212
+ assert test_catalogue2.predict("M2@F75V:0.9") == {"DRUG_A": "R", "DRUG_B": "U"}
213
+ assert test_catalogue2.predict("M2@F75V:0.123456789123456789") == {"DRUG_A": "R", "DRUG_B": "U"}
214
+
215
+ #Less than (so should just hit a default for now)
216
+ assert test_catalogue2.predict("M2@F75V:0.01") == {"DRUG_A": "U", "DRUG_B": "U"}
217
+ assert test_catalogue2.predict("M2@F75V:0.02") == {"DRUG_A": "U", "DRUG_B": "U"}
218
+
219
+ #Should fail
220
+ with pytest.raises(Exception):
221
+ test_catalogue2.predict("M2@F75V:0.0")
222
+ with pytest.raises(Exception):
223
+ test_catalogue2.predict("M2@F75V:-0.1")
224
+
225
+ assert test_catalogue2.predict("M2@45_del_aaa:0.01&M2@F75V:0.5") == {"DRUG_A": 'R', 'DRUG_B': 'U'}
226
+ assert test_catalogue2.predict("M2@45_del_a:0.12&M2@F75V:0.03") == {"DRUG_A": 'R', 'DRUG_B': 'R'}
227
+
228
+ assert test_catalogue.predict("M2@G74!:4&M2@G74X:2") == {"DRUG_B": "U"}
229
+ assert test_catalogue2.predict("M2@G74!:0.04&M2@G74X:0.02") == {"DRUG_B": "U"}
230
+
231
+ def test_misc():
232
+ '''Testing various edge cases
233
+ '''
234
+ test_catalogue = piezo.ResistanceCatalogue("tests/test-catalogue/NC_004148.2_TEST_v1.0_GARC1_RFUS.csv")
235
+
236
+ #Genes not in the catalogue should default to 'S'
237
+ assert test_catalogue.predict("K@g-7a") == 'S'
238
+ assert test_catalogue.predict("K@g-7a&K@S6L") == 'S'
239
+
240
+ #Our catalogue doesn't have default rules for 'N'
241
+ #So should cause errors
242
+ with pytest.raises(ValueError):
243
+ test_catalogue.predict("N@K45L")
244
+
245
+ #Malformed minor mutation should cause issues
246
+ with pytest.raises(AssertionError):
247
+ test_catalogue.predict("M2@F75V:nope")
248
+
249
+ #Trying with catalogues with issues, each hitting a different ValueError
250
+ with pytest.raises(ValueError):
251
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue.csv")
252
+
253
+ with pytest.raises(ValueError):
254
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue2.csv")
255
+
256
+ with pytest.raises(ValueError):
257
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue3.csv")
258
+
259
+ with pytest.raises(ValueError):
260
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue4.csv")
261
+
262
+ with pytest.raises(ValueError):
263
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue5.csv")
264
+
265
+ with pytest.raises(ValueError):
266
+ piezo.ResistanceCatalogue("tests/test-catalogue/broken-catalogue6.csv")
267
+
268
+ #Checking for deprication warnings
269
+ with pytest.warns(UserWarning):
270
+ test_catalogue.predict("M2@L73P", verbose=True)
271
+
272
+
@@ -1,5 +0,0 @@
1
- #! /usr/bin/env python
2
-
3
- # -*- coding: utf-8 -*-
4
-
5
- from .catalogue import ResistanceCatalogue
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes