-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProfileTrainer.hpp
9692 lines (8910 loc) · 543 KB
/
ProfileTrainer.hpp
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* \file ProfileTrainer.hpp
* \author D'Oleris Paul Thatcher Edlefsen [email protected]
* mods by Ted Holzman (2013)
*
* \par Library:
* galosh::profillic
* \brief
* Class definition for the Galosh Profile HMM parameter estimator class.
*
* \copyright © 2008, 2011, 2013 by Paul T. Edlefsen, Fred Hutchinson Cancer
* Research Center.
*
* \par License:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* \par History
* 9/13 TAH Modifications for boost::program_options to initialize
* parameters and centralize parameter/option manipulations
*****************************************************************************/
/*---------------------------------------------------------------------------##
## Library:
## galosh::profillic
## File:
## ProfileTrainer.hpp
## Author:
## D'Oleris Paul Thatcher Edlefsen [email protected]
## Description:
## Class definition for the Galosh Profile HMM parameter estimator class.
##
#*****************************************************************************/
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef __GALOSH_PROFILETRAINER_HPP__
#define __GALOSH_PROFILETRAINER_HPP__
#include "Profillic.hpp"
#include "Parameters.hpp"
using galosh::Parameters;
using galosh::DebugLevel;
using galosh::VerbosityLevel;
#include "DynamicProgramming.hpp"
using galosh::DynamicProgramming;
#include "ProlificParameters.hpp"
using galosh::ProlificParameters;
#include "Profile.hpp"
using galosh::ProfileTreeRoot;
#include "Sequence.hpp"
using galosh::Sequence;
#include "Random.hpp"
using galosh::Random;
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
//#include <cmath> // for isnan( double )
//using std::isnan; // doesn't work ! why?
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/version.hpp>
#include "boost/filesystem.hpp"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
#include "CommandlineParameters.hpp"
namespace galosh {
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType = typename profile_traits<ProfileType>::ResidueType,
//class InternalNodeType = ProfileTreeInternalNode<typename profile_traits<ProfileType>::ProbabilityType> >
class InternalNodeType = ProfileTreeRoot<typename profile_traits<ProfileType>::ResidueType, typename profile_traits<ProfileType>::ProbabilityType> >
class ProfileTrainer {
public:
typedef typename profile_traits<ProfileType>::ResidueType ResidueType;
typedef typename profile_traits<ProfileType>::ProbabilityType ProbabilityType;
typedef Sequence<SequenceResidueType> SequenceType;
class Parameters :
public ProlificParameters<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Parameters
{
private:
typedef typename ProlificParameters<ResidueType, ProbabilityType,ScoreType,MatrixValueType>::Parameters prolific_parameters_t;
// Boost serialization
friend class boost::serialization::access;
template<class Archive>
void serialize ( Archive & ar, const unsigned int /* file_version */ )
{
// save/load base class information
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( prolific_parameters_t );
/**
* ProfileTrainer Members to be serialized
* TAH 9/13
**/
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) ar & BOOST_SERIALIZATION_NVP( NAME )
#include "ProfileTrainerOptions.hpp" /// serialize ProfileTrainer parameters
} // serialize( Archive &, const unsigned int )
public:
/// PARAMETER definitions are now found in ProfileTrainerOptions.hpp
/// however pointer types cannot be initialized from the command line.
/// \todo They probably don't belong in "parameters". Maybe members
/// of surrounding class?
/**
* Define ProfileTrainer::Parameters "members". These are tightly tied to the options.
* TAH 9/13
**/
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) TYPE NAME
#include "ProfileTrainerOptions.hpp" /// declare Parameters members specific to ProfileTrainer
/* These are not "options" as they cannot be set from the command line */
/**
* It is possible to turn off training on a position-by-position basis.
* If this vector is non-null, it must be of the same length as the
* profile, and the truth value of the i^th position determines whether
* the i^th profile position should be trained (true means yes, train
* that position).
*/
myVector<bool> positionShouldBeTrained;
/**
* When usePriors is true, and when this is non-null, we use this for the
* Match-state emission prior. If this is null, a simple Laplace prior
* will be used.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::template DirichletMixtureMatchEmissionPrior<float> * matchEmissionPrior;
/**
* When usePriors is true, and when this is non-null, we use this for the
* priors for everything except the match-state emissions. If this is
* null, a simple Laplace prior will be used.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::template DirichletMixtureGlobalPrior<float> * globalPrior;
Parameters();
virtual ~Parameters () {};
// Copy constructor
template <class AnyParameters>
Parameters ( const AnyParameters & copy_from );
// Copy constructor/operator
template <class AnyParameters>
Parameters & operator= (
AnyParameters const& copy_from
);
template <class AnyParameters>
void
copyFromNonVirtual (
AnyParameters const & copy_from
);
template <class AnyParameters>
void
copyFromNonVirtualDontDelegate (
AnyParameters const & copy_from
);
virtual void
copyFrom ( const Parameters & copy_from );
virtual void
resetToDefaults ();
friend std::ostream&
operator<< (
std::ostream& os,
Parameters const& parameters
)
{
//TODO: REMOVE
//cout << "in ProfileTrainer::Parameters operator<<" << endl;
parameters.writeParameters( os );
return os;
} // friend operator<< ( basic_ostream &, Parameters const& )
void
writeParameters (
std::ostream& os
) const;
}; // End inner class Parameters
template <class ParametersType>
class ParametersModifierTemplate :
public ProlificParameters<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::template ParametersModifierTemplate<ParametersType>
{
typedef typename ProlificParameters<ResidueType, ProbabilityType,ScoreType,MatrixValueType>::template ParametersModifierTemplate<ParametersType> base_parameters_modifier_t;
private:
// Boost serialization
friend class boost::serialization::access;
template<class Archive>
void serialize ( Archive & ar, const unsigned int /* file_version */ )
{
// save/load base class information. This will serialize the
// parameters too.
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( base_parameters_modifier_t );
// Serialize the ProfileTrainer::ParameterModifierTemplate specific isModified_<member>s TAH 9/13
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) ar & BOOST_SERIALIZATION_NVP(isModified_##NAME)
#include "ProfileTrainerOptions.hpp" //archive ProfileTrainer::ParameterModifierTemplate isModified_<member>s
} // serialize( Archive &, const unsigned int )
public:
/// isModified flags for Parameters
/**
* Declare isModified_<member>s for isModified_<member>s of ProfileTrainer::ParameterModifierTemplate
* TAH 9/13
**/
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) bool isModified_##NAME
#include "ProfileTrainerOptions.hpp" // Declare isModified<member>s for ProfileTrainer::ParametersModifierTemplate
// Base constructor
ParametersModifierTemplate ();
// Copy constructor
template <class AnyParametersModifierTemplate>
ParametersModifierTemplate ( const AnyParametersModifierTemplate & copy_from );
// Copy constructor/operator
template <class AnyParametersModifierTemplate>
ParametersModifierTemplate & operator= (
AnyParametersModifierTemplate const& copy_from
);
template <class AnyParametersModifierTemplate>
void
copyFromNonVirtual (
AnyParametersModifierTemplate const & copy_from
);
template <class AnyParametersModifierTemplate>
void
isModified_copyFromNonVirtual (
AnyParametersModifierTemplate const & copy_from
);
void reset ();
void
isModified_reset ();
friend std::ostream&
operator<< (
std::ostream& os,
ParametersModifierTemplate const& parameters_modifier
)
{
parameters_modifier.writeParameters( os );
return os;
} // friend operator<< ( basic_ostream &, ParametersModifierTemplate const& )
void
writeParametersModifier (
std::ostream& os
);
template<class AnyParameters>
void
applyModifications ( AnyParameters & target_parameters );
}; // End inner class ParametersModifierTemplate
typedef ParametersModifierTemplate<typename ProfileTrainer::Parameters> ParametersModifier;
class Error {
public:
ProfileTrainer * m_trainer; // The enclosing state.
/**
* The different types of error that the ProfileTrainer::ProfileTrainer could be in.
* These should be consecutive from 0, and at the corresponding index in
* c_defaultDescription there should be some string entry (maybe "").
*/
enum type_t {
NoError = 0,
IncosistentStateError = 1
} m_type;
// TODO: Figure out how to get a static, constant array of strings
#define DEFAULT_DESCRIPTION_0 "There is no known problem with the ProfileTrainer instance."
#define DEFAULT_DESCRIPTION_1 "The ProfileTrainer instance appears to be in an incosistent state."
/**
* The (string) description of this error.
*/
string m_description;
Error (
ProfileTrainer * trainer,
type_t type = NoError,
string description = DEFAULT_DESCRIPTION_0 // TODO: Make this depend
// on type
) :
m_trainer( trainer ),
m_type( type ),
m_description( description )
{
// Do nothing else
} // <init>( trainer, [ type_t, [ string ] ] )
~Error () {
// Do nothing
} // <destroy>()
// TODO: Cast as int to the enum, and as str to the desc.
}; // End inner class Error
static int const trainingPhaseCount = 2;
typedef uint8_t TrainingPhase;
static int const TRAINING_PHASE_Positions = 0;
static int const TRAINING_PHASE_Globals = 1;
DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType> m_dynamic_programming;
Parameters m_parameters;
ProfileType * m_profile;
vector<SequenceType> const & m_sequences;
typedef Error error_t;
error_t m_error;
Parameters m_trainingParameters;
/**
* This profile is used to store globals to revert to during
* lengthadjust. It gets altered every time there is a reversion: the
* globals at that time are added into this, weighed by the iteration
* number.
*/
ProfileType m_globalsToRevertTo;
/**
* This is the starting score. It is not changed once it is set.
*/
ScoreType m_scoreBeforeTraining;
/**
* The score after the performing the current or most recent training
* step.
*/
ScoreType m_endingScore;
/**
* The score at the beginning of the current iteration.
*/
ScoreType m_startingScore_iteration;
/**
* The score at the beginning of the current position cycle.
*/
ScoreType m_startingScore_position_cycle;
/**
* The score at the beginning of the current position training step.
*/
ScoreType m_startingScore_position_step;
/**
* The score at the beginning of the current position training substep,
* when that substep is training the position-specific mixing parameters.
*/
ScoreType m_startingScore_position_step_mixingParameters;
/**
* The current position cycle (from 0)
*/
uint32_t m_position_cycle;
/**
* Sometimes we have to reject the conditional BW updates because the score
* would go down. In such cases we try again at various intermediate
* steps. We do this by adding some fraction of the updated position
* values to the original values. When this fraction is 1, for instance,
* the old and new values will be averaged. When the fraction is less than
* 1, it will be a weighted average. We try denomenators from
* minBaumWelchInverseScalar..maxBaumWelchInverseScalar by
* baumWelchInverseScalarIncrement. If minBaumWelchInverseScalar > 0, we
* don't even try the usual unscaled update. This is the current
* denomenator.
*/
float m_bw_inverse_scalar;
/**
* The current position of the profile (from the end, backwards)
*/
uint32_t m_row_i;
/**
* The index of the current sequence
*/
uint32_t m_seq_i;
/**
* The number of sequences to use in training (the index one greater than
* that of the last one to be used; must be <= m_sequences.size().
*/
// TODO: REMOVE CONST
const uint32_t m_sequence_count;
/**
* The percent change between m_startingScore_* and m_endingScore (as a
* percent of m_startingScore_*). Note that this could be negative (if
* the score decreases), and it could be a very large or a very small
* number. See also percentChange( a, b ).
*/
double m_scorePercentChange;
/**
* The current iteration, from 0..m_trainingParameters.maxIterations.
*/
uint32_t m_iteration;
/**
* Which set of parameters are we currently training?
*/
TrainingPhase m_trainingPhase;
/**
* The profile at the beginning of the current iteration.
*/
ProfileType m_startingProfile_iteration;
/**
* The profile at the beginning of the current position cycle.
*/
ProfileType m_startingProfile_position_cycle;
/**
* The forward rows, indexed first by row, then by sequence.
*/
// NOTE: No longer used.
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::SequentialAccessContainer m_forward_matrices;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_forward_rows_1;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_forward_rows_2;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_unconditional_last_forward_rows;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_unconditional_second_to_last_forward_rows;
/**
* A pointer to the forward_rows we're using ( for profile position
* m_row_i - 1 )
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_forward_rows_ptr;
/**
* A pointer to the forward_rows for the previous row...
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_prev_forward_rows_ptr;
/**
* Temp forward_rows ptr
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_temp_forward_rows_ptr;
/**
* The anchor columns, for forward_reverseCalculateRow(..).
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::SequentialAccessContainer m_anchor_columns;
/**
* The anchor rows, indexed first by row, then by sequence. This is the
* subset of the forward matrix that we store to account for numerical
* drift.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::SequentialAccessContainer m_anchor_rows;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_backward_rows_1;
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector m_backward_rows_2;
/**
* A pointer to the backward_rows we're using ( for profile position
* m_row_i - 1 )
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_backward_rows_ptr;
/**
* A pointer to the backward_rows for the following row...
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_next_backward_rows_ptr;
/**
* Temp backward_rows ptr
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Matrix::RowVector * m_temp_backward_rows_ptr;
/**
* The global_entente is the data structure that holds the intermediate
* values we need for Baum-Welch update of the global params.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::GlobalEntente m_global_entente;
/**
* This is the new way of storing entente information. It only stores the
* entente for one position (the current position), is only used for
* position-specific parameters (not globals), and is derived from a
* PositionSpecificParameters object. This is used in conjunction with the
* m_coefficients_vector object (it is the weighted sum of those
* coefficients).
*
* @see m_coefficients_vector
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::PositionEntente m_position_entente;
/**
* This object stores the position-specific and sequence-specific sequence
* score coefficients of the position-specific parameters. It is a vector
* of length (the number of sequences).
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::PositionSpecificSequenceScoreCoefficientsVector m_coefficients_vector;
/**
* When using unconditional Baum-Welch, we need to store up all of the
* position ententes and wait till the end to update the actual profile.
* Here is where we store the position ententes while we wait.
*
* Only used if parameters.useUnconditionalBaumWelch is true.
*/
vector<typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::PositionEntente> m_unconditional_position_ententes_vector;
#if defined( USE_DEL_IN_DEL_OUT ) && !defined( USE_SWENTRY_SWEXIT )
/**
* Many of the dp methods take the scaled match distributions as optional
* arguments. For efficiency we keep them up-to-date here and pass them into
* those methods. They are necessary because (only when USE_DEL_IN_DEL_OUT
* is defined) the Match distribution contains the M->W (DeletionOut open)
* probability, but actually the W->W extensions need to be incorporated, and they
* differ depending on the profile position (in particular, on its distance
* to the end of the profile).
*/
//vector<MultinomialDistribution<galosh::StateLabelTransitionTargets<galosh::MatchStateLabel, galosh::Plan7>::Type, ProbabilityType> > m_scaled_match_distributions;
// NOTE: I've changed this to MatrixValueType because with all of those DelOut Extensions, the values can get very very teensy tiny.
vector<MultinomialDistribution<galosh::StateLabelTransitionTargets<galosh::MatchStateLabel, galosh::Plan7>::Type, MatrixValueType> > m_scaled_match_distributions;
#endif // USE_DEL_IN_DEL_OUT && !USE_SWENTRY_SWEXIT
#ifdef ALLOW_BOLTZMANN_GIBBS
// TODO: REMOVE? FOR DEBUGGING BALDI STUFF.
static const bool m_baldi_be_verbose = false;//true;
/**
* When using unconditional Baum-Welch, we need to store up all of the
* position Baldi-style updates and wait till the end to update the actual
* profile. Here is where we store the position updates while we wait.
*
* Only used if parameters.useUnconditionalBaumWelch is true.
* Only used if parameters.baldiLearningRate > 0
*/
vector<PositionBoltzmannGibbs<ResidueType, ScoreType> > m_unconditional_baldi_position_boltzmann_gibbs_changes_vector;
/**
* When using Baldi-style gradient ascent, we do our changes in a
* Boltzmann-Gibbs transformed space. This is the current profile
* position, transformed.
*
* @see m_baldi_position_boltzmann_gibbs_change
* Only used if parameters.baldiLearningRate > 0
*/
PositionBoltzmannGibbs<ResidueType, ScoreType> m_baldi_position_boltzmann_gibbs;
/**
* When using Baldi-style gradient ascent, we do our changes in a
* Boltzmann-Gibbs transformed space. This is the change to the
* transformed current profile position that is induced by the Baldi update
* step.
*
* @see m_baldi_position_boltzmann_gibbs
* Only used if parameters.baldiLearningRate > 0
*/
//typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::PositionBoltzmannGibbsChange m_baldi_position_boltzmann_gibbs_change;
PositionBoltzmannGibbs<ResidueType, ScoreType> m_baldi_position_boltzmann_gibbs_change;
#endif // ALLOW_BOLTZMANN_GIBBS
/**
* When usePriors is true, this is the prior we use for the Match-state
* emissions.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::template DirichletMixtureMatchEmissionPrior<float> m_matchEmissionPrior;
/**
* When usePriors is true, this is the prior we use for everything except
* the Match-state emissions.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::template DirichletMixtureGlobalPrior<float> m_globalPrior;
/**
* This is used to save the profile position in case we want to revert
* after modifying it.
*/
ProfilePosition<ResidueType, ProbabilityType> m_backupProfilePosition;
/**
* This is used to save the entente position because when we do the wacky
* m_bw_inverse_scalar loop, we need to revert back to the original entente
* after scaling it.
*/
typename DynamicProgramming<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::PositionEntente m_backupEntentePosition;
/**
* This is used to save the global profile values in case we want to revert
* after modifying them.
*/
ProfileTreeRoot<ResidueType, ProbabilityType> m_backupProfileGlobals;
/**
* This is used to save the profile values in case we want to revert after
* modifying them, when we are using unconditional BW.
*
* Only used if parameters.useUnconditionalBaumWelch is true.
*/
ProfileTreeRoot<ResidueType, ProbabilityType> m_unconditional_backupProfile;
/**
* Default constructor. See reinitialize(..).
*/
ProfileTrainer ();
/**
* Construct a profile trainer with the given profile and sequences.
*/
ProfileTrainer (
ProfileType * profile,
vector<SequenceType> const & sequences
);
/**
* Construct a profile trainer with the same profile, sequences, and number
* of sequences to use as the given ProfileTrainer reference. Note that
* other members are not copied.
*/
ProfileTrainer (
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType> const & copy_from
);
/**
* Construct a profile trainer with the given profile and sequences, and
* the number of sequences to use (use the first num_sequences_to_use
* sequences only).
*/
ProfileTrainer (
ProfileType * profile,
vector<SequenceType> const & sequences,
uint32_t const & num_sequences_to_use // use only the first X sequences...
);
/**
* Reset everything to initial values, except for the profile, the
* sequences, and the number of sequences to use.
*/
void
reinitialize ();
/**
* (Re)set the profile and reinitialize.
*/
void
reinitialize (
ProfileType * profile
);
/**
* Store the given parameters, and starting profile, and set the trainer to
* its initial values.
*
* Note that (for now) the profile must be the same length as the original
* profile.
*/
void
restart (
const Parameters & parameters,
ProfileType * profile
);
ScoreType
train ();
// Updated to return the percent change of the log score (when we are using
// LogProbability-type scores).
double
percentChange ( ScoreType const & new_val, ScoreType const & old_val );
// TODO: move this down below with the other instantiations..
// Return the x value at which y is maximized, if ( x1, y1 ), ( x2, y2 ), and (
// x3, y3 ) are points on a parabola.
//
inline double
maximizeThreePointQuadratic (
double x1,
ScoreType y1,
double x2,
ScoreType y2,
double x3,
ScoreType y3
)
{
#ifndef NDEBUG
// They can't all be 0.
assert( !( ( x1 == 0 ) && ( x2 == 0 ) && ( x3 == 0 ) ) );
// Everything must be non-negative. The ys surely are (since they are ScoreTypes).
assert( ( x1 >= 0 ) && ( x2 >= 0 ) && ( x3 >= 0 ) );
// The middle value must be the highest.
assert( y2 >= y1 );
assert( y2 >= y3 );
// The x values must all be different and must be in order.
assert( x1 != x2 );
if( x1 < x2 ) {
assert( x2 < x3 );
} else { // x1 > x2
assert( x2 > x3 );
}
#endif // NDEBUG
if( ( x1 == x2 ) && ( x2 == x3 ) ) {
// They're all the same. This is silly.
return( x2 );
}
if( ( y1 == y2 ) && ( y2 == y3 ) ) {
// They're all the same. This is a plateau. Tha max is y1 == y2
// == y3, but since we're conservative we'll return the least x.
return // min( x1, x2, x3 ):
( ( x1 < x2 ) ? ( ( x1 < x3 ) ? x1 : x3 ) : ( ( x2 < x3 ) ? x2 : x3 ) );
}
// from http://www.chemeng.ed.ac.uk/people/jack/MSO/section5/maths/part3/handout1/index.html
ScoreType s21 = ( y2 - y1 );
bool s21_is_negative = false;
if( x2 > x1 ) {
s21 /= ( x2 - x1 );
} else if( x1 > x2 ) {
s21 /= ( x1 - x2 );
s21_is_negative = true;
} else {
// oookay, x1 == x2.
if( y3 > y2 ) {
return( x3 );
} else {
return( x2 );
}
}
ScoreType s32 = ( y2 - y3 );
bool s32_is_negative = true;
if( x3 > x2 ) {
s32 /= ( x3 - x2 );
} else if( x2 > x3 ) {
s32 /= ( x2 - x3 );
s32_is_negative = false;
} else {
// oookay, x3 == x2.
if( y1 > y2 ) {
return( x1 );
} else {
return( x2 );
}
}
assert( s21_is_negative != s32_is_negative );
const ScoreType s32_minus_s21 = ( s32 + s21 ); // adding because of the difference in signs
const int8_t s32_minus_s21_sign = ( s32_is_negative ? -1 : 1 );
const double s21_fraction_as_double = toDouble( s21 / s32_minus_s21 );
const int8_t sign_fix = ( s21_is_negative ? -1 : 1 ) * s32_minus_s21_sign;
const double return_value = ( ( ( x1 + x2 ) / 2 ) - ( ( ( x3 - x1 ) / 2 ) * sign_fix * s21_fraction_as_double ) );
#ifndef NDEBUG
if( x1 < x2 ) {
assert( return_value >= ( ( x1 + x2 ) / 2 ) );
assert( return_value <= ( ( x2 + x3 ) / 2 ) );
} else {
assert( return_value <= ( ( x1 + x2 ) / 2 ) );
assert( return_value >= ( ( x2 + x3 ) / 2 ) );
}
#endif // NDEBUG
return( return_value );
} // maximizeThreePointQuadratic(..)
}; // End class ProfileTrainer
//======//// potentially non-inline implementations ////========//
////// Class galosh::ProfileTrainer::Parameters ////
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
GALOSH_INLINE_INIT
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
Parameters (): matchEmissionPrior(NULL), globalPrior(NULL)
{
#ifdef DEBUG
cout << "[debug] ProfileTrainer::Parameters::<init>()" << endl;
cout << "[debug] using ProfileTrainerOptions.hpp" << endl;
#endif
/**
* Describe all options/parameters to the options_description object. In the main
* routine (whatever it may be) these descriptions will be parsed from the commandline
* and possibly other sources. This Parameters initializer calls it's parent to get
* the ProlificParameter::Parameters options.
**/
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) \
this->galosh::Parameters::m_galosh_options_description.add_options()(#NAME,po::value<TYPE>(&NAME)->default_value(DEFAULTVAL) TMP_EXTRA_STUFF,HELP)
#include "ProfileTrainerOptions.hpp" /// define all the commandline options for this module
} // galosh::ProfileTrainer::Parameters::<init>()
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
template <class AnyParameters>
GALOSH_INLINE_INIT
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
// Copy constructor
Parameters ( const AnyParameters & copy_from )
{
#ifdef DEBUG
cout << "[debug] ProfileTrainer::Parameters::<init>( copy_from )" << endl;
#endif
copyFromNonVirtual( copy_from );
} // <init>( AnyParameters const & )
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
template <class AnyParameters>
GALOSH_INLINE_COPY
typename ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters &
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
// Copy constructor/operator
operator= (
AnyParameters const& copy_from
)
{
#ifdef DEBUG
cout << "[debug] ProfileTrainer::Parameters::operator=( copy_from )" << endl;
#endif
copyFromNonVirtual( copy_from );
return *this;
} // operator=( AnyParameters const & )
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
template <class AnyParameters>
GALOSH_INLINE_COPY
void
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
copyFromNonVirtual (
AnyParameters const & copy_from
)
{ ///TAH 9/13 How much do we have to qualify copyFromNonVirtual?
ProlificParameters<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Parameters::copyFromNonVirtual( copy_from );
//if( copy_from.debug >= DEBUG_All ) {
// cout << "[debug] ProfileTrainer::Parameters::copyFromNonVirtual( copy_from )" << endl;
//} // End if DEBUG_All
copyFromNonVirtualDontDelegate( copy_from );
} // copyFromNonVirtual( AnyParameters const & )
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
template <class AnyParameters>
GALOSH_INLINE_COPY
void
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
copyFromNonVirtualDontDelegate (
AnyParameters const & copy_from
)
{
/// TAH 9/13
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) NAME = copy_from. NAME
#include "ProfileTrainerOptions.hpp" /// copy all ProfileTrainer::Parameters members
} // copyFromNonVirtualDontDelegate( AnyParameters const & )
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
GALOSH_INLINE_COPY
void
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
copyFrom ( const Parameters & copy_from )
{
copyFromNonVirtual( copy_from );
} // copyFrom( Parameters const & )
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
GALOSH_INLINE_REINITIALIZE
void
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
resetToDefaults ()
{ /// TAH 9/13 How far to qualify parent?
ProlificParameters<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Parameters::resetToDefaults();
#ifdef DEBUG
cout << "[debug] ProfileTrainer::Parameters::resetToDefaults()" << endl;
#endif
/// TAH 9/13
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) NAME = this->Parameters::m_galosh_options_map[#NAME].template as<TYPE>()
#include "ProfileTrainerOptions.hpp" /// reset all Parameters members
/// (ProfileTrainer and through inheritance tree)
matchEmissionPrior = NULL;
globalPrior = NULL;
} // resetToDefaults()
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
GALOSH_INLINE_OSTREAM
void
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::Parameters::
writeParameters (
std::ostream& os
) const
{ // TAH 9/13 How far to qualify?
//TODO: REMOVE
//cout << "in ProfileTrainer::writeParameters" << endl;
ProlificParameters<ResidueType, ProbabilityType, ScoreType, MatrixValueType>::Parameters::writeParameters( os );
os << endl;
//Note: we must comment out [ProfileTrainer] because it means something special to
//in configuration files sensu program_options
os << "#[ProfileTrainer]" << endl;
/**
* write out all ProfileTrainer specific parameters in the style of a configuration
* file, so that program_options parsers can read it back in
* TAH 9/13
**/
#undef GALOSH_DEF_OPT
#define GALOSH_DEF_OPT(NAME,TYPE,DEFAULTVAL,HELP) os << #NAME << " = " << lexical_cast<string>(NAME) << endl
#include "ProfileTrainerOptions.hpp" /// write all ProfileTrainer::Parameters members to os
} // writeParameters( ostream & ) const
////// Class galosh::ProfileTrainer::ParametersModifierTemplate ////
template <class ProfileType,
class ScoreType,
class MatrixValueType,
class SequenceResidueType,
class InternalNodeType>
template <class ParametersType>
GALOSH_INLINE_INIT
ProfileTrainer<ProfileType, ScoreType, MatrixValueType, SequenceResidueType, InternalNodeType>::ParametersModifierTemplate<ParametersType>::
// Base constructor
ParametersModifierTemplate ()
{