Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

673 wiersze
21 KiB

  1. # cython: embedsignature=True
  2. # cython: profile=True
  3. ###############################################################################
  4. ###############################################################################
  5. # Cython wrapper for SAM/BAM/CRAM files based on htslib
  6. ###############################################################################
  7. # The principal classes defined in this module are:
  8. #
  9. # class FastaFile random read read/write access to faidx indexd files
  10. # class FastxFile streamed read/write access to fasta/fastq files
  11. #
  12. # Additionally this module defines several additional classes that are part
  13. # of the internal API. These are:
  14. #
  15. # class FastqProxy
  16. # class FastxRecord
  17. #
  18. # For backwards compatibility, the following classes are also defined:
  19. #
  20. # class Fastafile equivalent to FastaFile
  21. # class FastqFile equivalent to FastxFile
  22. #
  23. ###############################################################################
  24. #
  25. # The MIT License
  26. #
  27. # Copyright (c) 2015 Andreas Heger
  28. #
  29. # Permission is hereby granted, free of charge, to any person obtaining a
  30. # copy of this software and associated documentation files (the "Software"),
  31. # to deal in the Software without restriction, including without limitation
  32. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  33. # and/or sell copies of the Software, and to permit persons to whom the
  34. # Software is furnished to do so, subject to the following conditions:
  35. #
  36. # The above copyright notice and this permission notice shall be included in
  37. # all copies or substantial portions of the Software.
  38. #
  39. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  42. # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  43. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  44. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  45. # DEALINGS IN THE SOFTWARE.
  46. #
  47. ###############################################################################
  48. import sys
  49. import os
  50. import re
  51. from libc.errno cimport errno
  52. from libc.string cimport strerror
  53. from cpython cimport array
  54. from cpython cimport PyErr_SetString, \
  55. PyBytes_Check, \
  56. PyUnicode_Check, \
  57. PyBytes_FromStringAndSize
  58. from pysam.libchtslib cimport \
  59. faidx_nseq, fai_load, fai_load3, fai_destroy, fai_fetch, \
  60. faidx_seq_len, faidx_iseq, faidx_seq_len, \
  61. faidx_fetch_seq, hisremote, \
  62. bgzf_open, bgzf_close
  63. from pysam.libcutils cimport force_bytes, force_str, charptr_to_str
  64. from pysam.libcutils cimport encode_filename, from_string_and_size
  65. from pysam.libcutils cimport qualitystring_to_array, parse_region
  66. cdef class FastqProxy
  67. cdef makeFastqProxy(kseq_t * src):
  68. '''enter src into AlignedRead.'''
  69. cdef FastqProxy dest = FastqProxy.__new__(FastqProxy)
  70. dest._delegate = src
  71. return dest
  72. ## TODO:
  73. ## add automatic indexing.
  74. ## add function to get sequence names.
  75. cdef class FastaFile:
  76. """Random access to fasta formatted files that
  77. have been indexed by :term:`faidx`.
  78. The file is automatically opened. The index file of file
  79. ``<filename>`` is expected to be called ``<filename>.fai``.
  80. Parameters
  81. ----------
  82. filename : string
  83. Filename of fasta file to be opened.
  84. filepath_index : string
  85. Optional, filename of the index. By default this is
  86. the filename + ".fai".
  87. filepath_index_compressed : string
  88. Optional, filename of the index if fasta file is. By default this is
  89. the filename + ".gzi".
  90. Raises
  91. ------
  92. ValueError
  93. if index file is missing
  94. IOError
  95. if file could not be opened
  96. """
  97. def __cinit__(self, *args, **kwargs):
  98. self.fastafile = NULL
  99. self._filename = None
  100. self._references = None
  101. self._lengths = None
  102. self.reference2length = None
  103. self._open(*args, **kwargs)
  104. def is_open(self):
  105. '''return true if samfile has been opened.'''
  106. return self.fastafile != NULL
  107. def __len__(self):
  108. if self.fastafile == NULL:
  109. raise ValueError("calling len() on closed file")
  110. return faidx_nseq(self.fastafile)
  111. def _open(self, filename, filepath_index=None, filepath_index_compressed=None):
  112. '''open an indexed fasta file.
  113. This method expects an indexed fasta file.
  114. '''
  115. # close a previously opened file
  116. if self.fastafile != NULL:
  117. self.close()
  118. self._filename = encode_filename(filename)
  119. cdef char *cfilename = self._filename
  120. cdef char *cindexname = NULL
  121. cdef char *cindexname_compressed = NULL
  122. self.is_remote = hisremote(cfilename)
  123. # open file for reading
  124. if (self._filename != b"-"
  125. and not self.is_remote
  126. and not os.path.exists(filename)):
  127. raise IOError("file `%s` not found" % filename)
  128. # 3 modes to open:
  129. # compressed fa: fai_load3 with filename, index_fai and index_gzi
  130. # uncompressed fa: fai_load3 with filename and index_fai
  131. # uncompressed fa: fai_load with default index name
  132. if filepath_index:
  133. # when opening, set flags to 0 - do not automatically
  134. # build index if it does not exist.
  135. if not os.path.exists(filepath_index):
  136. raise IOError("filename {} does not exist".format(filepath_index))
  137. cindexname = bindex_filename = encode_filename(filepath_index)
  138. if filepath_index_compressed:
  139. if not os.path.exists(filepath_index_compressed):
  140. raise IOError("filename {} does not exist".format(filepath_index_compressed))
  141. cindexname_compressed = bindex_filename_compressed = encode_filename(filepath_index_compressed)
  142. with nogil:
  143. self.fastafile = fai_load3(cfilename, cindexname, cindexname_compressed, 0)
  144. else:
  145. with nogil:
  146. self.fastafile = fai_load3(cfilename, cindexname, NULL, 0)
  147. else:
  148. with nogil:
  149. self.fastafile = fai_load(cfilename)
  150. if self.fastafile == NULL:
  151. raise IOError("error when opening file `%s`" % filename)
  152. cdef int nreferences = faidx_nseq(self.fastafile)
  153. cdef int x
  154. cdef const char * s
  155. self._references = []
  156. self._lengths = []
  157. for x from 0 <= x < nreferences:
  158. s = faidx_iseq(self.fastafile, x)
  159. ss = force_str(s)
  160. self._references.append(ss)
  161. self._lengths.append(faidx_seq_len(self.fastafile, s))
  162. self.reference2length = dict(zip(self._references, self._lengths))
  163. def close(self):
  164. """close the file."""
  165. if self.fastafile != NULL:
  166. fai_destroy(self.fastafile)
  167. self.fastafile = NULL
  168. def __dealloc__(self):
  169. if self.fastafile != NULL:
  170. fai_destroy(self.fastafile)
  171. self.fastafile = NULL
  172. # context manager interface
  173. def __enter__(self):
  174. return self
  175. def __exit__(self, exc_type, exc_value, traceback):
  176. self.close()
  177. return False
  178. property closed:
  179. """bool indicating the current state of the file object.
  180. This is a read-only attribute; the close() method changes the value.
  181. """
  182. def __get__(self):
  183. return not self.is_open()
  184. property filename:
  185. """filename associated with this object. This is a read-only attribute."""
  186. def __get__(self):
  187. return self._filename
  188. property references:
  189. '''tuple with the names of :term:`reference` sequences.'''
  190. def __get__(self):
  191. return self._references
  192. property nreferences:
  193. """int with the number of :term:`reference` sequences in the file.
  194. This is a read-only attribute."""
  195. def __get__(self):
  196. return len(self._references) if self.references else None
  197. property lengths:
  198. """tuple with the lengths of :term:`reference` sequences."""
  199. def __get__(self):
  200. return self._lengths
  201. def fetch(self,
  202. reference=None,
  203. start=None,
  204. end=None,
  205. region=None):
  206. """fetch sequences in a :term:`region`.
  207. A region can
  208. either be specified by :term:`reference`, `start` and
  209. `end`. `start` and `end` denote 0-based, half-open
  210. intervals.
  211. Alternatively, a samtools :term:`region` string can be
  212. supplied.
  213. If any of the coordinates are missing they will be replaced by the
  214. minimum (`start`) or maximum (`end`) coordinate.
  215. Note that region strings are 1-based, while `start` and `end` denote
  216. an interval in python coordinates.
  217. The region is specified by :term:`reference`, `start` and `end`.
  218. Returns
  219. -------
  220. string : a string with the sequence specified by the region.
  221. Raises
  222. ------
  223. IndexError
  224. if the coordinates are out of range
  225. ValueError
  226. if the region is invalid
  227. """
  228. if not self.is_open():
  229. raise ValueError("I/O operation on closed file" )
  230. cdef int length
  231. cdef char *seq
  232. cdef char *ref
  233. cdef int rstart, rend
  234. contig, rstart, rend = parse_region(reference, start, end, region)
  235. if contig is None:
  236. raise ValueError("no sequence/region supplied.")
  237. if rstart == rend:
  238. return ""
  239. contig_b = force_bytes(contig)
  240. ref = contig_b
  241. with nogil:
  242. length = faidx_seq_len(self.fastafile, ref)
  243. if length == -1:
  244. raise KeyError("sequence '%s' not present" % contig)
  245. if rstart >= length:
  246. return ""
  247. # fai_fetch adds a '\0' at the end
  248. with nogil:
  249. seq = faidx_fetch_seq(self.fastafile,
  250. ref,
  251. rstart,
  252. rend-1,
  253. &length)
  254. if not seq:
  255. if errno:
  256. raise IOError(errno, strerror(errno))
  257. else:
  258. raise ValueError("failure when retrieving sequence on '%s'" % contig)
  259. try:
  260. return charptr_to_str(seq)
  261. finally:
  262. free(seq)
  263. cdef char *_fetch(self, char *reference, int start, int end, int *length) except? NULL:
  264. '''fetch sequence for reference, start and end'''
  265. cdef char *seq
  266. with nogil:
  267. seq = faidx_fetch_seq(self.fastafile,
  268. reference,
  269. start,
  270. end-1,
  271. length)
  272. if not seq:
  273. if errno:
  274. raise IOError(errno, strerror(errno))
  275. else:
  276. raise ValueError("failure when retrieving sequence on '%s'" % reference)
  277. return seq
  278. def get_reference_length(self, reference):
  279. '''return the length of reference.'''
  280. return self.reference2length[reference]
  281. def __getitem__(self, reference):
  282. return self.fetch(reference)
  283. def __contains__(self, reference):
  284. '''return true if reference in fasta file.'''
  285. return reference in self.reference2length
  286. cdef class FastqProxy:
  287. """A single entry in a fastq file."""
  288. def __init__(self):
  289. raise ValueError("do not instantiate FastqProxy directly")
  290. property name:
  291. """The name of each entry in the fastq file."""
  292. def __get__(self):
  293. return charptr_to_str(self._delegate.name.s)
  294. property sequence:
  295. """The sequence of each entry in the fastq file."""
  296. def __get__(self):
  297. return charptr_to_str(self._delegate.seq.s)
  298. property comment:
  299. def __get__(self):
  300. if self._delegate.comment.l:
  301. return charptr_to_str(self._delegate.comment.s)
  302. else:
  303. return None
  304. property quality:
  305. """The quality score of each entry in the fastq file, represented as a string."""
  306. def __get__(self):
  307. if self._delegate.qual.l:
  308. return charptr_to_str(self._delegate.qual.s)
  309. else:
  310. return None
  311. cdef cython.str to_string(self):
  312. if self.comment is None:
  313. comment = ""
  314. else:
  315. comment = " %s" % self.comment
  316. if self.quality is None:
  317. return ">%s%s\n%s" % (self.name, comment, self.sequence)
  318. else:
  319. return "@%s%s\n%s\n+\n%s" % (self.name, comment,
  320. self.sequence, self.quality)
  321. cdef cython.str tostring(self):
  322. """deprecated : use :meth:`to_string`"""
  323. return self.to_string()
  324. def __str__(self):
  325. return self.to_string()
  326. cpdef array.array get_quality_array(self, int offset=33):
  327. '''return quality values as integer array after subtracting offset.'''
  328. if self.quality is None:
  329. return None
  330. return qualitystring_to_array(force_bytes(self.quality),
  331. offset=offset)
  332. cdef class FastxRecord:
  333. """A fasta/fastq record.
  334. A record must contain a name and a sequence. If either of them are
  335. None, a ValueError is raised on writing.
  336. """
  337. def __init__(self,
  338. name=None,
  339. comment=None,
  340. sequence=None,
  341. quality=None,
  342. FastqProxy proxy=None):
  343. if proxy is not None:
  344. self.comment = proxy.comment
  345. self.quality = proxy.quality
  346. self.sequence = proxy.sequence
  347. self.name = proxy.name
  348. else:
  349. self.comment = comment
  350. self.quality = quality
  351. self.sequence = sequence
  352. self.name = name
  353. def __copy__(self):
  354. return FastxRecord(self.name, self.comment, self.sequence, self.quality)
  355. def __deepcopy__(self, memo):
  356. return FastxRecord(self.name, self.comment, self.sequence, self.quality)
  357. cdef cython.str to_string(self):
  358. if self.name is None:
  359. raise ValueError("can not write record without name")
  360. if self.sequence is None:
  361. raise ValueError("can not write record without a sequence")
  362. if self.comment is None:
  363. comment = ""
  364. else:
  365. comment = " %s" % self.comment
  366. if self.quality is None:
  367. return ">%s%s\n%s" % (self.name, comment, self.sequence)
  368. else:
  369. return "@%s%s\n%s\n+\n%s" % (self.name, comment,
  370. self.sequence, self.quality)
  371. cdef cython.str tostring(self):
  372. """deprecated : use :meth:`to_string`"""
  373. return self.to_string()
  374. def set_name(self, name):
  375. if name is None:
  376. raise ValueError("FastxRecord must have a name and not None")
  377. self.name = name
  378. def set_comment(self, comment):
  379. self.comment = comment
  380. def set_sequence(self, sequence, quality=None):
  381. """set sequence of this record.
  382. """
  383. self.sequence = sequence
  384. if quality is not None:
  385. if len(sequence) != len(quality):
  386. raise ValueError("sequence and quality length do not match: {} vs {}".format(
  387. len(sequence), len(quality)))
  388. self.quality = quality
  389. else:
  390. self.quality = None
  391. def __str__(self):
  392. return self.to_string()
  393. cpdef array.array get_quality_array(self, int offset=33):
  394. '''return quality values as array after subtracting offset.'''
  395. if self.quality is None:
  396. return None
  397. return qualitystring_to_array(force_bytes(self.quality),
  398. offset=offset)
  399. cdef class FastxFile:
  400. r"""Stream access to :term:`fasta` or :term:`fastq` formatted files.
  401. The file is automatically opened.
  402. Entries in the file can be both fastq or fasta formatted or even a
  403. mixture of the two.
  404. This file object permits iterating over all entries in the
  405. file. Random access is not implemented. The iteration returns
  406. objects of type :class:`FastqProxy`
  407. Parameters
  408. ----------
  409. filename : string
  410. Filename of fasta/fastq file to be opened.
  411. persist : bool
  412. If True (default) make a copy of the entry in the file during
  413. iteration. If set to False, no copy will be made. This will
  414. permit much faster iteration, but an entry will not persist
  415. when the iteration continues and an entry is read-only.
  416. Notes
  417. -----
  418. Prior to version 0.8.2, this class was called FastqFile.
  419. Raises
  420. ------
  421. IOError
  422. if file could not be opened
  423. Examples
  424. --------
  425. >>> with pysam.FastxFile(filename) as fh:
  426. ... for entry in fh:
  427. ... print(entry.name)
  428. ... print(entry.sequence)
  429. ... print(entry.comment)
  430. ... print(entry.quality)
  431. >>> with pysam.FastxFile(filename) as fin, open(out_filename, mode='w') as fout:
  432. ... for entry in fin:
  433. ... fout.write(str(entry) + '\n')
  434. """
  435. def __cinit__(self, *args, **kwargs):
  436. # self.fastqfile = <gzFile*>NULL
  437. self._filename = None
  438. self.entry = NULL
  439. self._open(*args, **kwargs)
  440. def is_open(self):
  441. '''return true if samfile has been opened.'''
  442. return self.entry != NULL
  443. def _open(self, filename, persist=True):
  444. '''open a fastq/fasta file in *filename*
  445. Paramentes
  446. ----------
  447. persist : bool
  448. if True return a copy of the underlying data (default
  449. True). The copy will persist even if the iteration
  450. on the file continues.
  451. '''
  452. if self.fastqfile != NULL:
  453. self.close()
  454. self._filename = encode_filename(filename)
  455. cdef char *cfilename = self._filename
  456. self.is_remote = hisremote(cfilename)
  457. # open file for reading
  458. if (self._filename != b"-"
  459. and not self.is_remote
  460. and not os.path.exists(filename)):
  461. raise IOError("file `%s` not found" % filename)
  462. self.persist = persist
  463. with nogil:
  464. self.fastqfile = bgzf_open(cfilename, "r")
  465. self.entry = kseq_init(self.fastqfile)
  466. self._filename = filename
  467. def close(self):
  468. '''close the file.'''
  469. if self.fastqfile != NULL:
  470. bgzf_close(self.fastqfile)
  471. self.fastqfile = NULL
  472. if self.entry != NULL:
  473. kseq_destroy(self.entry)
  474. self.entry = NULL
  475. def __dealloc__(self):
  476. if self.fastqfile != NULL:
  477. bgzf_close(self.fastqfile)
  478. if self.entry:
  479. kseq_destroy(self.entry)
  480. # context manager interface
  481. def __enter__(self):
  482. return self
  483. def __exit__(self, exc_type, exc_value, traceback):
  484. self.close()
  485. return False
  486. property closed:
  487. """bool indicating the current state of the file object.
  488. This is a read-only attribute; the close() method changes the value.
  489. """
  490. def __get__(self):
  491. return not self.is_open()
  492. property filename:
  493. """string with the filename associated with this object."""
  494. def __get__(self):
  495. return self._filename
  496. def __iter__(self):
  497. if not self.is_open():
  498. raise ValueError("I/O operation on closed file")
  499. return self
  500. cdef kseq_t * getCurrent(self):
  501. return self.entry
  502. cdef int cnext(self):
  503. '''C version of iterator
  504. '''
  505. with nogil:
  506. return kseq_read(self.entry)
  507. def __next__(self):
  508. """
  509. python version of next().
  510. """
  511. cdef int l
  512. with nogil:
  513. l = kseq_read(self.entry)
  514. if (l >= 0):
  515. if self.persist:
  516. return FastxRecord(proxy=makeFastqProxy(self.entry))
  517. return makeFastqProxy(self.entry)
  518. elif (l == -1):
  519. raise StopIteration
  520. elif (l == -2):
  521. raise ValueError('truncated quality string in {0}'
  522. .format(self._filename))
  523. else:
  524. raise ValueError('unknown problem parsing {0}'
  525. .format(self._filename))
  526. # Compatibility Layer for pysam 0.8.1
  527. cdef class FastqFile(FastxFile):
  528. """FastqFile is deprecated: use FastxFile instead"""
  529. pass
  530. # Compatibility Layer for pysam < 0.8
  531. cdef class Fastafile(FastaFile):
  532. """Fastafile is deprecated: use FastaFile instead"""
  533. pass
  534. __all__ = ["FastaFile",
  535. "FastqFile",
  536. "FastxFile",
  537. "Fastafile",
  538. "FastxRecord",
  539. "FastqProxy"]