Debian Codegraph @

src/C++/Quiver/QuiverConsensus.cpp

raw
1 // Author: David Alexander, Lance Hepler
2
3 #include <ConsensusCore/Quiver/QuiverConsensus.hpp>
4
5 #include <ConsensusCore/Logging.hpp>
6 #include <ConsensusCore/Mutation.hpp>
7 #include <ConsensusCore/Quiver/MultiReadMutationScorer.hpp>
8 #include <ConsensusCore/Quiver/MutationEnumerator.hpp>
9 #include <ConsensusCore/Utils.hpp>
10
11 #include <algorithm>
12 #include <boost/functional/hash.hpp>
13 #include <boost/tuple/tuple.hpp>
14 #include <cmath>
15 #include <set>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 namespace ConsensusCore {
21 using std::vector;
22
23 namespace { // PRIVATE
24 using std::max_element;
25
26 struct RefineDinucleotideRepeatOptions : RefineOptions
27 {
28 explicit RefineDinucleotideRepeatOptions(int minDinucleotideRepeatElements)
29 : MinDinucleotideRepeatElements(minDinucleotideRepeatElements)
30 {
31 MaximumIterations = 1;
32 }
33
34 int MinDinucleotideRepeatElements;
35 };
36
37 vector<ScoredMutation> DeleteRange(vector<ScoredMutation> input, int rStart, int rEnd)
38 {
39 vector<ScoredMutation> output;
40 foreach (ScoredMutation s, input) {
41 int pos = s.Start();
42 if (!(rStart <= pos && pos <= rEnd)) {
43 output.push_back(s);
44 }
45 }
46 return output;
47 }
48
49 bool ScoreComparer(const ScoredMutation& i, const ScoredMutation& j)
50 {
51 return i.Score() < j.Score();
52 }
53
54 // Given a list of (mutation, score) tuples, this utility method
55 // greedily chooses the highest scoring well-separated elements. We
56 // use this to avoid applying adjacent high scoring mutations, which
57 // are the rule, not the exception. We only apply the best scoring one
58 // in each neighborhood, and then revisit the neighborhoods after
59 // applying the mutations.
60 //
61 // This is highly unoptimized. It is not in the critical path.
62 vector<ScoredMutation> BestSubset(vector<ScoredMutation> input, int mutationSeparation)
63 {
64 if (mutationSeparation == 0) return input;
65
66 vector<ScoredMutation> output;
67
68 while (!input.empty()) {
69 ScoredMutation& best = *max_element(input.begin(), input.end(), ScoreComparer);
70 output.push_back(best);
71 int nStart = best.Start() - mutationSeparation;
72 int nEnd = best.Start() + mutationSeparation;
73 input = DeleteRange(input, nStart, nEnd);
74 }
75
76 return output;
77 }
78
79 // Sadly and annoyingly there is no covariance on std::vector in C++, so we have
80 // to explicitly project back down to the superclass type to use the APIs as
81 // written.
82 vector<Mutation> ProjectDown(const vector<ScoredMutation>& smuts)
83 {
84 return vector<Mutation>(smuts.begin(), smuts.end());
85 }
86
87 int ProbabilityToQV(double probability, int cap = 93)
88 {
89 using std::min;
90
91 if (probability <= 0.0) return cap;
92
93 return min(cap, static_cast<int>(round(-10.0 * log10(probability))));
94 }
95
96 template <typename E, typename O>
97 E MutationEnumerator(const std::string& tpl, const O&)
98 {
99 return E(tpl);
100 }
101
102 //
103 // this MUST go last to properly specialize the MutationEnumerator
104 //
105 template <>
106 DinucleotideRepeatMutationEnumerator MutationEnumerator<>(
107 const std::string& tpl, const RefineDinucleotideRepeatOptions& opts)
108 {
109 return DinucleotideRepeatMutationEnumerator(tpl, opts.MinDinucleotideRepeatElements);
110 }
111
112 template <typename E, typename O>
113 bool AbstractRefineConsensus(AbstractMultiReadMutationScorer& mms, const O& opts)
114 {
115 bool isConverged = false;
116 float score = mms.BaselineScore();
117 boost::hash<std::string> hash;
118 std::set<size_t> tplHistory;
119
120 vector<ScoredMutation> favorableMutsAndScores;
121
122 for (int iter = 0; iter < opts.MaximumIterations; iter++) {
123 LDEBUG << "Round " << iter;
124 LDEBUG << "State of MMS: " << std::endl << mms.ToString();
125
126 if (tplHistory.find(hash(mms.Template())) != tplHistory.end()) {
127 LDEBUG << "Cycle detected!";
128 }
129
130 if (mms.BaselineScore() < score) {
131 LDEBUG << "Score decrease"; // Usually recoverable
132 }
133 score = mms.BaselineScore();
134
135 //
136 // Try all mutations in iteration 0. In subsequent iterations, try
137 // mutations
138 // nearby those used in previous iteration.
139 //
140 E mutationEnumerator = MutationEnumerator<E, O>(mms.Template(), opts);
141 vector<Mutation> mutationsToTry;
142 if (iter == 0) {
143 mutationsToTry = mutationEnumerator.Mutations();
144 } else {
145 mutationsToTry = UniqueNearbyMutations(
146 mutationEnumerator, ProjectDown(favorableMutsAndScores), opts.MutationNeighborhood);
147 }
148
149 //
150 // Screen for favorable mutations. If none, we are done (converged).
151 //
152 favorableMutsAndScores.clear();
153 foreach (const Mutation& m, mutationsToTry) {
154 if (mms.FastIsFavorable(m)) {
155 float mutScore = mms.Score(m);
156 favorableMutsAndScores.push_back(m.WithScore(mutScore));
157 }
158 }
159 if (favorableMutsAndScores.empty()) {
160 isConverged = true;
161 break;
162 }
163
164 //
165 // Go with the "best" subset of well-separated high scoring mutations
166 //
167 vector<ScoredMutation> bestSubset =
168 BestSubset(favorableMutsAndScores, opts.MutationSeparation);
169
170 //
171 // Attempt to avoid cycling. We could do a better job here.
172 //
173 if (bestSubset.size() > 1) {
174 std::string nextTpl = ApplyMutations(ProjectDown(bestSubset), mms.Template());
175 if (tplHistory.find(hash(nextTpl)) != tplHistory.end()) {
176 LDEBUG << "Attempting to avoid cycle";
177 bestSubset =
178 std::vector<ScoredMutation>(bestSubset.begin(), bestSubset.begin() + 1);
179 }
180 }
181
182 LDEBUG << "Applying mutations:";
183 foreach (const ScoredMutation& smut, bestSubset) {
184 LDEBUG << "\t" << smut;
185 }
186
187 tplHistory.insert(hash(mms.Template()));
188 mms.ApplyMutations(ProjectDown(bestSubset));
189 }
190
191 return isConverged;
192 }
193 } // PRIVATE
194
195 bool RefineConsensus(AbstractMultiReadMutationScorer& mms, const RefineOptions& opts)
196 {
197 return AbstractRefineConsensus<UniqueSingleBaseMutationEnumerator>(mms, opts);
198 }
199
200 void RefineDinucleotideRepeats(AbstractMultiReadMutationScorer& mms,
201 int minDinucleotideRepeatElements)
202 {
203 RefineDinucleotideRepeatOptions opts(minDinucleotideRepeatElements);
204 AbstractRefineConsensus<DinucleotideRepeatMutationEnumerator>(mms, opts);
205 }
206
207 std::vector<int> ConsensusQVs(AbstractMultiReadMutationScorer& mms)
208 {
209 std::vector<int> QVs;
210 UniqueSingleBaseMutationEnumerator mutationEnumerator(mms.Template());
211 for (size_t pos = 0; pos < mms.Template().length(); pos++) {
212 double scoreSum = 0.0;
213 foreach (const Mutation& m, mutationEnumerator.Mutations(pos, pos + 1)) {
214 scoreSum += std::exp(static_cast<double>(mms.FastScore(m)));
215 }
216 QVs.push_back(ProbabilityToQV(1.0 - 1.0 / (1.0 + scoreSum)));
217 }
218 return QVs;
219 }
220
221 #if 0
222 Matrix<float> MutationScoresMatrix(mms)
223 {
224 NotYetImplemented();
225 }
226
227
228 Matrix<float> MutationScoresMatrix(mms, mutationsToScore)
229 {
230 NotYetImplemented();
231 }
232 #endif
233 }