1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
|
.. currentmodule:: pybedtools
.. _intervals:
Intervals
=========
An :class:`Interval` object is how :mod:`pybedtools` represents a line in a BED,
GFF, GTF, or VCF file in a uniform fashion. This section will describe
some useful features of :class:`Interval` objects.
First, let's get a :class:`BedTool` to work with:
.. doctest::
>>> a = pybedtools.example_bedtool('a.bed')
We can access the :class:`Intervals` of `a` several different ways.
Probably the most convenient way is by indexing a :class:`BedTool` object:
.. doctest::
>>> feature = a[0]
:class:`BedTool` objects support slices, too:
.. doctest::
>>> features = a[1:3]
Common :class:`Interval` attributes
-----------------------------------
Printing a feature converts it into the original line from the file:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> print(feature)
chr1 1 100 feature1 0 +
The string representation of an :class:`Interval` object is simply a valid line,
**including the newline**, for the format from which that :class:`Interval` was
created (accessible via :attr:`Interval.file_type`).
All features, no matter what the file type, have `chrom`, `start`, `stop`,
`name`, `score`, and `strand` attributes. Note that `start` and `stop` are
integers, while everything else (including `score`) is a string.
:mod:`pybedtools` supports both Python 2 and 3. When using Python 3, all
strings are the `str` type. When using Python 2, all strings are unicode.
.. note::
This documentation undergoes testing with Python 2 and Python 3. These
versions handle strings differently. For example, under Python 2::
>>> feature.chrom
u'chr1'
But under Python 3::
>>> feature.chrom
'chr1'
Since all strings returned by Interval objects are unicode, we solve this
by making a helper function `show_value` that converts unicode to native
string -- but only under Python 2.
.. doctest::
>>> import sys
>>> def show_value(s):
... """
... Convert unicode to str under Python 2;
... all other values pass through unchanged
... """
... if sys.version_info.major == 2:
... if isinstance(s, unicode):
... return str(s)
... return s
.. doctest::
>>> show_value(feature.chrom)
'chr1'
>>> show_value(feature.start)
1
>>> show_value(feature.stop)
100
>>> show_value(feature.name)
'feature1'
>>> show_value(feature.score)
'0'
>>> show_value(feature.strand)
'+'
Let's make another feature that only has chrom, start, and stop to see how
:mod:`pybedtools` deals with missing attributes:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> feature2 = pybedtools.BedTool('chrX 500 1000', from_string=True)[0]
>>> print(feature2)
chrX 500 1000
>>> show_value(feature2.chrom)
'chrX'
>>> show_value(feature2.start)
500
>>> show_value(feature2.stop)
1000
>>> show_value(feature2.name)
'.'
>>> show_value(feature2.score)
'.'
>>> show_value(feature2.strand)
'.'
This illustrates that default values are the string "`.`".
Indexing into :class:`Interval` objects
---------------------------------------
:class:`Interval` objects can also be indexed by position into the original
line (like a list) or indexed by name of attribute (like a dictionary).
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> print(feature)
chr1 1 100 feature1 0 +
>>> show_value(feature[0])
'chr1'
>>> show_value(feature['chrom'])
'chr1'
>>> show_value(feature[1])
'1'
>>> show_value(feature['start'])
1
Fields
------
:class:`Interval` objects have a :attr:`Interval.fields` attribute that
contains the original line split into a list of strings. When an integer
index is used on the :class:`Interval` (for example, `feature[3]`), it is
the `fields` attribute that is actually being indexed into.
.. doctest::
>>> f = pybedtools.BedTool('chr1 1 100 asdf 0 + a b c d', from_string=True)[0]
>>> [show_value(i) for i in f.fields]
['chr1', '1', '100', 'asdf', '0', '+', 'a', 'b', 'c', 'd']
>>> len(f.fields)
10
.. _zero_based_coords:
BED is 0-based, others are 1-based
----------------------------------
One troublesome part about working with multiple formats is that BED files
have a different coordinate system than GFF/GTF/VCF/ files.
* **BED files are 0-based** (the first base of the chromosome is considered
position 0) and the **feature does not include the stop position**.
* **GFF, GTF, and VCF files are 1-based** (the first base of the chromosome
is considered position 1) and the **feature includes the stop position**.
:mod:`pybedtools` follows the following conventions:
* The value in :attr:`Interval.start` will *always contain the
0-based start position*, even if it came from a GFF or other 1-based
feature.
* Getting the `len()` of an :class:`Interval` will always return
`Interval.stop - Interval.start`, so no matter what format the
original file was in, the length will be correct. This greatly simplifies
underlying code, and it means you can treat all :class:`Intervals`
identically.
* The contents of :attr:`Interval.fields` will *always be strings*,
which in turn always represent the original line in the file.
* This means that for a GFF feature, :attr:`Interval.fields[3]` or
:attr:`Interval[3]`, which is 1-based according to the file format,
will always be one bp larger than :attr:`Interval.start`, which
always contains the 0-based start position. Their data types
are different; :attr:`Interval[3]` will be a string and
:attr:`Interval.start` will be a long.
* Printing an :class:`Interval` object created from a GFF file will
show the tab-delimited fields in GFF coords while printing an
:class:`Interval` object created from a BED file will show fields in
BED coords.
Worked example
~~~~~~~~~~~~~~
To illustrate and confirm this functionality, let's create a GFF feature and
a BED feature from scratch and compare them.
First, let's create a GFF :class:`Interval` from scratch:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> gff = ["chr1",
... "fake",
... "mRNA",
... "51", # <- start is 1 greater than start for the BED feature below
... "300",
... ".",
... "+",
... ".",
... "ID=mRNA1;Parent=gene1;"]
>>> gff = pybedtools.create_interval_from_list(gff)
Then let's create a corresponding BED :class:`Interval` that represents the
same genomic coordinates of of the GFF feature, but since BED format is
zero-based we need to subtract 1 from the start:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> bed = ["chr1",
... "50",
... "300",
... "mRNA1",
... ".",
... "+"]
>>> bed = pybedtools.create_interval_from_list(bed)
Let's confirm these new features were recognized as the right file type --
the format is auto-detected based on the position of chrom/start/stop coords in
the provided field list:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> show_value(gff.file_type)
'gff'
>>> show_value(bed.file_type)
'bed'
Printing the :class:`Intervals` shows that the strings are in the appropriate
coordinates:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> # for testing, we make sure keys are sorted. Not needed in practice.
>>> gff.attrs.sort_keys = True
>>> print(gff)
chr1 fake mRNA 51 300 . + . ID=mRNA1;Parent=gene1;
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> print(bed)
chr1 50 300 mRNA1 . +
Since `start` attributes are always zero-based, the GFF and BED `start` values
should be identical:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> bed.start == gff.start == 50
True
For the BED feature, the second string field (representing the start position)
and the `start` attribute should both be `50` (though one is an integer and the
other is a string) . . .
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> show_value(bed.start)
50
>>> show_value(bed[1])
'50'
. . . but for the GFF feature, they differ -- the `start` attribute is
zero-based while the string representation (the fourth field of a GFF file)
remains in one-based GFF coords:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> show_value(gff.start)
50
>>> show_value(gff[3])
'51'
As long as we use the integer `start` attributes, we can treat the
:class:`Interval` objects identically, without having to check for their format
every time:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> len(bed) == len(gff) == 250
True
GFF features have access to attributes
--------------------------------------
GFF and GTF files have lots of useful information in their attributes field
(the last field in each line). These attributes can be accessed with the
:attr:`Interval.attrs` attribute, which acts like a dictionary. For speed,
the attributes are lazy -- they are only parsed when you ask for them. BED
files, which do not have an attributes field, will return an empty
dictionary.
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> # original feature
>>> print(gff)
chr1 fake mRNA 51 300 . + . ID=mRNA1;Parent=gene1;
>>> # original attributes
>>> sorted(gff.attrs.items())
[('ID', 'mRNA1'), ('Parent', 'gene1')]
>>> # add some new attributes
>>> gff.attrs['Awesomeness'] = "99"
>>> gff.attrs['ID'] = 'transcript1'
>>> # Changes in attributes are propagated to the printable feature
>>> # for testing, we make sure keys are sorted. Not needed in practice.
>>> gff.attrs.sort_keys = True
>>> assert gff.attrs.sort_keys
>>> print(gff)
chr1 fake mRNA 51 300 . + . Awesomeness=99;ID=transcript1;Parent=gene1;
Understanding :class:`Interval` objects is important for using the powerful
filtering and mapping facilities of :class:`BedTool` objects, as described
in the next section.
|