comparison gene_family_scaffold_loader.py @ 0:177b62db4320 draft

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