| 1 | #ifndef SWAP_GENOMIC_REGION_COLLECTION_H |
| 2 | #define SWAP_GENOMIC_REGION_COLLECTION_H |
| 3 | |
| 4 | #include <vector> |
| 5 | #include <string> |
| 6 | #include <cstdlib> |
| 7 | #include <list> |
| 8 | |
| 9 | #include "SeqLib/IntervalTree.h" |
| 10 | #include "SeqLib/GenomicRegionCollection.h" |
| 11 | #include "SeqLib/BamRecord.h" |
| 12 | |
| 13 | namespace SeqLib { |
| 14 | |
| 15 | /** Simple structure to store overlap results |
| 16 | */ |
| 17 | typedef std::pair<size_t, size_t> OverlapResult; |
| 18 | |
| 19 | /** Class to store vector of intervals on the genome */ |
| 20 | typedef TInterval<int32_t> GenomicInterval; |
| 21 | typedef SeqHashMap<int, std::vector<GenomicInterval> > GenomicIntervalMap; |
| 22 | typedef TIntervalTree<int32_t> GenomicIntervalTree; |
| 23 | typedef SeqHashMap<int, GenomicIntervalTree> GenomicIntervalTreeMap; |
| 24 | typedef std::vector<GenomicInterval> GenomicIntervalVector; |
| 25 | |
| 26 | /** @brief Template class to store / query a collection of genomic intervals |
| 27 | * |
| 28 | * Can hold a collection of GenomicRegion objects, or any object whose |
| 29 | * class is a child of GenomicRegion. Contains an implementation of an |
| 30 | * interval tree (as provided by Erik Garrison) for fast interval queries. |
| 31 | */ |
| 32 | template<typename T=GenomicRegion> |
| 33 | class GenomicRegionCollection { |
| 34 | |
| 35 | public: |
| 36 | |
| 37 | /** Construct an empty GenomicRegionCollection |
| 38 | */ |
| 39 | GenomicRegionCollection(); |
| 40 | |
| 41 | ~GenomicRegionCollection(); |
| 42 | |
| 43 | /** Construct from a plain vector of GenomicRegion objects |
| 44 | */ |
| 45 | GenomicRegionCollection(std::vector<T>& vec); |
| 46 | |
| 47 | /** Construct from a single GenomicRegion |
| 48 | */ |
| 49 | GenomicRegionCollection(const T& gr); |
| 50 | |
| 51 | /** Construct from a vector of reads |
| 52 | * |
| 53 | * @note See BamRecord::AsGenomicRegion |
| 54 | */ |
| 55 | GenomicRegionCollection(const BamRecordVector& brv); |
| 56 | |
| 57 | /** Construct a GenomicRegionCollection with overlapping intervals |
| 58 | * |
| 59 | * @param width Desired bin width |
| 60 | * @param ovlp Amount that the bins should overlap |
| 61 | * @param gr GenomicRegion to divide into smaller overlapping bins |
| 62 | */ |
| 63 | GenomicRegionCollection(int width, int ovlp, const T &gr); |
| 64 | |
| 65 | /** Construct a tiled set of intervals across a genome |
| 66 | * |
| 67 | * @param width Width of each interval tile |
| 68 | * @param ovlp Amount of overlap between neighboring tiles |
| 69 | * @param h Set of chromosomes and their lengths to build the tile on |
| 70 | */ |
| 71 | GenomicRegionCollection(int width, int ovlp, const HeaderSequenceVector& h); |
| 72 | |
| 73 | // Read in a MuTect call-stats file and adds to GenomicRegionCollection object. |
| 74 | // |
| 75 | // Reads a MuTect call-stats file and imports only |
| 76 | // lines with KEEP marked. |
| 77 | // @param file Path to call-stats file |
| 78 | // @param pad Amount to pad intervals by |
| 79 | // @return True if file was succesfully read |
| 80 | // |
| 81 | //bool ReadMuTect(const std::string &file, const SeqLib::BamHeader& hdr); |
| 82 | |
| 83 | /** Read in a BED file and adds to GenomicRegionCollection object |
| 84 | * @param file Path to BED file |
| 85 | * @param hdr Dictionary for converting chromosome strings in BED file to chr indicies |
| 86 | * @return True if file was succesfully read |
| 87 | */ |
| 88 | bool ReadBED(const std::string &file, const SeqLib::BamHeader& hdr); |
| 89 | |
| 90 | /** Read in a VCF file and adds to GenomicRegionCollection object |
| 91 | * @param file Path to VCF file. All elements will be width = 1 (just read start point) |
| 92 | * @param hdr Dictionary for converting chromosome strings in BED file to chr indicies |
| 93 | */ |
| 94 | bool ReadVCF(const std::string &file, const SeqLib::BamHeader& hdr); |
| 95 | |
| 96 | /** Shuffle the order of the intervals */ |
| 97 | void Shuffle(); |
| 98 | |
| 99 | /** Read in a text file (can be gzipped) and construct a GenomicRegionCollection |
| 100 | * |
| 101 | * This function will automatically detect which file type is being input: |
| 102 | * -- ends in .vcf -> readVCFfile |
| 103 | * -- ends in .bed -> readBEDfile |
| 104 | * -- contains ':' -> Assumes single samtools-style region (eg 1:100-100) |
| 105 | * The values are appended to existing vector of GenomicRegion objects |
| 106 | * @param file Text file to read and store intervals |
| 107 | * @param hdr BamHeader to serve as dictionary for chromosomes |
| 108 | */ |
| 109 | GenomicRegionCollection(const std::string &file, const BamHeader& hdr); |
| 110 | |
| 111 | /** Create the set of interval trees (one per chromosome) |
| 112 | * |
| 113 | * A GenomicIntervalTreeMap is an unordered_map of GenomicIntervalTrees for |
| 114 | * each chromosome. A GenomicIntervalTree is an interval tree on the ranges |
| 115 | * defined by the genomic interval, with cargo set at the same GenomicRegion object. |
| 116 | */ |
| 117 | void CreateTreeMap(); |
| 118 | |
| 119 | /** Reduces the GenomicRegion objects to minimal set by merging overlapping intervals |
| 120 | * @note This will merge intervals that touch. eg [4,6] and [6,8] |
| 121 | * @note This will also call CreateTreeMap() at end to re-create the interval tree |
| 122 | */ |
| 123 | void MergeOverlappingIntervals(); |
| 124 | |
| 125 | /** Return the number of GenomicRegions stored |
| 126 | */ |
| 127 | size_t size() const { return m_grv->size(); } |
| 128 | |
| 129 | /** Add a new GenomicRegion (or child of) to end |
| 130 | */ |
| 131 | void add(const T& g) { m_grv->push_back(g); /*createTreeMap();*/ } |
| 132 | |
| 133 | /** Is this object empty? |
| 134 | */ |
| 135 | bool IsEmpty() const { return !m_grv->size(); } |
| 136 | |
| 137 | /** Clear out all of the GenomicRegion objects |
| 138 | */ |
| 139 | void clear() { m_grv->clear(); |
| 140 | m_tree->clear(); |
| 141 | idx = 0; |
| 142 | } |
| 143 | |
| 144 | /** Get the number of trees (eg number of chromosomes, each with own tree */ |
| 145 | int NumTree() const { return m_tree->size(); } |
| 146 | |
| 147 | /** Get the IDs of all intervals that overlap with a query range |
| 148 | * |
| 149 | * The IDs are created during CreateTreeMap, and are the position of the |
| 150 | * the individual intervals from the tree, in genomic order. e.g the first |
| 151 | * interval on chromosome 1 gets 0, the next one gets 1, etc. |
| 152 | * The returned IDs can then be used as lookups with [], as long as the |
| 153 | * collection is not altered in between. |
| 154 | * @param gr Query range to check overlaps against |
| 155 | * @param ignore_strand Should strandedness be ignore when doing overlaps |
| 156 | * @return A vector of IDs of intervals in this collection that overlap with gr |
| 157 | */ |
| 158 | template<class K> |
| 159 | std::vector<int> FindOverlappedIntervals(const K& gr, bool ignore_strand) const; |
| 160 | |
| 161 | /** Get a const pointer to the genomic interval tree map */ |
| 162 | const GenomicIntervalTreeMap* GetTree() const { return m_tree.get(); } |
| 163 | |
| 164 | /** Retrieve a GenomicRegion at given index. |
| 165 | * |
| 166 | * Note that this does not move the idx iterator, which is |
| 167 | * used to loop through all the regions. Throws an exception |
| 168 | * if the index is out of bounds. |
| 169 | * @return GenomicRegion pointed to by index i |
| 170 | */ |
| 171 | const T& at(size_t i) const; |
| 172 | |
| 173 | /** Find overlaps between this vector and input GenomicRegion. |
| 174 | * |
| 175 | * Requires that the GenomicIntervalTreeMap have been created first |
| 176 | * @param gr Region to test |
| 177 | * @return Number of overlapping elements in this GenomicRegionCollection |
| 178 | */ |
| 179 | size_t CountOverlaps(const T &gr) const; |
| 180 | |
| 181 | /** Test if two intervals overlap the same element in the collection |
| 182 | */ |
| 183 | template<class K> |
| 184 | bool OverlapSameInterval(const K &gr1, const K &gr2) const; |
| 185 | |
| 186 | /** Count the number of intervals in the collection contained in this range */ |
| 187 | size_t CountContained(const T &gr); |
| 188 | |
| 189 | /** Return the overlaps between the collection and the query collection |
| 190 | * @param subject Subject collection of intervals |
| 191 | * @param query_id Indices of the queries that have an overlap. Will be same size as output and subject_id and in same order |
| 192 | * @param subject_id Indices of the subject that have an overlap. Will be same size as output and query_id and in same order |
| 193 | * @param ignore_strand If true, won't exclude overlap if on different strand |
| 194 | * @return A collection of overlapping intervals from this collection, trimmed to be contained |
| 195 | * @exception Throws a logic_error if this tree is non-empty, but the interval tree has not been made with |
| 196 | * CreateTreeMap |
| 197 | * inside the query collection |
| 198 | */ |
| 199 | template<class K> |
| 200 | GenomicRegionCollection<GenomicRegion> FindOverlaps(const GenomicRegionCollection<K> &subject, std::vector<int32_t>& query_id, std::vector<int32_t>& subject_id, bool ignore_strand) const; |
| 201 | |
| 202 | /** Return the overlaps between the collection and the query interval |
| 203 | * @param gr Query region |
| 204 | * @param ignore_strand If true, won't exclude overlap if on different strand |
| 205 | * @return A collection of overlapping intervals from this collection, trimmed to be contained |
| 206 | * inside gr |
| 207 | */ |
| 208 | template<class K> |
| 209 | GenomicRegionCollection<GenomicRegion> FindOverlaps(const K& gr, bool ignore_strand) const; |
| 210 | |
| 211 | /** Return the number of bases in query that overlap this collection |
| 212 | * @param gr Query GenomicRegion (or child of) |
| 213 | * @param ignore_strand If true, won't exclude overlap if on different strand |
| 214 | * @return Number of bases in query that overlap with region in collection |
| 215 | */ |
| 216 | template<class K> |
| 217 | size_t FindOverlapWidth(const K& gr, bool ignore_strand) const; |
| 218 | |
| 219 | /** Return the total amount spanned by this collection */ |
| 220 | int TotalWidth() const; |
| 221 | |
| 222 | /** Increase the left and right ends of each contained GenomicRegion by |
| 223 | * the pad value. |
| 224 | * @param v Amount to pad each end by. Result is increase in width by 2*pad. |
| 225 | * @note See GenomicRegion::Pad |
| 226 | */ |
| 227 | void Pad(int v); |
| 228 | |
| 229 | /** Set the i'th GenomicRegion */ |
| 230 | T& operator[](size_t i) { return m_grv->at(i); } |
| 231 | |
| 232 | /** Retreive the i'th GenomicRegion */ |
| 233 | const T& operator[](size_t i) const { return m_grv->at(i); } |
| 234 | |
| 235 | /** Add two GenomicRegionCollection objects together */ |
| 236 | void Concat(const GenomicRegionCollection<T>& g); |
| 237 | |
| 238 | /** Output the GenomicRegionCollection to a BED format |
| 239 | * |
| 240 | * @param h Header to convert id to chromosome name |
| 241 | * @return BED formated string reprsentation |
| 242 | */ |
| 243 | std::string AsBEDString(const BamHeader& h) const; |
| 244 | |
| 245 | /** Coordinate sort the interval collection */ |
| 246 | void CoordinateSort(); |
| 247 | |
| 248 | /** Expand all the elements so they are sorted and become adjacent |
| 249 | * by stretching them to the right up to max |
| 250 | * @param max Element furthest to the right will be stretched to max. If set to 0, will not stretch furthest right element. |
| 251 | * @exception Throws an out_of_range if furthest right position is > max |
| 252 | */ |
| 253 | void SortAndStretchRight(int max); |
| 254 | |
| 255 | /** Expand all the elements so they are sorted and become adjacent |
| 256 | * by stretching them to the left down to min. |
| 257 | * @param min Element furthest to the left will be stretched to min. If set to < 0, will not stretch furthest right element. |
| 258 | * @exception Throws an out_of_range if furthest left is < min |
| 259 | */ |
| 260 | void SortAndStretchLeft(int min); |
| 261 | |
| 262 | /** Rewind the element pointer to the first GenomicRegion */ |
| 263 | void Rewind() { idx = 0; } |
| 264 | |
| 265 | /** Return elements as an STL vector of GenomicRegion objects */ |
| 266 | GenomicRegionVector AsGenomicRegionVector() const; |
| 267 | |
| 268 | /** Iterator to first element of the region collection */ |
| 269 | typename std::vector<T>::iterator begin() { return m_grv->begin(); } |
| 270 | |
| 271 | /** Iterator to end of the region collection */ |
| 272 | typename std::vector<T>::iterator end() { return m_grv->end(); } |
| 273 | |
| 274 | /** Const iterator to first element of the region collection */ |
| 275 | typename std::vector<T>::const_iterator begin() const { return m_grv->begin(); } |
| 276 | |
| 277 | /** Const iterator to end of the region collection */ |
| 278 | typename std::vector<T>::const_iterator end() const { return m_grv->end(); } |
| 279 | |
| 280 | /** Shortcut to FindOverlaps that just returns the intersecting regions |
| 281 | * without keeping track of the query / subject ids |
| 282 | * @param subject Collection of regions to intersect this object with |
| 283 | * @param ignore_strand Ignore strand considerations when performing intersection |
| 284 | * @return Intersecting regions between subject and query |
| 285 | */ |
| 286 | template <class K> |
| 287 | GenomicRegionCollection<GenomicRegion> Intersection(const GenomicRegionCollection<K>& subject, bool ignore_strand) const; |
| 288 | |
| 289 | protected: |
| 290 | |
| 291 | bool m_sorted; |
| 292 | |
| 293 | // always construct this object any time m_grv is modifed |
| 294 | SeqPointer<GenomicIntervalTreeMap> m_tree; |
| 295 | |
| 296 | // hold the genomic regions |
| 297 | SeqPointer<std::vector<T> > m_grv; |
| 298 | |
| 299 | // index for current GenomicRegion |
| 300 | size_t idx; |
| 301 | |
| 302 | // open the memory |
| 303 | void allocate_grc(); |
| 304 | |
| 305 | }; |
| 306 | |
| 307 | typedef GenomicRegionCollection<GenomicRegion> GRC; |
| 308 | |
| 309 | } |
| 310 | |
| 311 | #include "SeqLib/GenomicRegionCollection.cpp" |
| 312 | |
| 313 | #endif |