| 1 | #include "SeqLib/RefGenome.h" |
| 2 | |
| 3 | #include <stdexcept> |
| 4 | #include "SeqLib/SeqLibUtils.h" |
| 5 | |
| 6 | namespace SeqLib { |
| 7 | |
| 8 | bool RefGenome::LoadIndex(const std::string& file) { |
| 9 | |
| 10 | // clear the old one |
| 11 | if (index) |
| 12 | fai_destroy(index); |
| 13 | |
| 14 | index = NULL; |
| 15 | |
| 16 | // check that its readable |
| 17 | if (!read_access_test(file)) { |
| 18 | return false; |
| 19 | //throw std::invalid_argument("RefGenome: file not found - " + file); |
| 20 | } |
| 21 | |
| 22 | // load it in |
| 23 | index = fai_load(file.c_str()); |
| 24 | |
| 25 | if (!index) |
| 26 | return false; |
| 27 | |
| 28 | return true; |
| 29 | |
| 30 | } |
| 31 | |
| 32 | std::string RefGenome::QueryRegion(const std::string& chr_name, int32_t p1, int32_t p2) const { |
| 33 | |
| 34 | // check that we have a loaded index |
| 35 | if (!index) |
| 36 | throw std::invalid_argument("RefGenome::queryRegion index not loaded"); |
| 37 | |
| 38 | // check input is OK |
| 39 | if (p1 > p2) |
| 40 | throw std::invalid_argument("RefGenome::queryRegion p1 must be <= p2"); |
| 41 | if (p1 < 0) |
| 42 | throw std::invalid_argument("RefGenome::queryRegion p1 must be >= 0"); |
| 43 | |
| 44 | int len; |
| 45 | char * f = faidx_fetch_seq(index, const_cast<char*>(chr_name.c_str()), p1, p2, &len); |
| 46 | |
| 47 | if (!f) |
| 48 | throw std::invalid_argument("RefGenome::queryRegion - Could not find valid sequence"); |
| 49 | |
| 50 | std::string out(f); |
| 51 | |
| 52 | free(f); |
| 53 | |
| 54 | if (out.empty()) |
| 55 | throw std::invalid_argument("RefGenome::queryRegion - Returning empty query on " + chr_name + ":" + tostring(p1) + "-" + tostring(p2)); |
| 56 | |
| 57 | return (out); |
| 58 | |
| 59 | } |
| 60 | |
| 61 | } |