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