Debian Codegraph @

src/algorithm/Heteroduplex.cpp

raw
1 #include <pbcopper/algorithm/Heteroduplex.h>
2
3 #include <pbcopper/algorithm/internal/HeteroduplexUtils.h>
4 #include <pbcopper/math/FishersExact.h>
5 #include <pbcopper/utility/Ssize.h>
6
7 #include <algorithm>
8 #include <sstream>
9 #include <stdexcept>
10
11 #include <cassert>
12 #include <cstddef>
13
14 namespace PacBio {
15 namespace Algorithm {
16 namespace {
17
18 constexpr std::array<char, 5> BASES{'A', 'C', 'G', 'T', '-'};
19
20 // clang-format off
21 constexpr std::array<uint8_t, 256> BASE_TABLE{
22 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 15
23 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 31
24 // -
25 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,4, 255,255, // 47
26 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 63
27
28 // A C G
29 255,0, 255,1, 255,255,255,2, 255,255,255,255, 255,255,255,255, // 79
30 // T
31 255,255,255,255, 3, 255,255,255, 255,255,255,255, 255,255,255,255, // 95
32 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 111
33 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 127
34
35 // a c g
36 255,0, 255,1, 255,255,255,2, 255,255,255,255, 255,255,255,255, // 143
37 // t
38 255,255,255,255, 3, 255,255,255, 255,255,255,255, 255,255,255,255, // 159
39 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 175
40 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 191
41
42 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 207
43 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 223
44 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 239
45 255,255,255,255, 255,255,255,255, 255,255,255,255, 255,255,255,255, // 255
46 };
47 // clang-format on
48
49 double CalculatePValue(const int fwdCoverageCount, const int fwdMismatchCount,
50 const int revCoverageCount, const int revMismatchCount)
51 {
52 const int n11 = fwdCoverageCount - fwdMismatchCount; // fwd & match
53 const int n12 = revCoverageCount - revMismatchCount; // rev & match
54 const int n21 = fwdMismatchCount; // fwd & mismatch
55 const int n22 = revMismatchCount; // rev & mismatch
56
57 assert(n11 >= 0);
58 assert(n12 >= 0);
59 assert(n21 >= 0);
60 assert(n22 >= 0);
61
62 return Math::FishersExact(n11, n12, n21, n22);
63 }
64
65 } // namespace
66
67 namespace internal {
68
69 std::pair<char, int> MostCommonBase(const BaseCount& counts, const char refBase)
70 {
71 assert(static_cast<int>(refBase) < 256);
72
73 // a tie goes to reference base, so the max count starts there
74 int maxBaseCountIdx = BASE_TABLE[static_cast<unsigned char>(refBase)];
75 int maxBaseCount = counts[maxBaseCountIdx];
76
77 for (int i = 0; i < 5; ++i) {
78 const int baseCount = counts[i];
79 if (maxBaseCount < baseCount) {
80 maxBaseCount = baseCount;
81 maxBaseCountIdx = i;
82 }
83 }
84
85 return {BASES[maxBaseCountIdx], maxBaseCount};
86 }
87
88 StrandCounts::StrandCounts(const std::string& ref)
89 : NumReads(ref.size()), MismatchBaseCounts(ref.size()), MostCommonBases{ref}
90 {
91 assert(ref.size() == NumReads.size());
92 assert(ref.size() == MismatchBaseCounts.size());
93 assert(ref.size() == MostCommonBases.size());
94 }
95
96 StrandRawData::StrandRawData(const size_t refLength)
97 : NumReads(refLength, 0)
98 , BaseCounts{refLength, BaseCount{}}
99 , PotentialMismatches(refLength, 0)
100 , Insertions{refLength}
101 {
102 assert(refLength == NumReads.size());
103 assert(refLength == BaseCounts.size());
104 assert(refLength == PotentialMismatches.size());
105 assert(refLength == Insertions.size());
106 }
107
108 StrandRawData CalculateStrandRawData(const std::string& reference, const StrandInput& input)
109 {
110 assert(input.Sequences.size() == input.Cigars.size());
111 assert(input.Sequences.size() == input.Positions.size());
112
113 StrandRawData result{reference.size()};
114
115 const int referenceSize = Utility::Ssize(reference);
116 const int numSequences = Utility::Ssize(input.Sequences);
117 for (int i = 0; i < numSequences; ++i) {
118 const auto& cigar = input.Cigars[i];
119 const auto& seq = input.Sequences[i];
120 const auto startPos = input.Positions[i];
121
122 int targetPos = startPos;
123 int queryPos = 0;
124
125 for (const auto& op : cigar) {
126 const auto opType = op.Type();
127 const int opLength = op.Length();
128
129 switch (opType) {
130 case Data::CigarOperationType::SEQUENCE_MATCH: {
131 for (int j = 0; j < opLength; ++j) {
132 const int8_t base = seq[queryPos + j];
133 ++result.BaseCounts[targetPos + j][BASE_TABLE[base]];
134 }
135 break;
136 }
137 case Data::CigarOperationType::SEQUENCE_MISMATCH: {
138 for (int j = 0; j < opLength; ++j) {
139 const int8_t base = seq[queryPos + j];
140 ++result.BaseCounts[targetPos + j][BASE_TABLE[base]];
141 result.PotentialMismatches[targetPos + j] = 1;
142 }
143 break;
144 }
145 case Data::CigarOperationType::DELETION: {
146 for (int j = 0; j < opLength; ++j) {
147 ++result.BaseCounts[targetPos + j][4]; // 4 = [BaseValue('-')];
148 result.PotentialMismatches[targetPos + j] = 1;
149 }
150 break;
151 }
152 case Data::CigarOperationType::INSERTION: {
153 if (targetPos < referenceSize) {
154 result.Insertions[targetPos].emplace_back(seq.data() + queryPos, opLength);
155 }
156 break;
157 }
158
159 // Full ignore
160 case Data::CigarOperationType::SOFT_CLIP: // fallthrough
161 case Data::CigarOperationType::HARD_CLIP: // .
162 case Data::CigarOperationType::REFERENCE_SKIP: // .
163 case Data::CigarOperationType::PADDING: // .
164 break;
165 default:
166 std::ostringstream msg;
167 msg << "encountered unsupported CIGAR op: '"
168 << Data::CigarOperation::TypeToChar(opType) << "'";
169 throw std::runtime_error{msg.str()};
170 }
171
172 if (Data::ConsumesReference(opType)) {
173 for (int j = 0; j < opLength; ++j) {
174 ++result.NumReads[targetPos + j];
175 }
176 targetPos += opLength;
177 }
178 if (Data::ConsumesQuery(opType)) {
179 queryPos += opLength;
180 }
181 }
182 }
183
184 return result;
185 }
186
187 } // namespace internal
188
189 HeteroduplexResults FindHeteroduplex(
190 const std::string& reference, const std::vector<std::string>& fwdSequences,
191 const std::vector<std::string>& revSequences, const std::vector<Data::Cigar>& fwdCigars,
192 const std::vector<Data::Cigar>& revCigars, const std::vector<int32_t>& fwdPositions,
193 const std::vector<int32_t>& revPositions, const HeteroduplexSettings& settings)
194 {
195 assert(fwdSequences.size() == fwdCigars.size());
196 assert(fwdSequences.size() == fwdPositions.size());
197 assert(revSequences.size() == revCigars.size());
198 assert(revSequences.size() == revPositions.size());
199 assert(settings.MinimumPerStrandSubreadCoverage >= 0);
200
201 // quick exit on insufficient data
202 if (reference.empty() ||
203 (Utility::Ssize(fwdSequences) < settings.MinimumPerStrandSubreadCoverage) ||
204 (Utility::Ssize(revSequences) < settings.MinimumPerStrandSubreadCoverage)) {
205 return HeteroduplexResults{};
206 }
207
208 // combine fwd and rev input
209 std::vector<std::string> combinedSequences = fwdSequences;
210 combinedSequences.insert(combinedSequences.end(), revSequences.begin(), revSequences.end());
211 std::vector<Data::Cigar> combinedCigars = fwdCigars;
212 combinedCigars.insert(combinedCigars.end(), revCigars.begin(), revCigars.end());
213 std::vector<int32_t> combinedPositions = fwdPositions;
214 combinedPositions.insert(combinedPositions.end(), revPositions.begin(), revPositions.end());
215
216 // get data from CIGARs for base counts from combined strand input
217 const internal::StrandRawData& combinedStrands = internal::CalculateStrandRawData(
218 reference, internal::StrandInput{combinedSequences, combinedCigars, combinedPositions});
219
220 // get string of most common bases
221 const auto BaseCountsToMostCommonBasesString =
222 [](const std::vector<internal::BaseCount>& counts, const std::string_view& ref) {
223 std::string res;
224 res.reserve(counts.size());
225 for (int i = 0; i < Utility::Ssize(counts); ++i) {
226 res.push_back(internal::MostCommonBase(counts[i], ref[i]).first);
227 }
228 return res;
229 };
230
231 // recalculate reference by counting the most common base at each position
232 // since input reference does not represent the most common bases overall
233 const std::string& recalculatedReference =
234 BaseCountsToMostCommonBasesString(combinedStrands.BaseCounts, reference);
235
236 // gather pileup and potential mismatch sites from CIGARs for stranded input
237 const internal::StrandRawData fwdStrand = internal::CalculateStrandRawData(
238 recalculatedReference, internal::StrandInput{fwdSequences, fwdCigars, fwdPositions});
239 const internal::StrandRawData revStrand = internal::CalculateStrandRawData(
240 recalculatedReference, internal::StrandInput{revSequences, revCigars, revPositions});
241
242 std::string fwdMostCommonBases = recalculatedReference;
243 std::string revMostCommonBases = recalculatedReference;
244
245 std::vector<int32_t> variableSites;
246 std::vector<int32_t> significantSites;
247 std::vector<char> significantBases;
248
249 const int refLength = Utility::Ssize(reference);
250 const int start = std::max(1, settings.IgnoreEndBases);
251 const int end = std::min(refLength - 1, refLength - settings.IgnoreEndBases);
252 assert(start > 0);
253 assert(end > start);
254 assert(end < refLength);
255 for (int i = start; i < end; ++i) {
256
257 // nothing to see, carry on
258 if ((fwdStrand.PotentialMismatches[i] == 0) && (revStrand.PotentialMismatches[i] == 0)) {
259 continue;
260 }
261
262 // sanity check: ensure some coverage on both strands
263 const int fwdCoverageCount = fwdStrand.NumReads[i];
264 const int revCoverageCount = revStrand.NumReads[i];
265 if ((fwdCoverageCount == 0) || (revCoverageCount == 0)) {
266 continue;
267 }
268
269 // compute most common bases at position
270 const char refBase = recalculatedReference[i];
271
272 const auto fwdMostCommonBaseCount =
273 internal::MostCommonBase(fwdStrand.BaseCounts[i], refBase);
274 const char fwdMostCommonBase = fwdMostCommonBaseCount.first;
275 const int fwdMostCommonCount = fwdMostCommonBaseCount.second;
276
277 const auto revMostCommonBaseCount =
278 internal::MostCommonBase(revStrand.BaseCounts[i], refBase);
279 const char revMostCommonBase = revMostCommonBaseCount.first;
280 const int revMostCommonCount = revMostCommonBaseCount.second;
281 if (fwdMostCommonBase == revMostCommonBase) {
282 continue;
283 }
284 assert((fwdMostCommonBase != refBase) || (revMostCommonBase != refBase));
285
286 // skip deletion sites: the source of a large % of false positive HD calls
287 if ((fwdMostCommonBase == '-') || (revMostCommonBase == '-')) {
288 continue;
289 }
290
291 // mask SNPs with alleles matching up & downstream bases, respectively. e.g.
292 // v
293 // fwd: AAT
294 // AAT
295 // rev: ATT
296 // ATT
297 if ((fwdMostCommonBase == recalculatedReference[i - 1]) &&
298 (revMostCommonBase == recalculatedReference[i + 1])) {
299 continue;
300 }
301 if ((revMostCommonBase == recalculatedReference[i - 1]) &&
302 (fwdMostCommonBase == recalculatedReference[i + 1])) {
303 continue;
304 }
305
306 // mask SNPs adjacent to insertions, which contain the SNP alleles
307 const auto HasMostCommonBase = [fwdMostCommonBase,
308 revMostCommonBase](const std::string_view& ins) {
309 return (ins.find(fwdMostCommonBase) != std::string::npos) ||
310 (ins.find(revMostCommonBase) != std::string::npos);
311 };
312
313 const auto& fwdAdjacentInsertions = fwdStrand.Insertions[i + 1];
314 const int fwdRelevantInsertions = std::count_if(
315 fwdAdjacentInsertions.cbegin(), fwdAdjacentInsertions.cend(), HasMostCommonBase);
316 const auto& revAdjacentInsertions = revStrand.Insertions[i + 1];
317 const int revRelevantInsertions = std::count_if(
318 revAdjacentInsertions.cbegin(), revAdjacentInsertions.cend(), HasMostCommonBase);
319
320 const int numPositionInsertions =
321 Utility::Ssize(fwdAdjacentInsertions) + Utility::Ssize(revAdjacentInsertions);
322 const double fractionAdjacentInsertions =
323 static_cast<double>(fwdRelevantInsertions + revRelevantInsertions) /
324 std::max(1, numPositionInsertions);
325 if (fractionAdjacentInsertions >= settings.AdjacentInsertionThreshold) {
326 continue;
327 }
328
329 // store mismatch count & update "most common bases" for return
330 int fwdMismatchCount = 0;
331 int revMismatchCount = 0;
332 if (fwdMostCommonBase != refBase) {
333 fwdMismatchCount = fwdMostCommonCount;
334 fwdMostCommonBases[i] = fwdMostCommonBase;
335 }
336 if (revMostCommonBase != refBase) {
337 revMismatchCount = revMostCommonCount;
338 revMostCommonBases[i] = revMostCommonBase;
339 }
340
341 // check mismatch fractions
342 const double fwdMismatchFractionCoverage =
343 static_cast<double>(fwdMismatchCount) / std::max(1, fwdCoverageCount);
344 const double revMismatchFractionCoverage =
345 static_cast<double>(revMismatchCount) / std::max(1, revCoverageCount);
346 const bool meetsMinFractionCoverage =
347 ((fwdMismatchFractionCoverage >= settings.MinFractionMismatchCoverage) ||
348 (revMismatchFractionCoverage >= settings.MinFractionMismatchCoverage));
349 if (!meetsMinFractionCoverage) {
350 continue;
351 }
352
353 // store all variable sites that have met mismatch/coverage requirements
354 variableSites.push_back(i);
355
356 // determine the site's significance using Fisher's exact text
357 const double pValue =
358 CalculatePValue(fwdCoverageCount, fwdMismatchCount, revCoverageCount, revMismatchCount);
359 if (pValue < settings.AlphaLevel) {
360 significantSites.push_back(i);
361 significantBases.push_back((fwdMostCommonBase == refBase) ? revMostCommonBase
362 : fwdMostCommonBase);
363 }
364 }
365
366 // calculate results summary & return
367 const uint32_t numSignificantSites = significantSites.size();
368 const uint32_t numVariableSites = variableSites.size();
369 const double fractionSites =
370 static_cast<double>(numSignificantSites) / std::max(1u, numVariableSites);
371
372 return HeteroduplexResults{numSignificantSites,
373 numVariableSites,
374 static_cast<uint32_t>(refLength),
375 fractionSites,
376 std::move(variableSites),
377 std::move(significantSites),
378 std::move(significantBases),
379 std::move(fwdMostCommonBases),
380 std::move(revMostCommonBases)};
381 }
382
383 bool IsHeteroduplex(const std::string& reference, const std::vector<std::string>& fwdSequences,
384 const std::vector<std::string>& revSequences,
385 const std::vector<Data::Cigar>& fwdCigars,
386 const std::vector<Data::Cigar>& revCigars,
387 const std::vector<int32_t>& fwdPositions,
388 const std::vector<int32_t>& revPositions, const HeteroduplexSettings& settings)
389 {
390 const HeteroduplexResults results =
391 FindHeteroduplex(reference, fwdSequences, revSequences, fwdCigars, revCigars, fwdPositions,
392 revPositions, settings);
393 return results.FractionSites >= settings.MinFractionSites;
394 }
395
396 } // namespace Algorithm
397 } // namespace PacBio