Package BioSQL :: Module Loader
[hide private]
[frames] | no frames]

Source Code for Module BioSQL.Loader

   1  # Copyright 2002 by Andrew Dalke.  All rights reserved. 
   2  # Revisions 2007-2008 copyright by Peter Cock.  All rights reserved. 
   3  # Revisions 2008 copyright by Cymon J. Cox.  All rights reserved. 
   4  # This code is part of the Biopython distribution and governed by its 
   5  # license.  Please see the LICENSE file that should have been included 
   6  # as part of this package. 
   7  # 
   8  # Note that BioSQL (including the database schema and scripts) is 
   9  # available and licensed separately.  Please consult www.biosql.org 
  10   
  11  """Load biopython objects into a BioSQL database for persistent storage. 
  12   
  13  This code makes it possible to store biopython objects in a relational 
  14  database and then retrieve them back. You shouldn't use any of the 
  15  classes in this module directly. Rather, call the load() method on 
  16  a database object. 
  17  """ 
  18  # standard modules 
  19  from time import gmtime, strftime 
  20   
  21  # biopython 
  22  from Bio import Alphabet 
  23  from Bio.SeqUtils.CheckSum import crc64 
  24  from Bio import Entrez 
  25  from Bio.Seq import UnknownSeq 
  26   
27 -class DatabaseLoader:
28 """Object used to load SeqRecord objects into a BioSQL database."""
29 - def __init__(self, adaptor, dbid, fetch_NCBI_taxonomy=False):
30 """Initialize with connection information for the database. 31 32 Creating a DatabaseLoader object is normally handled via the 33 BioSeqDatabase DBServer object, for example: 34 35 from BioSQL import BioSeqDatabase 36 server = BioSeqDatabase.open_database(driver="MySQLdb", user="gbrowse", 37 passwd = "biosql", host = "localhost", db="test_biosql") 38 try : 39 db = server["test"] 40 except KeyError : 41 db = server.new_database("test", description="For testing GBrowse") 42 """ 43 self.adaptor = adaptor 44 self.dbid = dbid 45 self.fetch_NCBI_taxonomy = fetch_NCBI_taxonomy
46
47 - def load_seqrecord(self, record):
48 """Load a Biopython SeqRecord into the database. 49 """ 50 bioentry_id = self._load_bioentry_table(record) 51 self._load_bioentry_date(record, bioentry_id) 52 self._load_biosequence(record, bioentry_id) 53 self._load_comment(record, bioentry_id) 54 self._load_dbxrefs(record, bioentry_id) 55 references = record.annotations.get('references', ()) 56 for reference, rank in zip(references, range(len(references))): 57 self._load_reference(reference, rank, bioentry_id) 58 self._load_annotations(record, bioentry_id) 59 for seq_feature_num in range(len(record.features)): 60 seq_feature = record.features[seq_feature_num] 61 self._load_seqfeature(seq_feature, seq_feature_num, bioentry_id)
62
63 - def _get_ontology_id(self, name, definition=None):
64 """Returns the identifier for the named ontology (PRIVATE). 65 66 This looks through the onotology table for a the given entry name. 67 If it is not found, a row is added for this ontology (using the 68 definition if supplied). In either case, the id corresponding to 69 the provided name is returned, so that you can reference it in 70 another table. 71 """ 72 oids = self.adaptor.execute_and_fetch_col0( 73 "SELECT ontology_id FROM ontology WHERE name = %s", 74 (name,)) 75 if oids: 76 return oids[0] 77 self.adaptor.execute( 78 "INSERT INTO ontology(name, definition) VALUES (%s, %s)", 79 (name, definition)) 80 return self.adaptor.last_id("ontology")
81 82
83 - def _get_term_id(self, 84 name, 85 ontology_id=None, 86 definition=None, 87 identifier=None):
88 """Get the id that corresponds to a term (PRIVATE). 89 90 This looks through the term table for a the given term. If it 91 is not found, a new id corresponding to this term is created. 92 In either case, the id corresponding to that term is returned, so 93 that you can reference it in another table. 94 95 The ontology_id should be used to disambiguate the term. 96 """ 97 98 # try to get the term id 99 sql = r"SELECT term_id FROM term " \ 100 r"WHERE name = %s" 101 fields = [name] 102 if ontology_id: 103 sql += ' AND ontology_id = %s' 104 fields.append(ontology_id) 105 id_results = self.adaptor.execute_and_fetchall(sql, fields) 106 # something is wrong 107 if len(id_results) > 1: 108 raise ValueError("Multiple term ids for %s: %r" % 109 (name, id_results)) 110 elif len(id_results) == 1: 111 return id_results[0][0] 112 else: 113 sql = r"INSERT INTO term (name, definition," \ 114 r" identifier, ontology_id)" \ 115 r" VALUES (%s, %s, %s, %s)" 116 self.adaptor.execute(sql, (name, definition, 117 identifier, ontology_id)) 118 return self.adaptor.last_id("term")
119
120 - def _add_dbxref(self, dbname, accession, version):
121 """Insert a dbxref and return its id.""" 122 123 self.adaptor.execute( 124 "INSERT INTO dbxref(dbname, accession, version)" \ 125 " VALUES (%s, %s, %s)", (dbname, accession, version)) 126 return self.adaptor.last_id("dbxref")
127
128 - def _get_taxon_id(self, record):
129 """Get the taxon id for this record (PRIVATE). 130 131 record - a SeqRecord object 132 133 This searches the taxon/taxon_name tables using the 134 NCBI taxon ID, scientific name and common name to find 135 the matching taxon table entry's id. 136 137 If the species isn't in the taxon table, and we have at 138 least the NCBI taxon ID, scientific name or common name, 139 at least a minimal stub entry is created in the table. 140 141 Returns the taxon id (database key for the taxon table, 142 not an NCBI taxon ID), or None if the taxonomy information 143 is missing. 144 145 See also the BioSQL script load_ncbi_taxonomy.pl which 146 will populate and update the taxon/taxon_name tables 147 with the latest information from the NCBI. 148 """ 149 150 # To find the NCBI taxid, first check for a top level annotation 151 ncbi_taxon_id = None 152 if "ncbi_taxid" in record.annotations : 153 #Could be a list of IDs. 154 if isinstance(record.annotations["ncbi_taxid"],list) : 155 if len(record.annotations["ncbi_taxid"])==1 : 156 ncbi_taxon_id = record.annotations["ncbi_taxid"][0] 157 else : 158 ncbi_taxon_id = record.annotations["ncbi_taxid"] 159 if not ncbi_taxon_id: 160 # Secondly, look for a source feature 161 for f in record.features: 162 if f.type == 'source': 163 quals = getattr(f, 'qualifiers', {}) 164 if "db_xref" in quals: 165 for db_xref in f.qualifiers["db_xref"]: 166 if db_xref.startswith("taxon:"): 167 ncbi_taxon_id = int(db_xref[6:]) 168 break 169 if ncbi_taxon_id: break 170 171 try : 172 scientific_name = record.annotations["organism"][:255] 173 except KeyError : 174 scientific_name = None 175 try : 176 common_name = record.annotations["source"][:255] 177 except KeyError : 178 common_name = None 179 # Note: The maximum length for taxon names in the schema is 255. 180 # Cropping it now should help in getting a match when searching, 181 # and avoids an error if we try and add these to the database. 182 183 184 if ncbi_taxon_id: 185 #Good, we have the NCBI taxon to go on - this is unambiguous :) 186 #Note that the scientific name and common name will only be 187 #used if we have to record a stub entry. 188 return self._get_taxon_id_from_ncbi_taxon_id(ncbi_taxon_id, 189 scientific_name, 190 common_name) 191 192 if not common_name and not scientific_name : 193 # Nothing to go on... and there is no point adding 194 # a new entry to the database. We'll just leave this 195 # sequence's taxon as a NULL in the database. 196 return None 197 198 # Next, we'll try to find a match based on the species name 199 # (stored in GenBank files as the organism and/or the source). 200 if scientific_name: 201 taxa = self.adaptor.execute_and_fetch_col0( 202 "SELECT taxon_id FROM taxon_name" \ 203 " WHERE name_class = 'scientific name' AND name = %s", 204 (scientific_name,)) 205 if taxa: 206 #Good, mapped the scientific name to a taxon table entry 207 return taxa[0] 208 209 # Last chance... 210 if common_name: 211 taxa = self.adaptor.execute_and_fetch_col0( 212 "SELECT DISTINCT taxon_id FROM taxon_name" \ 213 " WHERE name = %s", 214 (common_name,)) 215 #Its natural that several distinct taxa will have the same common 216 #name - in which case we can't resolve the taxon uniquely. 217 if len(taxa) > 1: 218 raise ValueError("Taxa: %d species have name %r" % ( 219 len(taxa), 220 common_name)) 221 if taxa: 222 #Good, mapped the common name to a taxon table entry 223 return taxa[0] 224 225 # At this point, as far as we can tell, this species isn't 226 # in the taxon table already. So we'll have to add it. 227 # We don't have an NCBI taxonomy ID, so if we do record just 228 # a stub entry, there is no simple way to fix this later. 229 # 230 # TODO - Should we try searching the NCBI taxonomy using the 231 # species name? 232 # 233 # OK, let's try inserting the species. 234 # Chances are we don't have enough information ... 235 # Furthermore, it won't be in the hierarchy. 236 237 lineage = [] 238 for c in record.annotations.get("taxonomy", []): 239 lineage.append([None, None, c]) 240 if lineage: 241 lineage[-1][1] = "genus" 242 lineage.append([None, "species", record.annotations["organism"]]) 243 # XXX do we have them? 244 if "subspecies" in record.annotations: 245 lineage.append([None, "subspecies", 246 record.annotations["subspecies"]]) 247 if "variant" in record.annotations: 248 lineage.append([None, "varietas", 249 record.annotations["variant"]]) 250 lineage[-1][0] = ncbi_taxon_id 251 252 left_value = self.adaptor.execute_one( 253 "SELECT MAX(left_value) FROM taxon")[0] 254 if not left_value: 255 left_value = 0 256 left_value += 1 257 258 # XXX -- Brad: Fixing this for now in an ugly way because 259 # I am getting overlaps for right_values. I need to dig into this 260 # more to actually understand how it works. I'm not sure it is 261 # actually working right anyhow. 262 right_start_value = self.adaptor.execute_one( 263 "SELECT MAX(right_value) FROM taxon")[0] 264 if not right_start_value: 265 right_start_value = 0 266 right_value = right_start_value + 2 * len(lineage) - 1 267 268 parent_taxon_id = None 269 for taxon in lineage: 270 self.adaptor.execute( 271 "INSERT INTO taxon(parent_taxon_id, ncbi_taxon_id, node_rank,"\ 272 " left_value, right_value)" \ 273 " VALUES (%s, %s, %s, %s, %s)", (parent_taxon_id, 274 taxon[0], 275 taxon[1], 276 left_value, 277 right_value)) 278 taxon_id = self.adaptor.last_id("taxon") 279 self.adaptor.execute( 280 "INSERT INTO taxon_name(taxon_id, name, name_class)" \ 281 "VALUES (%s, %s, 'scientific name')", (taxon_id, taxon[2][:255])) 282 #Note the name field is limited to 255, some SwissProt files 283 #have a multi-species name which can be longer. So truncate this. 284 left_value += 1 285 right_value -= 1 286 parent_taxon_id = taxon_id 287 if common_name: 288 self.adaptor.execute( 289 "INSERT INTO taxon_name(taxon_id, name, name_class)" \ 290 "VALUES (%s, %s, 'common name')", ( 291 taxon_id, common_name)) 292 293 return taxon_id
294
295 - def _fix_name_class(self, entrez_name) :
296 """Map Entrez name terms to those used in taxdump (PRIVATE). 297 298 We need to make this conversion to match the taxon_name.name_class 299 values used by the BioSQL load_ncbi_taxonomy.pl script. 300 301 e.g. 302 "ScientificName" -> "scientific name", 303 "EquivalentName" -> "equivalent name", 304 "Synonym" -> "synonym", 305 """ 306 #Add any special cases here: 307 # 308 #known = {} 309 #try : 310 # return known[entrez_name] 311 #except KeyError: 312 # pass 313 314 #Try automatically by adding spaces before each capital 315 def add_space(letter) : 316 if letter.isupper() : 317 return " "+letter.lower() 318 else : 319 return letter
320 answer = "".join([add_space(letter) for letter in entrez_name]).strip() 321 assert answer == answer.lower() 322 return answer
323
324 - def _get_taxon_id_from_ncbi_taxon_id(self, ncbi_taxon_id, 325 scientific_name = None, 326 common_name = None):
327 """Get the taxon id for this record from the NCBI taxon ID (PRIVATE). 328 329 ncbi_taxon_id - string containing an NCBI taxon id 330 scientific_name - string, used if a stub entry is recorded 331 common_name - string, used if a stub entry is recorded 332 333 This searches the taxon table using ONLY the NCBI taxon ID 334 to find the matching taxon table entry's ID (database key). 335 336 If the species isn't in the taxon table, and the fetch_NCBI_taxonomy 337 flag is true, Biopython will attempt to go online using Bio.Entrez 338 to fetch the official NCBI lineage, recursing up the tree until an 339 existing entry is found in the database or the full lineage has been 340 fetched. 341 342 Otherwise the NCBI taxon ID, scientific name and common name are 343 recorded as a minimal stub entry in the taxon and taxon_name tables. 344 Any partial information about the lineage from the SeqRecord is NOT 345 recorded. This should mean that (re)running the BioSQL script 346 load_ncbi_taxonomy.pl can fill in the taxonomy lineage. 347 348 Returns the taxon id (database key for the taxon table, not 349 an NCBI taxon ID). 350 """ 351 assert ncbi_taxon_id 352 353 taxon_id = self.adaptor.execute_and_fetch_col0( 354 "SELECT taxon_id FROM taxon WHERE ncbi_taxon_id = %s", 355 (ncbi_taxon_id,)) 356 if taxon_id: 357 #Good, we have mapped the NCBI taxid to a taxon table entry 358 return taxon_id[0] 359 360 # At this point, as far as we can tell, this species isn't 361 # in the taxon table already. So we'll have to add it. 362 363 parent_taxon_id = None 364 rank = "species" 365 genetic_code = None 366 mito_genetic_code = None 367 species_names = [] 368 if scientific_name : 369 species_names.append(("scientific name", scientific_name)) 370 if common_name : 371 species_names.append(("common name", common_name)) 372 373 if self.fetch_NCBI_taxonomy : 374 #Go online to get the parent taxon ID! 375 handle = Entrez.efetch(db="taxonomy",id=ncbi_taxon_id,retmode="XML") 376 taxonomic_record = Entrez.read(handle) 377 if len(taxonomic_record) == 1: 378 assert taxonomic_record[0]["TaxId"] == str(ncbi_taxon_id), \ 379 "%s versus %s" % (taxonomic_record[0]["TaxId"], 380 ncbi_taxon_id) 381 parent_taxon_id = self._get_taxon_id_from_ncbi_lineage( \ 382 taxonomic_record[0]["LineageEx"]) 383 rank = taxonomic_record[0]["Rank"] 384 genetic_code = taxonomic_record[0]["GeneticCode"]["GCId"] 385 mito_genetic_code = taxonomic_record[0]["MitoGeneticCode"]["MGCId"] 386 species_names = [("scientific name", 387 taxonomic_record[0]["ScientificName"])] 388 try : 389 for name_class, names in taxonomic_record[0]["OtherNames"].iteritems(): 390 name_class = self._fix_name_class(name_class) 391 if not isinstance(names, list) : 392 #The Entrez parser seems to return single entry 393 #lists as just a string which is annoying. 394 names = [names] 395 for name in names : 396 #Want to ignore complex things like ClassCDE entries 397 if isinstance(name, basestring) : 398 species_names.append((name_class, name)) 399 except KeyError : 400 #OtherNames isn't always present, 401 #e.g. NCBI taxon 41205, Bromheadia finlaysoniana 402 pass 403 else : 404 pass 405 # If we are not allowed to go online, we will record the bare minimum; 406 # as long as the NCBI taxon id is present, then (re)running 407 # load_ncbi_taxonomy.pl should fill in the taxonomomy lineage 408 # (and update the species names). 409 # 410 # I am NOT going to try and record the lineage, even if it 411 # is in the record annotation as a list of names, as we won't 412 # know the NCBI taxon IDs for these parent nodes. 413 414 self.adaptor.execute( 415 "INSERT INTO taxon(parent_taxon_id, ncbi_taxon_id, node_rank,"\ 416 " genetic_code, mito_genetic_code, left_value, right_value)" \ 417 " VALUES (%s, %s, %s, %s, %s, %s, %s)", (parent_taxon_id, 418 ncbi_taxon_id, 419 rank, 420 genetic_code, 421 mito_genetic_code, 422 None, 423 None)) 424 taxon_id = self.adaptor.last_id("taxon") 425 426 #Record the scientific name, common name, etc 427 for name_class, name in species_names : 428 self.adaptor.execute( 429 "INSERT INTO taxon_name(taxon_id, name, name_class)" \ 430 " VALUES (%s, %s, %s)", (taxon_id, 431 name[:255], 432 name_class)) 433 return taxon_id
434
435 - def _get_taxon_id_from_ncbi_lineage(self, taxonomic_lineage) :
436 """This is recursive! (PRIVATE). 437 438 taxonomic_lineage - list of taxonomy dictionaries from Bio.Entrez 439 440 First dictionary in list is the taxonomy root, highest would be the species. 441 Each dictionary includes: 442 - TaxID (string, NCBI taxon id) 443 - Rank (string, e.g. "species", "genus", ..., "phylum", ...) 444 - ScientificName (string) 445 (and that is all at the time of writing) 446 447 This method will record all the lineage given, returning the the taxon id 448 (database key, not NCBI taxon id) of the final entry (the species). 449 """ 450 ncbi_taxon_id = taxonomic_lineage[-1]["TaxId"] 451 452 #Is this in the database already? Check the taxon table... 453 taxon_id = self.adaptor.execute_and_fetch_col0( 454 "SELECT taxon_id FROM taxon" \ 455 " WHERE ncbi_taxon_id=%s" % ncbi_taxon_id) 456 if taxon_id: 457 # we could verify that the Scientific Name etc in the database 458 # is the same and update it or print a warning if not... 459 if isinstance(taxon_id, list) : 460 assert len(taxon_id)==1 461 return taxon_id[0] 462 else : 463 return taxon_id 464 465 #We have to record this. 466 if len(taxonomic_lineage) > 1 : 467 #Use recursion to find out the taxon id (database key) of the parent. 468 parent_taxon_id = self._get_taxon_id_from_ncbi_lineage(taxonomic_lineage[:-1]) 469 assert isinstance(parent_taxon_id, int) or isinstance(parent_taxon_id, long), repr(parent_taxon_id) 470 else : 471 parent_taxon_id = None 472 473 # INSERT new taxon 474 rank = taxonomic_lineage[-1].get("Rank", None) 475 self.adaptor.execute( 476 "INSERT INTO taxon(ncbi_taxon_id, parent_taxon_id, node_rank)"\ 477 " VALUES (%s, %s, %s)", (ncbi_taxon_id, parent_taxon_id, rank)) 478 taxon_id = self.adaptor.last_id("taxon") 479 assert isinstance(taxon_id, int) or isinstance(taxon_id, long), repr(taxon_id) 480 # ... and its name in taxon_name 481 scientific_name = taxonomic_lineage[-1].get("ScientificName", None) 482 if scientific_name : 483 self.adaptor.execute( 484 "INSERT INTO taxon_name(taxon_id, name, name_class)" \ 485 " VALUES (%s, %s, 'scientific name')", (taxon_id, 486 scientific_name[:255])) 487 return taxon_id
488 489
490 - def _load_bioentry_table(self, record):
491 """Fill the bioentry table with sequence information (PRIVATE). 492 493 record - SeqRecord object to add to the database. 494 """ 495 # get the pertinent info and insert it 496 497 if record.id.count(".") == 1: # try to get a version from the id 498 #This assumes the string is something like "XXXXXXXX.123" 499 accession, version = record.id.split('.') 500 try : 501 version = int(version) 502 except ValueError : 503 accession = record.id 504 version = 0 505 else: # otherwise just use a version of 0 506 accession = record.id 507 version = 0 508 509 if "accessions" in record.annotations \ 510 and isinstance(record.annotations["accessions"],list) \ 511 and record.annotations["accessions"] : 512 #Take the first accession (one if there is more than one) 513 accession = record.annotations["accessions"][0] 514 515 #Find the taxon id (this is not just the NCBI Taxon ID) 516 #NOTE - If the species isn't defined in the taxon table, 517 #a new minimal entry is created. 518 taxon_id = self._get_taxon_id(record) 519 520 if "gi" in record.annotations : 521 identifier = record.annotations["gi"] 522 else : 523 identifier = record.id 524 525 #Allow description and division to default to NULL as in BioPerl. 526 description = getattr(record, 'description', None) 527 division = record.annotations.get("data_file_division", None) 528 529 sql = """ 530 INSERT INTO bioentry ( 531 biodatabase_id, 532 taxon_id, 533 name, 534 accession, 535 identifier, 536 division, 537 description, 538 version) 539 VALUES ( 540 %s, 541 %s, 542 %s, 543 %s, 544 %s, 545 %s, 546 %s, 547 %s)""" 548 #print self.dbid, taxon_id, record.name, accession, identifier, \ 549 # division, description, version 550 self.adaptor.execute(sql, (self.dbid, 551 taxon_id, 552 record.name, 553 accession, 554 identifier, 555 division, 556 description, 557 version)) 558 # now retrieve the id for the bioentry 559 bioentry_id = self.adaptor.last_id('bioentry') 560 561 return bioentry_id
562
563 - def _load_bioentry_date(self, record, bioentry_id):
564 """Add the effective date of the entry into the database. 565 566 record - a SeqRecord object with an annotated date 567 bioentry_id - corresponding database identifier 568 """ 569 # dates are GenBank style, like: 570 # 14-SEP-2000 571 date = record.annotations.get("date", 572 strftime("%d-%b-%Y", gmtime()).upper()) 573 annotation_tags_id = self._get_ontology_id("Annotation Tags") 574 date_id = self._get_term_id("date_changed", annotation_tags_id) 575 sql = r"INSERT INTO bioentry_qualifier_value" \ 576 r" (bioentry_id, term_id, value, rank)" \ 577 r" VALUES (%s, %s, %s, 1)" 578 self.adaptor.execute(sql, (bioentry_id, date_id, date))
579
580 - def _load_biosequence(self, record, bioentry_id):
581 """Record a SeqRecord's sequence and alphabet in the database (PRIVATE). 582 583 record - a SeqRecord object with a seq property 584 bioentry_id - corresponding database identifier 585 """ 586 if record.seq is None : 587 #The biosequence table entry is optional, so if we haven't 588 #got a sequence, we don't need to write to the table. 589 return 590 591 # determine the string representation of the alphabet 592 if isinstance(record.seq.alphabet, Alphabet.DNAAlphabet): 593 alphabet = "dna" 594 elif isinstance(record.seq.alphabet, Alphabet.RNAAlphabet): 595 alphabet = "rna" 596 elif isinstance(record.seq.alphabet, Alphabet.ProteinAlphabet): 597 alphabet = "protein" 598 else: 599 alphabet = "unknown" 600 601 if isinstance(record.seq, UnknownSeq) : 602 seq_str = None 603 else : 604 seq_str = str(record.seq) 605 606 sql = r"INSERT INTO biosequence (bioentry_id, version, " \ 607 r"length, seq, alphabet) " \ 608 r"VALUES (%s, 0, %s, %s, %s)" 609 self.adaptor.execute(sql, (bioentry_id, 610 len(record.seq), 611 seq_str, 612 alphabet))
613
614 - def _load_comment(self, record, bioentry_id):
615 """Record a SeqRecord's annotated comment in the database (PRIVATE). 616 617 record - a SeqRecord object with an annotated comment 618 bioentry_id - corresponding database identifier 619 """ 620 comments = record.annotations.get('comment') 621 if not comments: 622 return 623 if not isinstance(comments, list) : 624 #It should be a string then... 625 comments = [comments] 626 627 for index, comment in enumerate(comments) : 628 comment = comment.replace('\n', ' ') 629 #TODO - Store each line as a separate entry? This would preserve 630 #the newlines, but we should check BioPerl etc to be consistent. 631 sql = "INSERT INTO comment (bioentry_id, comment_text, rank)" \ 632 " VALUES (%s, %s, %s)" 633 self.adaptor.execute(sql, (bioentry_id, comment, index+1))
634
635 - def _load_annotations(self, record, bioentry_id) :
636 """Record a SeqRecord's misc annotations in the database (PRIVATE). 637 638 The annotation strings are recorded in the bioentry_qualifier_value 639 table, except for special cases like the reference, comment and 640 taxonomy which are handled with their own tables. 641 642 record - a SeqRecord object with an annotations dictionary 643 bioentry_id - corresponding database identifier 644 """ 645 mono_sql = "INSERT INTO bioentry_qualifier_value" \ 646 "(bioentry_id, term_id, value)" \ 647 " VALUES (%s, %s, %s)" 648 many_sql = "INSERT INTO bioentry_qualifier_value" \ 649 "(bioentry_id, term_id, value, rank)" \ 650 " VALUES (%s, %s, %s, %s)" 651 tag_ontology_id = self._get_ontology_id('Annotation Tags') 652 for key, value in record.annotations.iteritems() : 653 if key in ["references", "comment", "ncbi_taxid"] : 654 #Handled separately 655 continue 656 term_id = self._get_term_id(key, ontology_id=tag_ontology_id) 657 if isinstance(value, list) : 658 rank = 0 659 for entry in value : 660 if isinstance(entry, str) or isinstance(entry, int): 661 #Easy case 662 rank += 1 663 self.adaptor.execute(many_sql, \ 664 (bioentry_id, term_id, str(entry), rank)) 665 else : 666 pass 667 #print "Ignoring annotation '%s' sub-entry of type '%s'" \ 668 # % (key, str(type(entry))) 669 elif isinstance(value, str) or isinstance(value, int): 670 #Have a simple single entry, leave rank as the DB default 671 self.adaptor.execute(mono_sql, \ 672 (bioentry_id, term_id, str(value))) 673 else : 674 pass
675 #print "Ignoring annotation '%s' entry of type '%s'" \ 676 # % (key, type(value)) 677 678
679 - def _load_reference(self, reference, rank, bioentry_id):
680 """Record a SeqRecord's annotated references in the database (PRIVATE). 681 682 record - a SeqRecord object with annotated references 683 bioentry_id - corresponding database identifier 684 """ 685 686 refs = None 687 if reference.medline_id: 688 refs = self.adaptor.execute_and_fetch_col0( 689 "SELECT reference_id" \ 690 " FROM reference JOIN dbxref USING (dbxref_id)" \ 691 " WHERE dbname = 'MEDLINE' AND accession = %s", 692 (reference.medline_id,)) 693 if not refs and reference.pubmed_id: 694 refs = self.adaptor.execute_and_fetch_col0( 695 "SELECT reference_id" \ 696 " FROM reference JOIN dbxref USING (dbxref_id)" \ 697 " WHERE dbname = 'PUBMED' AND accession = %s", 698 (reference.pubmed_id,)) 699 if not refs: 700 s = [] 701 for f in reference.authors, reference.title, reference.journal: 702 s.append(f or "<undef>") 703 crc = crc64("".join(s)) 704 refs = self.adaptor.execute_and_fetch_col0( 705 "SELECT reference_id FROM reference" \ 706 r" WHERE crc = %s", (crc,)) 707 if not refs: 708 if reference.medline_id: 709 dbxref_id = self._add_dbxref("MEDLINE", 710 reference.medline_id, 0) 711 elif reference.pubmed_id: 712 dbxref_id = self._add_dbxref("PUBMED", 713 reference.pubmed_id, 0) 714 else: 715 dbxref_id = None 716 authors = reference.authors or None 717 title = reference.title or None 718 #The location/journal field cannot be Null, so default 719 #to an empty string rather than None: 720 journal = reference.journal or "" 721 self.adaptor.execute( 722 "INSERT INTO reference (dbxref_id, location," \ 723 " title, authors, crc)" \ 724 " VALUES (%s, %s, %s, %s, %s)", 725 (dbxref_id, journal, title, 726 authors, crc)) 727 reference_id = self.adaptor.last_id("reference") 728 else: 729 reference_id = refs[0] 730 731 if reference.location: 732 start = 1 + int(str(reference.location[0].start)) 733 end = int(str(reference.location[0].end)) 734 else: 735 start = None 736 end = None 737 738 sql = "INSERT INTO bioentry_reference (bioentry_id, reference_id," \ 739 " start_pos, end_pos, rank)" \ 740 " VALUES (%s, %s, %s, %s, %s)" 741 self.adaptor.execute(sql, (bioentry_id, reference_id, 742 start, end, rank + 1))
743
744 - def _load_seqfeature(self, feature, feature_rank, bioentry_id):
745 """Load a biopython SeqFeature into the database (PRIVATE). 746 """ 747 seqfeature_id = self._load_seqfeature_basic(feature.type, feature_rank, 748 bioentry_id) 749 self._load_seqfeature_locations(feature, seqfeature_id) 750 self._load_seqfeature_qualifiers(feature.qualifiers, seqfeature_id)
751
752 - def _load_seqfeature_basic(self, feature_type, feature_rank, bioentry_id):
753 """Load the first tables of a seqfeature and returns the id (PRIVATE). 754 755 This loads the "key" of the seqfeature (ie. CDS, gene) and 756 the basic seqfeature table itself. 757 """ 758 ontology_id = self._get_ontology_id('SeqFeature Keys') 759 seqfeature_key_id = self._get_term_id(feature_type, 760 ontology_id = ontology_id) 761 # XXX source is always EMBL/GenBank/SwissProt here; it should depend on 762 # the record (how?) 763 source_cat_id = self._get_ontology_id('SeqFeature Sources') 764 source_term_id = self._get_term_id('EMBL/GenBank/SwissProt', 765 ontology_id = source_cat_id) 766 767 sql = r"INSERT INTO seqfeature (bioentry_id, type_term_id, " \ 768 r"source_term_id, rank) VALUES (%s, %s, %s, %s)" 769 self.adaptor.execute(sql, (bioentry_id, seqfeature_key_id, 770 source_term_id, feature_rank + 1)) 771 seqfeature_id = self.adaptor.last_id('seqfeature') 772 773 return seqfeature_id
774
775 - def _load_seqfeature_locations(self, feature, seqfeature_id):
776 """Load all of the locations for a SeqFeature into tables (PRIVATE). 777 778 This adds the locations related to the SeqFeature into the 779 seqfeature_location table. Fuzzies are not handled right now. 780 For a simple location, ie (1..2), we have a single table row 781 with seq_start = 1, seq_end = 2, location_rank = 1. 782 783 For split locations, ie (1..2, 3..4, 5..6) we would have three 784 row tables with: 785 start = 1, end = 2, rank = 1 786 start = 3, end = 4, rank = 2 787 start = 5, end = 6, rank = 3 788 """ 789 # TODO - Record an ontology for the locations (using location.term_id) 790 # which for now as in BioPerl we leave defaulting to NULL. 791 792 # two cases, a simple location or a split location 793 if not feature.sub_features: # simple location 794 self._insert_seqfeature_location(feature, 1, seqfeature_id) 795 else: # split location 796 for rank, cur_feature in enumerate(feature.sub_features): 797 self._insert_seqfeature_location(cur_feature, 798 rank + 1, 799 seqfeature_id)
800
801 - def _insert_seqfeature_location(self, feature, rank, seqfeature_id):
802 """Add a location of a SeqFeature to the seqfeature_location table (PRIVATE). 803 804 TODO - Add location_operators to location_qualifier_value. 805 """ 806 # convert biopython locations to the 1-based location system 807 # used in bioSQL 808 # XXX This could also handle fuzzies 809 start = feature.location.nofuzzy_start + 1 810 end = feature.location.nofuzzy_end 811 812 # Biopython uses None when we don't know strand information but 813 # BioSQL requires something (non null) and sets this as zero 814 # So we'll use the strand or 0 if Biopython spits out None 815 strand = feature.strand or 0 816 817 # TODO - Record an ontology term for the location (location.term_id) 818 # which for now like BioPerl we'll leave as NULL. 819 loc_term_id = None 820 821 if feature.ref: 822 # sub_feature remote locations when they are in the same db as the current 823 # record do not have a value for ref_db, which the SeqFeature object 824 # stores as None. BioSQL schema requires a varchar and is not NULL 825 dbxref_id = self._get_dbxref_id(feature.ref_db or "", feature.ref) 826 else : 827 dbxref_id = None 828 829 sql = r"INSERT INTO location (seqfeature_id, dbxref_id, term_id," \ 830 r"start_pos, end_pos, strand, rank) " \ 831 r"VALUES (%s, %s, %s, %s, %s, %s, %s)" 832 self.adaptor.execute(sql, (seqfeature_id, dbxref_id, loc_term_id, 833 start, end, strand, rank)) 834 835 """ 836 # See Bug 2677 837 # TODO - Record the location_operator (e.g. "join" or "order") 838 # using the location_qualifier_value table (which we and BioPerl 839 # have historically left empty). 840 # Note this will need an ontology term for the location qualifer 841 # (location_qualifier_value.term_id) for which oddly the schema 842 # does not allow NULL. 843 if feature.location_operator: 844 #e.g. "join" (common), 845 #or "order" (see Tests/GenBank/protein_refseq2.gb) 846 location_id = self.adaptor.last_id('location') 847 loc_qual_term_id = None # Not allowed in BioSQL v1.0.1 848 sql = r"INSERT INTO location_qualifier_value" \ 849 r"(location_id, term_id, value)" \ 850 r"VALUES (%s, %s, %s)" 851 self.adaptor.execute(sql, (location_id, loc_qual_term_id, 852 feature.location_operator)) 853 """
854
855 - def _load_seqfeature_qualifiers(self, qualifiers, seqfeature_id):
856 """Insert the (key, value) pair qualifiers relating to a feature (PRIVATE). 857 858 Qualifiers should be a dictionary of the form: 859 {key : [value1, value2]} 860 """ 861 tag_ontology_id = self._get_ontology_id('Annotation Tags') 862 for qualifier_key in qualifiers.keys(): 863 # Treat db_xref qualifiers differently to sequence annotation 864 # qualifiers by populating the seqfeature_dbxref and dbxref 865 # tables. Other qualifiers go into the seqfeature_qualifier_value 866 # and (if new) term tables. 867 if qualifier_key != 'db_xref': 868 qualifier_key_id = self._get_term_id(qualifier_key, 869 ontology_id=tag_ontology_id) 870 # now add all of the values to their table 871 entries = qualifiers[qualifier_key] 872 if not isinstance(entries, list) : 873 # Could be a plain string, or an int or a float. 874 # However, we exect a list of strings here. 875 entries = [entries] 876 for qual_value_rank in range(len(entries)): 877 qualifier_value = entries[qual_value_rank] 878 sql = r"INSERT INTO seqfeature_qualifier_value "\ 879 r" (seqfeature_id, term_id, rank, value) VALUES"\ 880 r" (%s, %s, %s, %s)" 881 self.adaptor.execute(sql, (seqfeature_id, 882 qualifier_key_id, 883 qual_value_rank + 1, 884 qualifier_value)) 885 else: 886 # The dbxref_id qualifier/value sets go into the dbxref table 887 # as dbname, accession, version tuples, with dbxref.dbxref_id 888 # being automatically assigned, and into the seqfeature_dbxref 889 # table as seqfeature_id, dbxref_id, and rank tuples 890 self._load_seqfeature_dbxref(qualifiers[qualifier_key], 891 seqfeature_id)
892 893
894 - def _load_seqfeature_dbxref(self, dbxrefs, seqfeature_id):
895 """Add database crossreferences of a SeqFeature to the database (PRIVATE). 896 897 o dbxrefs List, dbxref data from the source file in the 898 format <database>:<accession> 899 900 o seqfeature_id Int, the identifier for the seqfeature in the 901 seqfeature table 902 903 Insert dbxref qualifier data for a seqfeature into the 904 seqfeature_dbxref and, if required, dbxref tables. 905 The dbxref_id qualifier/value sets go into the dbxref table 906 as dbname, accession, version tuples, with dbxref.dbxref_id 907 being automatically assigned, and into the seqfeature_dbxref 908 table as seqfeature_id, dbxref_id, and rank tuples 909 """ 910 # NOTE - In older versions of Biopython, we would map the GenBank 911 # db_xref "name", for example "GI" to "GeneIndex", and give a warning 912 # for any unknown terms. This was a long term maintainance problem, 913 # and differed from BioPerl and BioJava's implementation. See bug 2405 914 for rank, value in enumerate(dbxrefs): 915 # Split the DB:accession format string at colons. We have to 916 # account for multiple-line and multiple-accession entries 917 try: 918 dbxref_data = value.replace(' ','').replace('\n','').split(':') 919 db = dbxref_data[0] 920 accessions = dbxref_data[1:] 921 except: 922 raise ValueError("Parsing of db_xref failed: '%s'" % value) 923 # Loop over all the grabbed accessions, and attempt to fill the 924 # table 925 for accession in accessions: 926 # Get the dbxref_id value for the dbxref data 927 dbxref_id = self._get_dbxref_id(db, accession) 928 # Insert the seqfeature_dbxref data 929 self._get_seqfeature_dbxref(seqfeature_id, dbxref_id, rank+1)
930
931 - def _get_dbxref_id(self, db, accession):
932 """ _get_dbxref_id(self, db, accession) -> Int 933 934 o db String, the name of the external database containing 935 the accession number 936 937 o accession String, the accession of the dbxref data 938 939 Finds and returns the dbxref_id for the passed data. The method 940 attempts to find an existing record first, and inserts the data 941 if there is no record. 942 """ 943 # Check for an existing record 944 sql = r'SELECT dbxref_id FROM dbxref WHERE dbname = %s ' \ 945 r'AND accession = %s' 946 dbxref_id = self.adaptor.execute_and_fetch_col0(sql, (db, accession)) 947 # If there was a record, return the dbxref_id, else create the 948 # record and return the created dbxref_id 949 if dbxref_id: 950 return dbxref_id[0] 951 return self._add_dbxref(db, accession, 0)
952
953 - def _get_seqfeature_dbxref(self, seqfeature_id, dbxref_id, rank):
954 """ Check for a pre-existing seqfeature_dbxref entry with the passed 955 seqfeature_id and dbxref_id. If one does not exist, insert new 956 data 957 958 """ 959 # Check for an existing record 960 sql = r"SELECT seqfeature_id, dbxref_id FROM seqfeature_dbxref " \ 961 r"WHERE seqfeature_id = '%s' AND dbxref_id = '%s'" 962 result = self.adaptor.execute_and_fetch_col0(sql, (seqfeature_id, 963 dbxref_id)) 964 # If there was a record, return without executing anything, else create 965 # the record and return 966 if result: 967 return result 968 return self._add_seqfeature_dbxref(seqfeature_id, dbxref_id, rank)
969
970 - def _add_seqfeature_dbxref(self, seqfeature_id, dbxref_id, rank):
971 """ Insert a seqfeature_dbxref row and return the seqfeature_id and 972 dbxref_id 973 """ 974 sql = r'INSERT INTO seqfeature_dbxref ' \ 975 '(seqfeature_id, dbxref_id, rank) VALUES' \ 976 r'(%s, %s, %s)' 977 self.adaptor.execute(sql, (seqfeature_id, dbxref_id, rank)) 978 return (seqfeature_id, dbxref_id)
979
980 - def _load_dbxrefs(self, record, bioentry_id) :
981 """Load any sequence level cross references into the database (PRIVATE). 982 983 See table bioentry_dbxref.""" 984 for rank, value in enumerate(record.dbxrefs): 985 # Split the DB:accession string at first colon. 986 # We have to cope with things like: 987 # "MGD:MGI:892" (db="MGD", accession="MGI:892") 988 # "GO:GO:123" (db="GO", accession="GO:123") 989 # 990 # Annoyingly I have seen the NCBI use both the style 991 # "GO:GO:123" and "GO:123" in different vintages. 992 assert value.count("\n")==0 993 try: 994 db, accession = value.split(':',1) 995 db = db.strip() 996 accession = accession.strip() 997 except: 998 raise ValueError("Parsing of dbxrefs list failed: '%s'" % value) 999 # Get the dbxref_id value for the dbxref data 1000 dbxref_id = self._get_dbxref_id(db, accession) 1001 # Insert the bioentry_dbxref data 1002 self._get_bioentry_dbxref(bioentry_id, dbxref_id, rank+1)
1003
1004 - def _get_bioentry_dbxref(self, bioentry_id, dbxref_id, rank):
1005 """ Check for a pre-existing bioentry_dbxref entry with the passed 1006 seqfeature_id and dbxref_id. If one does not exist, insert new 1007 data 1008 1009 """ 1010 # Check for an existing record 1011 sql = r"SELECT bioentry_id, dbxref_id FROM bioentry_dbxref " \ 1012 r"WHERE bioentry_id = '%s' AND dbxref_id = '%s'" 1013 result = self.adaptor.execute_and_fetch_col0(sql, (bioentry_id, 1014 dbxref_id)) 1015 # If there was a record, return without executing anything, else create 1016 # the record and return 1017 if result: 1018 return result 1019 return self._add_bioentry_dbxref(bioentry_id, dbxref_id, rank)
1020
1021 - def _add_bioentry_dbxref(self, bioentry_id, dbxref_id, rank):
1022 """ Insert a bioentry_dbxref row and return the seqfeature_id and 1023 dbxref_id 1024 """ 1025 sql = r'INSERT INTO bioentry_dbxref ' \ 1026 '(bioentry_id,dbxref_id,rank) VALUES ' \ 1027 '(%s, %s, %s)' 1028 self.adaptor.execute(sql, (bioentry_id, dbxref_id, rank)) 1029 return (bioentry_id, dbxref_id)
1030
1031 -class DatabaseRemover:
1032 """Complement the Loader functionality by fully removing a database. 1033 1034 This probably isn't really useful for normal purposes, since you 1035 can just do a: 1036 DROP DATABASE db_name 1037 and then recreate the database. But, it's really useful for testing 1038 purposes. 1039 1040 YB: now use the cascaded deletions 1041 """
1042 - def __init__(self, adaptor, dbid):
1043 """Initialize with a database id and adaptor connection. 1044 """ 1045 self.adaptor = adaptor 1046 self.dbid = dbid
1047
1048 - def remove(self):
1049 """Remove everything related to the given database id. 1050 """ 1051 sql = r"DELETE FROM bioentry WHERE biodatabase_id = %s" 1052 self.adaptor.execute(sql, (self.dbid,)) 1053 sql = r"DELETE FROM biodatabase WHERE biodatabase_id = %s" 1054 self.adaptor.execute(sql, (self.dbid,))
1055