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
|
/*
This file is part of BioD.
Copyright (C) 2016 George Githinji <biorelated@gmail.com>
Copyright (C) 2018 Emilio Palumbo <emiliopalumbo@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
module bio.std.file.fasta;
import std.array;
import std.string;
import std.algorithm;
import std.stdio;
import std.range;
import std.conv;
import std.math;
import std.typecons;
import std.exception;
import std.path;
import std.file;
import bio.std.file.fai;
/*
A text-based single-letter format for representing
nucleotide (nt) and amino-acid (aa) sequences.
The ">" symbol/character marks the start of a fasta entry.
Each fasta entry comprise of an alphanumeric definition line followed by a
newline character and a single or multiline sequence of IUPAC codes used to
represent nucleotide or amino-acid sequences.
An example of a nucleotide fasta file
>Entry1_ID header field1|field2|...
TTGACGGGTTTTTGTCCTGATT
>Entry2_ID header field1|field2|...
ATTTTGGGTTACTGTTGGTTTTTGGGC
TODO:
1. Allow reading gzipped fasta files.
*/
struct FastaRecord {
string header;
string sequence;
ulong lineLen;
string lineTerm = "\n";
// split the header to array of fields
@property string[] headerFields(){
return split(header, "|").map!strip.array;
}
// return the length of the sequence
@property ulong len() {
return sequence.length;
}
string toString() {
string seq;
ulong i = lineLen;
for (; i<sequence.length; i+=lineLen) {
seq~=sequence[i-lineLen..i]~"\n";
}
seq~=sequence[i-lineLen..$];
return format(">%s\n%s", header, seq);
}
unittest {
auto recString = q"(
>chr2
acgtgagtgcacgtgagtgcacgtgagtgc
acgtgagtgcacgtgagtgc
)".outdent().strip();
auto header = "chr2";
auto seq = "acgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgc";
auto lineLen = 30;
auto rec = FastaRecord(header, seq, lineLen);
assert (rec.toString() == recString);
assert (rec.len == seq.length);
}
}
struct Region {
string reference;
ulong beg, end;
@property len() {
return end - beg;
}
string toString() {
if ( end == 0 ) {
if ( beg == 0 )
return reference;
else
return format("%s:%s", reference, beg+1);
}
return format("%s:%s-%s", reference, beg+1, end);
}
this(string q) {
auto res = q.split(":");
reference = res[0];
if ( res.length > 2) {
throw new Exception(format("Wrong format for region: %s", q));
} else if (res.length > 1) {
auto boundaries = res[1].replace(",","").split("-").map!(to!ulong);
beg = boundaries[0]-1;
if ( boundaries.length == 2 ) {
end = boundaries[1];
}
}
}
unittest {
assert ( Region("chr2:1-10").toString() == "chr2:1-10" );
assert ( Region("chr2:1-10").len == 10 );
assert ( Region("chr2").toString() == "chr2" );
assert ( Region("chr2:10").toString() == "chr2:10" );
assertThrown!Exception( Region("chr2:1:10") );
auto region1 = Region("chr1:1,000-2000");
assert(region1.reference == "chr1");
assert(region1.beg == 999);
assert(region1.end == 2000);
auto region2 = Region("chr2");
assert(region2.reference == "chr2");
assert(region2.beg == 0);
assert(region2.end == 0);
auto region3 = Region("chr3:1,000,000");
assert(region3.reference == "chr3");
assert(region3.beg == 999_999);
assert(region3.end == 0);
}
}
auto fastaRecords(string filename) {
auto f = new File(filename);
FastaRecord[] records;
string lineTerm = f.byLine(KeepTerminator.yes).take(1).front.endsWith("\r\n") ? "\r\n" : "\n";
f.seek(0);
ulong offset;
foreach(line; f.byLine(KeepTerminator.no, lineTerm)) {
offset+= line.length + lineTerm.length;
if ( line.startsWith(">") ) {
records~=FastaRecord();
records[$-1].lineTerm = lineTerm;
records[$-1].header ~= line[1..$];
} else {
if ( records[$-1].lineLen == 0 ) {
records[$-1].lineLen = line.length;
}
records[$-1].sequence ~= line;
}
}
f.close();
return records;
}
version(Broken) unittest {
auto testFa = tempDir.buildPath("test2.fa");
// scope(exit) testFa.remove;
auto f = File(testFa, "w");
f.writeln(q"(
>chr1
acgtgagtgc
>chr2
acgtgagtgcacgtgagtgcacgtgagtgc
acgtgagtgcacgtgagtgc
>chr3 hrsv | Kilifi | partial sequence
CATGTTATTACAAGTAGTGATATTTGCCCTAATAATAATATTGTAGTGAAATCCAATTTCACAACAATGC
)".outdent().strip());
f.flush();
f.close();
auto records = fastaRecords(testFa);
assert ( records.length == 3 );
assert ( records[0].header == "chr1" );
assert ( records[0].sequence == "acgtgagtgc" );
assert ( records[0].lineLen == 10 );
assert ( records[0].toString == q"(
>chr1
acgtgagtgc
)".outdent().strip());
assert ( records[1].header == "chr2" );
assert ( records[1].sequence == "acgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgc" );
assert ( records[1].lineLen == 30 );
assert ( records[1].toString == q"(
>chr2
acgtgagtgcacgtgagtgcacgtgagtgc
acgtgagtgcacgtgagtgc
)".outdent().strip());
assert(records[2].header == "chr3 hrsv | Kilifi | partial sequence" );
assert(records[2].headerFields.length == 3);
assert(records[2].headerFields == ["chr3 hrsv","Kilifi","partial sequence"]);
}
auto fastaRegions(string filename, string[] queries) {
auto f = new File(filename);
FaiRecord[string] index = makeIndex(readFai(filename~=".fai"));
Region[] regions = to!(Region[])(queries);
auto res = fetchFastaRegions(f, index, regions);
f.close();
return res;
}
auto fetchFastaRegions(File *fasta, FaiRecord[string] index, Region[] regions) {
FastaRecord[] records;
foreach (region; regions) {
string seq;
ulong len;
if ( region.reference in index ) {
auto reference = index[region.reference];
fasta.seek(reference.offset+region.beg+region.beg/reference.lineLen);
size_t bufLen;
if ( region.end == 0 )
bufLen = reference.seqLen + reference.seqLen/reference.lineLen;
else
bufLen = region.len + region.len/reference.lineLen;
seq = fasta.rawRead(new char[bufLen]).replace(reference.lineTerm,"").idup;
len = reference.lineLen;
}
records ~= FastaRecord(region.to!string, seq, len);
}
return records;
}
version(Broken) unittest {
auto testFa = tempDir.buildPath("test3.fa");
// scope(exit) remove(testFa);
auto fa = new File(testFa,"w");
fa.writeln(q"(
>chr1
acgtgagtgc
>chr2
acgtgagtgcacgtgagtgcacgtgagtgc
acgtgagtgcacgtgagtgc
)".outdent().strip());
fa.flush();
fa.close();
auto faiString = "
chr1\t10\t6\t10\t11
chr2\t50\t23\t30\t31
".outdent().strip();
auto testIndex = tempDir.buildPath("test3.fa.fai");
// scope(exit) testIndex.remove;
auto f2 = new File(testIndex,"w");
f2.writeln(faiString);
f2.flush();
f2.close();
auto regions = fastaRegions(testFa, ["chr1:4-6", "chr2:36-45"]);
assert ( regions.length == 2 );
assert ( regions[0].header == "chr1:4-6" );
assert ( regions[0].len == 3, regions[0].toString() );
assert ( regions[0].sequence == "tga" );
assert ( regions[0].lineLen == 10 );
assert ( regions[1].header == "chr2:36-45" );
assert ( regions[1].len == 10, regions[1].toString() );
assert ( regions[1].sequence == "agtgcacgtg" );
assert ( regions[1].lineLen == 30 );
regions = fastaRegions(testFa, ["chr1"]);
assert ( regions.length == 1 );
assert ( regions[0].header == "chr1" );
assert ( regions[0].len == 10, regions[0].toString() );
assert ( regions[0].sequence == "acgtgagtgc" );
assert ( regions[0].lineLen == 10, regions[0].toString() );
regions = fastaRegions(testFa, ["chr2"]);
assert ( regions.length == 1 );
assert ( regions[0].header == "chr2" );
assert ( regions[0].len == 50, regions[0].toString() );
assert ( regions[0].sequence == "acgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgcacgtgagtgc" );
assert ( regions[0].lineLen == 30 );
}
|