1 /*
2    This file is part of BioD.
3    Copyright (C) 2016   George Githinji <biorelated@gmail.com>
4    Copyright (C) 2018   Emilio Palumbo <emiliopalumbo@gmail.com> 
5    Permission is hereby granted, free of charge, to any person obtaining a
6    copy of this software and associated documentation files (the "Software"),
7    to deal in the Software without restriction, including without limitation
8    the rights to use, copy, modify, merge, publish, distribute, sublicense,
9    and/or sell copies of the Software, and to permit persons to whom the
10    Software is furnished to do so, subject to the following conditions:
11 
12    The above copyright notice and this permission notice shall be included in
13    all copies or substantial portions of the Software.
14 
15    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21    DEALINGS IN THE SOFTWARE.
22  */
23 
24 module bio.std.file.fai;
25 
26 import std.stdio;
27 import std.range;
28 import std.algorithm;
29 import std..string;
30 import std.conv;
31 import std.file;
32 import std.path;
33 
34 struct FaiRecord {
35     string header, lineTerm;
36     ulong seqLen, lineLen, offset;
37     @property ulong lineOffset() {
38         return lineLen + lineTerm.length;
39     }
40 
41     string toString() {
42         return format("%s\t%s\t%s\t%s\t%s", header, seqLen, offset, lineLen, lineOffset);
43     }
44     unittest {
45         auto rec = FaiRecord("chr2", "\n", 10, 50, 4);
46         assert(rec.toString() == "chr2\t10\t4\t50\t51");
47         rec.lineTerm = "\r\n";
48         assert(rec.toString() == "chr2\t10\t4\t50\t52");
49     }
50 
51     this(string str) {
52         auto res = str.split("\t");
53         header ~= res[0];
54         seqLen = to!ulong(res[1]);
55         offset = to!ulong(res[2]);
56         lineLen = to!ulong(res[3]);
57         lineTerm = (to!ulong(res[4])-lineLen) == 1 ? "\n" : "\r\n";
58     }
59     unittest {
60         auto s = "chr2\t10\t4\t50\t51";
61         assert(FaiRecord(s).toString() == s);
62     }
63 
64     this(string header, string lineTerm, ulong seqLen, ulong lineLen, ulong offset) {
65         this.header = header;
66         this.seqLen = seqLen;
67         this.offset = offset;
68         this.lineLen = lineLen;
69         this.lineTerm = lineTerm;
70     }
71     unittest {
72         assert(FaiRecord("chr2", "\n", 10, 50, 4).toString() == "chr2\t10\t4\t50\t51");
73     }
74 }
75 
76 auto readFai(string filename) {
77     File f = File(filename, "r");
78     return f.byLineCopy()
79             .map!(x => FaiRecord(x));
80 }
81 unittest {
82     auto faiString = "chr2\t10\t4\t50\t51";
83     auto testIndex = tempDir.buildPath("test.fa.fai");
84     scope(exit) testIndex.remove;
85     File(testIndex, "w").writeln(faiString);
86     auto recs = readFai(testIndex).array;
87     assert(recs.length == 1);
88     assert(is(typeof(recs[0])==FaiRecord));
89     assert(recs[0].toString() == faiString);
90 }
91 
92 auto makeIndex(T)(T records) {   
93     FaiRecord[string] index;
94     foreach (record; records) {
95         index[record.header] = record;
96     }
97     index.rehash;
98     return index;
99 }
100 unittest {
101     auto records = to!(FaiRecord[])(["chr2\t10\t4\t50\t51"]);
102     auto i = makeIndex(records);
103     assert( i.length == 1);
104     assert( "chr2" in i);
105     assert( i["chr2"] ==  FaiRecord("chr2\t10\t4\t50\t51"));
106 }
107 
108 auto buildFai(string filename) {
109 
110     File f = File(filename, "r");
111     FaiRecord[] records; 
112     string lineTerm = f.byLine(KeepTerminator.yes).take(1).front.endsWith("\r\n") ? "\r\n" : "\n";
113     f.seek(0);
114     ulong offset;
115     foreach(line; f.byLine(KeepTerminator.no, lineTerm)) {
116         offset+= line.length + lineTerm.length;
117         if ( line.startsWith(">") ) {
118             records~=FaiRecord();
119             records[$-1].lineTerm = lineTerm;
120             records[$-1].header ~= line.split(" ").front[1..$];
121             records[$-1].offset = offset;
122         } else {
123             if ( records[$-1].lineLen == 0 ) {
124                 records[$-1].lineLen = line.length;
125             }
126             records[$-1].seqLen += line.length;
127         }
128     }
129 
130     return records;
131 }
132 
133 unittest {
134     auto testFa = tempDir.buildPath("test.fa");
135     scope(exit) testFa.remove;
136     File(testFa, "w").writeln(q"(
137         >chr1
138         acgtgagtgc
139         >chr2
140         acgtgagtgcacgtgagtgcacgtgagtgc
141         acgtgagtgcacgtgagtgc
142     )".outdent().strip());
143     auto recs = buildFai(testFa).array;
144     assert(recs.length == 2);
145     assert(recs.all!(x => is(typeof(x)==FaiRecord)));
146     assert(recs[0].toString() == "chr1\t10\t6\t10\t11");
147     assert(recs[1].toString() == "chr2\t50\t23\t30\t31");
148 }