gsrap 0.8.2__py3-none-any.whl → 0.9.0__py3-none-any.whl

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.
Files changed (29) hide show
  1. gsrap/.ipynb_checkpoints/__init__-checkpoint.py +2 -0
  2. gsrap/__init__.py +2 -0
  3. gsrap/assets/kegg_compound_to_others.pickle +0 -0
  4. gsrap/assets/kegg_reaction_to_others.pickle +0 -0
  5. gsrap/commons/.ipynb_checkpoints/downloads-checkpoint.py +96 -4
  6. gsrap/commons/.ipynb_checkpoints/escherutils-checkpoint.py +72 -1
  7. gsrap/commons/.ipynb_checkpoints/excelhub-checkpoint.py +2 -2
  8. gsrap/commons/downloads.py +96 -4
  9. gsrap/commons/escherutils.py +72 -1
  10. gsrap/commons/excelhub.py +2 -2
  11. gsrap/getmaps/.ipynb_checkpoints/getmaps-checkpoint.py +14 -5
  12. gsrap/getmaps/.ipynb_checkpoints/kdown-checkpoint.py +75 -4
  13. gsrap/getmaps/getmaps.py +14 -5
  14. gsrap/getmaps/kdown.py +75 -4
  15. gsrap/parsedb/.ipynb_checkpoints/annotation-checkpoint.py +9 -0
  16. gsrap/parsedb/.ipynb_checkpoints/completeness-checkpoint.py +45 -11
  17. gsrap/parsedb/.ipynb_checkpoints/manual-checkpoint.py +10 -0
  18. gsrap/parsedb/.ipynb_checkpoints/parsedb-checkpoint.py +40 -19
  19. gsrap/parsedb/.ipynb_checkpoints/repeating-checkpoint.py +2 -2
  20. gsrap/parsedb/annotation.py +9 -0
  21. gsrap/parsedb/completeness.py +45 -11
  22. gsrap/parsedb/manual.py +10 -0
  23. gsrap/parsedb/parsedb.py +40 -19
  24. gsrap/parsedb/repeating.py +2 -2
  25. {gsrap-0.8.2.dist-info → gsrap-0.9.0.dist-info}/METADATA +1 -1
  26. {gsrap-0.8.2.dist-info → gsrap-0.9.0.dist-info}/RECORD +29 -29
  27. {gsrap-0.8.2.dist-info → gsrap-0.9.0.dist-info}/LICENSE.txt +0 -0
  28. {gsrap-0.8.2.dist-info → gsrap-0.9.0.dist-info}/WHEEL +0 -0
  29. {gsrap-0.8.2.dist-info → gsrap-0.9.0.dist-info}/entry_points.txt +0 -0
@@ -75,12 +75,14 @@ def main():
75
75
  parsedb_parser.add_argument("-z", "--initialize", metavar='', type=str, default='-', help="Initialize the universe on the provided medium. By default, the first medium in --media is used. Use 'none' to avoid initialization.")
76
76
  parsedb_parser.add_argument("--precursors", action='store_true', help="Verify biosynthesis of biomass precursors and show blocked ones.")
77
77
  parsedb_parser.add_argument("--biosynth", action='store_true', help="Check biosynthesis of all metabolites and detect dead-ends.")
78
+ parsedb_parser.add_argument("-t", "--taxon", metavar='', type=str, default='-', help="High-level taxon of interest. If provided, it must follow the syntax '{level}:{name}', where {level} is 'kingdom' or 'phylum'.")
78
79
  parsedb_parser.add_argument("-e", "--eggnog", nargs='+', metavar='', type=str, default='-', help="Path to the optional eggnog-mapper annotation table(s).")
79
80
  parsedb_parser.add_argument("-k", "--keggorg", metavar='', type=str, default='-', help="A single KEGG Organism code. If provided, it takes precedence over --eggnog.")
80
81
  parsedb_parser.add_argument("--goodbefore", metavar='', type=str, default='-', help="Syntax is {pure_mid}-{rid1}-{rid2}. From top to bottom, build the universe until reaction {rid1}, transport {rid2} and metabolite {pure_mid} are reached.")
81
82
  parsedb_parser.add_argument("--onlyauthor", metavar='', type=str, default='-', help="Build the universe by parsing contents of the specified author ID only. Contents affected by --goodbefore are parsed anyway.")
82
83
  parsedb_parser.add_argument("--nofigs", action='store_true', help="Do not generate figures.")
83
84
  parsedb_parser.add_argument("-j", "--justparse", action='store_true', help="Just parse the database without performing extra activities (saves time during universe expansion).")
85
+ parsedb_parser.add_argument("-d", "--keepdisconn", action='store_true', help="Do not remove disconnected metabolites.")
84
86
 
85
87
 
86
88
 
gsrap/__init__.py CHANGED
@@ -75,12 +75,14 @@ def main():
75
75
  parsedb_parser.add_argument("-z", "--initialize", metavar='', type=str, default='-', help="Initialize the universe on the provided medium. By default, the first medium in --media is used. Use 'none' to avoid initialization.")
76
76
  parsedb_parser.add_argument("--precursors", action='store_true', help="Verify biosynthesis of biomass precursors and show blocked ones.")
77
77
  parsedb_parser.add_argument("--biosynth", action='store_true', help="Check biosynthesis of all metabolites and detect dead-ends.")
78
+ parsedb_parser.add_argument("-t", "--taxon", metavar='', type=str, default='-', help="High-level taxon of interest. If provided, it must follow the syntax '{level}:{name}', where {level} is 'kingdom' or 'phylum'.")
78
79
  parsedb_parser.add_argument("-e", "--eggnog", nargs='+', metavar='', type=str, default='-', help="Path to the optional eggnog-mapper annotation table(s).")
79
80
  parsedb_parser.add_argument("-k", "--keggorg", metavar='', type=str, default='-', help="A single KEGG Organism code. If provided, it takes precedence over --eggnog.")
80
81
  parsedb_parser.add_argument("--goodbefore", metavar='', type=str, default='-', help="Syntax is {pure_mid}-{rid1}-{rid2}. From top to bottom, build the universe until reaction {rid1}, transport {rid2} and metabolite {pure_mid} are reached.")
81
82
  parsedb_parser.add_argument("--onlyauthor", metavar='', type=str, default='-', help="Build the universe by parsing contents of the specified author ID only. Contents affected by --goodbefore are parsed anyway.")
82
83
  parsedb_parser.add_argument("--nofigs", action='store_true', help="Do not generate figures.")
83
84
  parsedb_parser.add_argument("-j", "--justparse", action='store_true', help="Just parse the database without performing extra activities (saves time during universe expansion).")
85
+ parsedb_parser.add_argument("-d", "--keepdisconn", action='store_true', help="Do not remove disconnected metabolites.")
84
86
 
85
87
 
86
88
 
Binary file
Binary file
@@ -243,7 +243,99 @@ def format_expansion(logger, eggnog):
243
243
 
244
244
 
245
245
 
246
-
247
-
248
-
249
-
246
+ def check_taxon(logger, taxon, idcollection_dict):
247
+
248
+
249
+ # verify presence of needed assets
250
+ if 'ko_to_taxa' not in idcollection_dict.keys():
251
+ logger.error(f"Asset 'ko_to_taxa' not found in 'gsrap.maps'. Please update 'gsrap.maps' with 'gsrap getmaps'.")
252
+ return 1
253
+
254
+
255
+ # extract level and name
256
+ try: level, name = taxon.split(':')
257
+ except:
258
+ logger.error(f"Provided --taxon is not well formatted: '{taxon}'.")
259
+ return 1
260
+
261
+
262
+ # compute available levels and check
263
+ avail_levels = set(['kingdom', 'phylum'])
264
+ if level not in avail_levels:
265
+ logger.error(f"Provided level is not acceptable: '{level}' (see --taxon). Acceptable levels are {avail_levels}.")
266
+ return 1
267
+
268
+
269
+ # compute available taxa at input level
270
+ avail_taxa_at_level = set()
271
+ ko_to_taxa = idcollection_dict['ko_to_taxa']
272
+ for ko in ko_to_taxa.keys():
273
+ for taxon_name in ko_to_taxa[ko][level]:
274
+ avail_taxa_at_level.add(taxon_name)
275
+ if name not in avail_taxa_at_level:
276
+ logger.error(f"Provided taxon name is not acceptable: '{name}' (see --taxon). Acceptable taxon names for level '{level}' are {avail_taxa_at_level}.")
277
+ return 1
278
+
279
+
280
+ """
281
+ sorted(list(df.query("kingdom == 'Bacteria'")['phylum'].unique()))
282
+ ['Acidobacteriota',
283
+ 'Actinomycetota',
284
+ 'Alphaproteobacteria',
285
+ 'Aquificota',
286
+ 'Armatimonadota',
287
+ 'Atribacterota',
288
+ 'Bacilli',
289
+ 'Bacteria incertae sedis',
290
+ 'Bacteroidota',
291
+ 'Balneolota',
292
+ 'Bdellovibrionota',
293
+ 'Betaproteobacteria',
294
+ 'Caldisericota',
295
+ 'Calditrichota',
296
+ 'Campylobacterota',
297
+ 'Chlamydiota',
298
+ 'Chlorobiota',
299
+ 'Chloroflexota',
300
+ 'Chrysiogenota',
301
+ 'Cloacimonadota',
302
+ 'Clostridia',
303
+ 'Coprothermobacterota',
304
+ 'Cyanobacteriota',
305
+ 'Deferribacterota',
306
+ 'Deinococcota',
307
+ 'Deltaproteobacteria',
308
+ 'Dictyoglomota',
309
+ 'Elusimicrobiota',
310
+ 'Enterobacteria',
311
+ 'Fibrobacterota',
312
+ 'Fidelibacterota',
313
+ 'Fusobacteriota',
314
+ 'Gemmatimonadota',
315
+ 'Ignavibacteriota',
316
+ 'Kiritimatiellota',
317
+ 'Lentisphaerota',
318
+ 'Melainabacteria',
319
+ 'Mycoplasmatota',
320
+ 'Myxococcota',
321
+ 'Nitrospinota',
322
+ 'Nitrospirota',
323
+ 'Omnitrophota',
324
+ 'Planctomycetota',
325
+ 'Rhodothermota',
326
+ 'Spirochaetota',
327
+ 'Synergistota',
328
+ 'Thermodesulfobacteriota',
329
+ 'Thermodesulfobiota',
330
+ 'Thermomicrobiota',
331
+ 'Thermosulfidibacterota',
332
+ 'Thermotogota',
333
+ 'Verrucomicrobiota',
334
+ 'Vulcanimicrobiota',
335
+ 'other Bacillota',
336
+ 'other Gammaproteobacteria',
337
+ 'other Pseudomonadota',
338
+ 'unclassified Bacteria']
339
+ """
340
+
341
+ return 0
@@ -1,3 +1,9 @@
1
+ import warnings
2
+ import logging
3
+
4
+
5
+ import cobra
6
+
1
7
 
2
8
 
3
9
  def print_json_tree(data, level=0, max_level=2):
@@ -17,7 +23,7 @@ def print_json_tree(data, level=0, max_level=2):
17
23
 
18
24
 
19
25
 
20
- def count_undrawn_rids(logger, universe, lastmap):
26
+ def count_undrawn_rids(logger, universe, lastmap, focus):
21
27
 
22
28
 
23
29
  rids = set([r.id for r in universe.reactions])
@@ -32,6 +38,71 @@ def count_undrawn_rids(logger, universe, lastmap):
32
38
  logger.debug(f"Last universal map version detected: '{filename}'.")
33
39
  if len(remainings) > 0:
34
40
  logger.warning(f"Our universal map is {len(remainings)} reactions behind. Please draw!")
41
+ if focus == '-':
42
+ logger.warning(f"Drawing is eased when using '--focus'...")
35
43
  else:
36
44
  logger.info(f"Our universal map is {len(remainings)} reactions behind. Thank you ♥")
45
+
46
+
47
+
48
+ def count_undrawn_rids_focus(logger, universe, lastmap, focus, outdir):
49
+
50
+
51
+ # get modeled reads for this --focus:
52
+ rids = set()
53
+ try: gr = universe.groups.get_by_id(focus)
54
+ except:
55
+ logger.warning(f"Group '{focus}' not found!")
56
+ return
57
+ for r in gr.members:
58
+ rids.add(r.id)
59
+
60
+
61
+ # get rids on Escher:
62
+ drawn_rids = set()
63
+ for key, value in lastmap['json'][1]['reactions'].items():
64
+ drawn_rids.add(value['bigg_id'])
65
+
66
+
67
+ # get remaining rids for this map:
68
+ remainings = rids - drawn_rids
69
+ remainings_krs = set()
70
+ for rid in remainings:
71
+ r = universe.reactions.get_by_id(rid)
72
+ krs = r.annotation['kegg.reaction']
73
+ for kr in krs:
74
+ remainings_krs.add(kr)
75
+
76
+
77
+ if len(remainings) > 0:
78
+ if focus != 'transport':
79
+ logger.warning(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind: {' '.join(list(remainings_krs))}.")
80
+ else:
81
+ logger.warning(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind.") # usually no kegg codes for tranport reactions
82
+
83
+
84
+ # subset the universe to ease the drawing:
85
+ universe_focus = universe.copy()
86
+ to_remove = [r for r in universe_focus.reactions if r.id not in rids]
87
+
88
+
89
+ # trick to avoid the WARNING "cobra/core/group.py:147: UserWarning: need to pass in a list"
90
+ # triggered when trying to remove reactions that are included in groups.
91
+ with warnings.catch_warnings(): # temporarily suppress warnings for this block
92
+ warnings.simplefilter("ignore") # ignore all warnings
93
+ cobra_logger = logging.getLogger("cobra.util.solver")
94
+ old_level = cobra_logger.level
95
+ cobra_logger.setLevel(logging.ERROR)
96
+
97
+ universe_focus.remove_reactions(to_remove,remove_orphans=True)
98
+
99
+ # restore original behaviour:
100
+ cobra_logger.setLevel(old_level)
101
+
102
+
103
+ # save the subset for drawing in Escher!
104
+ logger.info(f"Writing '{outdir}/{focus}.json' to ease your drawing workflow...")
105
+ cobra.io.save_json_model(universe_focus, f'{outdir}/{focus}.json')
106
+ else:
107
+ logger.info(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind. Thank you ♥")
37
108
 
@@ -148,7 +148,7 @@ def write_excel_model(model, filepath, nofigs, memote_results_dict, df_E, df_B,
148
148
  else: df_T.append(row_dict)
149
149
 
150
150
  for g in model.genes:
151
- row_dict = {'gid': g.id, 'involved_in': '; '.join([r.id for r in g.reactions])}
151
+ row_dict = {'gid': g.id, 'name': g.name, 'involved_in': '; '.join([r.id for r in g.reactions])}
152
152
 
153
153
  for db in g.annotation.keys():
154
154
  annots = g.annotation[db]
@@ -171,7 +171,7 @@ def write_excel_model(model, filepath, nofigs, memote_results_dict, df_E, df_B,
171
171
  df_R = df_R[df_R_first_cols + sorted([c for c in df_R.columns if c not in df_R_first_cols])]
172
172
  df_T = df_T[df_R_first_cols + sorted([c for c in df_T.columns if c not in df_R_first_cols])]
173
173
  df_A = df_A[df_R_first_cols + sorted([c for c in df_A.columns if c not in df_R_first_cols])]
174
- df_G_first_cols = ['gid', 'involved_in']
174
+ df_G_first_cols = ['gid', 'name', 'involved_in']
175
175
  df_G = df_G[df_G_first_cols + sorted([c for c in df_G.columns if c not in df_G_first_cols])]
176
176
 
177
177
 
@@ -243,7 +243,99 @@ def format_expansion(logger, eggnog):
243
243
 
244
244
 
245
245
 
246
-
247
-
248
-
249
-
246
+ def check_taxon(logger, taxon, idcollection_dict):
247
+
248
+
249
+ # verify presence of needed assets
250
+ if 'ko_to_taxa' not in idcollection_dict.keys():
251
+ logger.error(f"Asset 'ko_to_taxa' not found in 'gsrap.maps'. Please update 'gsrap.maps' with 'gsrap getmaps'.")
252
+ return 1
253
+
254
+
255
+ # extract level and name
256
+ try: level, name = taxon.split(':')
257
+ except:
258
+ logger.error(f"Provided --taxon is not well formatted: '{taxon}'.")
259
+ return 1
260
+
261
+
262
+ # compute available levels and check
263
+ avail_levels = set(['kingdom', 'phylum'])
264
+ if level not in avail_levels:
265
+ logger.error(f"Provided level is not acceptable: '{level}' (see --taxon). Acceptable levels are {avail_levels}.")
266
+ return 1
267
+
268
+
269
+ # compute available taxa at input level
270
+ avail_taxa_at_level = set()
271
+ ko_to_taxa = idcollection_dict['ko_to_taxa']
272
+ for ko in ko_to_taxa.keys():
273
+ for taxon_name in ko_to_taxa[ko][level]:
274
+ avail_taxa_at_level.add(taxon_name)
275
+ if name not in avail_taxa_at_level:
276
+ logger.error(f"Provided taxon name is not acceptable: '{name}' (see --taxon). Acceptable taxon names for level '{level}' are {avail_taxa_at_level}.")
277
+ return 1
278
+
279
+
280
+ """
281
+ sorted(list(df.query("kingdom == 'Bacteria'")['phylum'].unique()))
282
+ ['Acidobacteriota',
283
+ 'Actinomycetota',
284
+ 'Alphaproteobacteria',
285
+ 'Aquificota',
286
+ 'Armatimonadota',
287
+ 'Atribacterota',
288
+ 'Bacilli',
289
+ 'Bacteria incertae sedis',
290
+ 'Bacteroidota',
291
+ 'Balneolota',
292
+ 'Bdellovibrionota',
293
+ 'Betaproteobacteria',
294
+ 'Caldisericota',
295
+ 'Calditrichota',
296
+ 'Campylobacterota',
297
+ 'Chlamydiota',
298
+ 'Chlorobiota',
299
+ 'Chloroflexota',
300
+ 'Chrysiogenota',
301
+ 'Cloacimonadota',
302
+ 'Clostridia',
303
+ 'Coprothermobacterota',
304
+ 'Cyanobacteriota',
305
+ 'Deferribacterota',
306
+ 'Deinococcota',
307
+ 'Deltaproteobacteria',
308
+ 'Dictyoglomota',
309
+ 'Elusimicrobiota',
310
+ 'Enterobacteria',
311
+ 'Fibrobacterota',
312
+ 'Fidelibacterota',
313
+ 'Fusobacteriota',
314
+ 'Gemmatimonadota',
315
+ 'Ignavibacteriota',
316
+ 'Kiritimatiellota',
317
+ 'Lentisphaerota',
318
+ 'Melainabacteria',
319
+ 'Mycoplasmatota',
320
+ 'Myxococcota',
321
+ 'Nitrospinota',
322
+ 'Nitrospirota',
323
+ 'Omnitrophota',
324
+ 'Planctomycetota',
325
+ 'Rhodothermota',
326
+ 'Spirochaetota',
327
+ 'Synergistota',
328
+ 'Thermodesulfobacteriota',
329
+ 'Thermodesulfobiota',
330
+ 'Thermomicrobiota',
331
+ 'Thermosulfidibacterota',
332
+ 'Thermotogota',
333
+ 'Verrucomicrobiota',
334
+ 'Vulcanimicrobiota',
335
+ 'other Bacillota',
336
+ 'other Gammaproteobacteria',
337
+ 'other Pseudomonadota',
338
+ 'unclassified Bacteria']
339
+ """
340
+
341
+ return 0
@@ -1,3 +1,9 @@
1
+ import warnings
2
+ import logging
3
+
4
+
5
+ import cobra
6
+
1
7
 
2
8
 
3
9
  def print_json_tree(data, level=0, max_level=2):
@@ -17,7 +23,7 @@ def print_json_tree(data, level=0, max_level=2):
17
23
 
18
24
 
19
25
 
20
- def count_undrawn_rids(logger, universe, lastmap):
26
+ def count_undrawn_rids(logger, universe, lastmap, focus):
21
27
 
22
28
 
23
29
  rids = set([r.id for r in universe.reactions])
@@ -32,6 +38,71 @@ def count_undrawn_rids(logger, universe, lastmap):
32
38
  logger.debug(f"Last universal map version detected: '{filename}'.")
33
39
  if len(remainings) > 0:
34
40
  logger.warning(f"Our universal map is {len(remainings)} reactions behind. Please draw!")
41
+ if focus == '-':
42
+ logger.warning(f"Drawing is eased when using '--focus'...")
35
43
  else:
36
44
  logger.info(f"Our universal map is {len(remainings)} reactions behind. Thank you ♥")
45
+
46
+
47
+
48
+ def count_undrawn_rids_focus(logger, universe, lastmap, focus, outdir):
49
+
50
+
51
+ # get modeled reads for this --focus:
52
+ rids = set()
53
+ try: gr = universe.groups.get_by_id(focus)
54
+ except:
55
+ logger.warning(f"Group '{focus}' not found!")
56
+ return
57
+ for r in gr.members:
58
+ rids.add(r.id)
59
+
60
+
61
+ # get rids on Escher:
62
+ drawn_rids = set()
63
+ for key, value in lastmap['json'][1]['reactions'].items():
64
+ drawn_rids.add(value['bigg_id'])
65
+
66
+
67
+ # get remaining rids for this map:
68
+ remainings = rids - drawn_rids
69
+ remainings_krs = set()
70
+ for rid in remainings:
71
+ r = universe.reactions.get_by_id(rid)
72
+ krs = r.annotation['kegg.reaction']
73
+ for kr in krs:
74
+ remainings_krs.add(kr)
75
+
76
+
77
+ if len(remainings) > 0:
78
+ if focus != 'transport':
79
+ logger.warning(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind: {' '.join(list(remainings_krs))}.")
80
+ else:
81
+ logger.warning(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind.") # usually no kegg codes for tranport reactions
82
+
83
+
84
+ # subset the universe to ease the drawing:
85
+ universe_focus = universe.copy()
86
+ to_remove = [r for r in universe_focus.reactions if r.id not in rids]
87
+
88
+
89
+ # trick to avoid the WARNING "cobra/core/group.py:147: UserWarning: need to pass in a list"
90
+ # triggered when trying to remove reactions that are included in groups.
91
+ with warnings.catch_warnings(): # temporarily suppress warnings for this block
92
+ warnings.simplefilter("ignore") # ignore all warnings
93
+ cobra_logger = logging.getLogger("cobra.util.solver")
94
+ old_level = cobra_logger.level
95
+ cobra_logger.setLevel(logging.ERROR)
96
+
97
+ universe_focus.remove_reactions(to_remove,remove_orphans=True)
98
+
99
+ # restore original behaviour:
100
+ cobra_logger.setLevel(old_level)
101
+
102
+
103
+ # save the subset for drawing in Escher!
104
+ logger.info(f"Writing '{outdir}/{focus}.json' to ease your drawing workflow...")
105
+ cobra.io.save_json_model(universe_focus, f'{outdir}/{focus}.json')
106
+ else:
107
+ logger.info(f"Focusing on '{focus}', our universal map is {len(remainings)} reactions behind. Thank you ♥")
37
108
 
gsrap/commons/excelhub.py CHANGED
@@ -148,7 +148,7 @@ def write_excel_model(model, filepath, nofigs, memote_results_dict, df_E, df_B,
148
148
  else: df_T.append(row_dict)
149
149
 
150
150
  for g in model.genes:
151
- row_dict = {'gid': g.id, 'involved_in': '; '.join([r.id for r in g.reactions])}
151
+ row_dict = {'gid': g.id, 'name': g.name, 'involved_in': '; '.join([r.id for r in g.reactions])}
152
152
 
153
153
  for db in g.annotation.keys():
154
154
  annots = g.annotation[db]
@@ -171,7 +171,7 @@ def write_excel_model(model, filepath, nofigs, memote_results_dict, df_E, df_B,
171
171
  df_R = df_R[df_R_first_cols + sorted([c for c in df_R.columns if c not in df_R_first_cols])]
172
172
  df_T = df_T[df_R_first_cols + sorted([c for c in df_T.columns if c not in df_R_first_cols])]
173
173
  df_A = df_A[df_R_first_cols + sorted([c for c in df_A.columns if c not in df_R_first_cols])]
174
- df_G_first_cols = ['gid', 'involved_in']
174
+ df_G_first_cols = ['gid', 'name', 'involved_in']
175
175
  df_G = df_G[df_G_first_cols + sorted([c for c in df_G.columns if c not in df_G_first_cols])]
176
176
 
177
177
 
@@ -4,6 +4,7 @@ import pickle
4
4
 
5
5
 
6
6
  from .kdown import download_raw_txtfiles
7
+ from .kdown import create_dict_keggorg
7
8
  from .kdown import create_dict_ko
8
9
  from .kdown import create_dict_c
9
10
  from .kdown import create_dict_r
@@ -20,13 +21,19 @@ def do_kdown(logger, outdir, usecache, keeptmp):
20
21
  logger.info(f"Respectfully retrieving metabolic information from KEGG. Raw data are being saved into '{outdir}/kdown/'. Be patient, could take a couple of days...")
21
22
  os.makedirs(f'{outdir}/kdown/', exist_ok=True)
22
23
 
24
+
23
25
  response = download_raw_txtfiles(logger, outdir, usecache)
24
26
  if type(response) == int: return 1
25
27
  else: RELEASE_kegg = response
26
28
 
29
+
27
30
 
28
31
  logger.info("Parsing downloaded KEGG information...")
29
-
32
+
33
+ response = create_dict_keggorg(logger, outdir)
34
+ if type(response) == int: return 1
35
+ else: dict_keggorg = response
36
+
30
37
  response = create_dict_ko(logger, outdir)
31
38
  if type(response) == int: return 1
32
39
  else: dict_ko = response
@@ -49,7 +56,7 @@ def do_kdown(logger, outdir, usecache, keeptmp):
49
56
 
50
57
 
51
58
  # create 'idcollection_dict' and 'summary_dict' dictionaries
52
- idcollection_dict = create_idcollection_dict(dict_ko, dict_c, dict_r, dict_map, dict_md)
59
+ idcollection_dict = create_idcollection_dict(dict_keggorg, dict_ko, dict_c, dict_r, dict_map, dict_md)
53
60
  summary_dict = create_summary_dict(dict_c, dict_r, dict_map, dict_md)
54
61
 
55
62
 
@@ -57,7 +64,6 @@ def do_kdown(logger, outdir, usecache, keeptmp):
57
64
 
58
65
 
59
66
 
60
-
61
67
  def main(args, logger):
62
68
 
63
69
 
@@ -67,7 +73,7 @@ def main(args, logger):
67
73
  os.makedirs(f'{args.outdir}/', exist_ok=True)
68
74
 
69
75
 
70
- # KEGG
76
+ # KEGG download
71
77
  response = do_kdown(logger, args.outdir, args.usecache, args.keeptmp)
72
78
  if type(response) == int: return 1
73
79
  else: RELEASE_kegg, idcollection_dict, summary_dict = response[0], response[1], response[2]
@@ -76,7 +82,9 @@ def main(args, logger):
76
82
  # create 'gsrap.maps':
77
83
  with open(f'{args.outdir}/gsrap.maps', 'wb') as wb_handler:
78
84
  pickle.dump({
79
- 'RELEASE_kegg': RELEASE_kegg, 'idcollection_dict': idcollection_dict, 'summary_dict': summary_dict,
85
+ 'RELEASE_kegg': RELEASE_kegg,
86
+ 'idcollection_dict': idcollection_dict,
87
+ 'summary_dict': summary_dict,
80
88
  }, wb_handler)
81
89
  logger.info(f"'{args.outdir}/gsrap.maps' created!")
82
90
 
@@ -87,4 +95,5 @@ def main(args, logger):
87
95
  logger.info(f"Temporary raw files deleted!")
88
96
 
89
97
 
98
+
90
99
  return 0
@@ -34,6 +34,7 @@ def download_raw_txtfiles(logger, outdir, usecache):
34
34
  'orthology',
35
35
  'module',
36
36
  'pathway',
37
+ 'organism',
37
38
  ]
38
39
  for db in databases:
39
40
  time.sleep(0.5)
@@ -45,8 +46,9 @@ def download_raw_txtfiles(logger, outdir, usecache):
45
46
 
46
47
  # mix the items to download to be respectful/compliant
47
48
  items_to_download = []
48
-
49
49
  for db in databases:
50
+ if db == 'organism':
51
+ continue # here we just need the list
50
52
  with open(f"{outdir}/kdown/{db}.txt", 'r') as file:
51
53
  res_string = file.read()
52
54
  rows = res_string.split('\n')
@@ -54,7 +56,6 @@ def download_raw_txtfiles(logger, outdir, usecache):
54
56
  item_id = row.split('\t', 1)[0]
55
57
  if item_id == '': continue
56
58
  items_to_download.append({'db': db, 'id': item_id})
57
-
58
59
  random.shuffle(items_to_download)
59
60
 
60
61
 
@@ -79,6 +80,51 @@ def download_raw_txtfiles(logger, outdir, usecache):
79
80
 
80
81
 
81
82
 
83
+ def create_dict_keggorg(logger, outdir):
84
+
85
+ organisms_raw = open(f'{outdir}/kdown/organism.txt', 'r').read()
86
+
87
+ # create a dataframe listing all organisms in KEGG;
88
+ # columns are [tnumber, name, domain, kingdom, phylum, classification]
89
+ df = [] # list fo dicts
90
+ for line in organisms_raw.strip().split("\n"):
91
+ fields = line.split("\t")
92
+ if len(fields) == 4:
93
+ tnumber, keggorg, name, classification = fields
94
+ levels = classification.split(";")
95
+ domain = levels[0]
96
+ kingdom = levels[1]
97
+ phylum = levels[2]
98
+ df.append({
99
+ 'tnumber':tnumber,
100
+ 'keggorg': keggorg,
101
+ 'name': name,
102
+ 'domain': domain,
103
+ 'kingdom': kingdom,
104
+ 'phylum': phylum,
105
+ 'classification': classification
106
+ })
107
+ else:
108
+ # never verified during tests!
109
+ logger.warning(f'Strange number of fields found in this line of "organism.txt": """{line}""".')
110
+ df = pnd.DataFrame.from_records(df)
111
+ df = df.set_index('keggorg', drop=True, verify_integrity=True)
112
+
113
+
114
+ # convert dataframe to dict
115
+ dict_keggorg = {}
116
+ for keggorg, row in df.iterrows():
117
+ dict_keggorg[keggorg] = {
118
+ 'kingdom': row['kingdom'],
119
+ 'phylum': row['phylum'],
120
+ #'name': row['name'], # not strictly needed. Commented to save disk space.
121
+ }
122
+
123
+ if logger != None: logger.info(f'Number of unique items (org): {len(dict_keggorg.keys())}.')
124
+ return dict_keggorg
125
+
126
+
127
+
82
128
  def create_dict_ko(logger, outdir):
83
129
 
84
130
  dict_ko = {} # main output
@@ -98,6 +144,7 @@ def create_dict_ko(logger, outdir):
98
144
  'ecs': set(),
99
145
  'cogs': set(),
100
146
  'gos': set(),
147
+ 'keggorgs': set(),
101
148
  }
102
149
  else:
103
150
  logger.error(f"{ko_id} already included!")
@@ -175,7 +222,13 @@ def create_dict_ko(logger, outdir):
175
222
  gos = content[len('GO: '):].strip().split(' ')
176
223
  for go in gos:
177
224
  dict_ko[ko_id]['gos'].add(go)
178
-
225
+
226
+
227
+ # parse the organism-specific genes
228
+ if curr_header == 'GENES ':
229
+ keggorg = content.split(': ',1)[0]
230
+ dict_ko[ko_id]['keggorgs'].add(keggorg.lower()) # organism.txt has IDs in lowercase
231
+
179
232
 
180
233
  # parse the reactions
181
234
  if curr_header == 'REACTION ':
@@ -547,7 +600,7 @@ def create_dict_md(logger, outdir):
547
600
 
548
601
 
549
602
 
550
- def create_idcollection_dict(dict_ko, dict_c, dict_r, dict_map, dict_md):
603
+ def create_idcollection_dict(dict_keggorg, dict_ko, dict_c, dict_r, dict_map, dict_md):
551
604
 
552
605
  idcollection_dict = {}
553
606
 
@@ -620,6 +673,24 @@ def create_idcollection_dict(dict_ko, dict_c, dict_r, dict_map, dict_md):
620
673
  for go in dict_ko[ko_id]['gos']:
621
674
  idcollection_dict['ko_to_gos'][ko_id].add(go)
622
675
 
676
+
677
+ # creation of 'ko_to_keggorgs' skipped as it takes too much disk space. Replaced with 'ko_to_taxa'.
678
+ idcollection_dict['ko_to_taxa'] = {}
679
+ missing_keggorgs = set()
680
+ for ko_id in dict_ko.keys():
681
+ idcollection_dict['ko_to_taxa'][ko_id] = {'kingdom': set(), 'phylum': set()}
682
+ for keggorg in dict_ko[ko_id]['keggorgs']:
683
+ try:
684
+ kingdom = dict_keggorg[keggorg]['kingdom']
685
+ phylum = dict_keggorg[keggorg]['phylum']
686
+ except:
687
+ if keggorg not in missing_keggorgs:
688
+ missing_keggorgs.add(keggorg)
689
+ #print(f"Organism '{keggorg}' appears in 'orthology/' but not in 'organism.txt'.")
690
+ continue
691
+ idcollection_dict['ko_to_taxa'][ko_id]['kingdom'].add(kingdom)
692
+ idcollection_dict['ko_to_taxa'][ko_id]['phylum'].add(phylum)
693
+
623
694
 
624
695
  idcollection_dict['map_to_name'] = {}
625
696
  for map_id in dict_map.keys():