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