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

Source Code for Module BioSQL.BioSeq

  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  """Implementations of Biopython-like Seq objects on top of BioSQL. 
 11   
 12  This allows retrival of items stored in a BioSQL database using 
 13  a biopython-like Seq interface. 
 14  """ 
 15   
 16  from Bio import Alphabet 
 17  from Bio.Seq import Seq 
 18  from Bio.SeqRecord import SeqRecord 
 19  from Bio import SeqFeature 
 20   
21 -class DBSeq(Seq): # This implements the biopython Seq interface
22 - def __init__(self, primary_id, adaptor, alphabet, start, length):
23 """Create a new DBSeq object referring to a BioSQL entry. 24 25 You wouldn't normally create a DBSeq object yourself, this is done 26 for you when retreiving a DBSeqRecord object from the database. 27 """ 28 self.primary_id = primary_id 29 self.adaptor = adaptor 30 self.alphabet = alphabet 31 self._length = length 32 self.start = start
33
34 - def __len__(self):
35 return self._length
36
37 - def __getitem__(self, index) : # Seq API requirement
38 #Note since Python 2.0, __getslice__ is deprecated 39 #and __getitem__ is used instead. 40 #See http://docs.python.org/ref/sequence-methods.html 41 if isinstance(index, int) : 42 #Return a single letter as a string 43 i = index 44 if i < 0: 45 if -i > self._length: 46 raise IndexError(i) 47 i = i + self._length 48 elif i >= self._length: 49 raise IndexError(i) 50 return self.adaptor.get_subseq_as_string(self.primary_id, 51 self.start + i, 52 self.start + i + 1) 53 if not isinstance(index, slice) : 54 raise ValueError("Unexpected index type") 55 56 #Return the (sub)sequence as another DBSeq or Seq object 57 #(see the Seq obect's __getitem__ method) 58 if index.start is None : 59 i=0 60 else : 61 i = index.start 62 if i < 0 : 63 #Map to equavilent positive index 64 if -i > self._length: 65 raise IndexError(i) 66 i = i + self._length 67 elif i >= self._length: 68 #Trivial case, should return empty string! 69 i = self._length 70 71 if index.stop is None : 72 j = self._length 73 else : 74 j = index.stop 75 if j < 0 : 76 #Map to equavilent positive index 77 if -j > self._length: 78 raise IndexError(j) 79 j = j + self._length 80 elif j >= self._length: 81 j = self._length 82 83 if i >= j: 84 #Trivial case, empty string. 85 return Seq("", self.alphabet) 86 elif index.step is None or index.step == 1 : 87 #Easy case - can return a DBSeq with the start and end adjusted 88 return self.__class__(self.primary_id, self.adaptor, self.alphabet, 89 self.start + i, j - i) 90 else : 91 #Tricky. Will have to create a Seq object because of the stride 92 full = self.adaptor.get_subseq_as_string(self.primary_id, 93 self.start + i, 94 self.start + j) 95 return Seq(full[::index.step], self.alphabet) 96
97 - def tostring(self):
98 """Returns the full sequence as a python string. 99 100 Although not formally deprecated, you are now encouraged to use 101 str(my_seq) instead of my_seq.tostring().""" 102 return self.adaptor.get_subseq_as_string(self.primary_id, 103 self.start, 104 self.start + self._length)
105 - def __str__(self):
106 """Returns the full sequence as a python string.""" 107 return self.adaptor.get_subseq_as_string(self.primary_id, 108 self.start, 109 self.start + self._length)
110 111 data = property(tostring, doc="Sequence as string (DEPRECATED)") 112
113 - def toseq(self):
114 """Returns the full sequence as a Seq object.""" 115 #Note - the method name copies that of the MutableSeq object 116 return Seq(str(self), self.alphabet)
117
118 - def __add__(self, other) :
119 #Let the Seq object deal with the alphabet issues etc 120 return self.toseq() + other
121
122 - def __radd__(self, other) :
123 #Let the Seq object deal with the alphabet issues etc 124 return other + self.toseq()
125 126
127 -def _retrieve_seq(adaptor, primary_id):
128 seqs = adaptor.execute_and_fetchall( 129 "SELECT alphabet, length(seq) FROM biosequence" \ 130 " WHERE bioentry_id = %s", (primary_id,)) 131 if seqs: 132 moltype, length = seqs[0] 133 moltype = moltype.lower() #might be upper case in database 134 #We have no way of knowing if these sequences will use IUPAC 135 #alphabets, and we certainly can't assume they are unambiguous! 136 if moltype == "dna": 137 alphabet = Alphabet.generic_dna 138 elif moltype == "rna": 139 alphabet = Alphabet.generic_rna 140 elif moltype == "protein": 141 alphabet = Alphabet.generic_protein 142 elif moltype == "unknown": 143 #This is used in BioSQL/Loader.py and would happen 144 #for any generic or nucleotide alphabets. 145 alphabet = Alphabet.single_letter_alphabet 146 else: 147 raise AssertionError("Unknown moltype: %s" % moltype) 148 seq = DBSeq(primary_id, adaptor, alphabet, 0, int(length)) 149 return seq 150 else: 151 return None
152
153 -def _retrieve_dbxrefs(adaptor, primary_id):
154 """Retrieve the database cross references for the sequence.""" 155 _dbxrefs = [] 156 dbxrefs = adaptor.execute_and_fetchall( 157 "SELECT dbname, accession, version" \ 158 " FROM bioentry_dbxref join dbxref using (dbxref_id)" \ 159 " WHERE bioentry_id = %s" \ 160 " ORDER BY rank", (primary_id,)) 161 for dbname, accession, version in dbxrefs: 162 if version and version != "0": 163 v = "%s.%s" % (accession, version) 164 else: 165 v = accession 166 _dbxrefs.append("%s:%s" % (dbname, v)) 167 return _dbxrefs
168
169 -def _retrieve_features(adaptor, primary_id):
170 sql = "SELECT seqfeature_id, type.name, rank" \ 171 " FROM seqfeature join term type on (type_term_id = type.term_id)" \ 172 " WHERE bioentry_id = %s" \ 173 " ORDER BY rank" 174 results = adaptor.execute_and_fetchall(sql, (primary_id,)) 175 seq_feature_list = [] 176 for seqfeature_id, seqfeature_type, seqfeature_rank in results: 177 # Get qualifiers [except for db_xref which is stored separately] 178 qvs = adaptor.execute_and_fetchall( 179 "SELECT name, value" \ 180 " FROM seqfeature_qualifier_value join term using (term_id)" \ 181 " WHERE seqfeature_id = %s" \ 182 " ORDER BY rank", (seqfeature_id,)) 183 qualifiers = {} 184 for qv_name, qv_value in qvs: 185 qualifiers.setdefault(qv_name, []).append(qv_value) 186 # Get db_xrefs [special case of qualifiers] 187 qvs = adaptor.execute_and_fetchall( 188 "SELECT dbxref.dbname, dbxref.accession" \ 189 " FROM dbxref join seqfeature_dbxref using (dbxref_id)" \ 190 " WHERE seqfeature_dbxref.seqfeature_id = %s" \ 191 " ORDER BY rank", (seqfeature_id,)) 192 for qv_name, qv_value in qvs: 193 value = "%s:%s" % (qv_name, qv_value) 194 qualifiers.setdefault("db_xref", []).append(value) 195 # Get locations 196 results = adaptor.execute_and_fetchall( 197 "SELECT location_id, start_pos, end_pos, strand" \ 198 " FROM location" \ 199 " WHERE seqfeature_id = %s" \ 200 " ORDER BY rank", (seqfeature_id,)) 201 locations = [] 202 # convert to Python standard form 203 # Convert strand = 0 to strand = None 204 # re: comment in Loader.py: 205 # Biopython uses None when we don't know strand information but 206 # BioSQL requires something (non null) and sets this as zero 207 # So we'll use the strand or 0 if Biopython spits out None 208 for location_id, start, end, strand in results: 209 if start: 210 start -= 1 211 if strand == 0: 212 strand = None 213 locations.append( (location_id, start, end, strand) ) 214 # Get possible remote reference information 215 remote_results = adaptor.execute_and_fetchall( 216 "SELECT location_id, dbname, accession, version" \ 217 " FROM location join dbxref using (dbxref_id)" \ 218 " WHERE seqfeature_id = %s", (seqfeature_id,)) 219 lookup = {} 220 for location_id, dbname, accession, version in remote_results: 221 if version and version != "0": 222 v = "%s.%s" % (accession, version) 223 else: 224 v = accession 225 # subfeature remote location db_ref are stored as a empty string when 226 # not present 227 if dbname == "": 228 dbname = None 229 lookup[location_id] = (dbname, v) 230 231 feature = SeqFeature.SeqFeature(type = seqfeature_type) 232 feature._seqfeature_id = seqfeature_id #Store the key as a private property 233 feature.qualifiers = qualifiers 234 if len(locations) == 0: 235 pass 236 elif len(locations) == 1: 237 location_id, start, end, strand = locations[0] 238 #See Bug 2677, we currently don't record the location_operator 239 #For consistency with older versions Biopython, default to "". 240 feature.location_operator = \ 241 _retrieve_location_qualifier_value(adaptor, location_id) 242 dbname, version = lookup.get(location_id, (None, None)) 243 feature.location = SeqFeature.FeatureLocation(start, end) 244 feature.strand = strand 245 feature.ref_db = dbname 246 feature.ref = version 247 else: 248 assert feature.sub_features == [] 249 for location in locations: 250 location_id, start, end, strand = location 251 dbname, version = lookup.get(location_id, (None, None)) 252 subfeature = SeqFeature.SeqFeature() 253 subfeature.type = seqfeature_type 254 subfeature.location_operator = \ 255 _retrieve_location_qualifier_value(adaptor, location_id) 256 #TODO - See Bug 2677 - we don't yet record location_operator, 257 #so for consistency with older versions of Biopython default 258 #to assuming its a join. 259 if not subfeature.location_operator : 260 subfeature.location_operator="join" 261 subfeature.location = SeqFeature.FeatureLocation(start, end) 262 subfeature.strand = strand 263 subfeature.ref_db = dbname 264 subfeature.ref = version 265 feature.sub_features.append(subfeature) 266 # Assuming that the feature loc.op is the same as the sub_feature 267 # loc.op: 268 feature.location_operator = \ 269 feature.sub_features[0].location_operator 270 # Locations are in order, but because of remote locations for 271 # sub-features they are not necessarily in numerical order: 272 start = locations[0][1] 273 end = locations[-1][2] 274 feature.location = SeqFeature.FeatureLocation(start, end) 275 feature.strand = feature.sub_features[0].strand 276 277 seq_feature_list.append(feature) 278 279 return seq_feature_list
280
281 -def _retrieve_location_qualifier_value(adaptor, location_id):
282 value = adaptor.execute_and_fetch_col0( 283 "SELECT value FROM location_qualifier_value" \ 284 " WHERE location_id = %s", (location_id,)) 285 try: 286 return value[0] 287 except IndexError: 288 return ""
289
290 -def _retrieve_annotations(adaptor, primary_id, taxon_id):
291 annotations = {} 292 annotations.update(_retrieve_qualifier_value(adaptor, primary_id)) 293 annotations.update(_retrieve_reference(adaptor, primary_id)) 294 annotations.update(_retrieve_taxon(adaptor, primary_id, taxon_id)) 295 return annotations
296
297 -def _retrieve_qualifier_value(adaptor, primary_id):
298 qvs = adaptor.execute_and_fetchall( 299 "SELECT name, value" \ 300 " FROM bioentry_qualifier_value JOIN term USING (term_id)" \ 301 " WHERE bioentry_id = %s" \ 302 " ORDER BY rank", (primary_id,)) 303 qualifiers = {} 304 for name, value in qvs: 305 if name == "keyword": name = "keywords" 306 elif name == "date_changed": name = "dates" 307 elif name == "secondary_accession": name = "accessions" 308 qualifiers.setdefault(name, []).append(value) 309 return qualifiers
310
311 -def _retrieve_reference(adaptor, primary_id):
312 # XXX dbxref_qualifier_value 313 314 refs = adaptor.execute_and_fetchall( 315 "SELECT start_pos, end_pos, " \ 316 " location, title, authors," \ 317 " dbname, accession" \ 318 " FROM bioentry_reference" \ 319 " JOIN reference USING (reference_id)" \ 320 " LEFT JOIN dbxref USING (dbxref_id)" \ 321 " WHERE bioentry_id = %s" \ 322 " ORDER BY rank", (primary_id,)) 323 references = [] 324 for start, end, location, title, authors, dbname, accession in refs: 325 reference = SeqFeature.Reference() 326 if start: start -= 1 327 reference.location = [SeqFeature.FeatureLocation(start, end)] 328 #Don't replace the default "" with None. 329 if authors : reference.authors = authors 330 if title : reference.title = title 331 reference.journal = location 332 if dbname == 'PUBMED': 333 reference.pubmed_id = accession 334 elif dbname == 'MEDLINE': 335 reference.medline_id = accession 336 references.append(reference) 337 return {'references': references}
338
339 -def _retrieve_taxon(adaptor, primary_id, taxon_id):
340 a = {} 341 common_names = adaptor.execute_and_fetch_col0( 342 "SELECT name FROM taxon_name WHERE taxon_id = %s" \ 343 " AND name_class = 'genbank common name'", (taxon_id,)) 344 if common_names: 345 a['source'] = common_names[0] 346 scientific_names = adaptor.execute_and_fetch_col0( 347 "SELECT name FROM taxon_name WHERE taxon_id = %s" \ 348 " AND name_class = 'scientific name'", (taxon_id,)) 349 if scientific_names: 350 a['organism'] = scientific_names[0] 351 ncbi_taxids = adaptor.execute_and_fetch_col0( 352 "SELECT ncbi_taxon_id FROM taxon WHERE taxon_id = %s", (taxon_id,)) 353 if ncbi_taxids and ncbi_taxids[0] and ncbi_taxids[0] != "0": 354 a['ncbi_taxid'] = ncbi_taxids[0] 355 356 #Old code used the left/right values in the taxon table to get the 357 #taxonomy lineage in one SQL command. This was actually very slow, 358 #and would fail if the (optional) left/right values were missing. 359 # 360 #The following code is based on a contribution from Eric Gibert, and 361 #relies on the taxon table's parent_taxon_id field only (ignoring the 362 #optional left/right values). This means that it has to make a 363 #separate SQL query for each entry in the lineage, but it does still 364 #appear to be *much* faster. See Bug 2494. 365 taxonomy = [] 366 while taxon_id : 367 name, rank, parent_taxon_id = adaptor.execute_one( 368 "SELECT taxon_name.name, taxon.node_rank, taxon.parent_taxon_id" \ 369 " FROM taxon, taxon_name" \ 370 " WHERE taxon.taxon_id=taxon_name.taxon_id" \ 371 " AND taxon_name.name_class='scientific name'" \ 372 " AND taxon.taxon_id = %s", (taxon_id,)) 373 if taxon_id == parent_taxon_id : 374 # If the taxon table has been populated by the BioSQL script 375 # load_ncbi_taxonomy.pl this is how top parent nodes are stored. 376 # Personally, I would have used a NULL parent_taxon_id here. 377 break 378 if rank != "no rank" : 379 #For consistency with older versions of Biopython, we are only 380 #interested in taxonomy entries with a stated rank. 381 #Add this to the start of the lineage list. 382 taxonomy.insert(0, name) 383 taxon_id = parent_taxon_id 384 385 if taxonomy: 386 a['taxonomy'] = taxonomy 387 return a
388
389 -class DBSeqRecord(SeqRecord):
390 """BioSQL equivalent of the biopython SeqRecord object. 391 """ 392
393 - def __init__(self, adaptor, primary_id):
394 self._adaptor = adaptor 395 self._primary_id = primary_id 396 397 (self._biodatabase_id, self._taxon_id, self.name, 398 accession, version, self._identifier, 399 self._division, self.description) = self._adaptor.execute_one( 400 "SELECT biodatabase_id, taxon_id, name, accession, version," \ 401 " identifier, division, description" \ 402 " FROM bioentry" \ 403 " WHERE bioentry_id = %s", (self._primary_id,)) 404 if version and version != "0": 405 self.id = "%s.%s" % (accession, version) 406 else: 407 self.id = accession
408
409 - def __get_seq(self):
410 if not hasattr(self, "_seq"): 411 self._seq = _retrieve_seq(self._adaptor, self._primary_id) 412 return self._seq
413 - def __set_seq(self, seq): self._seq = seq
414 - def __del_seq(self): del self._seq
415 seq = property(__get_seq, __set_seq, __del_seq, "Seq object") 416
417 - def __get_dbxrefs(self):
418 if not hasattr(self,"_dbxrefs"): 419 self._dbxrefs = _retrieve_dbxrefs(self._adaptor, self._primary_id) 420 return self._dbxrefs
421 - def __set_dbxrefs(self, dbxrefs): self._dbxrefs = dbxrefs
422 - def __del_dbxrefs(self): del self._dbxrefs
423 dbxrefs = property(__get_dbxrefs, __set_dbxrefs, __del_dbxrefs, 424 "Database cross references") 425
426 - def __get_features(self):
427 if not hasattr(self, "_features"): 428 self._features = _retrieve_features(self._adaptor, 429 self._primary_id) 430 return self._features
431 - def __set_features(self, features): self._features = features
432 - def __del_features(self): del self._features
433 features = property(__get_features, __set_features, __del_features, 434 "Features") 435
436 - def __get_annotations(self):
437 if not hasattr(self, "_annotations"): 438 self._annotations = _retrieve_annotations(self._adaptor, 439 self._primary_id, 440 self._taxon_id) 441 if self._identifier: 442 self._annotations["gi"] = self._identifier 443 if self._division: 444 self._annotations["data_file_division"] = self._division 445 return self._annotations
446 - def __set_annotations(self, annotations): self._annotations = annotations
447 - def __del_annotations(self): del self._annotations
448 annotations = property(__get_annotations, __set_annotations, 449 __del_annotations, "Annotations")
450