0
|
1 #!/usr/bin/env python
|
|
2 """
|
|
3 add_plant_tribes_scaffold.py - A script for adding a scaffold to the Galaxy PlantTribes
|
|
4 database efficiently by bypassing the Galaxy model and operating directly on the database.
|
|
5 PostgreSQL 9.1 or greater is required.
|
|
6 """
|
|
7 import argparse
|
|
8 import glob
|
|
9 import os
|
|
10 import sys
|
|
11
|
|
12 import psycopg2
|
3
|
13 from sqlalchemy import create_engine, MetaData, Table
|
0
|
14 from sqlalchemy.engine.url import make_url
|
|
15
|
3
|
16 BLACKLIST_STRINGS = ['NULL',
|
|
17 'Unknown protein',
|
|
18 'No TAIR description',
|
|
19 'Representative annotation below 0'
|
|
20 'Representative AHRD below 0']
|
|
21
|
0
|
22
|
|
23 class ScaffoldLoader(object):
|
|
24 def __init__(self):
|
|
25 self.args = None
|
|
26 self.clustering_methods = []
|
|
27 self.conn = None
|
|
28 self.gene_sequences_dict = {}
|
|
29 self.scaffold_genes_dict = {}
|
|
30 self.scaffold_recs = []
|
|
31 self.species_genes_dict = {}
|
|
32 self.species_ids_dict = {}
|
|
33 self.taxa_lineage_config = None
|
|
34 self.parse_args()
|
|
35 self.fh = open(self.args.output, "w")
|
|
36 self.connect_db()
|
3
|
37 self.engine = create_engine(self.args.database_connection_string)
|
|
38 self.metadata = MetaData(self.engine)
|
0
|
39
|
|
40 def parse_args(self):
|
|
41 parser = argparse.ArgumentParser()
|
|
42 parser.add_argument('--database_connection_string', dest='database_connection_string', help='Postgres database connection string'),
|
|
43 parser.add_argument('--output', dest='output', help='Output dataset'),
|
|
44 parser.add_argument('--scaffold_path', dest='scaffold_path', help='Full path to PlantTribes scaffold directory')
|
|
45 self.args = parser.parse_args()
|
|
46
|
|
47 def connect_db(self):
|
|
48 url = make_url(self.args.database_connection_string)
|
|
49 self.log('Connecting to database with URL: %s' % url)
|
|
50 args = url.translate_connect_args(username='user')
|
|
51 args.update(url.query)
|
|
52 assert url.get_dialect().name == 'postgresql', 'This script can only be used with PostgreSQL.'
|
|
53 self.conn = psycopg2.connect(**args)
|
|
54
|
|
55 def flush(self):
|
|
56 self.conn.commit()
|
|
57
|
|
58 def shutdown(self):
|
|
59 self.conn.close()
|
|
60
|
|
61 def update(self, sql, args):
|
|
62 try:
|
|
63 cur = self.conn.cursor()
|
|
64 cur.execute(sql, args)
|
|
65 except Exception as e:
|
|
66 msg = "Caught exception executing SQL:\n%s\nException:\n%s\n" % (sql.format(args), e)
|
|
67 self.stop_err(msg)
|
|
68 return cur
|
|
69
|
|
70 def stop_err(self, msg):
|
|
71 sys.stderr.write(msg)
|
|
72 self.fh.flush()
|
|
73 self.fh.close()
|
|
74 sys.exit(1)
|
|
75
|
|
76 def log(self, msg):
|
|
77 self.fh.write("%s\n" % msg)
|
|
78 self.fh.flush()
|
|
79
|
|
80 @property
|
|
81 def can_add_scaffold(self):
|
|
82 """
|
|
83 Make sure the scaffold has not already been added.
|
|
84 """
|
|
85 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
86 sql = "SELECT id FROM plant_tribes_scaffold WHERE scaffold_id = '%s';" % scaffold_id
|
|
87 cur = self.conn.cursor()
|
|
88 cur.execute(sql)
|
|
89 try:
|
|
90 cur.fetchone()[0]
|
|
91 # The scaffold has been added to the database.
|
|
92 return False
|
|
93 except:
|
|
94 # The scaffold has not yet been added.
|
|
95 return True
|
|
96
|
|
97 def run(self):
|
|
98 if self.can_add_scaffold:
|
|
99 self.process_annot_dir()
|
|
100 self.process_scaffold_config_files()
|
|
101 self.process_orthogroup_fasta_files()
|
|
102 self.fh.flush()
|
|
103 self.fh.close()
|
|
104 else:
|
|
105 self.stop_err("The scaffold %s has already been added to the database." % os.path.basename(self.args.scaffold_path))
|
|
106
|
|
107 def process_annot_dir(self):
|
|
108 """
|
|
109 1. Parse all of the *.min_evalue.summary files in the
|
|
110 ~/<scaffold_id>/annot directory (e.g., ~/22Gv1.1/annot) to populate
|
|
111 both the plant_tribes_scaffold and the plant_tribes_orthogroup tables.
|
|
112 1. Parse all of the *.list files in the same directory to populate
|
|
113 self.scaffold_genes_dict.
|
|
114 """
|
3
|
115 self.pto_table = Table('plant_tribes_orthogroup', self.metadata, autoload=True)
|
0
|
116 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
117 file_dir = os.path.join(self.args.scaffold_path, 'annot')
|
2
|
118 # The scaffold naming convention must follow this pattern:
|
0
|
119 # <integer1>Gv<integer2>.<integer3>
|
|
120 # where integer 1 is the number of genomes in the scaffold_id. For example:
|
|
121 # 22Gv1.1 -> 22 genomes
|
|
122 # 12Gv1.0 -> 12 genomes
|
|
123 # 26Gv2.0 -> 26 genomes, etc.
|
|
124 num_genomes = int(scaffold_id.split("Gv")[0])
|
|
125 super_ortho_start_index = num_genomes + 1
|
|
126 for file_name in glob.glob(os.path.join(file_dir, "*min_evalue.summary")):
|
|
127 items = os.path.basename(file_name).split(".")
|
|
128 clustering_method = items[0]
|
|
129 # Save all clustering methods for later processing.
|
|
130 if clustering_method not in self.clustering_methods:
|
|
131 self.clustering_methods.append(clustering_method)
|
|
132 # Insert a row in to the plant_tribes_scaffold table.
|
|
133 self.log("Inserting a row into the plant_tribes_scaffold table for scaffold %s and clustering method %s." % (scaffold_id, clustering_method))
|
|
134 args = [scaffold_id, clustering_method]
|
|
135 sql = """
|
|
136 INSERT INTO plant_tribes_scaffold
|
|
137 VALUES (nextval('plant_tribes_scaffold_id_seq'), %s, %s)
|
|
138 RETURNING id;
|
|
139 """
|
|
140 cur = self.update(sql, tuple(args))
|
|
141 self.flush()
|
|
142 scaffold_id_db = cur.fetchone()[0]
|
|
143 self.scaffold_recs.append([scaffold_id_db, scaffold_id, clustering_method])
|
|
144 with open(file_name, "r") as fh:
|
|
145 i = 0
|
|
146 for i2, line in enumerate(fh):
|
|
147 if i2 == 0:
|
|
148 # Skip first line.
|
|
149 continue
|
2
|
150 line = line.rstrip('\n')
|
0
|
151 num_genes = 0
|
|
152 num_species = 0
|
|
153 items = line.split("\t")
|
|
154 orthogroup_id = int(items[0])
|
|
155 # Zero based items 1 to num_genomes consists of the
|
|
156 # number of species classified in the orthogroup (i.e.,
|
|
157 # species with at least 1 gene in the orthogroup).
|
|
158 for j in range(1, num_genomes):
|
|
159 j_int = int(items[j])
|
|
160 if j_int > 0:
|
|
161 # The species has at least 1 gene
|
|
162 num_species += 1
|
|
163 num_genes += j_int
|
3
|
164 # Get the auto-incremented row id to insert a row inot
|
|
165 # the plant_tribes_orthogroup table.
|
|
166 sql = "SELECT nextval('plant_tribes_orthogroup_id_seq');"
|
|
167 cur = self.conn.cursor()
|
|
168 cur.execute(sql)
|
|
169 plant_tribes_orthogroup_id = cur.fetchone()[0]
|
|
170 args = [plant_tribes_orthogroup_id, orthogroup_id, scaffold_id_db, num_species, num_genes]
|
|
171 last_item = len(items)
|
|
172 for k in range(super_ortho_start_index, last_item):
|
|
173 bs_found = False
|
|
174 # The last 7 items in this range are as follows.
|
|
175 # items[last_item-6]: AHRD Descriptions
|
|
176 # items[last_item-5]: TAIR Gene(s) Descriptions
|
|
177 # items[last_item-4]: Pfam Domains
|
|
178 # items[last_item-3]: InterProScan Descriptions
|
|
179 # items[last_item-2]: GO Molecular Functions
|
|
180 # items[last_item-1]: GO Biological Processes
|
|
181 # items[last_item]: GO Cellular Components
|
|
182 # We'll translate each of these items into a JSON
|
|
183 # dictionary for inserting into the table.
|
|
184 if k >= (last_item-7) and k <= last_item:
|
|
185 json_str = str(items[k])
|
|
186 # Here is an example string:
|
|
187 # Phosphate transporter PHO1 [0.327] | Phosphate
|
|
188 for bs in BLACKLIST_STRINGS:
|
|
189 if json_str.find(bs) >= 0:
|
|
190 bs_found = True
|
|
191 args.append(None)
|
|
192 break
|
|
193 if not bs_found:
|
|
194 # We'll split the string on " | " to create each value.
|
|
195 # The keys will be zero-padded integers to enable sorting.
|
|
196 json_dict = dict()
|
|
197 json_vals = json_str.split(' | ')
|
|
198 for key_index, json_val in enumerate(json_vals):
|
|
199 # The zero-padded key is 1 based.
|
|
200 json_key = '%04d' % key_index
|
|
201 json_dict[json_key] = json_val
|
|
202 args.append(json_dict)
|
|
203 else:
|
|
204 args.append('%s' % str(items[k]))
|
|
205 sql = self.pto_table.insert().values(args)
|
|
206 try:
|
|
207 self.engine.execute(sql)
|
|
208 except Exception as e:
|
|
209 msg = "Caught exception executing SQL:\n%s\nvalues:\n%s\nException:\n%s\n" % (str(sql), str(args), e)
|
|
210 self.stop_err(msg)
|
0
|
211 i += 1
|
|
212 self.log("Inserted %d rows into the plant_tribes_orthogroup table for scaffold %s and clustering method %s." % (i, scaffold_id, clustering_method))
|
|
213 for file_name in glob.glob(os.path.join(file_dir, "*list")):
|
|
214 items = os.path.basename(file_name).split(".")
|
|
215 clustering_method = items[0]
|
|
216 with open(file_name, "r") as fh:
|
|
217 for i, line in enumerate(fh):
|
|
218 items = line.split("\t")
|
|
219 # The key will be a combination of clustering_method and
|
|
220 # orthogroup_id separated by "^^" for easy splitting later.
|
|
221 key = "%s^^%s" % (clustering_method, items[0])
|
|
222 # The value is the gen_id with all white space replaced by "_".
|
|
223 val = items[1].replace("|", "_")
|
|
224 if key in self.scaffold_genes_dict:
|
|
225 self.scaffold_genes_dict[key].append(val)
|
|
226 else:
|
|
227 self.scaffold_genes_dict[key] = [val]
|
|
228
|
|
229 def process_scaffold_config_files(self):
|
|
230 """
|
|
231 1. Parse ~/<scaffold_id>/<scaffold_id>/.rootingOrder.config
|
|
232 (e.g., ~/22Gv1.1/22Gv1.1..rootingOrder.config) to populate.
|
|
233 2. Calculate the number of genes found
|
|
234 for each species and add the number to self.species_genes_dict.
|
|
235 3. Parse ~/<scaffold_id>/<scaffold_id>.taxaLineage.config to
|
|
236 populate the plant_tribes_taxon table.
|
|
237 """
|
|
238 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
239 file_name = os.path.join(self.args.scaffold_path, '%s.rootingOrder.config' % scaffold_id)
|
|
240 self.log("Processing rooting order config: %s" % str(file_name))
|
|
241 # Populate self.species_ids_dict.
|
|
242 with open(file_name, "r") as fh:
|
|
243 for i, line in enumerate(fh):
|
|
244 line = line.strip()
|
|
245 if len(line) == 0 or line.startswith("#") or line.startswith("["):
|
|
246 # Skip blank lines, comments and section headers.
|
|
247 continue
|
|
248 # Example line:
|
|
249 # Physcomitrella patens=Phypa
|
|
250 items = line.split("=")
|
|
251 self.species_ids_dict[items[1]] = items[0]
|
|
252 # Get lineage information for orthogrpoup taxa.
|
|
253 for scaffold_genes_dict_key in sorted(self.scaffold_genes_dict.keys()):
|
|
254 # The format of key is <clustering_method>^^<orthogroup_id>.
|
|
255 # For example: {"gfam^^1" : "gnl_Musac1.0_GSMUA_Achr1T11000_001"
|
|
256 scaffold_genes_dict_key_items = scaffold_genes_dict_key.split("^^")
|
|
257 clustering_method = scaffold_genes_dict_key_items[0]
|
|
258 # Get the list of genes for the current scaffold_genes_dict_key.
|
|
259 gene_list = self.scaffold_genes_dict[scaffold_genes_dict_key]
|
|
260 for gene_id in gene_list:
|
|
261 # Example species_code: Musac1.0, where
|
|
262 # species_name is Musac and version is 1.0.
|
|
263 species_code = gene_id.split("_")[1]
|
|
264 # Strip the version from the species_code.
|
|
265 species_code = species_code[0:5]
|
|
266 # Get the species_name from self.species_ids_dict.
|
|
267 species_name = self.species_ids_dict[species_code]
|
|
268 # Create a key for self.species_genes_dict, with the format:
|
|
269 # <clustering_method>^^<species_name>
|
|
270 species_genes_dict_key = "%s^^%s" % (clustering_method, species_name)
|
|
271 # Add an entry to self.species_genes_dict, where the value
|
|
272 # is a list containing species_name and num_genes.
|
|
273 if species_genes_dict_key in self.species_genes_dict:
|
|
274 tup = self.species_genes_dict[species_genes_dict_key]
|
|
275 tup[1] += 1
|
|
276 self.species_genes_dict[species_genes_dict_key] = tup
|
|
277 else:
|
|
278 self.species_genes_dict[species_genes_dict_key] = [species_name, 1]
|
|
279 # Populate the plant_tribes_taxon table.
|
|
280 file_name = os.path.join(self.args.scaffold_path, '%s.taxaLineage.config' % scaffold_id)
|
|
281 self.log("Processing taxa lineage config: %s" % str(file_name))
|
|
282 with open(file_name, "r") as fh:
|
|
283 for line in fh:
|
|
284 line = line.strip()
|
|
285 if len(line) == 0 or line.startswith("#") or line.startswith("Species"):
|
|
286 # Skip blank lines, comments and section headers.
|
|
287 continue
|
|
288 # Example line: Populus trichocarpa\tSalicaceae\tMalpighiales\tRosids\tCore Eudicots
|
|
289 items = line.split("\t")
|
|
290 species_name = items[0]
|
|
291 i = 0
|
|
292 for clustering_method in self.clustering_methods:
|
|
293 # The format of species_genes_dict_key is <clustering_method>^^<species_name>.
|
|
294 species_genes_dict_key = "%s^^%s" % (clustering_method, species_name)
|
|
295 # Get the scaffold_rec for the current scaffold_id and clustering_method.
|
|
296 # The list is [<scaffold_id_db>, <scaffold_id>, <clustering_method>]
|
|
297 for scaffold_rec in self.scaffold_recs:
|
|
298 if scaffold_id in scaffold_rec and clustering_method in scaffold_rec:
|
|
299 scaffold_id_db = scaffold_rec[0]
|
|
300 # The value is a list containing species_name and num_genes.
|
|
301 val = self.species_genes_dict[species_genes_dict_key]
|
|
302 if species_name == val[0]:
|
|
303 num_genes = val[1]
|
|
304 else:
|
|
305 num_genes = 0
|
|
306 # Insert a row in to the plant_tribes_scaffold table.
|
|
307 args = [species_name, scaffold_id_db, num_genes, items[1], items[2], items[3], items[4]]
|
|
308 sql = """
|
|
309 INSERT INTO plant_tribes_taxon
|
|
310 VALUES (nextval('plant_tribes_taxon_id_seq'), %s, %s, %s, %s, %s, %s, %s);
|
|
311 """
|
|
312 self.update(sql, tuple(args))
|
|
313 self.flush()
|
|
314 i += 1
|
|
315 self.log("Inserted %d rows into the plant_tribes_taxon table for species name: %s." % (i, str(species_name)))
|
|
316
|
|
317 def process_orthogroup_fasta_files(self):
|
|
318 """
|
|
319 1. Analyze all of the scaffold .fna and .faa files for each clustering
|
|
320 method to populate the aa_dict and dna_dict sequence dictionaries.
|
|
321 2. Use the populated sequence dictionaries to populate the plant_tribes_gene
|
|
322 and gene_scaffold_orthogroup_taxon_association tables.
|
|
323 """
|
|
324 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
325 aa_dict = {}
|
|
326 dna_dict = {}
|
|
327 # Populate aa_dict and dna_dict.
|
|
328 for clustering_method in self.clustering_methods:
|
|
329 file_dir = os.path.join(self.args.scaffold_path, 'fasta', clustering_method)
|
|
330 for file_name in os.listdir(file_dir):
|
|
331 items = file_name.split(".")
|
|
332 orthogroup_id = items[0]
|
|
333 file_extension = items[1]
|
|
334 if file_extension == "fna":
|
|
335 adict = dna_dict
|
|
336 else:
|
|
337 adict = aa_dict
|
|
338 file_path = os.path.join(file_dir, file_name)
|
|
339 with open(file_path, "r") as fh:
|
|
340 for i, line in enumerate(fh):
|
|
341 line = line.strip()
|
|
342 if len(line) == 0:
|
|
343 # Skip blank lines (shoudn't happen).
|
|
344 continue
|
|
345 if line.startswith(">"):
|
|
346 # Example line:
|
|
347 # >gnl_Ambtr1.0.27_AmTr_v1.0_scaffold00001.110
|
|
348 gene_id = line.lstrip(">")
|
|
349 # The dictionary keys will combine the orthogroup_id,
|
|
350 # clustering method and gene id using the format
|
|
351 # ,orthogroup_id>^^<clustering_method>^^<gene_id>.
|
|
352 combined_id = "%s^^%s^^%s" % (orthogroup_id, clustering_method, gene_id)
|
|
353 if combined_id not in adict:
|
|
354 # The value will be the dna sequence string..
|
|
355 adict[combined_id] = ""
|
|
356 else:
|
|
357 # Example line:
|
|
358 # ATGGAGAAGGACTTT
|
|
359 # Here combined_id is set because the fasta format specifies
|
|
360 # that all lines following the gene id defined in the if block
|
|
361 # above will be the sequence associated with that gene until
|
|
362 # the next gene id line is encountered.
|
|
363 sequence = adict[combined_id]
|
|
364 sequence = "%s%s" % (sequence, line)
|
|
365 adict[combined_id] = sequence
|
|
366 # Populate the plant_tribes_gene and gene_scaffold_orthogroup_taxon_association tables
|
|
367 # from the contents of aa_dict and dna_dict.
|
|
368 self.log("Populating the plant_tribes_gene and gene_scaffold_orthogroup_taxon_association tables.")
|
|
369 gi = 0
|
|
370 for gsoai, combined_id in enumerate(sorted(dna_dict.keys())):
|
|
371 # The dictionary keys combine the orthogroup_id, clustering method and
|
|
372 # gene id using the format <orthogroup_id>^^<clustering_method>^^<gene_id>.
|
|
373 items = combined_id.split("^^")
|
|
374 orthogroup_id = items[0]
|
|
375 clustering_method = items[1]
|
|
376 gene_id = items[2]
|
|
377 # The value will be a list containing both
|
|
378 # clustering_method and the dna string.
|
|
379 dna_sequence = dna_dict[combined_id]
|
|
380 aa_sequence = aa_dict[combined_id]
|
|
381 # Get the species_code from the gene_id.
|
|
382 species_code = gene_id.split("_")[1]
|
|
383 # Strip the version from the species_code.
|
|
384 species_code = species_code[0:5]
|
|
385 # Get the species_name from self.species_ids_dict.
|
|
386 species_name = self.species_ids_dict[species_code]
|
|
387 # Get the plant_tribes_orthogroup primary key id for
|
|
388 # the orthogroup_id from the plant_tribes_orthogroup table.
|
|
389 sql = "SELECT id FROM plant_tribes_orthogroup WHERE orthogroup_id = '%s';" % orthogroup_id
|
|
390 cur = self.conn.cursor()
|
|
391 cur.execute(sql)
|
|
392 orthogroup_id_db = cur.fetchone()[0]
|
|
393 # If the plant_tribes_gene table contains a row that has the gene_id,
|
|
394 # then we'll add a row only to the gene_scaffold_orthogroup_taxon_association table.
|
|
395 # Get the taxon_id for the species_name from the plant_tribes_taxon table.
|
|
396 sql = "SELECT id FROM plant_tribes_taxon WHERE species_name = '%s';" % species_name
|
|
397 cur = self.conn.cursor()
|
|
398 cur.execute(sql)
|
|
399 taxon_id_db = cur.fetchone()[0]
|
|
400 # If the plant_tribes_gene table contains a row that has the gene_id,
|
|
401 # then we'll add a row only to the gene_scaffold_orthogroup_taxon_association table.
|
|
402 sql = "SELECT id FROM plant_tribes_gene WHERE gene_id = '%s';" % gene_id
|
|
403 cur = self.conn.cursor()
|
|
404 cur.execute(sql)
|
|
405 try:
|
|
406 gene_id_db = cur.fetchone()[0]
|
|
407 except:
|
|
408 # Insert a row into the plant_tribes_gene table.
|
|
409 args = [gene_id, dna_sequence, aa_sequence]
|
|
410 sql = """
|
|
411 INSERT INTO plant_tribes_gene
|
|
412 VALUES (nextval('plant_tribes_gene_id_seq'), %s, %s, %s)
|
|
413 RETURNING id;
|
|
414 """
|
|
415 cur = self.update(sql, tuple(args))
|
|
416 self.flush()
|
|
417 gene_id_db = cur.fetchone()[0]
|
|
418 gi += 1
|
|
419 if gi % 1000 == 0:
|
|
420 self.log("Inserted 1000 more rows into the plant_tribes_gene table.")
|
|
421 # Insert a row into the gene_scaffold_orthogroup_taxon_association table.
|
|
422 # Get the scaffold_rec for the current scaffold_id and clustering_method.
|
|
423 # The list is [<scaffold_id_db>, <scaffold_id>, <clustering_method>]
|
|
424 for scaffold_rec in self.scaffold_recs:
|
|
425 if scaffold_id in scaffold_rec and clustering_method in scaffold_rec:
|
|
426 scaffold_id_db = scaffold_rec[0]
|
|
427 args = [gene_id_db, scaffold_id_db, orthogroup_id_db, taxon_id_db]
|
|
428 sql = """
|
|
429 INSERT INTO gene_scaffold_orthogroup_taxon_association
|
|
430 VALUES (nextval('gene_scaffold_orthogroup_taxon_association_id_seq'), %s, %s, %s, %s);
|
|
431 """
|
|
432 cur = self.update(sql, tuple(args))
|
|
433 self.flush()
|
|
434 if gsoai % 1000 == 0:
|
|
435 self.log("Inserted 1000 more rows into the gene_scaffold_orthogroup_taxon_association table.")
|
|
436 self.log("Inserted a total of %d rows into the plant_tribes_gene table." % gi)
|
|
437 self.log("Inserted a total of %d rows into the gene_scaffold_orthogroup_taxon_association table." % gsoai)
|
|
438
|
|
439
|
|
440 if __name__ == '__main__':
|
|
441 scaffold_loader = ScaffoldLoader()
|
|
442 scaffold_loader.run()
|
|
443 scaffold_loader.shutdown()
|