pipemake-utils 0.1.1__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.

Potentially problematic release.


This version of pipemake-utils might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Kocher Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: pipemake_utils
3
+ Version: 0.1.1
4
+ Summary: Pipemake Utilities
5
+ Home-page: https://github.com/kocherlab/pipemake_utils
6
+ License: MIT
7
+ Project-URL: Code, https://github.com/kocherlab/pipemake_utils
8
+ Project-URL: Issue tracker, https://github.com/kocherlab/pipemake_utils/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/x-rst
11
+ License-File: LICENSE
12
+ Requires-Dist: biopython
13
+ Requires-Dist: gffutils
14
+ Requires-Dist: pandas
15
+
16
+ Pipemake Utilities
17
+ ==================
18
+
19
+ Basic utilities for Pipemake images
@@ -0,0 +1,4 @@
1
+ Pipemake Utilities
2
+ ==================
3
+
4
+ Basic utilities for Pipemake images
@@ -0,0 +1,16 @@
1
+ import sys
2
+
3
+ # Basic Information
4
+ __name__ = "pipemake_utils"
5
+ __version__ = "0.1.1"
6
+ __summary__ = "Pipemake Utilities"
7
+ __url__ = "https://github.com/kocherlab/pipemake_utils"
8
+ __code__ = "https://github.com/kocherlab/pipemake_utils"
9
+ __issue__ = "https://github.com/kocherlab/pipemake_utils/issues"
10
+ __docs__ = ""
11
+ __license__ = "MIT"
12
+ __copyright__ = "2023"
13
+
14
+ # Author Information
15
+ __authors__ = "Andrew Webb and Sarah Kocher"
16
+ __email__ = "19213578+aewebb80@users.noreply.github.com"
@@ -0,0 +1,56 @@
1
+ import sys
2
+ import argparse
3
+
4
+ import pandas as pd
5
+ import numpy as np
6
+
7
+ from pipemake_utils.misc import *
8
+ from pipemake_utils.logger import *
9
+
10
+ def argParser ():
11
+
12
+ parser = argparse.ArgumentParser(description = 'Filter GEMMA output')
13
+
14
+ parser.add_argument('--gemma-file', help = 'GEMMA output file', type = str, action = confirmFile(), required = True)
15
+ parser.add_argument('--min-log-pvalue', help = 'Minimum -log10(p-value) to keep', type = float, default = 0.5)
16
+ parser.add_argument('--out-prefix', help = 'Output prefix', type = str, default = 'out')
17
+ parser.add_argument('--pvalue-col', help = 'P-value column to filter', type = str, default = 'p_wald')
18
+ parser.add_argument('--chrom-col', help = 'CRHOM column', type = str, default = 'chr')
19
+ parser.add_argument('--pos-col', help = 'POS column', type = str, default = 'ps')
20
+
21
+ return vars(parser.parse_args())
22
+
23
+ def main():
24
+
25
+ # Parse the arguments
26
+ filter_args = argParser()
27
+
28
+ # Start logger and log the arguments
29
+ startLogger(f"{filter_args['out_prefix']}.filtered.log")
30
+ logArgDict(filter_args)
31
+
32
+ # Open the GEMMA output as a dataframe
33
+ gemma_dataframe = pd.read_csv(filter_args['gemma_file'], sep = '\t')
34
+
35
+ # Assign the name of the -log10(p-value) columns
36
+ log_y_col = f"-log10({filter_args['pvalue_col']})"
37
+
38
+ # Create the -log10(p-value) columns using the p-values
39
+ gemma_dataframe[log_y_col] = -np.log10(gemma_dataframe[filter_args['pvalue_col']])
40
+ gemma_dataframe[log_y_col] = gemma_dataframe[log_y_col].fillna(0)
41
+
42
+ # Store the number of rows before filtering
43
+ pre_filter_values = gemma_dataframe.shape[0]
44
+
45
+ logging.info(f"Filtering GEMMA column {log_y_col} to remove p-values less than {filter_args['min_log_pvalue']}")
46
+
47
+ # Filter the GEMMA dataset
48
+ gemma_dataframe = gemma_dataframe[(gemma_dataframe[log_y_col] >= filter_args['min_log_pvalue'])]
49
+
50
+ logging.info(f"Filtering complete: Removed {pre_filter_values - gemma_dataframe.shape[0]} values ({gemma_dataframe.shape[0]} remaining)")
51
+
52
+ # Save the filtered GEMMA dataset
53
+ gemma_dataframe.to_csv(f"{filter_args['out_prefix']}.filtered.assoc.txt", sep = '\t', index = False)
54
+
55
+ if __name__ == '__main__':
56
+ main()
@@ -0,0 +1,51 @@
1
+ import logging
2
+ import sys
3
+
4
+ def startLogger (log_filename = None, filemode = 'w'):
5
+
6
+ # Close any old loggers
7
+ for handler in logging.root.handlers[:]:
8
+ handler.close()
9
+ logging.root.removeHandler(handler)
10
+
11
+ # Star the logger
12
+ if log_filename: logging.basicConfig(filename = log_filename, filemode = filemode, level = 'INFO', format = '%(asctime)s - %(levelname)s: %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
13
+ else: logging.basicConfig(stream = sys.stdout, level = 'INFO', format = '%(asctime)s - %(levelname)s: %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
14
+
15
+ # Start logging to stdout
16
+ stdout_log = logging.StreamHandler()
17
+
18
+ # Assign the stdout logging level
19
+ stdout_log.setLevel(logging.WARNING)
20
+
21
+ # Define the stdout format
22
+ console_format = logging.Formatter('%(funcName)s - %(levelname)s: %(message)s')
23
+
24
+ # Assign the format
25
+ stdout_log.setFormatter(console_format)
26
+
27
+ # Add the stdout handler
28
+ logging.getLogger('').addHandler(stdout_log)
29
+
30
+ # Update the exception handler to log the exception
31
+ def expHandler(etype,val,tb):
32
+
33
+ # Log the error
34
+ logging.error("%s" % (val), exc_info=(etype,val,tb))
35
+
36
+ # Update the exception hook
37
+ sys.excepthook = expHandler
38
+
39
+ def logArgDict (arg_dict, print_undefined = False, omit = []):
40
+
41
+ # Loop the arguments
42
+ for arg, value in arg_dict.items():
43
+
44
+ # Skip arg if in omit list
45
+ if arg in omit: continue
46
+
47
+ # Report only defined arguments, unless print_undefined is True
48
+ if value is None and not print_undefined: continue
49
+
50
+ # Log the argument
51
+ logging.info('Argument %s: %s' % (arg, value))
@@ -0,0 +1,12 @@
1
+ import os
2
+ import argparse
3
+
4
+ def confirmFile ():
5
+
6
+ # Custom action to confirm file exists
7
+ class customAction(argparse.Action):
8
+ def __call__(self, parser, args, value, option_string=None):
9
+ if not os.path.isfile(value): raise IOError(f'Unable to locate file: {value}')
10
+ setattr(args, self.dest, value)
11
+
12
+ return customAction
@@ -0,0 +1,469 @@
1
+ import os
2
+ import sys
3
+ import json
4
+ import logging
5
+ import itertools
6
+ import copy
7
+
8
+ import numpy as np
9
+
10
+ from collections import defaultdict, OrderedDict
11
+
12
+ class ModelFile(dict):
13
+ def __init__(self, *arg, **kw):
14
+ super(ModelFile, self).__init__(*arg, **kw)
15
+ self.inds = []
16
+ self.ind_file = ''
17
+ self.exclude_file = ''
18
+
19
+ if arg and self.confirm_model_instance(arg[1]):
20
+ self.update_inds(arg[1])
21
+
22
+ def __setitem__(self, *arg, **kw):
23
+ super(ModelFile, self).__setitem__(*arg, **kw)
24
+
25
+ if arg and self.confirm_model_instance(arg[1]):
26
+ self.update_inds(model = arg[1])
27
+
28
+ def __delitem__(self, key):
29
+ super(ModelFile, self).__delitem__(key)
30
+ self.update_inds()
31
+
32
+ def confirm_model_instance (self, unknown):
33
+
34
+ if isinstance(unknown, Model):
35
+
36
+ return True
37
+
38
+ else:
39
+
40
+ return False
41
+
42
+ def copy_model (self, src_model_name, new_model_name):
43
+
44
+ src_model = super(ModelFile, self).__getitem__(src_model_name)
45
+
46
+ src_model_copy = copy.deepcopy(src_model)
47
+
48
+ src_model_copy.name = new_model_name
49
+
50
+ super(ModelFile, self).__setitem__(new_model_name, src_model_copy)
51
+
52
+ def rename_model (self, src_model_name, new_model_name):
53
+
54
+ src_model = super(ModelFile, self).pop(src_model_name)
55
+
56
+ src_model.name = new_model_name
57
+
58
+ super(ModelFile, self).__setitem__(new_model_name, src_model)
59
+
60
+ def update_inds (self, model = None):
61
+
62
+ if self.confirm_model_instance(model):
63
+
64
+ # Return error if inds is empty
65
+ if not model.inds:
66
+ raise IOError('No individuals found in %s.' % model.name)
67
+
68
+ # Create a list of the unique individuals
69
+ unique_inds = list(set(self.inds + model.inds))
70
+
71
+ else:
72
+
73
+ # Create an empty list for the unique individuals
74
+ unique_inds = []
75
+
76
+ # Loop the models in the file
77
+ for model_in_file in super(ModelFile, self).values():
78
+
79
+ # Create a list of the unique individuals
80
+ unique_inds = list(set(unique_inds + model_in_file.inds))
81
+
82
+
83
+ # Store the individuals
84
+ self.inds = unique_inds
85
+
86
+ def create_ind_file (self, file_ext = '', file_path = '', overwrite = False):
87
+ # Assign the filename for the population file
88
+ ind_filename = 'unique_individuals' + file_ext
89
+
90
+ # If a path is assigned, create the file at the specified location
91
+ if file_path:
92
+ ind_filename = os.path.join(file_path, ind_filename)
93
+
94
+ # Check if previous files should be overwriten
95
+ if not overwrite:
96
+ # Check if the file already exists
97
+ if os.path.isfile(ind_filename):
98
+ raise IOError('Individuals file exists. Use --overwrite to ignore')
99
+
100
+ # Create the population file
101
+ ind_file = open(ind_filename, 'w')
102
+ ind_file.write('%s\n' %'\n'.join(self.inds))
103
+ ind_file.close()
104
+
105
+ # Save the individuals filename
106
+ self.ind_file = ind_filename
107
+
108
+ def delete_ind_file (self):
109
+ # Check if an individuals file was created
110
+ if self.ind_file:
111
+
112
+ # Delete the individuals file
113
+ os.remove(self.ind_file)
114
+
115
+ # Remove the filename
116
+ self.ind_file = ''
117
+
118
+ def create_exclude_ind_file (self, inds_to_include = [], file_ext = '', file_path = '', overwrite = False):
119
+ # Assign the filename for the population file
120
+ ind_filename = 'exclude_individuals' + file_ext
121
+
122
+ # If a path is assigned, create the file at the specified location
123
+ if file_path:
124
+ ind_filename = os.path.join(file_path, ind_filename)
125
+
126
+ # Check if previous files should be overwriten
127
+ if not overwrite:
128
+ # Check if the file already exists
129
+ if os.path.isfile(ind_filename):
130
+ raise IOError('Individuals file exists.')
131
+
132
+ # Create exclude list by removing included individuals
133
+ exclude_inds = list(set(self.inds) - set(inds_to_include))
134
+
135
+ # Create the population file
136
+ ind_file = open(ind_filename, 'w')
137
+ ind_file.write('%s\n' %'\n'.join(exclude_inds))
138
+ ind_file.close()
139
+
140
+ # Save the individuals filename
141
+ self.exclude_file = ind_filename
142
+
143
+ def delete_exclude_ind_file (self):
144
+ # Check if an individuals file was created
145
+ if self.exclude_file:
146
+
147
+ # Delete the individuals file
148
+ os.remove(self.exclude_file)
149
+
150
+ # Remove the filename
151
+ self.exclude_file = ''
152
+
153
+ def to_json (self):
154
+
155
+ model_file_json = []
156
+
157
+ for model_name, model_data in super(ModelFile, self).items():
158
+ model_file_json.append(model_data.to_json())
159
+
160
+ return model_file_json
161
+
162
+ class Model:
163
+ def __init__ (self, name):
164
+ self.name = name
165
+ self.tree = ''
166
+ self.pop_list = []
167
+ self.ind_dict = defaultdict(list)
168
+ self.nind = defaultdict(int)
169
+ self.pop_files = []
170
+ self.ind_file = ''
171
+
172
+ def __str__ (self):
173
+ return self.name
174
+
175
+ @property
176
+ def npop (self):
177
+ return len(self.pop_list)
178
+
179
+ @property
180
+ def inds (self):
181
+ return list(itertools.chain.from_iterable(self.ind_dict.values()))
182
+
183
+ def assign_tree (self, tree):
184
+ self.tree = str(tree)
185
+
186
+ def assign_pop (self, pop, inds = []):
187
+ self.pop_list.append(str(pop))
188
+ if inds:
189
+ self.ind_dict[pop] = [str(ind) for ind in inds]
190
+ self.nind[pop] = len(self.ind_dict[pop])
191
+
192
+ def remove_pop (self, pop):
193
+
194
+ # Confirm the pop is in the model
195
+ if str(pop) not in self.pop_list:
196
+
197
+ # Raise error if pop not found
198
+ raise Exception('%s not found' % pop)
199
+
200
+ self.pop_list.remove(str(pop))
201
+ del self.ind_dict[pop]
202
+ del self.nind[pop]
203
+
204
+ def update_pop (self, pop, inds = [], rm_inds = []):
205
+
206
+ # Confirm the pop is in the model
207
+ if str(pop) not in self.pop_list:
208
+
209
+ # Raise error if pop not found
210
+ raise Exception('%s not found' % pop)
211
+
212
+ if inds:
213
+ self.ind_dict[pop].extend([str(ind) for ind in inds])
214
+
215
+ if rm_inds:
216
+ for rm_ind in rm_inds:
217
+ if str(rm_ind) in self.ind_dict[pop]:
218
+ self.ind_dict[pop].remove(str(rm_ind))
219
+
220
+ self.nind[pop] = len(self.ind_dict[pop])
221
+
222
+ def sample_pop (self, pop, sample_size, with_replacements = False):
223
+
224
+ # Confirm the pop is in the model
225
+ if str(pop) not in self.pop_list:
226
+
227
+ # Raise error if pop not found
228
+ raise Exception('%s not found' % pop)
229
+
230
+ # Confirm the sample size is an int
231
+ try:
232
+
233
+ sample_size = int(sample_size)
234
+
235
+ except:
236
+
237
+ # Raise error if sample_size not an int
238
+ raise Exception('%s not int' % sample_size)
239
+
240
+ # Check if the sample size is larger than the pop
241
+ if int(sample_size) > self.nind[pop]:
242
+
243
+ # Raise error if sample_size is larger
244
+ raise Exception('%s is larger than %s' % (sample_size, pop))
245
+
246
+ # Use numpy choice to randomly sample the pop
247
+ sampled_inds = np.random.choice(self.ind_dict[pop], sample_size, replace = with_replacements)
248
+
249
+ # Save the sampled inds as a list
250
+ self.ind_dict[pop] = list(sampled_inds)
251
+
252
+ def sample_pops (self, sample_size, with_replacements = False):
253
+
254
+ # Confirm the sample size is an int
255
+ try:
256
+
257
+ sample_size = int(sample_size)
258
+
259
+ except:
260
+
261
+ # Raise error if sample_size not an int
262
+ raise Exception('%s not int' % sample_size)
263
+
264
+ # Loop each pop in the pop list
265
+ for pop in self.pop_list:
266
+
267
+ # Check if the sample size is larger than the pop
268
+ if int(sample_size) > self.nind[pop]:
269
+
270
+ # Raise error if sample_size is larger
271
+ raise Exception('%s is larger than %s' % (sample_size, pop))
272
+
273
+ # Loop each pop in the pop list, if no error raised
274
+ for pop in self.pop_list:
275
+
276
+ # Use numpy choice to randomly sample the pop
277
+ sampled_inds = np.random.choice(self.ind_dict[pop], sample_size, replace = with_replacements)
278
+
279
+ # Save the sampled inds as a list
280
+ self.ind_dict[pop] = list(sampled_inds)
281
+
282
+ def create_pop_files (self, file_ext = '', file_path = '', overwrite = False):
283
+ for pop in self.pop_list:
284
+ # Assign the filename for the population file
285
+ pop_filename = pop + file_ext
286
+
287
+ # If a path is assigned, create the file at the specified location
288
+ if file_path:
289
+ pop_filename = os.path.join(file_path, pop_filename)
290
+
291
+ # Check if previous files should be overwriten
292
+ if not overwrite:
293
+ # Check if the file already exists
294
+ if os.path.isfile(pop_filename):
295
+ raise IOError('Population file exists.')
296
+
297
+ # Create the population file
298
+ pop_file = open(pop_filename, 'w')
299
+ pop_file.write('%s\n' %'\n'.join(self.ind_dict[pop]))
300
+ pop_file.close()
301
+
302
+ # Save the population filename
303
+ self.pop_files.append(pop_filename)
304
+
305
+ logging.info('Population files created for %s' % self)
306
+
307
+ def delete_pop_files (self):
308
+ # Check if pop files were created
309
+ if len(self.pop_files) != 0:
310
+
311
+ # Loop the created pop files
312
+ for pop_file in self.pop_files:
313
+ # Delete the pop file
314
+ os.remove(pop_file)
315
+
316
+ # Remove the filenames
317
+ self.pop_files = []
318
+
319
+ logging.info('Population files deleted for %s' % self)
320
+
321
+ def create_ind_file (self, file_ext = '', file_path = '', overwrite = False):
322
+ # Assign the filename for the population file
323
+ ind_filename = 'individual.keep' + file_ext
324
+
325
+ # If a path is assigned, create the file at the specified location
326
+ if file_path:
327
+ ind_filename = os.path.join(file_path, ind_filename)
328
+
329
+ # Check if previous files should be overwriten
330
+ if not overwrite:
331
+ # Check if the file already exists
332
+ if os.path.isfile(ind_filename):
333
+ raise IOError('Individuals file exists.')
334
+
335
+ # Create the population file
336
+ ind_file = open(ind_filename, 'w')
337
+ ind_file.write('%s\n' %'\n'.join(self.inds))
338
+ ind_file.close()
339
+
340
+ # Save the individuals filename
341
+ self.ind_file = ind_filename
342
+
343
+ logging.info('Individuals file created for %s' % self)
344
+
345
+ def delete_ind_file (self):
346
+ # Check if an individuals file was created
347
+ if self.ind_file:
348
+
349
+ # Delete the individuals file
350
+ os.remove(self.ind_file)
351
+
352
+ # Remove the filename
353
+ self.ind_file = ''
354
+
355
+ logging.info('Individuals file deleted for %s' % self)
356
+
357
+ def to_json (self):
358
+
359
+ model_json = OrderedDict()
360
+
361
+ model_json['name'] = self.name
362
+
363
+ pop_json = OrderedDict()
364
+
365
+ model_json['tree'] = self.tree
366
+
367
+ for pop in self.pop_list:
368
+
369
+ pop_json[pop] = OrderedDict()
370
+
371
+ pop_json[pop]['inds'] = self.ind_dict[pop]
372
+
373
+ model_json['pops'] = pop_json
374
+
375
+ return model_json
376
+
377
+ def return_pop (self, ind):
378
+
379
+ # Loop the pops within the model
380
+ for pop, inds in self.ind_dict.items():
381
+
382
+ # Check if the ind belongs to the pop
383
+ if ind in inds:
384
+
385
+ return pop
386
+
387
+ raise Exception('Individual (%s) not found within %s' % (ind, self.name))
388
+
389
+ def readModelFile (filename):
390
+ """
391
+ returns a ModelFile, which is a dictionary
392
+ """
393
+
394
+ # Check that the file exists
395
+ if not os.path.isfile(filename):
396
+ raise IOError
397
+
398
+ # Create ModelFile object
399
+ models_to_return = ModelFile()
400
+
401
+ # Check if using python 2 or 3
402
+ if sys.version_info[0] == 2:
403
+ # Open the model file in python 2
404
+ model_file = open(filename, 'rU')
405
+ else:
406
+ # Open the model file in python 3
407
+ model_file = open(filename, 'r', newline=None)
408
+
409
+ # Parse the model file using the json reader
410
+ models_dict = json.load(model_file)
411
+ model_file.close()
412
+
413
+ # List to store all unique individuals (i.e. individuals in all models)
414
+ individual_list = []
415
+
416
+ # Loop the parsed models
417
+ for model_dict in models_dict:
418
+
419
+ # Create the model
420
+ model = Model(str(model_dict['name']))
421
+
422
+ # Check if model has a tree
423
+ if 'tree' in model_dict:
424
+
425
+ # Assign the model tree
426
+ model.assign_tree(model_dict['tree'])
427
+
428
+ # Loop the populations in the model
429
+ for pop, pop_dict in model_dict['pops'].items():
430
+
431
+ # Convert all individuals names to str
432
+ ind_list = [str(pop_ind) for pop_ind in pop_dict['inds']]
433
+
434
+ # Assign the population ans it's individuals to the model
435
+ model.assign_pop(str(pop), ind_list)
436
+
437
+ # Assign the individuals to the unique individual list
438
+ individual_list.extend(ind_list)
439
+
440
+ # Remove duplicates from the unique individual list
441
+ individual_list = list(set(individual_list))
442
+
443
+ # Save the model
444
+ models_to_return[str(model.name)] = model
445
+
446
+ logging.info('Finished reading model file (%s)' % filename)
447
+
448
+ # Return the models
449
+ return models_to_return
450
+
451
+ def writeModelFile (model_file, filename, overwrite = False):
452
+
453
+ # Check if the file is to be overwritten
454
+ if not overwrite:
455
+
456
+ # Check if the file exists
457
+ if os.path.exists(filename):
458
+ raise Exception('%s already exists' % filename)
459
+
460
+ # Open the output file
461
+ output_file = open(filename, 'w')
462
+
463
+ # Write the json-formmated data to the output file
464
+ output_file.write(json.dumps(model_file.to_json(), indent = 4))
465
+
466
+ # Close the output file
467
+ output_file.close()
468
+
469
+ logging.info('Finished writing model file (%s)' % filename)
@@ -0,0 +1,41 @@
1
+ import argparse
2
+
3
+ import pandas as pd
4
+
5
+ from pipemake_utils.misc import *
6
+ from pipemake_utils.logger import *
7
+ from pipemake_utils.model import readModelFile
8
+
9
+ def argParser ():
10
+
11
+ # Create argument parser
12
+ parser = argparse.ArgumentParser(description = 'Create a file of the individuals from a model category')
13
+ parser.add_argument('--model', help = 'The model file', type = str, action = confirmFile(), required = True)
14
+ parser.add_argument('--model-category', help = 'The category to assign from the model file', type = str, required = True)
15
+ parser.add_argument('--out-prefix', help = 'The output prefix', type = str, default = 'out')
16
+
17
+ # Parse the arguments
18
+ return vars(parser.parse_args())
19
+
20
+ def main():
21
+
22
+ # Parse the arguments
23
+ map_args = argParser()
24
+
25
+ # Start logger and log the arguments
26
+ startLogger(f"{map_args['out_prefix']}.ind.log")
27
+ logArgDict(map_args)
28
+
29
+ # Assign the category
30
+ models = readModelFile(map_args['model'])
31
+ model_category = models[map_args['model_category']]
32
+
33
+ # Print the individuals to a file
34
+ with open(f"{map_args['out_prefix']}.ind.txt", 'w') as ind_file:
35
+ for inds in model_category.ind_dict.values():
36
+ for ind in inds:
37
+ ind_file.write(f"{ind}\n")
38
+ logging.info(f"Added {ind} to {map_args['out_prefix']}.ind.txt")
39
+
40
+ if __name__ == '__main__':
41
+ main()
@@ -0,0 +1,79 @@
1
+ import argparse
2
+
3
+ import pandas as pd
4
+
5
+ from pipemake_utils.misc import *
6
+ from pipemake_utils.logger import *
7
+ from pipemake_utils.model import readModelFile
8
+
9
+ def argParser ():
10
+
11
+ # Create argument parser
12
+ parser = argparse.ArgumentParser(description = 'Update plink fam file with model category information')
13
+ parser.add_argument('--fam', help = 'The plink table', type = str, action = confirmFile(), required = True)
14
+ parser.add_argument('--model', help = 'The model file', type = str, action = confirmFile(), required = True)
15
+ parser.add_argument('--model-category', help = 'The category to assign from the model file', type = str, required = True)
16
+ parser.add_argument('--categories-limit', help = 'The total number of categories allowed', type = int, default = 2)
17
+ parser.add_argument('--out-prefix', help = 'The output prefix', type = str, default = 'out')
18
+
19
+ # Parse the arguments
20
+ return vars(parser.parse_args())
21
+
22
+ def mapCategory (row, category_map):
23
+
24
+ # Assign the individual
25
+ row_ind = row[1]
26
+
27
+ # Check if the individual is in the map
28
+ if row_ind not in category_map: raise Exception(f"Individual ({row_ind}) not found in the category map")
29
+
30
+ # Map the category
31
+ row_category = category_map[row_ind]
32
+
33
+ # Update the row
34
+ row[5] = row_category
35
+
36
+ logging.info(f"Mapped individual: {row_ind} to {row_category}")
37
+
38
+ return row
39
+
40
+ def main():
41
+
42
+ # Parse the arguments
43
+ map_args = argParser()
44
+
45
+ # Start logger and log the arguments
46
+ startLogger(f"{map_args['out_prefix']}.pheno.log")
47
+ logArgDict(map_args)
48
+
49
+ # Assign the category
50
+ models = readModelFile(map_args['model'])
51
+ model_category = models[map_args['model_category']]
52
+
53
+ # Store the categorys
54
+ categories = list(model_category.ind_dict)
55
+
56
+ # Create a dictionary to map the individual to the category
57
+ ind_to_categories = {}
58
+
59
+ # Map the individuals to the categories and log the information
60
+ for category_idx, (category_str, inds) in enumerate(model_category.ind_dict.items(), 1):
61
+ logging.info(f"Mapping: {category_str} to {category_idx}")
62
+ for ind in inds:
63
+ ind_to_categories[ind] = category_idx
64
+
65
+ # Read the plink table
66
+ plink_table = pd.read_csv(map_args['fam'], sep = ' ', header = None)
67
+
68
+ # Map the categories
69
+ plink_table = plink_table.apply(mapCategory, category_map = ind_to_categories, axis = 1)
70
+
71
+ # Confirm that the categories were mapped
72
+ if len(plink_table[5].unique()) != map_args['categories_limit']:
73
+ raise Exception(f"Categories ({', '.join(categories)}) greater than the limit: {map_args['categories_limit']}")
74
+
75
+ # Save the updated plink table
76
+ plink_table[5].to_csv(f"{map_args['out_prefix']}.pheno.txt", sep = ' ', header = False, index = False)
77
+
78
+ if __name__ == '__main__':
79
+ main()
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import gffutils
7
+
8
+ from Bio import SeqIO
9
+ from itertools import chain
10
+ from collections import defaultdict
11
+
12
+ def processParser ():
13
+
14
+ def confirmFile ():
15
+ '''Custom action to confirm file exists'''
16
+ class customAction(argparse.Action):
17
+ def __call__(self, parser, args, value, option_string=None):
18
+ if not os.path.isfile(value):
19
+ raise IOError(f'Unable to find file: {value}')
20
+ setattr(args, self.dest, value)
21
+ return customAction
22
+
23
+ # Create the parser
24
+ process_parser = argparse.ArgumentParser(description="process-braker: Confirm and process BRAKER3 output")
25
+
26
+ process_parser.add_argument("--fasta-aa", help = "BRAKER3 amino acid fasta filename", type = str, action = confirmFile(), required = True)
27
+ process_parser.add_argument("--fasta-cds", help = "BRAKER3 CDS fasta filename", type = str, action = confirmFile(), required = True)
28
+ process_parser.add_argument("--gff", help = "BRAKER3 gff3 filename", type = str, action = confirmFile(), required = True)
29
+ process_parser.add_argument("--species", help = "Species", type = str, required = True)
30
+ process_parser.add_argument("--assembly-version", help = "Assembly version", type = str, required = True)
31
+ process_parser.add_argument("--annotation-version", help = "Annotation version", type = str, required = True)
32
+ process_parser.add_argument("--out-dir", help = "Output directory", type = str, required = True)
33
+
34
+ return vars(process_parser.parse_args())
35
+
36
+ def createSeqList (filename, seq_format = 'fasta'):
37
+
38
+ # Create dict to IDs
39
+ id_dict = defaultdict(list)
40
+
41
+ # Read the fasta and store gene and transcript IDs
42
+ for transcript_record in SeqIO.parse(filename, seq_format):
43
+ gene_id, _ = transcript_record.id.split('.')
44
+ id_dict[gene_id].append(transcript_record.id)
45
+
46
+ return id_dict
47
+
48
+ def checkGFF (gff_filename, id_dict):
49
+
50
+ # Store DB in memory
51
+ gff_db = gffutils.create_db(gff_filename, ':memory:')
52
+
53
+ # Create set of expected features
54
+ expected_features = set(['gene', 'mRNA', 'CDS', 'exon', 'intron', 'start_codon', 'stop_codon'])
55
+
56
+ # Create set of the features within the gff
57
+ gff_features = set(gff_db.featuretypes())
58
+ if expected_features != gff_features:
59
+ raise Exception (f'Unable to match GFF features: {gff_features}\n Expected: {expected_features}')
60
+
61
+ # Loop the ID dict confirm they match the GFF
62
+ for gene_id, transcript_list in id_dict.items():
63
+
64
+ # Load the gene, if possible
65
+ try: gff_gene = gff_db[gene_id]
66
+ except: raise Exception (f'Unable to locate ID in gff: {gene_id}')
67
+
68
+ # Create list of the transcripts of the gene
69
+ gff_mrna = [gff_mrna['ID'] for gff_mrna in gff_db.children(gff_gene, featuretype='mRNA')]
70
+ gff_mrna = set(chain.from_iterable(gff_mrna))
71
+
72
+ # Confirm the mRNA IDs match
73
+ if set(transcript_list) != gff_mrna:
74
+ raise Exception (f'Unable to match mRNA IDs between: {set(transcript_list)} and {gff_mrna}')
75
+
76
+ def createNewIDCvtDict (id_list, annotations_prefix):
77
+
78
+ # Create dict to IDs
79
+ new_id_cvt_dict = defaultdict(list)
80
+
81
+ # Assign the number of characters to justify
82
+ id_char_len = len(str(len(id_list)))
83
+
84
+ # Loop the ID list
85
+ for id_counter, id_str in enumerate(id_list, 1):
86
+
87
+ # Create the new ID
88
+ new_id = f"{annotations_prefix}_{str(id_counter).rjust(id_char_len, '0')}"
89
+
90
+ # Add new ID to the dict
91
+ new_id_cvt_dict[id_str] = new_id
92
+
93
+ return new_id_cvt_dict
94
+
95
+ def updateSeqFile (filename, id_cvt_dict, out_filename, seq_format = 'fasta'):
96
+
97
+ # Open the sequence output filename
98
+ with open(out_filename, 'w') as out_file:
99
+
100
+ # Read the fasta and store gene and transcript IDs
101
+ for transcript_record in SeqIO.parse(filename, seq_format):
102
+
103
+ # Assign the gene ID
104
+ gene_id, _ = transcript_record.id.split('.')
105
+
106
+ # Update the record
107
+ transcript_record.description = ''
108
+ transcript_record.id = transcript_record.id.replace(f"{gene_id}.", f"{id_cvt_dict[gene_id]}-")
109
+
110
+ # Add the updated record to the output file
111
+ SeqIO.write(transcript_record, out_file, seq_format)
112
+
113
+ def updateGFF (filename, id_cvt_dict, out_filename):
114
+
115
+ def attributesDict (attributes_str):
116
+
117
+ attributes_dict = {}
118
+
119
+ for attribute_str in attributes_str.split(';'):
120
+ if not attribute_str: continue
121
+ attribute_key, attribute_value = attribute_str.split('=')
122
+ attributes_dict[attribute_key] = attribute_value
123
+
124
+ return attributes_dict
125
+
126
+ # Open the gff output filename
127
+ out_file = open(out_filename, 'w')
128
+
129
+ # Store the old and new gene id
130
+ old_gene_id = None
131
+ new_gene_id = None
132
+
133
+ with open(filename, 'r') as gff_input:
134
+ for feature_line in gff_input:
135
+
136
+ # Write the header/comments to the out file
137
+ if feature_line.startswith('#'):
138
+ out_file.write(feature_line)
139
+ continue
140
+
141
+ # Assign the basic information of the current feature line
142
+ _, _, feature_type, _, _, _, _, _, feature_attributes_str = feature_line.strip().split('\t')
143
+
144
+ # Assign the gene ID and update the feature
145
+ if feature_type == 'gene':
146
+
147
+ # Assign the gene attributes
148
+ gene_attributes_dict = attributesDict(feature_attributes_str)
149
+
150
+ # Confirm the ID was found
151
+ if 'ID' not in gene_attributes_dict:
152
+ raise Exception (f'Unable to assign gene ID from: {feature_attributes_str}')
153
+
154
+ # Confirm the ID is within the conversion dict
155
+ if gene_attributes_dict['ID'] not in id_cvt_dict:
156
+ raise Exception (f"Unable to convert gene ID: {gene_attributes_dict['ID']}")
157
+
158
+ # Update the old and new gene IDs
159
+ old_gene_id = gene_attributes_dict['ID']
160
+ new_gene_id = id_cvt_dict[old_gene_id]
161
+
162
+ # Update the feature line
163
+ feature_line = feature_line.replace(old_gene_id, new_gene_id)
164
+
165
+ else:
166
+
167
+ # Update the feature line
168
+ feature_line = feature_line.replace(f'{old_gene_id}.', f'{new_gene_id}-')
169
+ feature_line = feature_line.replace(old_gene_id, new_gene_id)
170
+
171
+ # Write the updated feature line
172
+ out_file.write(feature_line)
173
+
174
+ # Close the output file
175
+ out_file.close()
176
+
177
+ def main():
178
+
179
+ # Assign the process args
180
+ process_args = processParser()
181
+
182
+ # Create an ID list from the amino acid sequences
183
+ aa_id_dict = createSeqList(process_args['fasta_aa'])
184
+
185
+ # Create an ID list from the CDS
186
+ cds_id_dict = createSeqList(process_args['fasta_cds'])
187
+
188
+ # Confirm the amino acid and CDS IDs are the same
189
+ if aa_id_dict != cds_id_dict:
190
+ raise Exception (f'Unable to match IDs between: {prot_filename} and {transcript_filename}')
191
+
192
+ # Confirm the GFF matches the sequence files
193
+ checkGFF(process_args['gff'], aa_id_dict)
194
+
195
+ # Assign the annotations prefix
196
+ annotations_prefix = f"{process_args['species']}_{process_args['assembly_version']}.{process_args['annotation_version']}"
197
+
198
+ # Create the new ID conversion dict
199
+ new_id_cvt_dict = createNewIDCvtDict(aa_id_dict, annotations_prefix)
200
+
201
+ # Create the output directory, if it does not alraady exits
202
+ if not os.path.exists(process_args['out_dir']): os.makedirs(process_args['out_dir'])
203
+
204
+ # Create the output filename prefix
205
+ out_prefix = os.path.join(process_args['out_dir'], f"{process_args['species']}_OGS_{process_args['assembly_version']}.{process_args['annotation_version']}")
206
+
207
+ # Update the sequence files
208
+ updateSeqFile(process_args['fasta_aa'], new_id_cvt_dict, f'{out_prefix}_pep.fa')
209
+ updateSeqFile(process_args['fasta_cds'], new_id_cvt_dict, f'{out_prefix}_trans.fa')
210
+
211
+ # Update the GFF
212
+ updateGFF(process_args['gff'], new_id_cvt_dict, f'{out_prefix}.gff3')
213
+
214
+ if __name__ == '__main__':
215
+ main()
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: pipemake_utils
3
+ Version: 0.1.1
4
+ Summary: Pipemake Utilities
5
+ Home-page: https://github.com/kocherlab/pipemake_utils
6
+ License: MIT
7
+ Project-URL: Code, https://github.com/kocherlab/pipemake_utils
8
+ Project-URL: Issue tracker, https://github.com/kocherlab/pipemake_utils/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/x-rst
11
+ License-File: LICENSE
12
+ Requires-Dist: biopython
13
+ Requires-Dist: gffutils
14
+ Requires-Dist: pandas
15
+
16
+ Pipemake Utilities
17
+ ==================
18
+
19
+ Basic utilities for Pipemake images
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.rst
3
+ setup.py
4
+ pipemake_utils/__init__.py
5
+ pipemake_utils/filter_gemma.py
6
+ pipemake_utils/logger.py
7
+ pipemake_utils/misc.py
8
+ pipemake_utils/model.py
9
+ pipemake_utils/model_category_inds.py
10
+ pipemake_utils/ped_phenotype_file.py
11
+ pipemake_utils/process_braker.py
12
+ pipemake_utils.egg-info/PKG-INFO
13
+ pipemake_utils.egg-info/SOURCES.txt
14
+ pipemake_utils.egg-info/dependency_links.txt
15
+ pipemake_utils.egg-info/entry_points.txt
16
+ pipemake_utils.egg-info/requires.txt
17
+ pipemake_utils.egg-info/top_level.txt
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ filter-gemma = pipemake_utils.filter_gemma:main
3
+ model-category-inds = pipemake_utils.model_category_inds:main
4
+ ped-phenotype-file = pipemake_utils.ped_phenotype_file:main
5
+ process-braker = pipemake_utils.process_braker:main
@@ -0,0 +1,3 @@
1
+ biopython
2
+ gffutils
3
+ pandas
@@ -0,0 +1 @@
1
+ pipemake_utils
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ import io
2
+ import os
3
+
4
+ from setuptools import setup
5
+
6
+ import pipemake_utils
7
+
8
+ with io.open("README.rst", "rt", encoding="utf8") as f:
9
+ readme = f.read()
10
+
11
+ # Read requirements.txt
12
+ lib_folder = os.path.dirname(os.path.realpath(__file__))
13
+ requirement_path = lib_folder + "/requirements.txt"
14
+ requirements = []
15
+ if os.path.isfile(requirement_path):
16
+ with open(requirement_path) as f:
17
+ requirements = f.read().splitlines()
18
+
19
+ setup(
20
+ name=pipemake_utils.__name__,
21
+ version=pipemake_utils.__version__,
22
+ project_urls={
23
+ # "Documentation": pipemake_utils.__docs__,
24
+ "Code": pipemake_utils.__code__,
25
+ "Issue tracker": pipemake_utils.__issue__,
26
+ },
27
+ license=pipemake_utils.__license__,
28
+ url=pipemake_utils.__url__,
29
+ description=pipemake_utils.__summary__,
30
+ long_description_content_type="text/x-rst",
31
+ long_description=readme,
32
+ packages=["pipemake_utils"],
33
+ install_requires=requirements,
34
+ entry_points={
35
+ "console_scripts": [
36
+ "process-braker=pipemake_utils.process_braker:main",
37
+ "ped-phenotype-file=pipemake_utils.ped_phenotype_file:main",
38
+ "model-category-inds = pipemake_utils.model_category_inds:main",
39
+ "filter-gemma = pipemake_utils.filter_gemma:main"
40
+ ],
41
+ },
42
+ python_requires=">=3.7",
43
+ )