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
|
|
13 from sqlalchemy.engine.url import make_url
|
|
14
|
|
15
|
|
16 class AddScaffold(object):
|
|
17 def __init__(self):
|
|
18 self.args = None
|
|
19 self.clustering_methods = []
|
|
20 self.conn = None
|
|
21 self.gene_sequences_dict = {}
|
|
22 self.scaffold_genes_dict = {}
|
|
23 self.scaffold_recs = []
|
|
24 self.species_genes_dict = {}
|
|
25 self.species_ids_dict = {}
|
|
26 self.taxa_lineage_config = None
|
3
|
27 self.parse_args()
|
|
28 self.fh = open(self.args.output, "w")
|
|
29 self.connect_db()
|
0
|
30
|
3
|
31 def parse_args(self):
|
0
|
32 parser = argparse.ArgumentParser()
|
|
33 parser.add_argument('--database_connection_string', dest='database_connection_string', help='Postgres database connection string'),
|
|
34 parser.add_argument('--output', dest='output', help='Output dataset'),
|
|
35 parser.add_argument('--scaffold_path', dest='scaffold_path', help='Full path to PlantTribes scaffold directory')
|
|
36 self.args = parser.parse_args()
|
|
37
|
5
|
38 def stop_err(self, msg):
|
0
|
39 sys.stderr.write(msg)
|
3
|
40 self.fh.flush()
|
|
41 self.fh.close()
|
0
|
42 sys.exit(1)
|
|
43
|
3
|
44 def connect_db(self):
|
0
|
45 url = make_url(self.args.database_connection_string)
|
|
46 self.fh.write('Connecting to database with URL: %s' % url)
|
|
47 args = url.translate_connect_args(username='user')
|
|
48 args.update(url.query)
|
|
49 assert url.get_dialect().name == 'postgresql', 'This script can only be used with PostgreSQL.'
|
|
50 self.conn = psycopg2.connect(**args)
|
|
51
|
3
|
52 def flush(self):
|
0
|
53 self.conn.commit()
|
|
54
|
3
|
55 def shutdown(self):
|
0
|
56 self.conn.close()
|
|
57
|
3
|
58 def update(self, sql, args):
|
0
|
59 try:
|
|
60 cur = self.conn.cursor()
|
|
61 cur.execute(sql, args)
|
|
62 except Exception as e:
|
4
|
63 msg = "Caught exception executing SQL:\n%s\nException:\n%s\n" % (sql.format(args), e)
|
|
64 self.stop_err(msg)
|
0
|
65 return cur
|
|
66
|
6
|
67 @property
|
|
68 def can_add_scaffold(self):
|
0
|
69 """
|
|
70 Make sure the scaffold has not already been added.
|
|
71 """
|
|
72 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
73 sql = "SELECT id FROM plant_tribes_scaffold WHERE scaffold_id = '%s';" % scaffold_id
|
|
74 cur = self.conn.cursor()
|
|
75 cur.execute(sql)
|
|
76 try:
|
|
77 cur.fetchone()[0]
|
7
|
78 # The scaffold has been added to the database.
|
6
|
79 return False
|
0
|
80 except:
|
|
81 # The scaffold has not yet been added.
|
6
|
82 return True
|
0
|
83
|
3
|
84 def run(self):
|
6
|
85 if self.can_add_scaffold:
|
|
86 self.process_annot_dir()
|
|
87 self.process_scaffold_config_files()
|
|
88 self.process_orthogroup_fasta_files()
|
|
89 self.fh.flush()
|
|
90 self.fh.close()
|
7
|
91 else:
|
8
|
92 self.stop_err("The scaffold %s has already been added to the database." % os.path.basename(self.args.scaffold_path))
|
0
|
93
|
|
94 def process_annot_dir(self):
|
|
95 """
|
|
96 First, parse all of the *.min_evalue.summary files in the
|
|
97 ~/<scaffold_id>/annot directory (e.g., ~/22Gv1.1/annot) to populate
|
|
98 both the plant_tribes_scaffold and the plant_tribes_orthogroup tables.
|
|
99 Next, parse all of the *.list files in the same directory to populate
|
|
100 self.scaffold_genes_dict.
|
|
101 """
|
|
102 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
103 file_dir = os.path.join(self.args.scaffold_path, 'annot')
|
|
104 # The scaffol naming convention must follow this pattern:
|
|
105 # <integer1>Gv<integer2>.<integer3>
|
|
106 # where integer 1 is the number of genomes in the scaffold_id. For example:
|
|
107 # 22Gv1.1 -> 22 genomes
|
|
108 # 12Gv1.0 -> 12 genomes
|
|
109 # 26Gv2.0 -> 26 genomes, etc.
|
|
110 num_genomes = int(scaffold_id.split("Gv")[0])
|
|
111 super_ortho_start_index = num_genomes + 1
|
|
112 for file_name in glob.glob(os.path.join(file_dir, "*min_evalue.summary")):
|
|
113 items = os.path.basename(file_name).split(".")
|
|
114 clustering_method = items[0]
|
|
115 # Save all clustering methods for later processing.
|
|
116 if clustering_method not in self.clustering_methods:
|
|
117 self.clustering_methods.append(clustering_method)
|
|
118 # Insert a row in to the plant_tribes_scaffold table.
|
|
119 self.fh.write("Inserting a row into the plant_tribes_scaffold table for scaffold %s and clustering method %s..." % (scaffold_id, clustering_method))
|
|
120 args = [scaffold_id, clustering_method]
|
|
121 sql = """
|
|
122 INSERT INTO plant_tribes_scaffold
|
|
123 VALUES (nextval('plant_tribes_scaffold_id_seq'), %s, %s)
|
|
124 RETURNING id;
|
|
125 """
|
3
|
126 cur = self.update(sql, tuple(args))
|
|
127 self.flush()
|
0
|
128 scaffold_id_db = cur.fetchone()[0]
|
|
129 self.scaffold_recs.append([scaffold_id_db, scaffold_id, clustering_method])
|
|
130 with open(file_name, "r") as fh:
|
|
131 for i, line in enumerate(fh):
|
|
132 if i == 0:
|
|
133 # Skip first line.
|
|
134 continue
|
|
135 num_genes = 0
|
|
136 num_species = 0
|
|
137 items = line.split("\t")
|
|
138 orthogroup_id = int(items[0])
|
|
139 # Zero based items 1 to num_genomes consists of the
|
|
140 # number of species classified in the orthogroup (i.e.,
|
|
141 # species with at least 1 gene in the orthogroup).
|
|
142 for j in range(1, num_genomes):
|
|
143 j_int = int(items[j])
|
|
144 if j_int > 0:
|
|
145 # The species has at least 1 gene
|
|
146 num_species += 1
|
|
147 num_genes += j_int
|
|
148 # Insert a row into the plant_tribes_orthogroup table.
|
|
149 self.fh.write("Inserting a row into the plant_tribes_orthogroup table...")
|
|
150 args = [orthogroup_id, scaffold_id_db, num_species, num_genes]
|
|
151 for k in range(super_ortho_start_index, len(items)):
|
|
152 args.append('%s' % str(items[k]))
|
|
153 sql = """
|
|
154 INSERT INTO plant_tribes_orthogroup
|
|
155 VALUES (nextval('plant_tribes_orthogroup_id_seq'), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
|
|
156 """
|
3
|
157 cur = self.update(sql, tuple(args))
|
|
158 self.flush()
|
0
|
159 for file_name in glob.glob(os.path.join(file_dir, "*list")):
|
|
160 items = os.path.basename(file_name).split(".")
|
|
161 clustering_method = items[0]
|
|
162 with open(file_name, "r") as fh:
|
|
163 for i, line in enumerate(fh):
|
|
164 items = line.split("\t")
|
|
165 # The key will be a combination of clustering_method and
|
|
166 # orthogroup_id separated by "^^" for easy splitting later.
|
|
167 key = "%s^^%s" % (clustering_method, items[0])
|
|
168 # The value is the gen_id with all white space replaced by "_".
|
|
169 val = items[1].replace("|", "_")
|
|
170 if key in self.scaffold_genes_dict:
|
|
171 self.scaffold_genes_dict[key].append(val)
|
|
172 else:
|
|
173 self.scaffold_genes_dict[key] = [val]
|
|
174
|
|
175 def process_scaffold_config_files(self):
|
|
176 """
|
|
177 1. Parse ~/<scaffold_id>/<scaffold_id>/.rootingOrder.config
|
|
178 (e.g., ~/22Gv1.1/22Gv1.1..rootingOrder.config) to populate.
|
|
179 2. Calculate the number of genes found
|
|
180 for each species and add the number to self.species_genes_dict.
|
|
181 3. Parse ~/<scaffold_id>/<scaffold_id>.taxaLineage.config to
|
|
182 populate the plant_tribes_taxon table.
|
|
183 """
|
|
184 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
185 file_name = os.path.join(self.args.scaffold_path, '%s.rootingOrder.config' % scaffold_id)
|
|
186 self.fh.write("Processing rooting order config: %s" % str(file_name))
|
|
187 # Populate self.species_ids_dict.
|
|
188 with open(file_name, "r") as fh:
|
|
189 for i, line in enumerate(fh):
|
|
190 line = line.strip()
|
|
191 if len(line) == 0 or line.startswith("#") or line.startswith("["):
|
|
192 # Skip blank lines, comments and section headers.
|
|
193 continue
|
|
194 # Example line:
|
|
195 # Physcomitrella patens=Phypa
|
|
196 items = line.split("=")
|
|
197 self.species_ids_dict[items[1]] = items[0]
|
|
198 # Get lineage information for orthogrpoup taxa.
|
|
199 for scaffold_genes_dict_key in sorted(self.scaffold_genes_dict.keys()):
|
|
200 # The format of key is <clustering_method>^^<orthogroup_id>.
|
|
201 # For example: {"gfam^^1" : "gnl_Musac1.0_GSMUA_Achr1T11000_001"
|
|
202 scaffold_genes_dict_key_items = scaffold_genes_dict_key.split("^^")
|
|
203 clustering_method = scaffold_genes_dict_key_items[0]
|
|
204 # Get the list of genes for the current scaffold_genes_dict_key.
|
|
205 gene_list = self.scaffold_genes_dict[scaffold_genes_dict_key]
|
|
206 for gene_id in gene_list:
|
|
207 # Example species_code: Musac1.0, where
|
|
208 # species_name is Musac and version is 1.0.
|
|
209 species_code = gene_id.split("_")[1]
|
|
210 # Strip the version from the species_code.
|
|
211 species_code = species_code[0:5]
|
|
212 # Get the species_name from self.species_ids_dict.
|
|
213 species_name = self.species_ids_dict[species_code]
|
|
214 # Create a key for self.species_genes_dict, with the format:
|
|
215 # <clustering_method>^^<species_code>
|
|
216 species_genes_dict_key = "%s^^%s" % (clustering_method, species_code)
|
|
217 # Add an entry to self.species_genes_dict, where the value
|
|
218 # is a list containing species_name and num_genes.
|
|
219 if species_genes_dict_key in self.species_genes_dict:
|
|
220 tup = self.species_genes_dict[species_genes_dict_key]
|
|
221 tup[1] += 1
|
|
222 self.species_genes_dict[species_genes_dict_key] = tup
|
|
223 else:
|
|
224 self.species_genes_dict[species_genes_dict_key] = [species_name, 1]
|
|
225 # Populate the plant_tribes_taxon table.
|
|
226 file_name = os.path.join(self.args.scaffold_path, '%s.taxaLineage.config' % scaffold_id)
|
|
227 self.fh.write("Processing taxa lineage config: %s" % str(file_name))
|
|
228 with open(file_name, "r") as fh:
|
|
229 for i, line in enumerate(fh):
|
|
230 line = line.strip()
|
|
231 if len(line) == 0 or line.startswith("#") or line.startswith("Species"):
|
|
232 # Skip blank lines, comments and section headers.
|
|
233 continue
|
|
234 # Example line: Populus trichocarpa\tSalicaceae\tMalpighiales\tRosids\tCore Eudicots
|
|
235 items = line.split("\t")
|
|
236 species_name = items[0]
|
|
237 self.fh.write("Calculating the number of genes for species_name: %s" % str(species_name))
|
|
238 for species_genes_dict_key in sorted(self.species_genes_dict.keys()):
|
|
239 # The format of species_genes_dict_key is <clustering_method>^^<species_code>.
|
|
240 species_genes_dict_key_items = species_genes_dict_key.split("^^")
|
|
241 clustering_method = species_genes_dict_key_items[0]
|
|
242 species_code = species_genes_dict_key_items[1]
|
|
243 # Get the scaffold_rec for the current scaffold_id and clustering_method.
|
|
244 # The list is [<scaffold_id_db>, <scaffold_id>, <clustering_method>]
|
|
245 for scaffold_rec in self.scaffold_recs:
|
|
246 if scaffold_id in scaffold_rec and clustering_method in scaffold_rec:
|
|
247 scaffold_id_db = scaffold_rec[0]
|
|
248 # The value is a list containing species_name and num_genes.
|
|
249 val = self.species_genes_dict[species_genes_dict_key]
|
|
250 if species_name == val[0]:
|
|
251 num_genes = val[1]
|
|
252 else:
|
|
253 num_genes = 0
|
|
254 # Insert a row in to the plant_tribes_scaffold table.
|
|
255 args = [species_name, scaffold_id_db, num_genes, items[1], items[2], items[3], items[4]]
|
|
256 sql = """
|
|
257 INSERT INTO plant_tribes_taxon
|
|
258 VALUES (nextval('plant_tribes_taxon_id_seq'), %s, %s, %s, %s, %s, %s, %s);
|
|
259 """
|
3
|
260 self.update(sql, tuple(args))
|
|
261 self.flush()
|
0
|
262
|
|
263 def process_orthogroup_fasta_files(self):
|
|
264 scaffold_id = os.path.basename(self.args.scaffold_path)
|
|
265 aa_dict = {}
|
|
266 dna_dict = {}
|
|
267 # Populate aa_dict and dna_dict.
|
|
268 for clustering_method in self.clustering_methods:
|
|
269 file_dir = os.path.join(self.args.scaffold_path, 'fasta', clustering_method)
|
|
270 for file_name in os.listdir(file_dir):
|
|
271 items = file_name.split(".")
|
|
272 orthogroup_id = items[0]
|
|
273 file_extension = items[1]
|
|
274 if file_extension == "fna":
|
|
275 adict = dna_dict
|
|
276 else:
|
|
277 adict = aa_dict
|
|
278 file_path = os.path.join(file_dir, file_name)
|
|
279 with open(file_path, "r") as fh:
|
|
280 for i, line in enumerate(fh):
|
|
281 line = line.strip()
|
|
282 if len(line) == 0:
|
|
283 # Skip blank lines (shoudn't happen).
|
|
284 continue
|
|
285 if line.startswith(">"):
|
|
286 # Example line:
|
|
287 # >gnl_Ambtr1.0.27_AmTr_v1.0_scaffold00001.110
|
|
288 gene_id = line.lstrip(">")
|
|
289 # The dictionary keys will combine the orthogroup_id,
|
|
290 # clustering method and gene id using the format
|
|
291 # ,orthogroup_id>^^<clustering_method>^^<gene_id>.
|
|
292 combined_id = "%s^^%s^^%s" % (orthogroup_id, clustering_method, gene_id)
|
|
293 if combined_id not in adict:
|
|
294 # The value will be the dna sequence string..
|
|
295 adict[combined_id] = ""
|
|
296 else:
|
|
297 # Example line:
|
|
298 # ATGGAGAAGGACTTT
|
|
299 # Here combined_id is set because the fasta format specifies
|
|
300 # that all lines following the gene id defined in the if block
|
|
301 # above will be the sequence associated with that gene until
|
|
302 # the next gene id line is encountered.
|
|
303 sequence = adict[combined_id]
|
|
304 sequence = "%s%s" % (sequence, line)
|
|
305 adict[combined_id] = sequence
|
|
306 # Populate the plant_tribes_gene and gen_scaffold_association tables
|
|
307 # from the contents of aa_dict and dna_dict.
|
|
308 for combined_id in sorted(dna_dict.keys()):
|
|
309 # The dictionary keys combine the orthogroup_id, clustering method and
|
|
310 # gene id using the format <orthogroup_id>^^<clustering_method>^^<gene_id>.
|
|
311 items = combined_id.split("^^")
|
|
312 orthogroup_id = items[0]
|
|
313 clustering_method = items[1]
|
|
314 gene_id = items[2]
|
|
315 self.fh.write("Populating the plant_tribes_gene and gene_scaffold_orthogroup_association tables with gene %s, scaffold %s and orthogroup %s..." % (gene_id, scaffold_id, orthogroup_id))
|
|
316 # The value will be a list containing both
|
|
317 # clustering_method and the dna string.
|
|
318 dna_sequence = dna_dict[combined_id]
|
|
319 aa_sequence = aa_dict[combined_id]
|
|
320 # Get the species_code from the gene_id.
|
|
321 species_code = gene_id.split("_")[1]
|
|
322 # Strip the version from the species_code.
|
|
323 species_code = species_code[0:5]
|
|
324 # Get the species_name from self.species_ids_dict.
|
|
325 species_name = self.species_ids_dict[species_code]
|
|
326 # Get the plant_tribes_orthogroup primary key id for
|
|
327 # the orthogroup_id from the plant_tribes_orthogroup table.
|
|
328 sql = "SELECT id FROM plant_tribes_orthogroup WHERE orthogroup_id = '%s';" % orthogroup_id
|
|
329 cur = self.conn.cursor()
|
|
330 cur.execute(sql)
|
|
331 orthogroup_id_db = cur.fetchone()[0]
|
|
332 # If the plant_tribes_gene table contains a row that has the gene_id,
|
|
333 # then we'll add a row only to the gene_scaffold_orthogroup_association table.
|
|
334 # Get the taxon_id for the species_name from the plant_tribes_taxon table.
|
|
335 sql = "SELECT id FROM plant_tribes_taxon WHERE species_name = '%s';" % species_name
|
|
336 cur = self.conn.cursor()
|
|
337 cur.execute(sql)
|
|
338 taxon_id = cur.fetchone()[0]
|
|
339 # If the plant_tribes_gene table contains a row that has the gene_id,
|
|
340 # then we'll add a row only to the gene_scaffold_orthogroup_association table.
|
|
341 sql = "SELECT id FROM plant_tribes_gene WHERE gene_id = '%s';" % gene_id
|
|
342 cur = self.conn.cursor()
|
|
343 cur.execute(sql)
|
|
344 try:
|
|
345 gene_id_db = cur.fetchone()[0]
|
|
346 except:
|
|
347 # Insert a row into the plant_tribes_gene table.
|
|
348 args = [gene_id, taxon_id, dna_sequence, aa_sequence]
|
|
349 sql = """
|
|
350 INSERT INTO plant_tribes_gene
|
|
351 VALUES (nextval('plant_tribes_gene_id_seq'), %s, %s, %s, %s)
|
|
352 RETURNING id;
|
|
353 """
|
3
|
354 cur = self.update(sql, tuple(args))
|
|
355 self.flush()
|
0
|
356 gene_id_db = cur.fetchone()[0]
|
|
357 # Insert a row into the gene_scaffold_orthogroup_association table.
|
|
358 # Get the scaffold_rec for the current scaffold_id and clustering_method.
|
|
359 # The list is [<scaffold_id_db>, <scaffold_id>, <clustering_method>]
|
|
360 for scaffold_rec in self.scaffold_recs:
|
|
361 if scaffold_id in scaffold_rec and clustering_method in scaffold_rec:
|
|
362 scaffold_id_db = scaffold_rec[0]
|
|
363 args = [gene_id_db, scaffold_id_db, orthogroup_id_db]
|
|
364 sql = """
|
|
365 INSERT INTO gene_scaffold_orthogroup_association
|
|
366 VALUES (nextval('gene_scaffold_orthogroup_association_id_seq'), %s, %s, %s);
|
|
367 """
|
3
|
368 cur = self.update(sql, tuple(args))
|
|
369 self.flush()
|
0
|
370
|
|
371
|
|
372 if __name__ == '__main__':
|
|
373 add_scaffold = AddScaffold()
|
3
|
374 add_scaffold.run()
|
|
375 add_scaffold.shutdown()
|