File: sequence_string_set.hpp

package info (click to toggle)
r-bioc-alabaster.base 1.6.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,652 kB
  • sloc: cpp: 11,377; sh: 29; makefile: 2
file content (372 lines) | stat: -rw-r--r-- 13,597 bytes parent folder | download | duplicates (2)
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
365
366
367
368
369
370
371
372
#ifndef TAKANE_SEQUENCE_STRING_SET_HPP
#define TAKANE_SEQUENCE_STRING_SET_HPP

#include "byteme/byteme.hpp"

#include "ritsuko/ritsuko.hpp"
#include "utils_other.hpp"

#include <array>
#include <algorithm>
#include <stdexcept>
#include <limits>
#include <cctype>
#include <filesystem>

/**
 * @file sequence_string_set.hpp
 * @brief Validation for sequence string sets.
 */

namespace takane {

/**
 * @namespace takane::sequence_string_set
 * @brief Definitions for sequence string sets.
 */
namespace sequence_string_set {

/**
 * @cond
 */
namespace internal {

inline int char2int(char val) {
    return static_cast<int>(val) - static_cast<int>(std::numeric_limits<char>::min());
}

template<bool has_quality_, bool parallel_>
size_t parse_sequences(const std::filesystem::path& path, std::array<bool, 255> allowed, char lowest_quality) {
    auto gzreader = internal_other::open_reader<byteme::GzipFileReader>(path);
    typedef typename std::conditional<parallel_, byteme::PerByteParallel<>, byteme::PerByte<> >::type PB;
    PB pb(&gzreader);

    size_t nseq = 0;
    size_t line_count = 0;
    auto advance_and_check = [&]() -> char {
        if (!pb.advance()) {
            throw std::runtime_error("premature end of the file at line " + std::to_string(line_count + 1));
        }
        return pb.get();
    };

    while (pb.valid()) {
        // Processing the name. 
        char val = pb.get();
        if constexpr(!has_quality_) {
            if (val != '>') {
                throw std::runtime_error("sequence name should start with '>' at line " + std::to_string(line_count + 1));
            }
        } else {
            if (val != '@') {
                throw std::runtime_error("sequence name should start with '@' at line " + std::to_string(line_count + 1));
            }
        }

        val = advance_and_check();
        size_t proposed = 0;
        bool empty = true;
        while (val != '\n') {
            if (!std::isdigit(val)) {
                throw std::runtime_error("sequence name should be a non-negative integer at line " + std::to_string(line_count + 1));
            }
            empty = false;
            proposed *= 10;
            proposed += (val - '0'); 
            val = advance_and_check();
        }
        if (empty || proposed != nseq) {
            throw std::runtime_error("sequence name should be its index at line " + std::to_string(line_count + 1));
        }
        ++line_count;

        if constexpr(!has_quality_) {
            // Processing the sequence itself until we get to a '>' or we run out of bytes.
            val = advance_and_check();
            while (true) {
                if (val == '\n') {
                    ++line_count;
                    if (!pb.advance()) {
                        break;
                    }
                    val = pb.get();
                    if (val == '>') {
                        break;
                    }
                } else {
                    if (!allowed[char2int(val)]) {
                        throw std::runtime_error("forbidden character '" + std::string(1, val) + "' in sequence at line " + std::to_string(line_count + 1));
                    }
                    val = advance_and_check();
                }
            }

        } else {
            // Processing the sequence itself until we get to a '+'.
            val = advance_and_check();
            size_t seq_length = 0;
            while (true) {
                if (val == '\n') {
                    ++line_count;
                    val = advance_and_check();
                    if (val == '+') {
                        break;
                    }
                } else {
                    if (!allowed[char2int(val)]) {
                        throw std::runtime_error("forbidden character '" + std::string(1, val) + "' in sequence at line " + std::to_string(line_count + 1));
                    }
                    ++seq_length;
                    val = advance_and_check();
                }
            }

            // Next should be a single line; starting with '+' is implicit from above.
            do {
                val = advance_and_check();
            } while (val != '\n');
            ++line_count;

            // Processing the qualities. Extraction is allowed to fail if we're at
            // the end of the file. Note that we can't check for '@' as a
            // delimitor, as this can be a valid score, so instead we check at each
            // newline whether we've reached the specified length, and quit if so.
            size_t qual_length = 0;
            while (true) {
                val = advance_and_check();
                if (val == '\n') {
                    ++line_count;
                    if (qual_length >= seq_length) {
                        while (pb.advance() && pb.get() == '\n') {} // sneak past any newlines.
                        break;
                    }
                } else {
                    if (val < lowest_quality) {
                        throw std::runtime_error("out-of-range quality score '" + std::string(1, val) + "' detected at line " + std::to_string(line_count + 1));
                    }
                    ++qual_length;
                }
            }

            if (qual_length != seq_length) {
                throw std::runtime_error("unequal lengths for quality and sequence strings at line " + std::to_string(line_count + 1) + ")");
            }
        }

        ++nseq;
    }

    return nseq;
}

template<bool parallel_>
size_t parse_names(const std::filesystem::path& path) {
    auto gzreader = internal_other::open_reader<byteme::GzipFileReader>(path);
    typedef typename std::conditional<parallel_, byteme::PerByteParallel<>, byteme::PerByte<> >::type PB;
    PB pb(&gzreader);

    size_t nseq = 0;
    size_t line_count = 0;
    auto advance_and_check = [&]() -> char {
        if (!pb.advance()) {
            throw std::runtime_error("premature end of the file at line " + std::to_string(line_count + 1));
        }
        return pb.get();
    };

    while (pb.valid()) {
        char val = pb.get();
        if (val != '"') {
            throw std::runtime_error("name should start with a quote");
        }

        while (true) {
            val = advance_and_check();
            if (val == '"') {
                val = advance_and_check();
                if (val == '\n') {
                    ++nseq;
                    ++line_count;
                    pb.advance();
                    break;
                } else if (val != '"') {
                    throw std::runtime_error("characters present after end quote at line " + std::to_string(line_count + 1));
                }
            } else if (val == '\n') {
                ++line_count;
            }
        }
    }

    return nseq;
}

}
/**
 * @endcond
 */

/**
 * @param path Path to a directory containing a sequence string set.
 * @param metadata Metadata for the object, typically read from its `OBJECT` file.
 * @param options Validation options.
 */
inline void validate(const std::filesystem::path& path, const ObjectMetadata& metadata, Options& options) {
    const auto& obj = internal_json::extract_typed_object_from_metadata(metadata.other, "sequence_string_set");
    const auto& vstring = internal_json::extract_string_from_typed_object(obj, "version", "sequence_string_set");
    auto version = ritsuko::parse_version_string(vstring.c_str(), vstring.size(), /* skip_patch = */ true);
    if (version.major != 1) {
        throw std::runtime_error("unsupported version string '" + vstring + "'");
    }

    size_t expected_nseq = 0;
    {
        auto lIt = obj.find("length");
        if (lIt == obj.end()) {
            throw std::runtime_error("expected a 'sequence_string_set.length' property");
        }

        const auto& val = lIt->second;
        if (val->type() != millijson::NUMBER) {
            throw std::runtime_error("'sequence_string_set.length' property should be a JSON number");
        }

        auto num = reinterpret_cast<const millijson::Number*>(val.get())->value;
        if (num < 0 || std::floor(num) != num) {
            throw std::runtime_error("'sequence_string_set.length' should be a non-negative integer");
        }

        expected_nseq = num;
    }

    std::array<bool, 255> allowed;
    std::fill(allowed.begin(), allowed.end(), false);
    {
        const std::string& stype = internal_json::extract_string(obj, "sequence_type", [&](std::exception& e) -> void {
            throw std::runtime_error("failed to extract 'sequence_string_set.sequence_type' from the object metadata; " + std::string(e.what())); 
        });

        std::string allowable;
        if (stype == "DNA" || stype == "RNA") {
            allowable = "ACGRYSWKMBDHVN";
            if (stype == "DNA") {
                allowable += "T";
            } else {
                allowable += "U";
            }
        } else if (stype == "AA") {
            allowable = "ACDEFGHIKLMNPQRSTVWY";
        } else if (stype == "custom") {
            std::fill(allowed.begin() + internal::char2int('!'), allowed.begin() + internal::char2int('~') + 1, true);
        } else {
            throw std::runtime_error("invalid string '" + stype + "' in the 'sequence_string_set.sequence_type' property");
        }

        for (auto a : allowable) {
            allowed[internal::char2int(a)] = true;
            allowed[internal::char2int(std::tolower(a))] = true;
        }
        allowed[internal::char2int('.')] = true;
        allowed[internal::char2int('-')] = true;
    }

    bool has_qualities = false;
    char lowest_quality = 0;
    {
        auto xIt = obj.find("quality_type");
        if (xIt != obj.end()) {
            const auto& val = xIt->second;
            if (val->type() != millijson::STRING) {
                throw std::runtime_error("'sequence_string_set.quality_type' property should be a JSON string");
            }

            const auto& qtype = reinterpret_cast<const millijson::String*>(val.get())->value;
            has_qualities = true;

            if (qtype == "phred") {
                auto oIt = obj.find("quality_offset");
                if (oIt == obj.end()) {
                    throw std::runtime_error("expected a 'sequence_string_set.quality_offset' property for Phred quality scores");
                }

                const auto& val = oIt->second;
                if (val->type() != millijson::NUMBER) {
                    throw std::runtime_error("'sequence_string_set.quality_offset' property should be a JSON number");
                }

                double offset = reinterpret_cast<const millijson::Number*>(val.get())->value;
                if (offset == 33) {
                    lowest_quality = '!';
                } else if (offset == 64) {
                    lowest_quality = '@';
                } else {
                    throw std::runtime_error("'sequence_string_set.quality_offset' property should be either 33 or 64");
                }

            } else if (qtype == "solexa") {
                lowest_quality = ';';

            } else if (qtype == "none") {
                has_qualities = false;

            } else {
                throw std::runtime_error("invalid string '" + qtype + "' for the 'sequence_string_set.quality_type' property");
            }
        }
    }

    size_t nseq = 0;
    if (has_qualities) {
        auto spath = path / "sequences.fastq.gz";
        if (options.parallel_reads) {
            nseq = internal::parse_sequences<true, true>(spath, allowed, lowest_quality);
        } else {
            nseq = internal::parse_sequences<true, false>(spath, allowed, lowest_quality);
        }
    } else {
        auto spath = path / "sequences.fasta.gz";
        if (options.parallel_reads) {
            nseq = internal::parse_sequences<false, true>(spath, allowed, lowest_quality);
        } else {
            nseq = internal::parse_sequences<false, false>(spath, allowed, lowest_quality);
        }
    }
    if (nseq != expected_nseq) {
        throw std::runtime_error("observed number of sequences is different from the expected number (" + std::to_string(nseq) + " to " + std::to_string(expected_nseq) + ")");
    }

    auto npath = path / "names.txt.gz";
    if (std::filesystem::exists(npath)) {
        size_t nnames = 0;
        if (options.parallel_reads) {
            nnames = internal::parse_names<true>(npath);
        } else {
            nnames = internal::parse_names<false>(npath);
        }
        if (nnames != expected_nseq) {
            throw std::runtime_error("number of names is different from the number of sequences (" + std::to_string(nnames) + " to " + std::to_string(expected_nseq) + ")");
        }
    }

    internal_other::validate_mcols(path, "sequence_annotations", nseq, options);
    internal_other::validate_metadata(path, "other_annotations", options);
}

/**
 * @param path Path to a directory containing a sequence string set.
 * @param metadata Metadata for the object, typically read from its `OBJECT` file.
 * @param options Validation options.
 * @return The number of sequences.
 */
inline size_t height([[maybe_unused]] const std::filesystem::path& path, const ObjectMetadata& metadata, [[maybe_unused]] Options& options) {
    const auto& obj = internal_json::extract_typed_object_from_metadata(metadata.other, "sequence_string_set");
    auto lIt = obj.find("length");
    const auto& val = lIt->second;
    return reinterpret_cast<const millijson::Number*>(val.get())->value;
}

}

}

#endif