Debian Codegraph @

edu/mit/compbio/ChromHMM/ChromHMM.java

raw symbols SCIP
1 /**
2 * ChromHMM - automating chromatin state discovery and characterization
3 * Copyright (C) 2008-2012 Massachusetts Institute of Technology
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 **/
18 package edu.mit.compbio.ChromHMM;
19
20 import java.io.*;
21 import java.util.*;
22 import java.math.*;
23 import java.text.*;
24 import java.awt.*;
25 import java.awt.geom.*;
26 import java.awt.image.*;
27 import java.net.*;
28 import java.util.zip.*;
29 import org.tc33.jheatchart.HeatChart;
30
31
32 /**
33 * The main class of ChromHMM implements command line parsing and core algorithms
34 * The ChromHMM code was written by Jason Ernst
35 */
36 public class ChromHMM
37 {
38
39 /**
40 * True if should print out debug information
41 */
42 static boolean BVERBOSE = false;
43 static double EPSILONEMISSIONS = Math.pow(10,-300);
44
45 static double EPSILONSTATE = Math.pow(10,-300);
46
47 static String SZSEGMENTEXTENSION = "_segments.bed";
48 static String SZPOSTERIOREXTENSION = "_posterior.txt";
49 static String SZSTATEBYLINEEXTENSION = "_statebyline.txt";
50
51 /**
52 * The default number of base pairs in a bin
53 */
54 static int DEFAULT_BINSIZEBASEPAIRS = 200;
55
56 /**
57 * When splitting the default number of bins per file
58 */
59 static int DEFAULT_NUMSPLITBINS = 5000;
60
61 static int DEFAULT_OVERLAPENRICHMENT_NOFFSETLEFT = 0;
62 static int DEFAULT_OVERLAPENRICHMENT_NOFFSETRIGHT = 1;
63 static boolean DEFAULT_OVERLAPENRICHMENT_BCENTER = false;
64 static boolean DEFAULT_OVERLAPENRICHMENT_BCOUNTMULTI = false;
65 static boolean DEFAULT_OVERLAPENRICHMENT_BUSESIGNAL = false;
66 static boolean DEFAULT_OVERLAPENRICHMENT_BBASERES = true;
67 static boolean DEFAULT_OVERLAPENRICHMENT_BUNIFORMHEAT = false;
68
69 static int DEFAULT_NEIGHBORHOOD_NUMLEFT = 10;
70 static int DEFAULT_NEIGHBORHOOD_NUMRIGHT = 10;
71 static boolean DEFAULT_NEIGHBORHOOD_BUSESTRAND = true;
72 static boolean DEFAULT_NEIGHBORHOOD_BUSESIGNAL= false;
73 static int DEFAULT_NEIGHBORHOOD_NOFFSETANCHOR= 0;
74
75 static String ANCHORFILEDIR = "ANCHORFILES";
76 static String COORDDIR = "COORDS";
77 static String CHROMSIZESDIR = "CHROMSIZES";
78
79 static String SZNEIGHBORHOODEXTENSION = "_neighborhood";
80 static String SZOVERLAPEXTENSION = "_overlap";
81 static String SZBROWSERDENSEEXTENSION ="_dense";
82 static String SZBROWSEREXPANDEDEXTENSION ="_expanded";
83
84 /**
85 * This is a parameter just to improve efficiency of the model learn does not impact results
86 * in terms of when to try to exploit transition sparsity for improved effeciency
87 */
88 private static double SPARSECUTOFFRATIO = 0.7;
89
90 /**
91 * This is a parameter just to improve efficiency of the model learning does not impact results
92 * in terms of when to try to exploit transition sparsity for improved effeciency
93 */
94 private static double SPARSECUTOFFLOOSERRATIO = 0.8;
95
96 /**
97 * Default Red value for heatmaps on 0 to 255 scale
98 */
99 static int DEFAULTCOLOR_R = 0;
100
101 /**
102 * Default Green value for heatmaps on 0 to 255 scale
103 */
104 static int DEFAULTCOLOR_G = 0;
105
106 /**
107 * Default Blue value for heatmaps on 0 to 255 scale
108 */
109 static int DEFAULTCOLOR_B = 255;
110
111 static String[] ORDERSTRINGS = {"User","Emission","Transition","Fixed"};
112
113 static char[] ORDERCHARS = {'U','E','T','F'};
114
115 /**
116 * Constant for user supplied state ordering
117 */
118 static int STATEORDER_USER = 0;
119
120 /**
121 * Constant for state ordering being based on the emission paraemters
122 */
123 static int STATEORDER_EMISSION = 1;
124
125 /**
126 * Constant for state ordering being based on the transition parameters
127 */
128 static int STATEORDER_TRANSITION = 2;
129
130 /**
131 * Constant for state ordering being fixed
132 */
133 static int STATEORDER_FIXED = 3;
134
135
136 /**
137 * Constant for parameter initialization based on information measure
138 */
139 static int INITMETHOD_INFORMATION = 0;
140
141 /**
142 * Constant for parameter initialization being randomly selected
143 */
144 static int INITMETHOD_RANDOM = 1;
145
146 /**
147 * Constant for parameter initialization to be based on loading a model file
148 */
149 static int INITMETHOD_LOAD = 2;
150
151 /**
152 * The log likelihood of the model
153 */
154 double dloglike;
155
156 /**
157 * Parameter used in the information based smoothing to smooth away from 0
158 */
159 double dinformationsmooth;
160
161
162 /**
163 * The directory where the model should be output
164 */
165 String szoutputdir = "";
166
167 /**
168 * The directory with the binarized input that should be used
169 */
170 String szinputdir = "";
171
172 /**
173 * Initial probability of each state
174 */
175 double[] probinit;
176
177 /**
178 * transitionprobs[ni][nj] contains the probability of transitioning from state i to state j
179 */
180 double[][] transitionprobs;
181
182 /**
183 * transitionprobs[ni] has the number of transitions from state i that have not been eliminated
184 * because of low probability.
185 */
186 int[] transitionprobsnum;
187
188 /**
189 * transitionprobs[ni] from 0 to transitionprobsnum[ni]-1 has the indicies of the
190 * states from state ni which have a non-eliminated transition
191 */
192 int[][] transitionprobsindex;
193
194 /**
195 * True if the transition between states has been eliminated, false otherwise.
196 */
197 boolean[][] elim;
198
199 /**
200 * Terminates if the estimated likelihood change after a full iteration is less than the value
201 * If the value is negative this value is not used. The estimated likelihood is computed by adding
202 * the likelihood of each sequence from its most recent pass through the genome.
203 */
204 double dconvergediff;
205
206
207 /**
208 * HashSet with all the file prefixes
209 */
210 HashSet hsprefix;
211
212 /**
213 * The maximum number of training iterations
214 */
215 int nmaxiterations;
216
217 /**
218 * The number of non-eliminated states into state i
219 */
220 int[] transitionprobsnumCol;
221
222
223 /**
224 * trainsitionprobsindexCol[ni] from 0 to transitionprobsindexCol[ni]-1 has the indicies of the
225 * states which have a non-eliminated transition
226 */
227 int[][] transitionprobsindexCol;
228
229
230 /**
231 * For each state, each feature we have an emission probability for each bucket
232 */
233 double[][][] emissionprobs;
234
235 /**
236 * The number of buckets for the emission parameter.
237 * The assumed data is binary but this is kept as a parameter for flexibility
238 */
239 private int numbuckets = 2;
240
241 /**
242 * The number of hidden states in the model
243 */
244 int numstates;
245
246 /**
247 * traindingdataObservedIndex[ni][nj] indicates for the i^th sequence and j^th position
248 * the combination which was observed.
249 */
250 int[][] traindataObservedIndex;
251
252 /**
253 * trainingdataObservedValues[ni][nj] indicates if for the i^th combination of marks the value
254 * of the j^th mark
255 */
256 boolean[][] traindataObservedValues;
257
258 /**
259 * traindataNotMissing[ni][j] indicates if for the i^th combination of marks and missing values
260 * the j^th mark is not missing
261 */
262 boolean[][] traindataNotMissing;
263
264 /**
265 * traindataObservedSeqFlags[ni][nj] contains whether on the i^th sequence the j^th combination of
266 * marks were observed
267 */
268 boolean[][] traindataObservedSeqFlags;
269
270
271 /**
272 * The names of the data sets for which a joint model will be learned
273 */
274 String[] datasets;
275
276 /**
277 * The number of data sets that for which a joint model will be learned this is datasets.length
278 */
279 int numdatasets;
280
281
282 /**
283 * Stores the random number generator
284 */
285 Random theRandom;
286
287
288 /**
289 * Name of the file from which to base parameter initialization off of
290 * If null then randomly initialize parameters
291 */
292 String szInitFile;
293
294
295 /**
296 * Determines how much weight is given to uniform vs. is the pre-loaded setting used to smooth around 0
297 */
298 double dloadsmoothtransition;
299
300 /**
301 * Determines how much weight is given to uniform vs. is the pre-loaded setting used to smooth around 0
302 */
303 double dloadsmoothemission;
304
305
306 /**
307 * Stores the cell associated with each sequence
308 */
309 String[] cellSeq;
310
311 /**
312 * Stores the chromosome associated with each sequence
313 */
314 String[] chromSeq;
315
316 /**
317 * File containing a list of 1-based state mapping
318 */
319 String szstateorderingfile;
320
321 /**
322 * File containing the desired order of columns listed sequentially
323 */
324 String szcolumnorderingfile;
325
326
327 /**
328 * The set of chromosome sequence files from which to learn the model
329 */
330 String[] chromfiles;
331
332
333 /**
334 * Maps the internal state ordering to an actual ordering. This
335 * is reflect in the emission, transition, and model files.
336 */
337 int[] stateordering;
338
339 /**
340 * Maps the column ordering to the ordering used in viewing the emission table
341 * Note the columns are not reordered in the model file. They are the same as
342 * the inital input files
343 */
344 int[] colordering;
345
346 /**
347 * Stores the selected parameter initialization method
348 */
349 int ninitmethod;
350
351 /**
352 * Stores the selected state ordering method
353 */
354 int nstateorder;
355
356 /**
357 * If true reorders columns in the emission matrix
358 */
359 boolean bordercols;
360
361
362 /**
363 * If true reorders rows of emission matrix
364 */
365 boolean borderrows;
366
367
368 /**
369 * File with list of input files to learn
370 */
371 String szinputfilelist;
372
373 /**
374 * If true prints to files the posterior distributions
375 */
376 boolean bprintposterior;
377
378 /**
379 * If true prints a four column segmentation file
380 */
381 boolean bprintsegment;
382
383 /**
384 * If true prints the maximum state assignment one per line
385 */
386 boolean bprintstatebyline;
387
388
389 /**
390 * The number of base pairs in a bin
391 */
392 int nbinsize;
393
394 /**
395 * Transitions below 10^ntransitionpower will be eliminated for efficiency
396 */
397 int nzerotransitionpower;
398
399 /**
400 * Stores the Color to be used for the heatmap
401 */
402 Color theColor;
403
404
405 /**
406 * Character storing ordering method E-emission, T-transition, U-user
407 */
408 char chorder;
409
410 /**
411 * Descriptive string on the state ordering
412 */
413 String szorder;
414
415 /**
416 * An ID or name that will be included in some output files
417 */
418 String szoutfileID;
419
420 /**
421 * This parameter specifies the maximum number of seconds in learning and terminates
422 * after a full iteration in which this is exceeded
423 */
424 int nmaxseconds;
425
426 /**
427 * Contains the maximum coordinate for each chromosome
428 */
429 String szchromlengthfile;
430
431 /**
432 * The header line of a loaded model
433 */
434 private String szLoadHeader;
435
436 /**
437 * Stores a mapping from states to labels
438 */
439 HashMap hmlabelExtend;
440
441 ///////////////////////
442 //code for confusion matrix
443 /**
444 * True iff EvalSubset should read input from posterior files
445 */
446 boolean breadposterior;
447
448 /**
449 * True iff EvalSubset should read input from standard segment files
450 */
451 boolean breadsegment;
452
453 /**
454 * True iff EvalSubset should read input from segmentation file with one position per line
455 */
456 boolean breadstatebyline;
457
458 /**
459 * A bit string specifying for each mark whether each mark is included '1' or not included '0'
460 */
461 String szincludemarks;
462
463 /**
464 * True if the confusion matrix should be appended to the confusion output file
465 */
466 boolean bappend;
467
468 /**
469 * The directory containing the segmentations
470 */
471 String szsegmentdir;
472
473 /**
474 * The file to output confusion matrix
475 */
476 String szconfusionfileprefix;
477
478 /**
479 * Variable which determines whether to do incremental or normal EM
480 */
481 boolean bnormalEM;
482
483 /**
484 * Maximum number of threads to try launching also constrained by what is available
485 * If less than one then set to maximum available
486 */
487 int nmaxprocessors;
488
489 /**
490 * stores length of each chromosome
491 */
492 int[] numtime;
493
494 /**
495 * whether to use low memory
496 */
497 boolean blowmem;
498
499 /**
500 * number of sequences to include in sampling
501 */
502 int numincludeseq;
503
504
505 /**
506 * Whether to print emission and transition parameter image files in addition to text files
507 */
508 boolean bprintimage;
509
510
511 /**
512 * true if emission parameters should be rescaled
513 */
514 boolean bscaleemissions = false;
515
516 /**
517 * true if should add pseudo-counts when learning models
518 */
519 boolean bpseudo = false;
520
521 /**
522 * true if should skip the last input from pseudo
523 */
524 boolean bnopseudolast = false;
525
526
527 /**
528 * true if output should be zipped files
529 */
530 boolean bgzip = false;
531
532
533 /**
534 * True if the binarized files aren't true chromosomes and instead are split portions
535 */
536 boolean bsplit = false;
537
538
539 /**
540 * The max number of bins per file when splitting
541 */
542 int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
543
544 /**
545 * BED file input that is remapped in Reorder
546 */
547 String szreorderinbedfile;
548
549 /**
550 * BED file output that was remapped in Reorder
551 */
552 String szreorderoutbedfile;
553
554
555 /**
556 * Indicate the beta's should be rescaled separately and also enforces that no beta value goes below STATEEPSILON or alpha if emission is greater than 0
557 */
558 boolean bscalebeta;
559
560 /**
561 * True if should also reorder the columns of the model file
562 */
563 boolean breordercolsmodel;
564
565 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
566 /**
567 * Stores an integer index and array of boolean flags
568 */
569 static class ObservedRec
570 {
571 int nobserved;
572 boolean[] flagA;
573
574 ObservedRec(int nobserved, boolean[] flagA)
575 {
576 this.nobserved = nobserved;
577 this.flagA = flagA;
578 }
579 }
580
581
582 ///////////////////////////////////////////////////////////////////////////////////////////
583 /**
584 * Record stores an integer and random values, with reccompare can be used to
585 * randomly sort a set of indicies
586 */
587 static class RecIntDouble
588 {
589 int nindex;
590 double dval;
591
592 RecIntDouble(int nindex, double dval)
593 {
594 this.nindex = nindex;
595 this.dval = dval;
596 }
597 }
598
599 ///////////////////////////////////////////////////////////////////////////////////////////
600 /**
601 * Sorts the records based on the value of dval
602 */
603 public static class RecIntDoubleCompare implements Comparator, Serializable
604 {
605
606 public int compare(Object o1, Object o2)
607 {
608 RecIntDouble r1 = (RecIntDouble) o1;
609 RecIntDouble r2 = (RecIntDouble) o2;
610 if (r1.dval< r2.dval)
611 {
612 return -1;
613 }
614 else if (r1.dval > r2.dval)
615 {
616 return 1;
617 }
618 else
619 {
620 return 0;
621 }
622 }
623 }
624
625 ///////////////////////////////////////////////////////////////////////////////////////
626
627 /**
628 * Record stores an integer and random values, with reccompare can be used to
629 * randomly sort a set of indicies
630 */
631 static class RecIntString
632 {
633 int nindex;
634 String sz;
635
636 RecIntString(int nindex, String sz)
637 {
638 this.nindex = nindex;
639 this.sz = sz;
640 }
641 }
642
643 ///////////////////////////////////////////////////////////////////////////////////////////
644 /**
645 * Sorts the records based on the value of dval
646 */
647 public static class RecIntStringCompare implements Comparator, Serializable
648 {
649
650 public int compare(Object o1, Object o2)
651 {
652 RecIntString r1 = (RecIntString) o1;
653 RecIntString r2 = (RecIntString) o2;
654 return r1.sz.compareTo(r2.sz);
655 }
656 }
657
658
659 ///////////////////////////////////////////////////////////////////////////////////////
660
661 /**
662 * Record stores the overall index, cell, chromosome values, and index within the chromosome which with RecIntStringSplitCompare can be used to
663 * sort the files
664 */
665 static class RecIntStringSplit
666 {
667 int nindex; //overall index of file
668 String szcell;
669 String szchrom;
670 int nsplitbinindex; //index within chromosome
671
672 RecIntStringSplit(int nindex, String szcell, String szchrom, int nsplitbinindex)
673 {
674 this.nindex = nindex;
675 this.szcell = szcell;
676 this.szchrom = szchrom;
677 this.nsplitbinindex = nsplitbinindex;
678 }
679 }
680
681
682 ///////////////////////////////////////////////////////////////////////////////////////////
683 /**
684 * Sorts the records based on the value of szcell, then szchrom, then nsplitbinindex
685 */
686 public static class RecIntStringSplitCompare implements Comparator, Serializable
687 {
688
689 public int compare(Object o1, Object o2)
690 {
691 //need to sort on chromosome name not file name
692 RecIntStringSplit r1 = (RecIntStringSplit) o1;
693 RecIntStringSplit r2 = (RecIntStringSplit) o2;
694
695 if (r1.szcell.equals(r2.szcell))
696 {
697 if (r1.szchrom.equals(r2.szchrom))
698 {
699 if (r1.nsplitbinindex < r2.nsplitbinindex)
700 {
701 return -1;
702 }
703 else if (r1.nsplitbinindex > r2.nsplitbinindex)
704 {
705 return 1;
706 }
707 else
708 {
709 return 0;
710 }
711 }
712 else
713 {
714 return (r1.szchrom+"_").compareTo(r2.szchrom+"_");
715 }
716 }
717 else
718 {
719 return (r1.szcell+"_").compareTo(r2.szcell+"_");
720 }
721 }
722 }
723
724
725
726
727 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
728
729 /**
730 * Constructor initializes the variable and loads the data used for learning the model
731 */
732 public ChromHMM(String szinputdir, String szoutputdir, String szinputfilelist,String szchromlengthfile, int numstates,int nseed, int ninitmethod,
733 String szInitFile, double dloadsmoothemission,double dloadsmoothtransition,double dinformationsmooth,
734 int nmaxiterations,double dcovergediff,int nmaxseconds,boolean bprintposterior,
735 boolean bprintsegment,boolean bprintstatebyline, int nbinsize,String szoutfileID,int nstateorder,boolean bordercols,int nzerotransitionpower,
736 Color theColor, boolean bnormalEM, int nmaxprocessors, boolean blowmem,
737 int numincludeseq, boolean bprintimage, boolean bscaleemissions,
738 boolean bpseudo, boolean bnopseudolast, boolean bgzip,boolean bsplit, boolean borderrows, boolean bscalebeta) throws IOException
739 {
740 this.szinputdir = szinputdir;
741 this.szoutputdir = szoutputdir;
742 this.szinputfilelist = szinputfilelist;
743 this.szchromlengthfile = szchromlengthfile;
744 this.numstates = numstates;
745 this.ninitmethod = ninitmethod;
746 this.szInitFile = szInitFile;
747 this.dloadsmoothemission = dloadsmoothemission;
748 this.dloadsmoothtransition = dloadsmoothtransition;
749 this.dinformationsmooth = dinformationsmooth;
750 this.nmaxiterations = nmaxiterations;
751 this.nmaxseconds = nmaxseconds;
752 this.dconvergediff = dcovergediff;
753 this.bprintposterior = bprintposterior;
754 this.bprintsegment = bprintsegment;
755 this.bprintstatebyline = bprintstatebyline;
756 this.nbinsize = nbinsize;
757 this.szoutfileID = szoutfileID;
758 this.nstateorder = nstateorder;
759 this.chorder = ChromHMM.ORDERCHARS[nstateorder];
760 this.szorder = ChromHMM.ORDERSTRINGS[nstateorder];
761 this.bordercols = bordercols;
762 this.borderrows = borderrows;
763 this.nzerotransitionpower = nzerotransitionpower;
764 this.theColor = theColor;
765 this.bnormalEM = bnormalEM;
766 this.nmaxprocessors = nmaxprocessors;
767 this.numincludeseq = numincludeseq;
768 this.blowmem = blowmem;
769 this.bprintimage = bprintimage;
770 this.bscaleemissions = bscaleemissions;
771 this.bpseudo = bpseudo;
772 this.bnopseudolast = bnopseudolast;
773 this.bgzip = bgzip;
774 this.bscalebeta = bscalebeta;
775 //this.numsplitbins = numsplitbins;
776 this.bsplit = bsplit;
777
778 hmlabelExtend = new HashMap();
779 theRandom = new Random(nseed);
780
781 if (blowmem)
782 {
783 loadDataFileStubs();
784 }
785 else
786 {
787 loadData();
788 }
789 //loadData();
790 //loadDataFileStubs();
791
792 stateordering = new int[numstates];
793 colordering = new int[numdatasets];
794 for (int ni = 0; ni < stateordering.length; ni++)
795 {
796 stateordering[ni] = ni;
797 }
798
799 for (int ni = 0; ni < colordering.length; ni++)
800 {
801 colordering[ni] = ni;
802 }
803 }
804
805 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
806
807 /////////////////////////////////////////////////////////////////
808 /**
809 * Loads contents of szlabelmapping into a HashMap
810 */
811 private void makeLabelMapping(String szlabelmapping) throws IOException
812 {
813 if (szlabelmapping != null)
814 {
815 BufferedReader bridlabel = Util.getBufferedReader(szlabelmapping);
816 String szLine;
817
818 //Loading in a mapping from state ID to a label description
819
820 while ((szLine = bridlabel.readLine())!=null)
821 {
822 StringTokenizer st = new StringTokenizer(szLine,"\t");
823 String szID = st.nextToken().trim();
824 String szLabelExtend = st.nextToken().trim();
825 hmlabelExtend.put(szID,szLabelExtend);
826 }
827 bridlabel.close();
828 }
829 }
830
831 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
832 /**
833 * Constructor for API use of ChromHMM that starts with a model loaded from a file
834 */
835 public ChromHMM(String szInitFile) throws IOException
836 {
837
838 this.szInitFile = szInitFile;
839 loadModel();
840 }
841
842 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
843 /**
844 * Constructor involved in reordering the data
845 */
846 public ChromHMM(String szInitFile, String szoutputdir, String szstateorderingfile, String szcolumnorderingfile,
847 String szoutfileID,int nstateorder,boolean bordercols,Color theColor,
848 String szlabelmapping, boolean bprintimage,String szreorderinbedfile, String szreorderoutbedfile,
849 boolean breordercolsmodel) throws IOException
850 {
851 this.szcolumnorderingfile = szcolumnorderingfile;
852 this.szInitFile = szInitFile;
853 this.szoutputdir = szoutputdir;
854 this.szstateorderingfile = szstateorderingfile;
855 this.szoutfileID = szoutfileID;
856 this.bprintimage = bprintimage;
857
858 this.bordercols = bordercols;
859 this.theColor = theColor;
860
861 this.szreorderinbedfile = szreorderinbedfile;
862 this.szreorderoutbedfile = szreorderoutbedfile;
863 this.breordercolsmodel = breordercolsmodel;
864 hmlabelExtend = new HashMap();
865 makeLabelMapping(szlabelmapping);
866
867 loadModel();
868
869 //moved after loadModel in v1.12 since was getting overwritten if having user defined ordering
870 if (nstateorder != ChromHMM.STATEORDER_FIXED)
871 {
872 this.nstateorder = nstateorder;
873 }
874
875 this.chorder = ChromHMM.ORDERCHARS[this.nstateorder];
876 this.szorder = ChromHMM.ORDERSTRINGS[this.nstateorder];
877
878 stateordering = new int[numstates];
879 colordering = new int[numdatasets];
880 for (int ni = 0; ni < stateordering.length; ni++)
881 {
882 stateordering[ni] = ni;
883 }
884
885 for (int ni = 0; ni < colordering.length; ni++)
886 {
887 colordering[ni] = ni;
888 }
889 }
890
891 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
892 /**
893 * Constructor initializes the variable and loads the data used for making segmentation from a model
894 */
895 public ChromHMM(String szinputdir, String szinputfilelist, String szchromlengthfile, String szoutputdir, String szInitFile, String szoutfileID,
896 int nbinsize, boolean bprintposterior, boolean bprintsegment,boolean bprintstatebyline,
897 boolean blowmem, boolean bscaleemissions, boolean bgzip, boolean bsplit, boolean bscalebeta) throws IOException
898 {
899 this.szinputdir = szinputdir;
900 this.szinputfilelist = szinputfilelist;
901 this.szchromlengthfile = szchromlengthfile;
902 this.bprintposterior = bprintposterior;
903 this.bprintsegment = bprintsegment;
904 this.bprintstatebyline = bprintstatebyline;
905 this.szoutfileID = szoutfileID;
906 this.szoutputdir = szoutputdir;
907 this.szInitFile = szInitFile;
908 this.nbinsize = nbinsize;
909 this.blowmem = blowmem;
910 this.bscaleemissions = bscaleemissions;
911 this.bgzip = bgzip;
912 this.bsplit = bsplit;
913 this.bscalebeta = bscalebeta;
914
915 hmlabelExtend = new HashMap();
916
917 if (blowmem)
918 {
919 loadDataFileStubs();
920 }
921 else
922 {
923 loadData();
924 }
925
926 loadModel();
927
928 stateordering = new int[numstates];
929 colordering = new int[numdatasets];
930 for (int ni = 0; ni < stateordering.length; ni++)
931 {
932 stateordering[ni] = ni;
933 }
934
935 for (int ni = 0; ni < colordering.length; ni++)
936 {
937 colordering[ni] = ni;
938 }
939 }
940
941 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
942 /**
943 * Constructor used for computing confusion results using a subset of marks for the EvalSubset command
944 */
945 public ChromHMM(String szinputdir, String szsegmentdir, String szinputfilelist, String szconfusionfileprefix,
946 String szInitFile, String szoutfileID,
947 int nbinsize, boolean breadposterior, boolean breadsegment,boolean breadstatebyline,
948 String szincludemarks, boolean bappend, Color theColor, boolean bprintimage,
949 boolean blowmem, boolean bscaleemissions, boolean bscalebeta) throws IOException
950 {
951 this.bappend = bappend;
952 this.szinputdir = szinputdir;
953 this.szsegmentdir = szsegmentdir;
954 this.szinputfilelist = szinputfilelist;
955 //this.szchromlengthfile = szchromlengthfile; //removed since not doing anything
956 this.breadposterior = breadposterior;
957 this.breadsegment = breadsegment;
958 this.breadstatebyline = breadstatebyline;
959 this.szoutfileID = szoutfileID;
960 this.szconfusionfileprefix = szconfusionfileprefix;
961 this.szInitFile = szInitFile;
962 this.nbinsize = nbinsize;
963 this.szincludemarks = szincludemarks;
964 this.theColor = theColor;
965 this.bprintimage = bprintimage;
966 this.blowmem = blowmem;
967 this.bscaleemissions = bscaleemissions;
968 this.bscalebeta = bscalebeta;
969 hmlabelExtend = new HashMap();
970
971 if (blowmem)
972 {
973 loadDataFileStubs();
974 }
975 else
976 {
977 loadData();
978 }
979 //loadData();
980 loadModel();
981
982 stateordering = new int[numstates];
983 colordering = new int[numdatasets];
984 for (int ni = 0; ni < stateordering.length; ni++)
985 {
986 stateordering[ni] = ni;
987 }
988
989 for (int ni = 0; ni < colordering.length; ni++)
990 {
991 colordering[ni] = ni;
992 }
993 }
994
995
996 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
997
998 /**
999 * Converts order abbreviation character to string
1000 */
1001 static String convertCharOrderToStringOrder(char ch)
1002 {
1003 for (int ni = 1; ni < ChromHMM.ORDERCHARS.length; ni++)
1004 {
1005 if (ChromHMM.ORDERCHARS[ni] == ch)
1006 {
1007 return ChromHMM.ORDERSTRINGS[ni];
1008 }
1009 }
1010 return ChromHMM.ORDERSTRINGS[0];
1011 }
1012
1013
1014
1015 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
1016
1017 /**
1018 * Initializes the parameters based on the method determined by ninitmethod
1019 * then calls trainParameters
1020 */
1021 public void buildModel() throws IOException
1022 {
1023 if (ninitmethod ==ChromHMM.INITMETHOD_LOAD)
1024 {
1025 //loads parameters of the initial model
1026 loadModelSmooth(dloadsmoothemission,dloadsmoothtransition);
1027 }
1028 else if (ninitmethod == ChromHMM.INITMETHOD_INFORMATION)
1029 {
1030 if (blowmem)
1031 {
1032 informationInitializeNestedWithLoad();
1033 }
1034 else
1035 {
1036 informationInitializeNested();
1037 }
1038 }
1039 else if (ninitmethod == ChromHMM.INITMETHOD_RANDOM)
1040 {
1041 randomlyInitializeParams();
1042 }
1043
1044 //trains the model
1045 //trainParameters();
1046 //trainParametersNormalEM();
1047 if (bnormalEM)
1048 {
1049 if (blowmem)
1050 {
1051 trainParametersParallelWithLoad();
1052 }
1053 else
1054 {
1055 trainParametersParallel();
1056 }
1057 }
1058 else
1059 {
1060 if (blowmem)
1061 {
1062 trainParametersWithLoad();
1063 }
1064 else
1065 {
1066 trainParameters();
1067 }
1068 }
1069 }
1070
1071 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1072 private void reorderModel() throws IOException
1073 {
1074 if (szstateorderingfile !=null)
1075 {
1076 int[] stateorderingOLDtoNEW = new int[stateordering.length];
1077 BufferedReader brstate = Util.getBufferedReader(szstateorderingfile);
1078 String szLine;
1079 while ((szLine = brstate.readLine())!=null)
1080 {
1081 StringTokenizer st = new StringTokenizer(szLine,"\t ");
1082 int nold = Integer.parseInt(st.nextToken())-1;
1083 int nnew = Integer.parseInt(st.nextToken())-1;
1084 stateordering[nnew] = nold;
1085 stateorderingOLDtoNEW[nold] = nnew;
1086 }
1087 brstate.close();
1088
1089 if (szreorderinbedfile != null)
1090 {
1091 reorderBEDfile(stateorderingOLDtoNEW);
1092 }
1093 }
1094 else
1095 {
1096 makeStateOrdering();
1097 }
1098
1099
1100 if (szcolumnorderingfile !=null)
1101 {
1102 int ncol = 0;
1103 BufferedReader brcol = Util.getBufferedReader(szcolumnorderingfile);
1104 String szLine;
1105 HashMap hm = new HashMap();
1106 while ((szLine = brcol.readLine())!=null)
1107 {
1108 hm.put(szLine,Integer.valueOf(ncol));
1109 ncol++;
1110 }
1111 brcol.close();
1112
1113 for (int ni = 0; ni < datasets.length; ni++)
1114 {
1115 Integer obj = ((Integer) hm.get(datasets[ni]));
1116 if (obj == null)
1117 {
1118 throw new IllegalArgumentException(datasets[ni]+" not found!");
1119 }
1120 else
1121 {
1122 colordering[obj.intValue()] = ni;
1123 }
1124 }
1125 }
1126 else if (bordercols)
1127 {
1128 makeColOrdering();
1129 }
1130 //updates after each iteration the current status of the search
1131 printTransitionTable(-1);
1132 printEmissionTable(-1);
1133
1134 if (bprintimage)
1135 {
1136 printEmissionImage(-1);
1137 printTransitionImage(-1);
1138 }
1139 printParametersToFile(-1);
1140 }
1141
1142
1143 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1144 private void reorderBEDfile(int[] stateorderingOLDtoNEW) throws IOException
1145 {
1146 BufferedReader brin = Util.getBufferedReader(szreorderinbedfile);
1147 System.out.println("Writing to file "+szreorderoutbedfile);
1148 if (szreorderoutbedfile.toLowerCase(Locale.ENGLISH).endsWith(".gz"))
1149 {
1150 GZIPOutputStream pwzip = new GZIPOutputStream(new FileOutputStream(szreorderoutbedfile));
1151 //output zipfile
1152 String szLine;
1153 while ((szLine = brin.readLine())!=null)
1154 {
1155 StringTokenizer st = new StringTokenizer(szLine, "\t");
1156 if (st.countTokens() < 4)
1157 {
1158 //not full line just directly outputting except updating header info
1159 szLine = szLine.replaceAll("Emission ordered","User ordered");
1160 szLine = szLine.replaceAll("Transition ordered","User ordered");
1161 byte[] btformat = szLine.getBytes();
1162 pwzip.write(btformat,0,btformat.length);
1163 continue;
1164 }
1165 StringBuffer sb = new StringBuffer(st.nextToken().trim()+"\t"+st.nextToken().trim()+"\t"+st.nextToken().trim());
1166 String szinstate = st.nextToken().trim();
1167 String szoutstate;
1168
1169 if (!Character.isDigit(szinstate.charAt(0)))
1170 {
1171 szoutstate = (""+chorder) + (stateorderingOLDtoNEW[Integer.parseInt(szinstate.substring(1))-1]+1);
1172 }
1173 else
1174 {
1175 szoutstate = ""+(stateorderingOLDtoNEW[Integer.parseInt(szinstate)-1]+1);
1176 }
1177 sb.append("\t"+szoutstate);
1178
1179 while (st.hasMoreTokens())
1180 {
1181 sb.append("\t"+st.nextToken().trim());
1182 }
1183 sb.append("\n");
1184
1185 byte[] btformat = sb.toString().getBytes();
1186 pwzip.write(btformat,0,btformat.length);
1187 }
1188 pwzip.finish();
1189 pwzip.close();
1190 brin.close();
1191 }
1192 else
1193 {
1194 PrintWriter pw = new PrintWriter(new FileWriter(szreorderoutbedfile));
1195 //output zipfile
1196 String szLine;
1197 while ((szLine = brin.readLine())!=null)
1198 {
1199 StringTokenizer st = new StringTokenizer(szLine, "\t");
1200 if (st.countTokens() < 4)
1201 {
1202 //not full line just directly outputting except updating header info
1203 szLine = szLine.replaceAll("Emission ordered","User ordered");
1204 szLine = szLine.replaceAll("Transition ordered","User ordered");
1205 pw.println(szLine);
1206 continue;
1207 }
1208 pw.print(st.nextToken().trim()+"\t"+st.nextToken().trim()+"\t"+st.nextToken().trim());
1209 String szinstate = st.nextToken().trim();
1210 String szoutstate;
1211 if (!Character.isDigit(szinstate.charAt(0)))
1212 {
1213 szoutstate = (""+chorder) + (stateorderingOLDtoNEW[Integer.parseInt(szinstate.substring(1))-1]+1);
1214 }
1215 else
1216 {
1217 szoutstate = ""+ (stateorderingOLDtoNEW[Integer.parseInt(szinstate)-1]+1);
1218 }
1219 pw.print("\t"+szoutstate);
1220
1221 while (st.hasMoreTokens())
1222 {
1223 pw.print("\t"+st.nextToken().trim());
1224 }
1225 pw.println();
1226 }
1227 brin.close();
1228 pw.close();
1229 }
1230 }
1231
1232 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
1233 /**
1234 * If nstateorder is ChromHMM.STATEORDER_EMISSION orders emission parameters based on emission parameters and stores in stateordering
1235 * If nstateorder is ChromHMM.STATEORDER_TRANSITION orders emission parameters based on transition parameters and stores in stateordering
1236 */
1237 private void makeStateOrdering()
1238 {
1239 if (nstateorder == ChromHMM.STATEORDER_EMISSION)
1240 {
1241 double[][] emissionprobspos = new double[numstates][numdatasets];
1242 //just gets out the emissionprobability in index 1 of the third index
1243 for (int ni = 0; ni < numstates; ni++)
1244 {
1245 double[] emissionprobspos_ni = emissionprobspos[ni];
1246 double[][] emissionprobs_ni = emissionprobs[ni];
1247 for (int nj = 0; nj < numdatasets; nj++)
1248 {
1249 emissionprobspos_ni[nj] = emissionprobs_ni[nj][1];
1250 }
1251 }
1252
1253 makeOrderingCorrelation(emissionprobspos, stateordering);
1254 }
1255 else if (nstateorder == ChromHMM.STATEORDER_TRANSITION)
1256 {
1257 makeOrderingTransition(stateordering);
1258 }
1259 }
1260
1261 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1262 /**
1263 * Stores in colordering an ordering of the columns of the emission parameter matrix based on parameter correlaton
1264 */
1265 public void makeColOrdering()
1266 {
1267
1268 double[][] emissionprobspostranspose = new double[numdatasets][numstates];
1269 for (int ni = 0; ni < numdatasets; ni++)
1270 {
1271 double[] emissionprobspostranspose_ni = emissionprobspostranspose[ni];
1272 for (int nj = 0; nj < numstates; nj++)
1273 {
1274 emissionprobspostranspose_ni[nj] = emissionprobs[nj][ni][1];
1275 }
1276 }
1277 makeOrderingCorrelation(emissionprobspostranspose,colordering);
1278 }
1279
1280 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
1281 /**
1282 * Returns an ordering of states using an approximation algorithm to minimize the total distance between neighboring states
1283 * where distance between neighboring states (i,j) is defined as 2- (t_i,j +t_j,i)
1284 * The ordering is the best greedy ordering considering each state as the initial state
1285 */
1286 private void makeOrderingTransition(int[] ordering)
1287 {
1288 boolean[] assignedrow = new boolean[ordering.length];
1289 int[] temproworder = new int[ordering.length];
1290 double dmintotsum = Double.MAX_VALUE;
1291
1292 for (int ninitrow = 0; ninitrow < ordering.length; ninitrow++)
1293 {
1294 //tries ordering starting from each possible initial location
1295 temproworder[0] = ninitrow;
1296
1297 for (int ni = 0; ni < assignedrow.length; ni++)
1298 {
1299 assignedrow[ni] = false;
1300 }
1301
1302 assignedrow[ninitrow] = true;
1303
1304 double dtotsum = 0;
1305 int nminrow;
1306 int nprevminrow=ninitrow;
1307
1308 for (int ncurrow = 1; ncurrow < ordering.length; ncurrow++)
1309 {
1310 //finding the next state for the ordering
1311 double dmindist = Double.MAX_VALUE;
1312 nminrow = 0;
1313 //considering all not already assigned states
1314 for (int nrow = 0; nrow < ordering.length; nrow++)
1315 {
1316 if (!assignedrow[nrow])
1317 {
1318 double ddist = 2-(transitionprobs[nrow][nprevminrow]+transitionprobs[nprevminrow][nrow]);
1319 //checks if distance is less than minimum distance found so far, if so uses it
1320 if (ddist < dmindist)
1321 {
1322 dmindist= ddist;
1323 nminrow = nrow;
1324 }
1325 }
1326 }
1327
1328 dtotsum += dmindist; //increment total sum
1329 temproworder[ncurrow] = nminrow;
1330 assignedrow[nminrow] = true;
1331 nprevminrow = nminrow; //this is now the best previous row
1332 }
1333
1334 if (dtotsum < dmintotsum)
1335 {
1336 //best one found so far updating totalsum and storing roworder
1337 dmintotsum = dtotsum;
1338 for (int ni = 0; ni < ordering.length; ni++)
1339 {
1340 ordering[ni] = temproworder[ni];
1341 }
1342 }
1343 }
1344 }
1345
1346 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1347 /**
1348 * Returns an ordering of states using an approximation algorithm to minimize the total distance between neighboring states
1349 * where distance between neighboring states (i,j) is defined as the sqrt of 1-minus the correlation coefficient
1350 * The ordering is the best greedy ordering considering each state as the initial state
1351 */
1352 private void makeOrderingCorrelation(double[][] data, int[] ordering)
1353 {
1354 boolean[] assignedrow = new boolean[ordering.length];
1355 int[] temproworder = new int[ordering.length];
1356 double dmintotsum = Double.MAX_VALUE;
1357
1358 double[][] correlationdistance = new double[ordering.length][ordering.length];
1359 for (int ni = 0; ni < ordering.length; ni++)
1360 {
1361 for (int nj = 0; nj < ordering.length; nj++)
1362 {
1363 correlationdistance[ni][nj] = Math.sqrt(1-Util.correlation(data[ni],data[nj]));
1364 }
1365 }
1366
1367 for (int ninitrow = 0; ninitrow < ordering.length; ninitrow++)
1368 {
1369 temproworder[0] = ninitrow;
1370
1371 for (int ni = 0; ni < assignedrow.length; ni++)
1372 {
1373 assignedrow[ni] = false;
1374 }
1375 assignedrow[ninitrow] = true;
1376
1377 double dtotsum = 0;
1378 int nminrow;
1379 int nprevminrow = ninitrow;
1380
1381 for (int ncurrow = 1; ncurrow < ordering.length; ncurrow++)
1382 {
1383 //finding the next state for the ordering
1384 double dmindist = Double.MAX_VALUE;
1385 nminrow = 0;
1386 //considering all not already assigned states
1387 for (int nrow = 0; nrow < ordering.length; nrow++)
1388 {
1389 if (!assignedrow[nrow])
1390 {
1391 double ddist = correlationdistance[nrow][nprevminrow];
1392 //checks if distance is less than minimum distance found so far, if so uses it
1393 if (ddist < dmindist)
1394 {
1395 dmindist= ddist;
1396 nminrow = nrow;
1397 }
1398 }
1399 }
1400
1401 dtotsum += dmindist; //increment total sum
1402 temproworder[ncurrow] = nminrow;
1403 assignedrow[nminrow] = true;
1404 nprevminrow = nminrow; //this is now the best previous row
1405 }
1406 if (dtotsum < dmintotsum)
1407 {
1408 //best one found so far updating totalsum and storing roworder
1409 dmintotsum = dtotsum;
1410 for (int ni = 0; ni < ordering.length; ni++)
1411 {
1412 ordering[ni] = temproworder[ni];
1413 }
1414 }
1415 }
1416 }
1417
1418 ///////////////////////////////////////////////////////////////////////////////////////////
1419 /**
1420 * Outputs the transition parameters as a '.png' and 'svg' heatmap in the szoutputdir directory
1421 * the file name startswith 'transitions_numstates' and if szoutfileID is non-empty that is
1422 * included as well.
1423 */
1424 public void printTransitionImage(int niteration) throws IOException
1425 {
1426 //stores in sorteddata the contents of transitionprobs with the states
1427 //reordered based on stateordering
1428 double[][] sorteddata = new double[numstates][numstates];
1429 String[] statelabels = new String[numstates];
1430
1431 for (int ni = 0; ni < numstates; ni++)
1432 {
1433 double[] sorteddata_ni = sorteddata[ni];
1434 double[] transitionprobs_stateordering_ni = transitionprobs[stateordering[ni]];
1435 for (int nj =0; nj < numstates; nj++)
1436 {
1437 sorteddata_ni[nj] = transitionprobs_stateordering_ni[stateordering[nj]];
1438 }
1439 }
1440
1441 for (int ni = 0; ni < numstates; ni++)
1442 {
1443 statelabels[ni] = ""+(ni+1);
1444 String szsuffix;
1445 //changing in v1.12 to be state labels for new state to match char ordering
1446 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
1447 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
1448 {
1449 statelabels[ni]+= "_"+szsuffix;
1450 }
1451 }
1452
1453 HeatChart map = new HeatChart(sorteddata);
1454
1455 map.setTitle("Transition Parameters");
1456 map.setXAxisLabel("State To ("+szorder+" order)");
1457 map.setYAxisLabel("State From ("+szorder+" order)");
1458 map.setAxisValuesFont(new Font("SansSerif",0,20));
1459 map.setAxisLabelsFont(new Font("SansSerif",0,22));
1460 map.setTitleFont(new Font("SansSerif",0,24));
1461 if (sorteddata.length <=5)
1462 {
1463 map.setChartMargin(125);
1464 }
1465 else
1466 {
1467 map.setChartMargin(50);
1468 }
1469 map.setXValues(statelabels); //sets the state labels to be the state IDs
1470 map.setYValues(statelabels);
1471 map.setHighValueColour(theColor);
1472
1473 String szfileprefix;
1474 if (szoutfileID.equals(""))
1475 {
1476 szfileprefix = szoutputdir+"/transitions_"+numstates;
1477 }
1478 else
1479 {
1480 szfileprefix = szoutputdir+"/transitions_"+numstates+"_"+szoutfileID;
1481 }
1482
1483 map.saveToFile(new File(szfileprefix+".png"));
1484 Util.printImageToSVG(map, szfileprefix+".svg");
1485
1486 if (niteration <= 1)
1487 {
1488 System.out.println("Writing to file "+szfileprefix+".png");
1489 System.out.println("Writing to file "+szfileprefix+".svg");
1490 }
1491 }
1492
1493 ///////////////////////////////////////////////////////////////////////////////////////////
1494
1495 /**
1496 * Outputs the emission parameters as a '.png' and '.svg' heatmap in the szoutputdir directory
1497 * the file name startswith 'emissions_numstates' and if szoutfileID is non-empty that is
1498 * included as well.
1499 */
1500 public void printEmissionImage(int niteration) throws IOException
1501 {
1502 double[][] sorteddata =new double[numstates][numdatasets];
1503 String[] sortedcollabels = new String[numdatasets];
1504 String[] rowlabels = new String[numstates];
1505
1506 //copying in the emission parameters for the positive on bucket
1507 for (int ni = 0; ni < sorteddata.length; ni++)
1508 {
1509 for (int nj =0; nj < sorteddata[ni].length; nj++)
1510 {
1511 sorteddata[ni][nj] = emissionprobs[stateordering[ni]][colordering[nj]][1];
1512 }
1513 }
1514
1515 for (int ni = 0; ni < numdatasets; ni++)
1516 {
1517 //column labels also need to be reordered
1518 sortedcollabels[ni] = datasets[colordering[ni]];
1519 }
1520
1521 for (int ni = 0; ni < numstates; ni++)
1522 {
1523 rowlabels[ni] = ""+(ni+1);
1524 String szsuffix;
1525 //changing in v1.12 to be state labels for new state to match char ordering
1526 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
1527 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
1528 {
1529 rowlabels[ni]+= "_"+szsuffix;
1530 }
1531 }
1532
1533 HeatChart map = new HeatChart(sorteddata);
1534
1535 map.setTitle("Emission Parameters");
1536 map.setXAxisLabel("Mark");
1537 map.setAxisValuesFont(new Font("SansSerif",0,20));
1538 map.setAxisLabelsFont(new Font("SansSerif",0,22));
1539 map.setTitleFont(new Font("SansSerif",0,24));
1540 map.setYAxisLabel("State ("+szorder+" order)");
1541 if (sorteddata.length <=5)
1542 {
1543 map.setChartMargin(125);
1544 }
1545 else
1546 {
1547 map.setChartMargin(50);
1548 }
1549 map.setXValues(sortedcollabels);
1550 map.setYValues(rowlabels);
1551 map.setHighValueColour(theColor);
1552
1553 String szfileprefix;
1554 if (szoutfileID.equals(""))
1555 {
1556 szfileprefix = szoutputdir+"/emissions_"+numstates;
1557 }
1558 else
1559 {
1560 szfileprefix = szoutputdir+"/emissions_"+numstates+"_"+szoutfileID;
1561 }
1562
1563 Util.printImageToSVG(map, szfileprefix+".svg");
1564 map.saveToFile(new File(szfileprefix+".png"));
1565
1566 if (niteration <= 1)
1567 {
1568 System.out.println("Writing to file "+szfileprefix+".svg");
1569 System.out.println("Writing to file "+szfileprefix+".png");
1570 }
1571 }
1572
1573 ///////////////////////////////////////////////////////////////////////////////////////////
1574
1575 /**
1576 * Prints the contents of the mark present emission parameters out to a text file with the
1577 * states and marks ordered based on stateordering and colordering
1578 */
1579 public void printEmissionTable(int niteration) throws IOException
1580 {
1581 PrintWriter pw;
1582
1583 String szfile;
1584 if (szoutfileID.equals(""))
1585 {
1586 szfile = szoutputdir+"/emissions_"+numstates+".txt";
1587 pw = new PrintWriter(szfile);
1588 }
1589 else
1590 {
1591 szfile = szoutputdir+"/emissions_"+numstates+"_"+szoutfileID+".txt";
1592 pw = new PrintWriter(szfile);
1593 }
1594
1595 if (niteration <= 1)
1596 {
1597 System.out.println("Writing to file "+szfile);
1598 }
1599
1600 pw.print("State ("+szorder+" order)");
1601 for (int ni = 0; ni < datasets.length; ni++)
1602 {
1603 pw.print("\t"+datasets[colordering[ni]]);
1604 }
1605 pw.println();
1606
1607
1608 for (int ni = 0; ni < numstates; ni++)
1609 {
1610 pw.print((ni+1));
1611 String szsuffix;
1612 //changing in v1.12 to be state labels for new state to match char ordering
1613 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
1614 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
1615 {
1616 pw.print("_"+szsuffix);
1617 }
1618
1619 for (int nj = 0; nj < emissionprobs[ni].length; nj++)
1620 {
1621 pw.print("\t"+emissionprobs[stateordering[ni]][colordering[nj]][1]);
1622 }
1623 pw.println();
1624 }
1625 pw.close();
1626 }
1627
1628 ///////////////////////////////////////////////////////////////////////////////////////////
1629
1630 /**
1631 * Prints the contents of the transition parameters out to a text file with the states ordered
1632 */
1633 public void printTransitionTable(int niteration) throws IOException
1634 {
1635 PrintWriter pw;
1636 String szfile;
1637 if (szoutfileID.equals(""))
1638 {
1639 szfile = szoutputdir+"/transitions_"+numstates+".txt";
1640 pw = new PrintWriter(szfile);
1641 }
1642 else
1643 {
1644 szfile = szoutputdir+"/transitions_"+numstates+"_"+szoutfileID+".txt";
1645 pw = new PrintWriter(szfile);
1646 }
1647
1648 if (niteration <= 1)
1649 {
1650 System.out.println("Writing to file "+szfile);
1651 }
1652
1653 pw.print("State (from\\to) ("+szorder+" order)");
1654 for (int ni = 0; ni < numstates; ni++)
1655 {
1656 pw.print("\t"+(ni+1));
1657 String szsuffix;
1658 //changing in v1.12 to be state labels for new state to match char ordering
1659 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
1660 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
1661 {
1662 pw.print("_"+szsuffix);
1663 }
1664 }
1665 pw.println();
1666
1667
1668 for (int ni = 0; ni < numstates; ni++)
1669 {
1670 pw.print(""+(ni+1));
1671 String szsuffix;
1672 //changing in v1.12 to be state labels for new state to match char ordering
1673 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
1674 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
1675 {
1676 pw.print("_"+szsuffix);
1677 }
1678 double[] transitionprobs_stateordering_ni = transitionprobs[stateordering[ni]];
1679 for (int nj = 0; nj < numstates; nj++)
1680 {
1681 pw.print("\t"+transitionprobs_stateordering_ni[stateordering[nj]]);
1682 }
1683 pw.println();
1684 }
1685 pw.close();
1686 }
1687
1688 ///////////////////////////////////////////////////////////////////////////////////////////
1689
1690 /**
1691 * Prints to a file the contents of the model. States are printed based on state-ordering
1692 * but columns are not reordered and are consistent as in the original data file
1693 * szoutputdir+"/model_"+numstates+"_"+szoutfileID+".txt"
1694 * if -1 then uses model header
1695 */
1696 private void printParametersToFile(int niteration) throws IOException
1697 {
1698 PrintWriter pw;
1699
1700 String szfile;
1701 if (szoutfileID.equals(""))
1702 {
1703 szfile = szoutputdir+"/model_"+numstates+".txt";
1704 pw = new PrintWriter(szfile);
1705 }
1706 else
1707 {
1708 szfile = szoutputdir+"/model_"+numstates+"_"+szoutfileID+".txt";
1709 pw = new PrintWriter(szfile);
1710 }
1711
1712 if (niteration <= 1)
1713 {
1714 System.out.println("Writing to file "+szfile);
1715 }
1716
1717 if (niteration == -1)
1718 {
1719 StringTokenizer st = new StringTokenizer(szLoadHeader);
1720 pw.print(st.nextToken()+"\t"+st.nextToken()+"\t"+chorder);
1721 st.nextToken(); //might be changing the order type
1722 if (st.hasMoreTokens())
1723 {
1724 //added this check in version 1.11 since elim models won't have these two tokens for loglikelihood and iteration
1725 pw.println("\t"+st.nextToken()+"\t"+st.nextToken());
1726 }
1727 }
1728 else
1729 {
1730 pw.println(numstates+"\t"+numdatasets+"\t"+chorder+"\t"+dloglike+"\t"+niteration);
1731 }
1732
1733 for (int ni = 0; ni < numstates; ni++)
1734 {
1735 pw.println("probinit\t"+(ni+1)+"\t"+probinit[stateordering[ni]]);
1736 }
1737
1738 for (int ni = 0; ni < transitionprobs.length; ni++)
1739 {
1740 double[] transitionprobs_stateordering_ni = transitionprobs[stateordering[ni]];
1741 for (int nj = 0; nj < transitionprobs_stateordering_ni.length; nj++)
1742 {
1743 pw.println("transitionprobs\t"+(ni+1)+"\t"+(nj+1)+"\t"+transitionprobs_stateordering_ni[stateordering[nj]]);
1744 }
1745 }
1746
1747 for (int ni = 0; ni < numstates; ni++)
1748 {
1749 double[][] emissionprobs_stateordering_ni = emissionprobs[stateordering[ni]];
1750 for (int nj = 0; nj < emissionprobs_stateordering_ni.length; nj++)
1751 {
1752 double[] emissionprobs_stateordering_ni_nj;
1753 String szdataset;
1754 if (breordercolsmodel)
1755 {
1756 emissionprobs_stateordering_ni_nj = emissionprobs_stateordering_ni[colordering[nj]];
1757 szdataset = datasets[colordering[nj]];
1758 }
1759 else
1760 {
1761 emissionprobs_stateordering_ni_nj = emissionprobs_stateordering_ni[nj];
1762 szdataset = datasets[nj];
1763 }
1764
1765 for (int nk = 0; nk < emissionprobs_stateordering_ni_nj.length; nk++)
1766 {
1767 pw.println("emissionprobs\t"+(ni+1)+"\t"+nj+"\t"+szdataset+"\t"+nk+"\t"+emissionprobs_stateordering_ni_nj[nk]);
1768 }
1769 }
1770 }
1771 pw.close();
1772 }
1773
1774 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
1775
1776
1777
1778
1779 public void informationInitializeNestedWithLoad() throws IOException
1780 {
1781 //inital probability vector
1782 probinit = new double[numstates];
1783
1784 //creates the emission probability matrix
1785 emissionprobs = new double[numstates][numdatasets][numbuckets];
1786
1787 //set to true if a transition has been eliminated
1788 elim = new boolean[numstates][numstates];
1789
1790 //initalize the transition matrix
1791 transitionprobs = new double[numstates][numstates];
1792
1793 //initialize index of the next non-zero transition
1794 transitionprobsindex = new int[numstates][numstates];
1795
1796 //initalize number of non-zero transitions
1797 transitionprobsnum = new int[numstates];
1798
1799 //initalize column-wise index of non-zero transitions
1800 transitionprobsindexCol = new int[numstates][numstates];
1801
1802 //number of non-zero column transitions
1803 transitionprobsnumCol = new int[numstates];
1804
1805 int nmaxtime = 0;
1806 for (int nseq = 0; nseq < numtime.length; nseq++)
1807 {
1808 //numtime[nseq] = traindataObservedIndex[nseq].length;
1809 if (numtime[nseq] > nmaxtime)
1810 {
1811 nmaxtime = numtime[nseq];
1812 }
1813 }
1814
1815
1816
1817 int[][] traindataObservedIndexPair = new int[chromfiles.length][];
1818
1819 //stores the indicies of the data
1820 int[] traindataObservedIndex = new int[nmaxtime];
1821
1822 //saving the mapping of signatures and chromsome observed on
1823 //stores whether there is a present call at each location
1824 boolean[][] traindataObservedValues = new boolean[nmaxtime][numdatasets];
1825
1826 //stores whether the mark is not considered missing
1827 boolean[][] traindataNotMissing = new boolean[nmaxtime][numdatasets]; //usually nobserved
1828
1829
1830 ArrayList alobservedpairflags = new ArrayList(); //is an index from the element combination to the associated flags
1831
1832 HashMap hmObserved= new HashMap(); //is an index from the associated flags to the element index
1833
1834 int nobserved= 0; //index on the unique observation combination we are observing
1835
1836 int[] samples= null;
1837
1838 int ncurrnumincludeseq;
1839 if (numincludeseq >= 1)
1840 {
1841 ncurrnumincludeseq = Math.min(numincludeseq, chromfiles.length);
1842 samples = new int[ncurrnumincludeseq];
1843 }
1844 else
1845 {
1846 ncurrnumincludeseq = chromfiles.length;
1847 }
1848
1849 boolean[] bincludeseq = new boolean[chromfiles.length];
1850 for (int nk = 0; nk < bincludeseq.length; nk++)
1851 {
1852 bincludeseq[nk] = true;
1853 }
1854
1855 if (numincludeseq >=1)
1856 {
1857 for (int ni = 0; ni < samples.length; ni++)
1858 {
1859 samples[ni] = ni;
1860 }
1861
1862 //Random theRandom2 = new Random(412);//433
1863
1864 //sampling without replacement data locations wanted
1865 for (int ni = ncurrnumincludeseq; ni < chromfiles.length; ni++)
1866 {
1867 if (theRandom.nextDouble() < ncurrnumincludeseq/((double) ni +1))
1868 {
1869 samples[theRandom.nextInt(ncurrnumincludeseq)] = ni;
1870 }
1871 }
1872
1873 for (int nk = 0; nk < bincludeseq.length; nk++)
1874 {
1875 bincludeseq[nk] = false;
1876 }
1877
1878 for (int nk = 0; nk < samples.length; nk++)
1879 {
1880 bincludeseq[samples[nk]] = true;
1881 //System.out.println("including\t"+samples[nk]+"\t"+bincludeseq[samples[nk]]);
1882 }
1883 }
1884
1885 //generates all vectors of combinations of consecutive of '1' calls
1886 for (int nseq = 0; nseq < chromfiles.length; nseq++)
1887 {
1888 if (bincludeseq[nseq])
1889 {
1890 //going through each sequence
1891
1892 //int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
1893 //int traindataObservedIndex_nseq_m1 = traindataObservedIndex_nseq.length -1;
1894 int numtime_nseq_m1 = numtime[nseq] - 1;
1895
1896 HashMap hmObservedLoad = new HashMap(); //maps an observation string to an index and set of flags
1897
1898 int nobservedload = 0;
1899
1900 if (ChromHMM.BVERBOSE)
1901 {
1902 System.out.println("reading\t"+szinputdir+" "+chromfiles[nseq]);
1903 }
1904
1905 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nseq]);
1906 String szLine = br.readLine(); //first line tells cell type and chromosome
1907 br.readLine();//flush mark header
1908 ArrayList aldata = new ArrayList();
1909 while ((szLine = br.readLine())!=null)
1910 {
1911 StringTokenizer st = new StringTokenizer(szLine,"\t ");
1912 StringBuffer sb = new StringBuffer();
1913
1914 for (int ncol = 0; ncol < numdatasets; ncol++)
1915 {
1916 if (!st.hasMoreTokens())
1917 {
1918 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nseq]);
1919 }
1920
1921 String sztoken = st.nextToken();//.trim();
1922
1923 if (sztoken.equals("0"))
1924 {
1925 sb.append("0");
1926 }
1927 else if (sztoken.equals("1"))
1928 {
1929 sb.append("1");
1930 }
1931 else if (sztoken.equals("2"))
1932 {
1933 //this means missing
1934 sb.append("2");
1935 }
1936 else
1937 {
1938 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nseq]);
1939 }
1940 }
1941 aldata.add(sb.toString());
1942 }
1943 br.close();
1944
1945 int nsize = aldata.size();
1946
1947 //traindataObservedIndex[nfile] = new int[nsize];
1948 //int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
1949
1950 for (int nrow = 0; nrow < nsize; nrow++)
1951 {
1952 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
1953 Integer theObservedInt = (Integer) hmObservedLoad.get(theBigInteger);
1954 //boolean[] flagA;
1955
1956 if (theObservedInt == null)
1957 {
1958 //System.out.println(szmappingbyte.length());
1959 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
1960 hmObservedLoad.put(theBigInteger, Integer.valueOf(nobservedload));
1961
1962 //saving this observed index
1963 traindataObservedIndex[nrow] = nobservedload;
1964
1965 //increments the number of observed combinations of marks
1966 nobservedload++;
1967 }
1968 else
1969 {
1970 //storing the index of the flags associated with this row
1971 traindataObservedIndex[nrow] = ((Integer) theObservedInt).intValue();
1972 }
1973 }
1974
1975 Iterator hmObservedIterator = hmObservedLoad.entrySet().iterator();
1976 while (hmObservedIterator.hasNext())
1977 {
1978 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
1979 BigInteger theBigInteger = (BigInteger) pairs.getKey();
1980 String szmapping = theBigInteger.toString(3); //getting back the mapping string
1981
1982 //ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
1983 int ncurrindex = ((Integer) pairs.getValue()).intValue();// theObservedRec.nobserved;//this is an index on which obervation combination it is
1984
1985 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
1986 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
1987
1988 //if the mapping string is less than the number of data sets then
1989 //there are leading 0's will set for leading 0's not missing and absent
1990 int numch = szmapping.length();
1991 int numleading0 = numdatasets - numch;
1992 for (int nj = 0; nj < numleading0; nj++)
1993 {
1994 traindataObservedValues_ncurrindex[nj] = false;
1995 traindataNotMissing_ncurrindex[nj] = true;
1996 }
1997
1998 int nmappedindex = numleading0; //starting from the leading 0 position
1999 for (int nj = 0; nj < numch; nj++)
2000 {
2001 char ch = szmapping.charAt(nj);
2002
2003 if (ch == '0')
2004 {
2005 traindataObservedValues_ncurrindex[nmappedindex] = false;
2006 traindataNotMissing_ncurrindex[nmappedindex] = true;
2007 }
2008 else if (ch=='1')
2009 {
2010 traindataObservedValues_ncurrindex[nmappedindex] = true;
2011 traindataNotMissing_ncurrindex[nmappedindex] = true;
2012 }
2013 else
2014 {
2015 //missing data
2016 traindataObservedValues_ncurrindex[nmappedindex] = false;
2017 traindataNotMissing_ncurrindex[nmappedindex] = false;
2018 }
2019 nmappedindex++;
2020 }
2021 }
2022
2023 traindataObservedIndexPair[nseq] = new int[numtime_nseq_m1];
2024 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2025 boolean[] currvals = traindataObservedValues[traindataObservedIndex[0]];
2026
2027 for (int nindex = 0; nindex < numtime_nseq_m1; nindex++)//traindataObservedIndex_nseq_m1
2028 {
2029 boolean[] nextvals = traindataObservedValues[traindataObservedIndex[nindex+1]];
2030 StringBuffer sb = new StringBuffer();
2031 for (int nmark = 0; nmark < numdatasets;nmark++)
2032 {
2033 if (currvals[nmark]&&nextvals[nmark])
2034 {
2035 sb.append("1");
2036 }
2037 else
2038 {
2039 sb.append("0");
2040 }
2041 }
2042
2043 BigInteger theBigInteger = new BigInteger(sb.toString(),2);
2044 Object obj = hmObserved.get(theBigInteger);
2045 int ncurrobserved;
2046 if (obj == null)
2047 {
2048 //first time we saw the combination storing index
2049 hmObserved.put(theBigInteger,Integer.valueOf(nobserved));
2050 ncurrobserved = nobserved;
2051 nobserved++;
2052
2053 boolean[] pairflags = new boolean[numdatasets];
2054 for (int nmark = 0; nmark < numdatasets;nmark++)
2055 {
2056 pairflags[nmark] = (currvals[nmark]&&nextvals[nmark]);
2057 }
2058 alobservedpairflags.add(pairflags);
2059 }
2060 else
2061 {
2062 //we already have seen this
2063 ncurrobserved= ((Integer) hmObserved.get(theBigInteger)).intValue();
2064 }
2065 //storing which element pair the observation corresponds to
2066 traindataObservedIndexPair_nseq[nindex] = ncurrobserved;
2067 currvals = nextvals;
2068 }
2069 }//include
2070 }
2071
2072 int numels = alobservedpairflags.size();
2073
2074 //computes a tally for each flag combination observed of how frequently observed
2075 //int[] tallys = new int[numels];
2076 long[] tallys = new long[numels];
2077
2078 //stores the total number of flag combinations observed
2079 //int ntotaltally = 0;
2080 long ntotaltally = 0;
2081
2082 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2083 {
2084 if (bincludeseq[nseq])
2085 {
2086 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2087 //updating element counts
2088 for (int nindex = 0; nindex < traindataObservedIndexPair_nseq.length; nindex++)
2089 {
2090 tallys[traindataObservedIndexPair_nseq[nindex]]++;
2091 }
2092 //updates the total element counts
2093 ntotaltally += traindataObservedIndexPair_nseq.length;
2094 }
2095 }
2096
2097 //first state always smoothed zero
2098 for (int nj = 0; nj < numdatasets; nj++)
2099 {
2100 emissionprobs[0][nj][1] = dinformationsmooth*1.0/numbuckets;
2101 emissionprobs[0][nj][0] = 1- emissionprobs[0][nj][1];
2102 }
2103
2104
2105 //stores how many elements are currently assigned to the split node
2106 //int[] partitionTally = new int[numstates];
2107 long[] partitionTally = new long[numstates];
2108
2109 //initally everything gets assigned to split node 0
2110 partitionTally[0] = ntotaltally;
2111
2112 //stores the partition assignment of each split node
2113 // initially everything is assigned to split node 0
2114 int[] initStateAssign = new int[numels];
2115
2116 //stores back pointers to the parent split nodes
2117 int[] backptr = new int[numstates];
2118
2119 //stores for all prior splits how many elements would be split off
2120 //if partitioning on that mark
2121 //int[][] nextpartitionTally = new int[numstates-1][numdatasets];
2122 long[][] nextpartitionTally = new long[numstates-1][numdatasets];
2123
2124 for (int niteration = 1; niteration < numstates; niteration++)
2125 {
2126 //need to the same number of assignments as we have states
2127
2128 for (int ni = 0; ni < niteration-1; ni++)
2129 {
2130 //initializes the nextpartitionTally to 0
2131
2132 //int[] nextpartitionTally_ni = nextpartitionTally[ni];
2133 long[] nextpartitionTally_ni = nextpartitionTally[ni];
2134 for (int nmark = 0; nmark < numdatasets; nmark++)
2135 {
2136 nextpartitionTally_ni[nmark] = 0;
2137 }
2138 }
2139
2140 for (int nel = 0; nel < tallys.length; nel++)
2141 {
2142 //considering each mark to partition on
2143
2144 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2145 //gets the current assignment of the element type
2146 int initStateAssign_nel = initStateAssign[nel];
2147
2148 //counting how many from current partition would be split
2149 for (int nsplitmark = 0; nsplitmark <numdatasets; nsplitmark++)
2150 {
2151 if (pairflags[nsplitmark])
2152 {
2153 //if element is positive for the mark then increments the count
2154 nextpartitionTally[initStateAssign_nel][nsplitmark] += tallys[nel];
2155 }
2156 }
2157 }
2158
2159 //finding the split that results in the greatest information change
2160 double dbestinformationchange = 0;
2161 //stores the best split
2162 int nbestsplit = -1;
2163 //stores the best split mark
2164 int nbestsplitmark = -1;
2165
2166 for (int nsplit = 0; nsplit < niteration; nsplit++)
2167 {
2168 //considering all previous splits to split again
2169
2170 //fraction of total weighted elements in this node about to be split
2171 //int partitionTally_nsplit = partitionTally[nsplit];
2172 long partitionTally_nsplit = partitionTally[nsplit];
2173 double dprobfull = partitionTally_nsplit/(double) ntotaltally;
2174 double dprobfullterm;
2175 if (dprobfull> 0)
2176 {
2177 //the information term for this node about to be split
2178 dprobfullterm = dprobfull*Math.log(dprobfull);
2179 }
2180 else
2181 {
2182 dprobfullterm = 0;
2183 }
2184
2185 //int[] nextpartitionTally_nsplit = nextpartitionTally[nsplit];
2186 long[] nextpartitionTally_nsplit = nextpartitionTally[nsplit];
2187
2188 for (int nsplitmark = 0; nsplitmark < numdatasets; nsplitmark++)
2189 {
2190 //considering each mark to split on
2191
2192 //numerator is how many weighted elements would remain in the partition after splitting on the mark
2193 double dprob1 = (partitionTally_nsplit-nextpartitionTally_nsplit[nsplitmark])/(double) ntotaltally;
2194
2195 //numerator is how many weighted elements would go to the new partition
2196 double dprob2 = nextpartitionTally_nsplit[nsplitmark]/(double) ntotaltally;
2197 double dinformationchange = dprobfullterm;
2198 if (dprob1 > 0)
2199 {
2200 dinformationchange -= dprob1*Math.log(dprob1);
2201 }
2202
2203 if (dprob2 > 0)
2204 {
2205 dinformationchange -= dprob2*Math.log(dprob2);
2206 }
2207 //-p_1*log(p_1)-p_2*log(p_2)- -(p1+p2)*log(p1+p2)
2208
2209 if (dinformationchange > dbestinformationchange)
2210 {
2211 dbestinformationchange = dinformationchange;
2212 nbestsplit = nsplit;
2213 nbestsplitmark = nsplitmark;
2214 }
2215 }
2216 }
2217
2218 if (ChromHMM.BVERBOSE)
2219 {
2220 System.out.println("====>\t"+nbestsplit+"\t"+nbestsplitmark+"\t"+datasets[nbestsplitmark]+"\t"+dbestinformationchange+"\t"+
2221 nextpartitionTally[nbestsplit][nbestsplitmark]+"\t"+partitionTally[nbestsplit]);
2222 }
2223
2224 if (nbestsplit == -1)
2225 {
2226 throw new IllegalArgumentException("On this data the INFORMATION initialization strategy can only support "+niteration+" states. "+
2227 "Check if the binarization was done correctly, and if so "+
2228 "use the RANDOM or LOAD options for more states");
2229 }
2230
2231 //the number of elements in the new split
2232 //int numnewsplit =nextpartitionTally[nbestsplit][nbestsplitmark];
2233 long numnewsplit =nextpartitionTally[nbestsplit][nbestsplitmark];
2234 partitionTally[niteration] = numnewsplit;
2235
2236 //removes from the node we splitting from those we just split;
2237 partitionTally[nbestsplit] -= numnewsplit;
2238
2239 //stores a back pointer to the node split to generate this one
2240 backptr[niteration] = nbestsplit;
2241
2242 for (int nel = 0; nel < tallys.length; nel++)
2243 {
2244 //goes through all elements and if recorded as being part of this split and positive for the split mark
2245 //then updates its initial state
2246 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2247 if ((initStateAssign[nel]==nbestsplit)&& (pairflags[nbestsplitmark]))
2248 {
2249 initStateAssign[nel]= niteration;
2250 }
2251 }
2252 }
2253
2254 //int[][] postally = new int[numstates][numdatasets];
2255 long[][] postally = new long[numstates][numdatasets];
2256
2257 for (int nel = 0; nel < tallys.length; nel++)
2258 {
2259 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2260
2261 for (int nmark = 0; nmark < numdatasets; nmark++)
2262 {
2263 if(pairflags[nmark])
2264 {
2265 //this have a positive assignment for this flag
2266 //walking to all ancestors and incrementing tally for this mark
2267 int ncurrstate = initStateAssign[nel];
2268 do
2269 {
2270 postally[ncurrstate][nmark] += tallys[nel];
2271 ncurrstate = backptr[ncurrstate];
2272 }
2273 while (ncurrstate != 0);
2274 }
2275 }
2276 }
2277
2278 //int[] partitionTallySum = new int[partitionTally.length];
2279 long[] partitionTallySum = new long[partitionTally.length];
2280 for (int nstate = 1; nstate < numstates; nstate++)
2281 {
2282 //figures out how many descendants there are of each split
2283 int ncurrstate = nstate;
2284 //int ntotsum = 0;
2285 //int ncurrval = partitionTally[ncurrstate];
2286 long ncurrval = partitionTally[ncurrstate];
2287 do
2288 {
2289 //incrementing counts for the parents
2290 partitionTallySum[ncurrstate] += ncurrval;
2291 ncurrstate = backptr[ncurrstate];
2292 }
2293 while (ncurrstate != 0);
2294 }
2295
2296 for (int nstate = 1; nstate < numstates; nstate++)
2297 {
2298 for (int nj = 0; nj < numdatasets; nj++)
2299 {
2300 emissionprobs[nstate][nj][1] = dinformationsmooth*1.0/numbuckets
2301 +(1-dinformationsmooth)*(postally[nstate][nj]/(double) partitionTallySum[nstate]);
2302 emissionprobs[nstate][nj][0] = 1- emissionprobs[nstate][nj][1];
2303 }
2304 }
2305
2306 //initialize the inital probability based on the partition of the first vector
2307
2308 //int[] numstarts = new int[numstates];
2309 long[] numstarts = new long[numstates];
2310 //int nvalidseq = 0;
2311 long nvalidseq = 0;
2312
2313 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2314 {
2315 if ((bincludeseq[nseq])&&(traindataObservedIndexPair[nseq].length > 0))
2316 {
2317 //updated in v1.14
2318 numstarts[initStateAssign[traindataObservedIndexPair[nseq][0]]]++;
2319 nvalidseq++;
2320 }
2321 }
2322
2323 for (int ni = 0; ni < probinit.length; ni++)
2324 {
2325 //weighted probability of uniform and the fraction of starts from that partition
2326 probinit[ni] = dinformationsmooth*1.0/numstates+(1-dinformationsmooth)*numstarts[ni]/(double) nvalidseq; //updated in v1.14
2327 }
2328
2329
2330 //determining initial settings for the transition probability
2331 //int[][] transitiontally = new int[numstates][numstates];
2332 long[][] transitiontally = new long[numstates][numstates];
2333 int nnextstate;
2334 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2335 {
2336 if ((bincludeseq[nseq])&&(traindataObservedIndexPair[nseq].length > 0))
2337 {
2338 //going through each sequence
2339 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2340 int nprevstate = initStateAssign[traindataObservedIndexPair_nseq[0]];
2341 for (int nindex = 1; nindex < traindataObservedIndexPair_nseq.length; nindex++)
2342 {
2343 //going through all the elements of the sequence computing a tallly of each bigram
2344 nnextstate = initStateAssign[traindataObservedIndexPair_nseq[nindex]];
2345 transitiontally[nprevstate][nnextstate]++;
2346 nprevstate = nnextstate;
2347 }
2348 }
2349 }
2350
2351 for (int ni = 0; ni < numstates; ni++)
2352 {
2353 double[] transitionprobs_ni = transitionprobs[ni];
2354 double dnumfromi = 0;
2355 //int[] transitiontally_ni = transitiontally[ni];
2356 long[] transitiontally_ni = transitiontally[ni];
2357
2358 for (int nj = 0; nj < numstates; nj++)
2359 {
2360 dnumfromi += transitiontally_ni[nj];
2361 }
2362 for (int nj = 0; nj < numstates; nj++)
2363 {
2364 elim[ni][nj] = false;
2365 //computes a weighted average of a uniform transition probability and the empirical frequency
2366 transitionprobs_ni[nj] = dinformationsmooth*1.0/numstates
2367 +(1-dinformationsmooth)*(transitiontally_ni[nj]/(double) dnumfromi);
2368 transitionprobsindex[ni][nj] = nj;
2369 transitionprobsindexCol[ni][nj] = nj;
2370 }
2371 transitionprobsnum[ni] = numstates;
2372 transitionprobsnumCol[ni] = numstates;
2373 }
2374 }
2375
2376
2377 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2378
2379
2380 public void informationInitializeNested()
2381 {
2382 //inital probability vector
2383 probinit = new double[numstates];
2384
2385 //creates the emission probability matrix
2386 emissionprobs = new double[numstates][numdatasets][numbuckets];
2387
2388 //set to true if a transition has been eliminated
2389 elim = new boolean[numstates][numstates];
2390
2391 //initalize the transition matrix
2392 transitionprobs = new double[numstates][numstates];
2393
2394 //initialize index of the next non-zero transition
2395 transitionprobsindex = new int[numstates][numstates];
2396
2397 //initalize number of non-zero transitions
2398 transitionprobsnum = new int[numstates];
2399
2400 //initalize column-wise index of non-zero transitions
2401 transitionprobsindexCol = new int[numstates][numstates];
2402
2403 //number of non-zero column transitions
2404 transitionprobsnumCol = new int[numstates];
2405
2406 int[][] traindataObservedIndexPair = new int[traindataObservedIndex.length][];
2407
2408 ArrayList alobservedpairflags = new ArrayList(); //is an index from the element combination to the associated flags
2409
2410 HashMap hmObserved= new HashMap(); //is an index from the associated flags to the element index
2411
2412 int nobserved= 0; //index on the unique observation combination we are observing
2413
2414 int[] samples= null;
2415
2416 int ncurrnumincludeseq;
2417 if (numincludeseq >= 1)
2418 {
2419 ncurrnumincludeseq = Math.min(numincludeseq, chromfiles.length);
2420 samples = new int[ncurrnumincludeseq];
2421 }
2422 else
2423 {
2424 ncurrnumincludeseq = chromfiles.length;
2425 }
2426
2427 boolean[] bincludeseq = new boolean[chromfiles.length];
2428 for (int nk = 0; nk < bincludeseq.length; nk++)
2429 {
2430 bincludeseq[nk] = true;
2431 }
2432
2433 if (numincludeseq >=1)
2434 {
2435 for (int ni = 0; ni < samples.length; ni++)
2436 {
2437 samples[ni] = ni;
2438 }
2439 //Random theRandom2 = new Random(412);//433
2440
2441 //sampling without replacement data locations wanted
2442 for (int ni = ncurrnumincludeseq; ni < chromfiles.length; ni++)
2443 {
2444 if (theRandom.nextDouble() < ncurrnumincludeseq/((double) ni +1))
2445 {
2446 samples[theRandom.nextInt(ncurrnumincludeseq)] = ni;
2447 }
2448 }
2449
2450 for (int nk = 0; nk < bincludeseq.length; nk++)
2451 {
2452 bincludeseq[nk] = false;
2453 }
2454
2455 for (int nk = 0; nk < samples.length; nk++)
2456 {
2457 bincludeseq[samples[nk]] = true;
2458 //System.out.println("including\t"+samples[nk]+"\t"+bincludeseq[samples[nk]]);
2459 }
2460 }
2461
2462 //generates all vectors of combinations of consecutive of '1' calls
2463 for (int nseq = 0; nseq <traindataObservedIndex.length; nseq++)
2464 {
2465 if (bincludeseq[nseq])
2466 {
2467 //going through each sequence
2468
2469 int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
2470 int traindataObservedIndex_nseq_m1 = traindataObservedIndex_nseq.length -1;
2471 traindataObservedIndexPair[nseq] = new int[traindataObservedIndex_nseq_m1];
2472 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2473 boolean[] currvals = traindataObservedValues[traindataObservedIndex_nseq[0]];
2474
2475 for (int nindex = 0; nindex < traindataObservedIndex_nseq_m1; nindex++)
2476 {
2477 boolean[] nextvals = traindataObservedValues[traindataObservedIndex_nseq[nindex+1]];
2478 StringBuffer sb = new StringBuffer();
2479 for (int nmark = 0; nmark < numdatasets;nmark++)
2480 {
2481 if (currvals[nmark]&&nextvals[nmark])
2482 {
2483 sb.append("1");
2484 }
2485 else
2486 {
2487 sb.append("0");
2488 }
2489 }
2490
2491 BigInteger theBigInteger = new BigInteger(sb.toString(),2);
2492 Object obj = hmObserved.get(theBigInteger);
2493 int ncurrobserved;
2494 if (obj == null)
2495 {
2496 //first time we saw the combination storing index
2497 hmObserved.put(theBigInteger,Integer.valueOf(nobserved));
2498 ncurrobserved = nobserved;
2499 nobserved++;
2500
2501 boolean[] pairflags = new boolean[numdatasets];
2502 for (int nmark = 0; nmark < numdatasets;nmark++)
2503 {
2504 pairflags[nmark] = (currvals[nmark]&&nextvals[nmark]);
2505 }
2506 alobservedpairflags.add(pairflags);
2507 }
2508 else
2509 {
2510 //we already have seen this
2511 ncurrobserved= ((Integer) hmObserved.get(theBigInteger)).intValue();
2512 }
2513
2514 //storing which element pair the observation corresponds to
2515 traindataObservedIndexPair_nseq[nindex] = ncurrobserved;
2516 currvals = nextvals;
2517 }
2518 }
2519 }
2520
2521 int numels = alobservedpairflags.size();
2522
2523 //computes a tally for each flag combination observed of how frequently observed
2524 //int[] tallys = new int[numels];
2525 long[] tallys = new long[numels];
2526
2527 //stores the total number of flag combinations observed
2528 //int ntotaltally = 0;
2529 long ntotaltally = 0;
2530
2531 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2532 {
2533 if (bincludeseq[nseq])
2534 {
2535 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2536 //updating element counts
2537 for (int nindex = 0; nindex < traindataObservedIndexPair_nseq.length; nindex++)
2538 {
2539 tallys[traindataObservedIndexPair_nseq[nindex]]++;
2540 }
2541 //updates the total element counts
2542 ntotaltally += traindataObservedIndexPair_nseq.length;
2543 }
2544 }
2545
2546 //first state always smoothed zero
2547 for (int nj = 0; nj < numdatasets; nj++)
2548 {
2549 emissionprobs[0][nj][1] = dinformationsmooth*1.0/numbuckets;
2550 emissionprobs[0][nj][0] = 1- emissionprobs[0][nj][1];
2551 }
2552
2553
2554 //stores how many elements are currently assigned to the split node
2555 //int[] partitionTally = new int[numstates];
2556 long[] partitionTally = new long[numstates];
2557
2558 //initally everything gets assigned to split node 0
2559 partitionTally[0] = ntotaltally;
2560
2561 //stores the partition assignment of each split node
2562 // initially everything is assigned to split node 0
2563 int[] initStateAssign = new int[numels];
2564
2565 //stores back pointers to the parent split nodes
2566 int[] backptr = new int[numstates];
2567
2568 //stores for all prior splits how many elements would be split off
2569 //if partitioning on that mark
2570 //int[][] nextpartitionTally = new int[numstates-1][numdatasets];
2571 long[][] nextpartitionTally = new long[numstates-1][numdatasets];
2572
2573 for (int niteration = 1; niteration < numstates; niteration++)
2574 {
2575 //need to the same number of assignments as we have states
2576
2577 for (int ni = 0; ni < niteration-1; ni++)
2578 {
2579 //initializes the nextpartitionTally to 0
2580
2581 //int[] nextpartitionTally_ni = nextpartitionTally[ni];
2582 long[] nextpartitionTally_ni = nextpartitionTally[ni];
2583 for (int nmark = 0; nmark < numdatasets; nmark++)
2584 {
2585 nextpartitionTally_ni[nmark] = 0;
2586 }
2587 }
2588
2589 for (int nel = 0; nel < tallys.length; nel++)
2590 {
2591 //considering each mark to partition on
2592
2593 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2594 //gets the current assignment of the element type
2595 int initStateAssign_nel = initStateAssign[nel];
2596
2597 //counting how many from current partition would be split
2598 for (int nsplitmark = 0; nsplitmark <numdatasets; nsplitmark++)
2599 {
2600 if (pairflags[nsplitmark])
2601 {
2602 //if element is positive for the mark then increments the count
2603 nextpartitionTally[initStateAssign_nel][nsplitmark] += tallys[nel];
2604 }
2605 }
2606 }
2607
2608 //finding the split that results in the greatest information change
2609 double dbestinformationchange = 0;
2610 //stores the best split
2611 int nbestsplit = -1;
2612 //stores the best split mark
2613 int nbestsplitmark = -1;
2614
2615 for (int nsplit = 0; nsplit < niteration; nsplit++)
2616 {
2617 //considering all previous splits to split again
2618
2619 //fraction of total weighted elements in this node about to be split
2620 //int partitionTally_nsplit = partitionTally[nsplit];
2621 long partitionTally_nsplit = partitionTally[nsplit];
2622 double dprobfull = partitionTally_nsplit/(double) ntotaltally;
2623 double dprobfullterm;
2624 if (dprobfull> 0)
2625 {
2626 //the information term for this node about to be split
2627 dprobfullterm = dprobfull*Math.log(dprobfull);
2628 }
2629 else
2630 {
2631 dprobfullterm = 0;
2632 }
2633
2634 //int[] nextpartitionTally_nsplit = nextpartitionTally[nsplit];
2635 long[] nextpartitionTally_nsplit = nextpartitionTally[nsplit];
2636
2637 for (int nsplitmark = 0; nsplitmark < numdatasets; nsplitmark++)
2638 {
2639 //considering each mark to split on
2640
2641 //numerator is how many weighted elements would remain in the partition after splitting on the mark
2642 double dprob1 = (partitionTally_nsplit-nextpartitionTally_nsplit[nsplitmark])/(double) ntotaltally;
2643
2644 //numerator is how many weighted elements would go to the new partition
2645 double dprob2 = nextpartitionTally_nsplit[nsplitmark]/(double) ntotaltally;
2646 double dinformationchange = dprobfullterm;
2647 if (dprob1 > 0)
2648 {
2649 dinformationchange -= dprob1*Math.log(dprob1);
2650 }
2651
2652 if (dprob2 > 0)
2653 {
2654 dinformationchange -= dprob2*Math.log(dprob2);
2655 }
2656 //-p_1*log(p_1)-p_2*log(p_2)- -(p1+p2)*log(p1+p2)
2657
2658 if (dinformationchange > dbestinformationchange)
2659 {
2660 dbestinformationchange = dinformationchange;
2661 nbestsplit = nsplit;
2662 nbestsplitmark = nsplitmark;
2663 }
2664 }
2665 }
2666
2667 if (ChromHMM.BVERBOSE)
2668 {
2669 System.out.println("====>\t"+nbestsplit+"\t"+nbestsplitmark+"\t"+datasets[nbestsplitmark]+"\t"+dbestinformationchange+"\t"+
2670 nextpartitionTally[nbestsplit][nbestsplitmark]+"\t"+partitionTally[nbestsplit]);
2671 }
2672
2673 if (nbestsplit == -1)
2674 {
2675 throw new IllegalArgumentException("On this data the INFORMATION initialization strategy can only support "+niteration+" states. "+
2676 "Check if the binarization was done correctly, and if so "+
2677 "use the RANDOM or LOAD options for more states");
2678 }
2679
2680 //the number of elements in the new split
2681 //int numnewsplit =nextpartitionTally[nbestsplit][nbestsplitmark];
2682 long numnewsplit = nextpartitionTally[nbestsplit][nbestsplitmark];
2683 partitionTally[niteration] = numnewsplit;
2684
2685 //removes from the node we splitting from those we just split;
2686 partitionTally[nbestsplit] -= numnewsplit;
2687
2688 //stores a back pointer to the node split to generate this one
2689 backptr[niteration] = nbestsplit;
2690
2691 for (int nel = 0; nel < tallys.length; nel++)
2692 {
2693 //goes through all elements and if recorded as being part of this split and positive for the split mark
2694 //then updates its initial state
2695 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2696 if ((initStateAssign[nel]==nbestsplit)&& (pairflags[nbestsplitmark]))
2697 {
2698 initStateAssign[nel]= niteration;
2699 }
2700 }
2701 }
2702
2703 //int[][] postally = new int[numstates][numdatasets];
2704 long[][] postally = new long[numstates][numdatasets];
2705
2706 for (int nel = 0; nel < tallys.length; nel++)
2707 {
2708 boolean[] pairflags = (boolean[]) alobservedpairflags.get(nel);
2709
2710 for (int nmark = 0; nmark < numdatasets; nmark++)
2711 {
2712 if(pairflags[nmark])
2713 {
2714 //this have a positive assignment for this flag
2715 //walking to all ancestors and incrementing tally for this mark
2716 int ncurrstate = initStateAssign[nel];
2717 do
2718 {
2719 postally[ncurrstate][nmark] += tallys[nel];
2720 ncurrstate = backptr[ncurrstate];
2721 }
2722 while (ncurrstate != 0);
2723 }
2724 }
2725 }
2726
2727 //int[] partitionTallySum = new int[partitionTally.length];
2728 long[] partitionTallySum = new long[partitionTally.length];
2729 for (int nstate = 1; nstate < numstates; nstate++)
2730 {
2731 //figures out how many descendants there are of each split
2732 int ncurrstate = nstate;
2733 //int ntotsum = 0;
2734 //int ncurrval = partitionTally[ncurrstate];
2735 long ncurrval = partitionTally[ncurrstate];
2736 do
2737 {
2738 //incrementing counts for the parents
2739 partitionTallySum[ncurrstate] += ncurrval;
2740 ncurrstate = backptr[ncurrstate];
2741 }
2742 while (ncurrstate != 0);
2743 }
2744
2745 for (int nstate = 1; nstate < numstates; nstate++)
2746 {
2747 for (int nj = 0; nj < numdatasets; nj++)
2748 {
2749 emissionprobs[nstate][nj][1] = dinformationsmooth*1.0/numbuckets
2750 +(1-dinformationsmooth)*(postally[nstate][nj]/(double) partitionTallySum[nstate]);
2751 emissionprobs[nstate][nj][0] = 1- emissionprobs[nstate][nj][1];
2752 }
2753 }
2754
2755 //initialize the inital probability based on the partition of the first vector
2756
2757 //int[] numstarts = new int[numstates];
2758 long[] numstarts = new long[numstates];
2759 //int nvalidseq = 0;
2760 long nvalidseq = 0;
2761 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2762 {
2763 if ((bincludeseq[nseq])&&(traindataObservedIndexPair[nseq].length > 0))
2764 {
2765 //updated in v1.14
2766 numstarts[initStateAssign[traindataObservedIndexPair[nseq][0]]]++;
2767 nvalidseq++;
2768 }
2769 }
2770
2771 for (int ni = 0; ni < probinit.length; ni++)
2772 {
2773 //weighted probability of uniform and the fraction of starts from that partition
2774 probinit[ni] = dinformationsmooth*1.0/numstates+(1-dinformationsmooth)*numstarts[ni]/(double) nvalidseq; //updated in v1.14
2775 }
2776
2777
2778 //determining initial settings for the transition probability
2779 //int[][] transitiontally = new int[numstates][numstates];
2780 long[][] transitiontally = new long[numstates][numstates];
2781 int nnextstate;
2782 for (int nseq = 0; nseq < traindataObservedIndexPair.length; nseq++)
2783 {
2784 if ((bincludeseq[nseq])&&(traindataObservedIndexPair[nseq].length > 0)) //updated in v1.14
2785 {
2786 //going through each sequence
2787 int[] traindataObservedIndexPair_nseq = traindataObservedIndexPair[nseq];
2788 int nprevstate = initStateAssign[traindataObservedIndexPair_nseq[0]];
2789 for (int nindex = 1; nindex < traindataObservedIndexPair_nseq.length; nindex++)
2790 {
2791 //going through all the elements of the sequence computing a tallly of each bigram
2792 nnextstate = initStateAssign[traindataObservedIndexPair_nseq[nindex]];
2793 transitiontally[nprevstate][nnextstate]++;
2794 nprevstate = nnextstate;
2795 }
2796 }
2797 }
2798
2799 for (int ni = 0; ni < numstates; ni++)
2800 {
2801 double[] transitionprobs_ni = transitionprobs[ni];
2802 double dnumfromi = 0;
2803 //int[] transitiontally_ni = transitiontally[ni];
2804 long[] transitiontally_ni = transitiontally[ni];
2805
2806 for (int nj = 0; nj < numstates; nj++)
2807 {
2808 dnumfromi += transitiontally_ni[nj];
2809 }
2810 for (int nj = 0; nj < numstates; nj++)
2811 {
2812 elim[ni][nj] = false;
2813 //computes a weighted average of a uniform transition probability and the empirical frequency
2814 transitionprobs_ni[nj] = dinformationsmooth*1.0/numstates
2815 +(1-dinformationsmooth)*(transitiontally_ni[nj]/(double) dnumfromi);
2816 transitionprobsindex[ni][nj] = nj;
2817 transitionprobsindexCol[ni][nj] = nj;
2818 }
2819 transitionprobsnum[ni] = numstates;
2820 transitionprobsnumCol[ni] = numstates;
2821 }
2822 }
2823
2824 ///////////////////////////////////////////////////////////////////////////////////////////
2825
2826
2827 /**
2828 * Randomly initializes parameters of the HMM based on a uniform distribution
2829 */
2830 public void randomlyInitializeParams()
2831 {
2832 //initializes the initial state parameters
2833 double dsum = 0;
2834 probinit = new double[numstates];
2835 for (int ni = 0; ni < probinit.length; ni++)
2836 {
2837 probinit[ni] = theRandom.nextDouble();
2838 dsum += probinit[ni];
2839 }
2840
2841 for (int ni = 0; ni < probinit.length; ni++)
2842 {
2843 probinit[ni] /= dsum;
2844 }
2845
2846 //set to true if a transition has been eliminated
2847 elim = new boolean[numstates][numstates];
2848
2849 //initalize the transition matrix
2850 transitionprobs = new double[numstates][numstates];
2851
2852 //initialize index of the next non-zero transition
2853 transitionprobsindex = new int[numstates][numstates];
2854
2855 //initalize number of non-zero transitions
2856 transitionprobsnum = new int[numstates];
2857
2858 //initalize column-wise index of non-zero transitions
2859 transitionprobsindexCol = new int[numstates][numstates];
2860
2861 //number of non-zero column transitions
2862 transitionprobsnumCol = new int[numstates];
2863
2864 //uniformly randomly assigns transition probability values
2865 //also initializes transition indicies
2866 for (int ni = 0; ni < transitionprobs.length; ni++)
2867 {
2868 dsum = 0;
2869 double[] transitionprobs_ni = transitionprobs[ni];
2870 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
2871 {
2872 elim[ni][nj] = false;
2873 double dval = theRandom.nextDouble();
2874 transitionprobs_ni[nj] = dval;
2875 dsum += transitionprobs_ni[nj];
2876 transitionprobsindex[ni][nj] = nj;
2877 transitionprobsindexCol[ni][nj] = nj;
2878 }
2879 transitionprobsnum[ni] = numstates;
2880 transitionprobsnumCol[ni] = numstates;
2881
2882 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
2883 {
2884 transitionprobs_ni[nj] /= dsum;
2885 }
2886 }
2887
2888 //uniformly randomly assigns emission probability values
2889 //also initializes emission indicies
2890 emissionprobs = new double[numstates][numdatasets][numbuckets];
2891 for (int ni = 0; ni < emissionprobs.length; ni++)
2892 {
2893 double[][] emissionprobs_ni = emissionprobs[ni];
2894 for (int nj = 0; nj < emissionprobs_ni.length; nj++)
2895 {
2896 double[] emissionprobs_ni_nj = emissionprobs_ni[nj];
2897 dsum = 0;
2898 for (int nk = 0; nk < emissionprobs_ni_nj.length; nk++)
2899 {
2900 double dval = theRandom.nextDouble();
2901 dsum += dval;
2902 emissionprobs_ni_nj[nk] = dval;
2903 }
2904
2905 for (int nk = 0; nk < emissionprobs_ni_nj.length; nk++)
2906 {
2907 emissionprobs_ni_nj[nk] /= dsum;
2908 }
2909 }
2910 }
2911 }
2912
2913
2914 ///////////////////////////////////////////////////////////////////////////////////////////
2915
2916 /**
2917 * loadModel loads a model directly by calling loadModelSmooth with emission parameters set to 0
2918 */
2919 public void loadModel() throws IOException
2920 {
2921 loadModelSmooth(0,0);
2922 }
2923
2924 ///////////////////////////////////////////////////////////////////////////////////////////
2925
2926 /**
2927 * Loads the model contained in szInitFile with the smoothing specified
2928 * based on the dsmoothtransition and dsmoothemission parameters
2929 */
2930 public void loadModelSmooth(double dproceduresmoothemission, double dproceduresmoothtransition) throws IOException
2931 {
2932 BufferedReader br = Util.getBufferedReader(szInitFile);
2933 String szLine;
2934 szLoadHeader = br.readLine();
2935 if (szLoadHeader == null)
2936 {
2937 throw new IllegalArgumentException(szLoadHeader+" is empty!");
2938 }
2939 StringTokenizer st = new StringTokenizer(szLoadHeader,"\t");
2940
2941 //first token of the first line of the model file is assume to give the number of states
2942 numstates = Integer.parseInt(st.nextToken().trim());
2943 numdatasets = Integer.parseInt(st.nextToken().trim());
2944 if (datasets ==null)
2945 {
2946 datasets = new String[numdatasets];
2947 }
2948 chorder = st.nextToken().trim().charAt(0);
2949
2950 if ((nstateorder != ChromHMM.STATEORDER_TRANSITION)&&(nstateorder != ChromHMM.STATEORDER_EMISSION)&&(nstateorder != ChromHMM.STATEORDER_FIXED))
2951 {
2952 nstateorder = -1;
2953 for (int ni = 0; ni < ChromHMM.ORDERCHARS.length; ni++)
2954 {
2955 if (chorder == ChromHMM.ORDERCHARS[ni])
2956 {
2957 nstateorder = ni;
2958 break;
2959 }
2960 }
2961
2962 if (nstateorder == -1)
2963 {
2964 throw new IllegalArgumentException(chorder+" is an invalid order type");
2965 }
2966 szorder = ChromHMM.ORDERSTRINGS[nstateorder];
2967 }
2968
2969 probinit = new double[numstates];
2970
2971 //transitions that are strictly 0 are elminated
2972 elim = new boolean[numstates][numstates];
2973
2974 transitionprobs = new double[numstates][numstates];
2975
2976 //contains the indicies of non-0 transitions
2977 transitionprobsindex = new int[numstates][numstates];
2978 transitionprobsnum = new int[numstates];
2979
2980 transitionprobsindexCol = new int[numstates][numstates];
2981 transitionprobsnumCol = new int[numstates];
2982
2983 //initialize the transition structure without any parameter elimination
2984 for (int ni = 0; ni < transitionprobs.length; ni++)
2985 {
2986 for (int nj = 0; nj < transitionprobs[ni].length; nj++)
2987 {
2988 elim[ni][nj] = false;
2989 transitionprobsindex[ni][nj] = nj;
2990 transitionprobsindexCol[ni][nj] = nj;
2991 }
2992 transitionprobsnum[ni] = numstates;
2993 transitionprobsnumCol[ni] = numstates;
2994 }
2995
2996 emissionprobs = new double[numstates][numdatasets][numbuckets];
2997
2998 boolean btransition0 = false;
2999
3000 while ((szLine = br.readLine())!=null)
3001 {
3002 st = new StringTokenizer(szLine,"\t");
3003 String szvartype = st.nextToken().trim();
3004
3005 if (szvartype.equalsIgnoreCase("probinit"))
3006 {
3007 //reading an inital probability
3008 int nstate = Integer.parseInt(st.nextToken().trim())-1;
3009 double dprob = Double.parseDouble(st.nextToken().trim());
3010 probinit[nstate] = dprob;
3011 }
3012 else if (szvartype.equalsIgnoreCase("transitionprobs"))
3013 {
3014 int nfrom = Integer.parseInt(st.nextToken().trim())-1;
3015 int nto = Integer.parseInt(st.nextToken().trim())-1;
3016 double dprob = Double.parseDouble(st.nextToken().trim());
3017 //this smooths the transition probability if dproceduresmmothtransition>0 using a weighted average with uniform
3018 transitionprobs[nfrom][nto] = dproceduresmoothtransition/((double) transitionprobs.length)+(1-dproceduresmoothtransition)*dprob;
3019 if (transitionprobs[nfrom][nto] == 0)
3020 {
3021 //we have a 0 transition
3022 btransition0 = true;
3023 elim[nfrom][nto] = true;
3024 }
3025 }
3026 else if (szvartype.equalsIgnoreCase("emissionprobs"))
3027 {
3028 int nstate = Integer.parseInt(st.nextToken().trim())-1;
3029 int nmod = Integer.parseInt(st.nextToken().trim());
3030 String szdataset = st.nextToken().trim();
3031 if (datasets[nmod]==null)
3032 {
3033 datasets[nmod] = szdataset;//st.nextToken().trim();
3034 }
3035 else if (!szdataset.equals(datasets[nmod]))
3036 {
3037 throw new IllegalArgumentException("For mark "+nmod+" in model file found "+szdataset+", but expecting "+datasets[nmod]+"."
3038 +" This might be because columns of binarized file are in a different order from model learning.");
3039 }
3040 int nval = Integer.parseInt(st.nextToken().trim());
3041 double dprob = Double.parseDouble(st.nextToken().trim());
3042 //smooths the emission probability if dproceduresmoothemission>0 using a weighted average with uniform
3043 emissionprobs[nstate][nmod][nval] = dproceduresmoothemission/((double) numbuckets)+(1-dproceduresmoothemission)*dprob;
3044 }
3045 else
3046 {
3047 throw new IllegalArgumentException(szvartype+" is not recognized in the input model file");
3048 }
3049 }
3050 br.close();
3051
3052 if (btransition0)
3053 {
3054 //we have a non-zero transition will update the sparse indicies
3055 for (int ni = 0; ni < transitionprobs.length; ni++)
3056 {
3057 int nindex = 0;
3058 boolean[] elim_ni = elim[ni];
3059 int[] transitionprobsindex_ni = transitionprobsindex[ni];
3060 for (int nj = 0; nj < transitionprobsindex_ni.length; nj++)
3061 {
3062 if (!elim_ni[nj])
3063 {
3064 //we have not eliminated this transition
3065 //stores its index in order and add sum to denominator
3066 transitionprobsindex_ni[nindex] = nj;
3067 nindex++;
3068 }
3069 }
3070 //update the number of valid transitions
3071 transitionprobsnum[ni] = nindex;
3072 }
3073
3074 for (int ni = 0; ni < transitionprobs.length; ni++)
3075 {
3076 int nindex =0;
3077 for (int nj = 0; nj < numstates; nj++)
3078 {
3079 if (!elim[nj][ni])
3080 {
3081 //copy into the column i the indicies of all non-eliminated transitions into i
3082 transitionprobsindexCol[ni][nindex] = nj;
3083 nindex++;
3084 }
3085 }
3086 //updates the number of non-zero transitions from column i
3087 transitionprobsnumCol[ni] = nindex;
3088 }
3089 }
3090 }
3091
3092 /**
3093 * Takes an existing model and segmentation and outputs a confusion matrix by a selected subset
3094 */
3095 public void makeSegmentationConfusion() throws IOException
3096 {
3097 NumberFormat nf = NumberFormat.getInstance();
3098 nf.setMaximumFractionDigits(4);
3099
3100 //number of non-zero transition required to be less than this at the more stringent cutoff
3101 //for trying to exploit sparsity in the transition matrix for efficiency gains
3102 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
3103
3104 int[] numtime = new int[traindataObservedIndex.length];
3105
3106 //stores the maximum number of locations in any sequence and in each sequence
3107 int nmaxtime = 0;
3108 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
3109 {
3110 numtime[nseq] = traindataObservedIndex[nseq].length;
3111 if (numtime[nseq] > nmaxtime)
3112 {
3113 nmaxtime = numtime[nseq];
3114 }
3115 }
3116
3117 //double
3118 double[][] fullposterior = null;
3119
3120 int[] fullmax = null;
3121 double[][] confusion = new double[numstates][numstates];
3122 double[][] normalizedconfusion = new double[numstates][numstates];
3123
3124 if (breadposterior)
3125 {
3126 fullposterior = new double[nmaxtime][numstates];
3127 }
3128
3129 if ((breadstatebyline)||(breadsegment))
3130 {
3131 fullmax = new int[nmaxtime];
3132 }
3133
3134
3135 if (ChromHMM.BVERBOSE)
3136 {
3137 System.out.println("Maximum number of locations\t"+nmaxtime);
3138 }
3139
3140
3141 //stores the emission probability for the i^th combination of marks in the j^th state
3142 double[][] emissionproducts = new double[traindataObservedValues.length][numstates];
3143
3144 //stores temporary product terms
3145 double[] tempproductbetaemiss = new double[numstates];
3146
3147 //This stores the alpha values at each time point and number of states
3148 double[][] alpha = new double[nmaxtime][numstates];
3149
3150 //Temporary storage of the gamma's for each state
3151 double[][] gamma = new double[nmaxtime][numstates];
3152
3153 //Temporary storage of the beta values for each state
3154 double[] beta_nt = new double[numstates];
3155
3156 //Temporary storage of the beta values for each state at the next time point
3157 double[] beta_ntp1 = new double[numstates];
3158
3159 //stores the scaling value for each time point
3160 double[] scale = new double[nmaxtime];
3161
3162 //stores the transition probabilities for each column
3163 double[][] coltransitionprobs = new double[numstates][numstates];
3164
3165 boolean[] includemarks = new boolean[numdatasets];
3166
3167 double[] surplus = new double[numstates];
3168 double[] deficit = new double[numstates];
3169 double[] dstatesagree = new double[numstates];
3170
3171 if (szincludemarks.length()!=numdatasets)
3172 {
3173 throw new IllegalArgumentException("Number of marks in "+szincludemarks+" of "+szincludemarks.length()+" does not equal expected number of "+numdatasets);
3174 }
3175
3176
3177 if ((breadstatebyline)||(breadsegment))
3178 {
3179 //stores the maximum assignment with all marks
3180 fullmax = new int[nmaxtime];
3181 }
3182 else
3183 {
3184 //stores the posterior assignment with all marks
3185 fullposterior = new double[nmaxtime][numstates];
3186 }
3187
3188 String szdatasets = "";
3189 for (int nmark = 0; nmark < includemarks.length; nmark++)
3190 {
3191 if (szincludemarks.charAt(nmark) == '1')
3192 {
3193 //stores in includemarks those data sets that have a '1' for the mark
3194 includemarks[nmark] = true;
3195 if (szdatasets.equals(""))
3196 {
3197 szdatasets += datasets[nmark];
3198 }
3199 else
3200 {
3201 szdatasets += "," + datasets[nmark];
3202 }
3203 }
3204 else if (szincludemarks.charAt(nmark) == '0')
3205 {
3206 includemarks[nmark] = false;
3207 }
3208 else
3209 {
3210 throw new IllegalArgumentException(szincludemarks+" is not a valid bit string for includemarks!");
3211 }
3212 }
3213
3214 RecIntString[] ordered = new RecIntString[chromfiles.length];
3215 for (int nindex = 0; nindex < ordered.length; nindex++)
3216 {
3217 ordered[nindex] = new RecIntString(nindex,chromfiles[nindex]);
3218 }
3219 Arrays.sort(ordered,new RecIntStringCompare());
3220
3221
3222
3223 hsprefix = new HashSet();
3224
3225 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
3226 {
3227 int nordered_nseq = ordered[nseq].nindex;
3228 //goes through each sequence
3229
3230 int[] traindataObservedIndex_nseq = traindataObservedIndex[nordered_nseq];
3231 boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nordered_nseq];
3232
3233 String szprefix = "";
3234 if (!cellSeq[nordered_nseq].equals(""))
3235 {
3236 szprefix += cellSeq[nordered_nseq]+"_";
3237 }
3238 szprefix += numstates;
3239 if (!szoutfileID.equals(""))
3240 {
3241 szprefix += "_"+szoutfileID;
3242 }
3243 hsprefix.add(szprefix);
3244
3245 if (breadposterior)
3246 {
3247 BufferedReader brprobs = null;
3248 //creates the posterior file
3249 String szposteriorinfilename = szsegmentdir+"/POSTERIOR/"+szprefix+"_"+chromSeq[nordered_nseq]+ChromHMM.SZPOSTERIOREXTENSION;
3250
3251 //updated in v.1.11 to check for gz extensions
3252 File f = new File (szposteriorinfilename);
3253 File fgz = new File (szposteriorinfilename+".gz");
3254 if ((!f.exists())&&(fgz.exists()))
3255 {
3256 szposteriorinfilename = szposteriorinfilename + ".gz";
3257 }
3258 brprobs = Util.getBufferedReader(szposteriorinfilename);// new BufferedReader(new FileReader(szposteriorinfilename));
3259
3260 //skips the header lines
3261 brprobs.readLine();
3262 brprobs.readLine();
3263 String szLinePosterior;
3264
3265 int nline = 0;
3266 while ((szLinePosterior = brprobs.readLine())!=null)
3267 {
3268 StringTokenizer stposterior = new StringTokenizer(szLinePosterior,"\t ");
3269 for (int nstate = 0; nstate < numstates; nstate++)
3270 {
3271 fullposterior[nline][nstate] = Double.parseDouble(stposterior.nextToken());
3272 }
3273 nline++;
3274 }
3275 brprobs.close();
3276 }
3277 else if (breadstatebyline)
3278 {
3279 String szcurrchrom = chromSeq[nordered_nseq];
3280 //reads a file which has the state with the maximum posterior probability
3281 String szmaxinfilename = szsegmentdir+"/STATEBYLINE/"+szprefix+"_"+szcurrchrom+ChromHMM.SZSTATEBYLINEEXTENSION;
3282
3283 //updated in v.1.11 to check for gz extensions
3284 File f = new File (szmaxinfilename);
3285 File fgz = new File (szmaxinfilename+".gz");
3286 if ((!f.exists())&&(fgz.exists()))
3287 {
3288 szmaxinfilename = szmaxinfilename + ".gz";
3289 }
3290 BufferedReader brmax = Util.getBufferedReader(szmaxinfilename);// new BufferedReader(new FileReader(szmaxinfilename));
3291 //skip the header lines
3292 brmax.readLine();
3293 brmax.readLine();
3294 String szLineMax;
3295 int nline = 0;
3296 while ((szLineMax = brmax.readLine())!=null)
3297 {
3298 fullmax[nline] = Integer.parseInt(szLineMax)-1;
3299 nline++;
3300 }
3301 brmax.close();
3302 }
3303 else if (breadsegment)
3304 {
3305
3306 BufferedReader brbed = null;
3307 //creates a file which has the maximum segmentation
3308 //we only have one file per cell type here
3309 String szcurrchrom = chromSeq[nordered_nseq];
3310
3311 String szsegmentinfilename = szsegmentdir+"/" + szprefix+ChromHMM.SZSEGMENTEXTENSION;
3312
3313 //updated in v.1.11 to check for gz extensions
3314 File f = new File (szsegmentinfilename);
3315 File fgz = new File (szsegmentinfilename+".gz");
3316 if ((!f.exists())&&(fgz.exists()))
3317 {
3318 szsegmentinfilename = szsegmentinfilename + ".gz";
3319 }
3320
3321 brbed = Util.getBufferedReader(szsegmentinfilename); // new BufferedReader(new FileReader(szsegmentinfilename));
3322
3323 String szLineMax;
3324 while ((szLineMax = brbed.readLine())!=null)
3325 {
3326 StringTokenizer stchrom = new StringTokenizer(szLineMax,"\t");
3327 String szchrom = stchrom.nextToken().trim();
3328
3329 if (szchrom.equals(szcurrchrom))
3330 {
3331 int nbegin = Integer.parseInt(stchrom.nextToken().trim())/nbinsize;
3332 int nend = (Integer.parseInt(stchrom.nextToken().trim())-1)/nbinsize;
3333 int nstate = Integer.parseInt(stchrom.nextToken().trim().substring(1))-1;
3334 for (int nj = nbegin; nj <= nend; nj++)
3335 {
3336 fullmax[nj] = nstate;
3337 }
3338 }
3339 }
3340 brbed.close();
3341 }
3342
3343
3344 if (bscaleemissions)
3345 {
3346 for (int ni = 0; ni < emissionproducts.length; ni++)
3347 {
3348 //going through each combination of marks
3349 if (traindataObservedSeqFlags_nseq[ni])
3350 {
3351 //this signature of marks is observed on the current chromosome so
3352 //updating its emission probabilities
3353 double[] emissionproducts_ni = emissionproducts[ni];
3354 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
3355 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
3356
3357 for (int ns = 0; ns < numstates; ns++)
3358 {
3359 emissionproducts_ni[ns] = 1;
3360 }
3361
3362 for (int nmod = 0; nmod < numdatasets; nmod++)
3363 {
3364 for (int ns = 0; ns < numstates; ns++)
3365 {
3366 if ((traindataNotMissing_ni[nmod])&&(includemarks[nmod]))
3367 {
3368 //we are include this marks emission probability
3369 if (traindataObservedValues_ni[nmod])
3370 {
3371 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
3372 }
3373 else
3374 {
3375 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
3376 }
3377 }
3378 // otherwise treated as missing omitting from product
3379 }
3380
3381 double dmaxval = 0;
3382 for (int ns = 0; ns < numstates; ns++)
3383 {
3384 if (emissionproducts_ni[ns] > dmaxval)
3385 {
3386 dmaxval = emissionproducts_ni[ns];
3387 }
3388 }
3389
3390 if (dmaxval <= 0)
3391 {
3392 for (int ns = 0; ns < numstates; ns++)
3393 {
3394 emissionproducts_ni[ns] = 1;
3395 }
3396 }
3397 else
3398 {
3399 for (int ns = 0; ns < numstates; ns++)
3400 {
3401 emissionproducts_ni[ns]/= dmaxval;
3402 }
3403 }
3404 }
3405 }
3406 }
3407 }
3408 else
3409 {
3410 for (int ni = 0; ni < emissionproducts.length; ni++)
3411 {
3412 //going through each combination of marks
3413 if (traindataObservedSeqFlags_nseq[ni])
3414 {
3415 //this signature of marks is observed on the current chromosome so
3416 //updating its emission probabilities
3417 double[] emissionproducts_ni = emissionproducts[ni];
3418 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
3419 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
3420 boolean ballzero = true;
3421
3422 for (int ns = 0; ns < numstates; ns++)
3423 {
3424 double dproduct = 1;
3425 double[][] emissionprobs_ni = emissionprobs[ns];
3426
3427 //going through all marks
3428 for (int nmod = 0; nmod < numdatasets; nmod++)
3429 {
3430 if ((traindataNotMissing_ni[nmod])&&(includemarks[nmod]))
3431 {
3432 //we have observed the mark
3433 if (traindataObservedValues_ni[nmod])
3434 {
3435 dproduct *= emissionprobs_ni[nmod][1];
3436 }
3437 else
3438 {
3439 dproduct *= emissionprobs_ni[nmod][0];
3440 }
3441 }
3442 // otherwise treated as missing omitting from product
3443 }
3444 emissionproducts_ni[ns] = dproduct;
3445
3446 if (dproduct >= EPSILONEMISSIONS)
3447 {
3448 ballzero = false;
3449 }
3450 }
3451
3452 if (ballzero)
3453 {
3454 for (int ns = 0; ns < numstates; ns++)
3455 {
3456 emissionproducts_ni[ns] = EPSILONEMISSIONS;
3457 }
3458 }
3459 }
3460 }
3461 }
3462
3463 //initial probability in state s is initial probability times emission probability at first position
3464 double[] alpha_nt = alpha[0];
3465 double dscale = 0;
3466 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex_nseq[0]];
3467 for (int ns = 0; ns < numstates; ns++)
3468 {
3469 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
3470 dscale += alpha_nt[ns];
3471 }
3472 scale[0] = dscale;
3473
3474 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
3475 //converts the alpha terms to probabilities
3476
3477 if (bscalebeta)
3478 {
3479
3480 if (dscale == 0)
3481 {
3482 for (int ns = 0; ns < numstates; ns++)
3483 {
3484 //added
3485 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
3486 {
3487 alpha_nt[ns] = EPSILONSTATE;
3488 dscale += EPSILONSTATE;
3489 }
3490 }
3491 scale[0] = dscale;
3492 }
3493
3494 for (int ns = 0; ns < numstates; ns++)
3495 {
3496 alpha_nt[ns] /= dscale;
3497
3498 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))// (ns < numstates-1)))
3499 {
3500 alpha_nt[ns] = EPSILONSTATE;
3501 }
3502 }
3503 }
3504 else
3505 {
3506 for (int ns = 0; ns < numstates; ns++)
3507 {
3508 alpha_nt[ns] /= dscale;
3509 }
3510 }
3511 //for (int ni = 0; ni < numstates; ni++)
3512 //{
3513 // alpha_nt[ni] /= dscale;
3514 //}
3515
3516 //stores in coltransitionprobs the transpose of transitionprobs
3517 for (int ni = 0; ni < numstates; ni++)
3518 {
3519 double[] coltransitionprobs_ni = coltransitionprobs[ni];
3520 for (int nj = 0; nj < numstates; nj++)
3521 {
3522 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
3523 }
3524 }
3525
3526 //forward step
3527 int numtime_nseq = numtime[nordered_nseq];
3528 for (int nt = 1; nt < numtime_nseq; nt++)
3529 {
3530 //the actual observed combination at position t
3531 double[] alpha_ntm1 = alpha[nt-1];
3532 alpha_nt = alpha[nt];
3533
3534 dscale = 0;
3535 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex_nseq[nt]];
3536 for (int ns = 0; ns < numstates; ns++)
3537 {
3538 //going through each state
3539
3540 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
3541 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
3542 double[] coltransitionprobs_ns = coltransitionprobs[ns];
3543
3544 double dtempsum = 0;
3545 if (transitionprobsnumCol_ns < nsparsecutoff)
3546 {
3547 //if it is sparse enough then it is worth the extra array indirection here
3548 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
3549 {
3550 //for each next state computing inner sum of all previous alpha and the transition probability
3551 //for all non-zero transitions into the state
3552 int nmappedindex = transitionprobsindexCol_ns[nj];
3553 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
3554 }
3555 }
3556 else
3557 {
3558 for (int nj = 0; nj < numstates; nj++)
3559 {
3560 //for each next state computing inner sum of all previous alpha and the transition probability
3561 //for all transitions into the state
3562 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
3563 }
3564 }
3565
3566 //multiply the transition sum by the emission probability
3567 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
3568 alpha_nt[ns] = dalphaval;
3569 dscale += dalphaval;
3570 }
3571
3572 //rescaling alpha
3573 scale[nt] = dscale;
3574 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
3575
3576 if (bscalebeta)
3577 {
3578 if (dscale == 0)
3579 {
3580 for (int ns = 0; ns < numstates; ns++)
3581 {
3582 //added
3583 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
3584 {
3585 alpha_nt[ns] = EPSILONSTATE;
3586 dscale += EPSILONSTATE;
3587 }
3588 }
3589 scale[nt] = dscale;
3590 }
3591
3592 for (int ns = 0; ns < numstates; ns++)
3593 {
3594 alpha_nt[ns] /= dscale;
3595
3596 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
3597 {
3598 alpha_nt[ns] = EPSILONSTATE;
3599 }
3600 }
3601 }
3602 else
3603 {
3604 for (int ns = 0; ns < numstates; ns++)
3605 {
3606 alpha_nt[ns] /= dscale;
3607 }
3608 }
3609 //for (int ns = 0; ns < numstates; ns++)
3610 //{
3611 // alpha_nt[ns] /= dscale;
3612 //}
3613 }
3614
3615 //backward step
3616 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
3617 int nlastindex = numtime_nseq-1;
3618 double dinitval;
3619 if (bscalebeta)
3620 {
3621 dinitval = 1.0/numstates;
3622 }
3623 else
3624 {
3625 dinitval = 1.0/scale[nlastindex];
3626 }
3627
3628 for (int ns = 0; ns < numstates; ns++)
3629 {
3630 beta_ntp1[ns] = dinitval;
3631 }
3632 //double dinitval = 1.0/scale[nlastindex];
3633 //for (int ns = 0; ns < numstates; ns++)
3634 //{
3635 // beta_ntp1[ns] = dinitval;
3636 //}
3637
3638 int nmappedindexouter;
3639
3640 double ddenom = 0;
3641
3642 //gamma_nt - P(x=S| o_0,...,o_t)
3643 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,x_t=s|lambda)
3644 double[] gamma_nt = gamma[nlastindex];
3645 for (int ns = 0; ns < gamma_nt.length; ns++)
3646 {
3647 double dval = alpha[nlastindex][ns]*beta_ntp1[ns];
3648 ddenom += dval;
3649 gamma_nt[ns] = dval;
3650 }
3651
3652 if (ddenom > 0)
3653 {
3654 for (int ns = 0; ns < gamma_nt.length; ns++)
3655 {
3656 gamma_nt[ns] /= ddenom;
3657 }
3658 }
3659
3660
3661 for (int nt = nlastindex - 1; nt >= 0; nt--)
3662 {
3663 gamma_nt = gamma[nt];
3664 int ntp1 = (nt+1);
3665
3666 double[] emissionproducts_ncombo_ntp1 = emissionproducts[traindataObservedIndex_nseq[ntp1]];
3667
3668 double dsumbeta = 0;
3669 double dscale_nt = scale[nt];
3670
3671 for (int ns = 0; ns < numstates; ns++)
3672 {
3673 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_ncombo_ntp1[ns];
3674 }
3675
3676 if (bscaleemissions)
3677 {
3678 //adding here to help numerical stability
3679 double dmaxval = 0;
3680 for (int ns = 0; ns < numstates; ns++)
3681 {
3682 if (tempproductbetaemiss[ns] > dmaxval)
3683 {
3684 dmaxval = tempproductbetaemiss[ns];
3685 }
3686 }
3687 for (int ns = 0; ns < numstates; ns++)
3688 {
3689 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
3690 }
3691 }
3692
3693 //double dscaleinv = 1.0/scale[nt];
3694 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
3695 for (int ni = 0; ni < numstates; ni++)
3696 {
3697 double dtempsum = 0;
3698 int[] transitionprobsindex_ni = transitionprobsindex[ni];
3699 double[] transitionprobs_ni = transitionprobs[ni];
3700 int transitionprobsnum_ni = transitionprobsnum[ni];
3701
3702 if (transitionprobsnum_ni < nsparsecutoff)
3703 {
3704 //if it is sparse enough then it is worth the extra array indirection here
3705 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
3706 {
3707 //for each state summing over transition probability to state j, emission probablity in j at next step
3708 //and probability of observing the remaining sequence
3709 nmappedindexouter = transitionprobsindex_ni[nj];
3710 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
3711 }
3712 }
3713 else
3714 {
3715 for (int nj = 0; nj < numstates; nj++)
3716 {
3717 //for each state summing over transition probability to state j, emission probablity in j at next step
3718 //and probability of observing the remaining sequence
3719 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
3720 }
3721 }
3722
3723 if (bscalebeta)
3724 {
3725 beta_nt[ni] = dtempsum;
3726 dsumbeta += dtempsum;
3727 }
3728 else
3729 {
3730 double dratio = dtempsum/dscale_nt;
3731 if (dratio > Double.MAX_VALUE)
3732 {
3733 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
3734 }
3735 else
3736 {
3737 beta_nt[ni] = dratio;
3738 }
3739 }
3740
3741 //double dratio = dtempsum/dscale_nt;
3742 //if (dratio > Double.MAX_VALUE)
3743 //{
3744 // beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
3745 //}
3746 //else
3747 //{
3748 // beta_nt[ni] = dratio;// dtempsum/dscale_nt;
3749 //}
3750 }
3751
3752 if (bscalebeta)
3753 {
3754 for (int ni = 0; ni < numstates; ni++)
3755 {
3756 beta_nt[ni]/= dsumbeta;
3757
3758 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
3759 {
3760 beta_nt[ni] = EPSILONSTATE;
3761 }
3762 }
3763 }
3764
3765 ddenom = 0;
3766 alpha_nt = alpha[nt];
3767
3768 //gamma_nt - P(x=S| o_0,...,o_t)
3769 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
3770
3771 for (int ns = 0; ns < gamma_nt.length; ns++)
3772 {
3773 double dval = alpha_nt[ns]*beta_nt[ns];
3774
3775 ddenom += dval;
3776 gamma_nt[ns] = dval;
3777 }
3778
3779 if (ddenom > 0)
3780 {
3781 for (int ns = 0; ns < gamma_nt.length; ns++)
3782 {
3783 gamma_nt[ns]/=ddenom;
3784 }
3785 }
3786 beta_ntp1 = beta_nt;
3787 }
3788
3789
3790 for (int nt = 0; nt < numtime_nseq; nt++)
3791 {
3792
3793 gamma_nt = gamma[nt];
3794
3795 //handling the first line
3796 if ((breadsegment)||(breadstatebyline))
3797 {
3798 double dmaxval = 0;
3799 int nmaxstate = 0;
3800
3801 for (int ns = 0; ns < gamma_nt.length; ns++)
3802 {
3803 double dprob = gamma_nt[ns];
3804
3805 if (dprob > dmaxval)
3806 {
3807 //best one found so far
3808 dmaxval = dprob;
3809 nmaxstate = ns;
3810 }
3811 }
3812
3813 confusion[fullmax[nt]][nmaxstate]++;
3814 }
3815 else
3816 {
3817 double[] fullposterior_nt = fullposterior[nt];
3818 for (int nstate = 0; nstate < numstates; nstate++)
3819 {
3820 double dfullval = fullposterior_nt[nstate];
3821 double dpartialval = gamma_nt[nstate];
3822 if (dfullval >= dpartialval)
3823 {
3824 //assigned less to this state with the subset of the marks adding that amount to the decifict
3825 dstatesagree[nstate] += dpartialval;
3826 deficit[nstate] = dfullval - dpartialval;
3827 surplus[nstate] = 0;
3828 }
3829 else
3830 {
3831 //we have a surplus of posterior assigned to this state with a subset of marks
3832 dstatesagree[nstate] += dfullval;
3833 surplus[nstate] = dpartialval - dfullval;
3834 deficit[nstate] = 0;
3835 }
3836 }
3837
3838 double dsumdenom = 0;
3839 for (int nb = 0; nb < surplus.length; nb++)
3840 {
3841 dsumdenom += surplus[nb];
3842 }
3843 for (int nb = 0; nb < surplus.length; nb++)
3844 {
3845 //re-normalize surplus
3846 surplus[nb] /= dsumdenom;
3847 }
3848
3849 for (int nb = 0; nb < confusion.length; nb++)
3850 {
3851 double[] confusion_nb = confusion[nb];
3852 if (deficit[nb] > 0)
3853 {
3854 double ddeficit_nb = deficit[nb];
3855 for (int nc = 0; nc < confusion_nb.length; nc++)
3856 {
3857 confusion_nb[nc] += ddeficit_nb*surplus[nc];
3858 //there is a deficit for state nb with the subset of marks
3859 //allocating it to the states that proportionally have additional posterior
3860 }
3861 }
3862 }
3863
3864 for (int nb = 0; nb < confusion.length; nb++)
3865 {
3866 confusion[nb][nb] = dstatesagree[nb];
3867 }
3868 }
3869 }
3870 }
3871
3872 System.out.println("Writing to file "+szconfusionfileprefix+".txt");
3873 if (bprintimage)
3874 {
3875 System.out.println("Writing to file "+szconfusionfileprefix+".svg");
3876 System.out.println("Writing to file "+szconfusionfileprefix+".png");
3877 }
3878 PrintWriter pwconfusion = new PrintWriter(new FileWriter(szconfusionfileprefix+".txt",bappend));
3879 pwconfusion.print("EvalSubset\t"+szincludemarks);
3880 pwconfusion.println("\t"+szdatasets);
3881
3882 for (int na = 0; na < confusion.length; na++)
3883 {
3884 pwconfusion.print("\t"+chorder+(na+1));
3885 }
3886 pwconfusion.println();
3887
3888 for (int na = 0; na < confusion.length; na++)
3889 {
3890 pwconfusion.print(""+chorder+(na+1));
3891 double ddenom = 0;
3892 for (int nb = 0; nb < confusion[na].length; nb++)
3893 {
3894 ddenom += confusion[na][nb];
3895 }
3896
3897 for (int nb = 0; nb < confusion[na].length; nb++)
3898 {
3899 normalizedconfusion[na][nb] = confusion[na][nb]/(double) ddenom;
3900 pwconfusion.print("\t"+nf.format(normalizedconfusion[na][nb]));
3901 }
3902 pwconfusion.println();
3903 }
3904 pwconfusion.close();
3905 if (bprintimage)
3906 {
3907 printConfusionImage(normalizedconfusion, szconfusionfileprefix, szincludemarks);
3908 }
3909 }
3910
3911
3912 /**
3913 * Takes an existing model and segmentation and outputs a confusion matrix by a selected subset
3914 */
3915 public void makeSegmentationConfusionWithLoad() throws IOException
3916 {
3917 //added in 1.15
3918 NumberFormat nf = NumberFormat.getInstance();
3919 nf.setMaximumFractionDigits(4);
3920
3921 //number of non-zero transition required to be less than this at the more stringent cutoff
3922 //for trying to exploit sparsity in the transition matrix for efficiency gains
3923 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
3924
3925 //int[] numtime = new int[traindataObservedIndex.length];
3926
3927 //stores the maximum number of locations in any sequence and in each sequence
3928 int nmaxtime = 0;
3929 for (int nseq = 0; nseq < numtime.length; nseq++)
3930 {
3931 //numtime[nseq] = traindataObservedIndex[nseq].length;
3932 if (numtime[nseq] > nmaxtime)
3933 {
3934 nmaxtime = numtime[nseq];
3935 }
3936 }
3937
3938 //double
3939 double[][] fullposterior = null;
3940
3941 int[] fullmax = null;
3942 double[][] confusion = new double[numstates][numstates];
3943 double[][] normalizedconfusion = new double[numstates][numstates];
3944
3945 if (breadposterior)
3946 {
3947 fullposterior = new double[nmaxtime][numstates];
3948 }
3949
3950 if ((breadstatebyline)||(breadsegment))
3951 {
3952 fullmax = new int[nmaxtime];
3953 }
3954
3955
3956 if (ChromHMM.BVERBOSE)
3957 {
3958 System.out.println("Maximum number of locations\t"+nmaxtime);
3959 }
3960
3961
3962 //stores the emission probability for the i^th combination of marks in the j^th state
3963 double[][] emissionproducts = new double[nmaxtime][numstates]; //previously traindataObservedValues.length
3964
3965 //stores temporary product terms
3966 double[] tempproductbetaemiss = new double[numstates];
3967
3968 //This stores the alpha values at each time point and number of states
3969 double[][] alpha = new double[nmaxtime][numstates];
3970
3971 //Temporary storage of the gamma's for each state
3972 double[][] gamma = new double[nmaxtime][numstates];
3973
3974 //Temporary storage of the beta values for each state
3975 double[] beta_nt = new double[numstates];
3976
3977 //Temporary storage of the beta values for each state at the next time point
3978 double[] beta_ntp1 = new double[numstates];
3979
3980 //stores the scaling value for each time point
3981 double[] scale = new double[nmaxtime];
3982
3983 //stores the transition probabilities for each column
3984 double[][] coltransitionprobs = new double[numstates][numstates];
3985
3986
3987 //stores the indicies of the data
3988 int[] traindataObservedIndex = new int[nmaxtime];
3989
3990 //saving the mapping of signatures and chromsome observed on
3991 //stores whether there is a present call at each location
3992 boolean[][] traindataObservedValues = new boolean[nmaxtime][numdatasets];
3993
3994 //stores whether the mark is not considered missing
3995 boolean[][] traindataNotMissing = new boolean[nmaxtime][numdatasets]; //usually nobserved
3996
3997 boolean[] includemarks = new boolean[numdatasets];
3998
3999 double[] surplus = new double[numstates];
4000 double[] deficit = new double[numstates];
4001 double[] dstatesagree = new double[numstates];
4002
4003 if (szincludemarks.length()!=numdatasets)
4004 {
4005 throw new IllegalArgumentException("Number of marks in "+szincludemarks+" of "+szincludemarks.length()+" does not equal expected number of "+numdatasets);
4006 }
4007
4008
4009 if ((breadstatebyline)||(breadsegment))
4010 {
4011 //stores the maximum assignment with all marks
4012 fullmax = new int[nmaxtime];
4013 }
4014 else
4015 {
4016 //stores the posterior assignment with all marks
4017 fullposterior = new double[nmaxtime][numstates];
4018 }
4019
4020 String szdatasets = "";
4021 for (int nmark = 0; nmark < includemarks.length; nmark++)
4022 {
4023 if (szincludemarks.charAt(nmark) == '1')
4024 {
4025 //stores in includemarks those data sets that have a '1' for the mark
4026 includemarks[nmark] = true;
4027 if (szdatasets.equals(""))
4028 {
4029 szdatasets += datasets[nmark];
4030 }
4031 else
4032 {
4033 szdatasets += "," + datasets[nmark];
4034 }
4035 }
4036 else if (szincludemarks.charAt(nmark) == '0')
4037 {
4038 includemarks[nmark] = false;
4039 }
4040 else
4041 {
4042 throw new IllegalArgumentException(szincludemarks+" is not a valid bit string for includemarks!");
4043 }
4044 }
4045
4046 RecIntString[] ordered = new RecIntString[chromfiles.length];
4047 for (int nindex = 0; nindex < ordered.length; nindex++)
4048 {
4049 ordered[nindex] = new RecIntString(nindex,chromfiles[nindex]);
4050 }
4051 Arrays.sort(ordered,new RecIntStringCompare());
4052
4053
4054
4055 hsprefix = new HashSet();
4056
4057 for (int nseq = 0; nseq < chromfiles.length; nseq++) // traindataObservedIndex.length
4058 {
4059 int nordered_nseq = ordered[nseq].nindex;
4060 //goes through each sequence
4061
4062 ///////////////////////////////////////////////////////////////////////////////
4063 //load data here
4064
4065 HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
4066
4067 int nobserved = 0;
4068
4069 if (ChromHMM.BVERBOSE)
4070 {
4071 System.out.println("reading\t"+szinputdir+" "+chromfiles[nordered_nseq]);
4072 }
4073 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nordered_nseq]); //fixed bug was chromfiles[nseq]
4074 String szLine;
4075 br.readLine(); //first line tells cell type and chromosome
4076 br.readLine();//flush mark header
4077
4078 ArrayList aldata = new ArrayList();
4079 while ((szLine = br.readLine())!=null)
4080 {
4081 StringTokenizer st = new StringTokenizer(szLine,"\t ");
4082 StringBuffer sb = new StringBuffer();
4083
4084 for (int ncol = 0; ncol < numdatasets; ncol++)
4085 {
4086 if (!st.hasMoreTokens())
4087 {
4088 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nordered_nseq]);
4089 }
4090
4091 String sztoken = st.nextToken();//.trim();
4092
4093 if (sztoken.equals("0"))
4094 {
4095 sb.append("0");
4096 }
4097 else if (sztoken.equals("1"))
4098 {
4099 sb.append("1");
4100 }
4101 else if (sztoken.equals("2"))
4102 {
4103 //this means missing
4104 sb.append("2");
4105 }
4106 else
4107 {
4108 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nordered_nseq]);
4109 }
4110 }
4111 aldata.add(sb.toString());
4112 }
4113 br.close();
4114
4115 int nsize = aldata.size();
4116
4117 for (int nrow = 0; nrow < nsize; nrow++)
4118 {
4119 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
4120 Integer theObservedInt = (Integer) hmObserved.get(theBigInteger);
4121 //boolean[] flagA;
4122
4123 if (theObservedInt == null)
4124 {
4125 //System.out.println(szmappingbyte.length());
4126 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
4127 hmObserved.put(theBigInteger, Integer.valueOf(nobserved));
4128
4129 //saving this observed index
4130 traindataObservedIndex[nrow] = nobserved;
4131
4132 //increments the number of observed combinations of marks
4133 nobserved++;
4134 }
4135 else
4136 {
4137 //storing the index of the flags associated with this row
4138 traindataObservedIndex[nrow] = ((Integer) theObservedInt).intValue();
4139 }
4140 }
4141
4142 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
4143 while (hmObservedIterator.hasNext())
4144 {
4145 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
4146 BigInteger theBigInteger = (BigInteger) pairs.getKey();
4147 String szmapping = theBigInteger.toString(3); //getting back the mapping string
4148
4149 //ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
4150 int ncurrindex = ((Integer) pairs.getValue()).intValue();// theObservedRec.nobserved;//this is an index on which obervation combination it is
4151
4152 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
4153 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
4154
4155 //if the mapping string is less than the number of data sets then
4156 //there are leading 0's will set for leading 0's not missing and absent
4157 int numch = szmapping.length();
4158 int numleading0 = numdatasets - numch;
4159 for (int nj = 0; nj < numleading0; nj++)
4160 {
4161 traindataObservedValues_ncurrindex[nj] = false;
4162 traindataNotMissing_ncurrindex[nj] = true;
4163 }
4164
4165 int nmappedindex = numleading0; //starting from the leading 0 position
4166 for (int nj = 0; nj < numch; nj++)
4167 {
4168 char ch = szmapping.charAt(nj);
4169
4170 if (ch == '0')
4171 {
4172 traindataObservedValues_ncurrindex[nmappedindex] = false;
4173 traindataNotMissing_ncurrindex[nmappedindex] = true;
4174 }
4175 else if (ch=='1')
4176 {
4177 traindataObservedValues_ncurrindex[nmappedindex] = true;
4178 traindataNotMissing_ncurrindex[nmappedindex] = true;
4179 }
4180 else
4181 {
4182 //missing data
4183 traindataObservedValues_ncurrindex[nmappedindex] = false;
4184 traindataNotMissing_ncurrindex[nmappedindex] = false;
4185 }
4186 nmappedindex++;
4187 }
4188 }
4189
4190
4191 //int[] traindataObservedIndex_nseq = traindataObservedIndex[nordered_nseq];
4192 //boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nordered_nseq];
4193
4194 String szprefix = "";
4195 if (!cellSeq[nordered_nseq].equals(""))
4196 {
4197 szprefix += cellSeq[nordered_nseq]+"_";
4198 }
4199 szprefix += numstates;
4200 if (!szoutfileID.equals(""))
4201 {
4202 szprefix += "_"+szoutfileID;
4203 }
4204 hsprefix.add(szprefix);
4205
4206 if (breadposterior)
4207 {
4208 BufferedReader brprobs = null;
4209 //creates the posterior file
4210 String szposteriorinfilename = szsegmentdir+"/POSTERIOR/"+szprefix+"_"+chromSeq[nordered_nseq]+ChromHMM.SZPOSTERIOREXTENSION;
4211
4212 //updated in v.1.11 to check for gz extensions
4213 File f = new File (szposteriorinfilename);
4214 File fgz = new File (szposteriorinfilename+".gz");
4215 if ((!f.exists())&&(fgz.exists()))
4216 {
4217 szposteriorinfilename = szposteriorinfilename + ".gz";
4218 }
4219 brprobs = Util.getBufferedReader(szposteriorinfilename);// new BufferedReader(new FileReader(szposteriorinfilename));
4220
4221 //skips the header lines
4222 brprobs.readLine();
4223 brprobs.readLine();
4224 String szLinePosterior;
4225
4226 int nline = 0;
4227 while ((szLinePosterior = brprobs.readLine())!=null)
4228 {
4229 StringTokenizer stposterior = new StringTokenizer(szLinePosterior,"\t ");
4230 for (int nstate = 0; nstate < numstates; nstate++)
4231 {
4232 fullposterior[nline][nstate] = Double.parseDouble(stposterior.nextToken());
4233 }
4234 nline++;
4235 }
4236 brprobs.close();
4237 }
4238 else if (breadstatebyline)
4239 {
4240 String szcurrchrom = chromSeq[nordered_nseq];
4241 //reads a file which has the state with the maximum posterior probability
4242 String szmaxinfilename = szsegmentdir+"/STATEBYLINE/"+szprefix+"_"+szcurrchrom+ChromHMM.SZSTATEBYLINEEXTENSION;
4243
4244 //updated in v.1.11 to check for gz extensions
4245 File f = new File (szmaxinfilename);
4246 File fgz = new File (szmaxinfilename+".gz");
4247 if ((!f.exists())&&(fgz.exists()))
4248 {
4249 szmaxinfilename = szmaxinfilename + ".gz";
4250 }
4251 BufferedReader brmax = Util.getBufferedReader(szmaxinfilename);// new BufferedReader(new FileReader(szmaxinfilename));
4252 //skip the header lines
4253 brmax.readLine();
4254 brmax.readLine();
4255 String szLineMax;
4256 int nline = 0;
4257 while ((szLineMax = brmax.readLine())!=null)
4258 {
4259 fullmax[nline] = Integer.parseInt(szLineMax)-1;
4260 nline++;
4261 }
4262 brmax.close();
4263 }
4264 else if (breadsegment)
4265 {
4266
4267 BufferedReader brbed = null;
4268 //creates a file which has the maximum segmentation
4269 //we only have one file per cell type here
4270 String szcurrchrom = chromSeq[nordered_nseq];
4271
4272 String szsegmentinfilename = szsegmentdir+"/" + szprefix+ChromHMM.SZSEGMENTEXTENSION;
4273
4274 //updated in v.1.11 to check for gz extensions
4275 File f = new File (szsegmentinfilename);
4276 File fgz = new File (szsegmentinfilename+".gz");
4277 if ((!f.exists())&&(fgz.exists()))
4278 {
4279 szsegmentinfilename = szsegmentinfilename + ".gz";
4280 }
4281
4282 brbed = Util.getBufferedReader(szsegmentinfilename); // new BufferedReader(new FileReader(szsegmentinfilename));
4283
4284 String szLineMax;
4285 while ((szLineMax = brbed.readLine())!=null)
4286 {
4287 StringTokenizer stchrom = new StringTokenizer(szLineMax,"\t");
4288 String szchrom = stchrom.nextToken().trim();
4289
4290 if (szchrom.equals(szcurrchrom))
4291 {
4292 int nbegin = Integer.parseInt(stchrom.nextToken().trim())/nbinsize;
4293 int nend = (Integer.parseInt(stchrom.nextToken().trim())-1)/nbinsize;
4294 int nstate = Integer.parseInt(stchrom.nextToken().trim().substring(1))-1;
4295 for (int nj = nbegin; nj <= nend; nj++)
4296 {
4297 fullmax[nj] = nstate;
4298 }
4299 }
4300 }
4301 brbed.close();
4302 }
4303
4304
4305 if (bscaleemissions)
4306 {
4307 for (int ni = 0; ni < nobserved; ni++) //emissionproducts.length
4308 {
4309 //going through each combination of marks
4310 //if (traindataObservedSeqFlags_nseq[ni])
4311 //{
4312 //this signature of marks is observed on the current chromosome so
4313 //updating its emission probabilities
4314 double[] emissionproducts_ni = emissionproducts[ni];
4315 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
4316 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
4317
4318 for (int ns = 0; ns < numstates; ns++)
4319 {
4320 emissionproducts_ni[ns] = 1;
4321 }
4322
4323 for (int nmod = 0; nmod < numdatasets; nmod++)
4324 {
4325 for (int ns = 0; ns < numstates; ns++)
4326 {
4327 if ((traindataNotMissing_ni[nmod])&&(includemarks[nmod]))
4328 {
4329 //we are include this marks emission probability
4330 if (traindataObservedValues_ni[nmod])
4331 {
4332 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
4333 }
4334 else
4335 {
4336 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
4337 }
4338 }
4339 // otherwise treated as missing omitting from product
4340 }
4341
4342 double dmaxval = 0;
4343 for (int ns = 0; ns < numstates; ns++)
4344 {
4345 if (emissionproducts_ni[ns] > dmaxval)
4346 {
4347 dmaxval = emissionproducts_ni[ns];
4348 }
4349 }
4350
4351 if (dmaxval <= 0)
4352 {
4353 for (int ns = 0; ns < numstates; ns++)
4354 {
4355 emissionproducts_ni[ns] = 1;
4356 }
4357 }
4358 else
4359 {
4360 for (int ns = 0; ns < numstates; ns++)
4361 {
4362 emissionproducts_ni[ns]/= dmaxval;
4363 }
4364 }
4365 }
4366 }
4367 //}
4368 }
4369 else
4370 {
4371 for (int ni = 0; ni < nobserved; ni++)
4372 {
4373 //going through each combination of marks
4374 //if (traindataObservedSeqFlags_nseq[ni])
4375 //{
4376 //this signature of marks is observed on the current chromosome so
4377 //updating its emission probabilities
4378 double[] emissionproducts_ni = emissionproducts[ni];
4379 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
4380 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
4381 boolean ballzero = true;
4382
4383 for (int ns = 0; ns < numstates; ns++)
4384 {
4385 double dproduct = 1;
4386 double[][] emissionprobs_ni = emissionprobs[ns];
4387
4388 //going through all marks
4389 for (int nmod = 0; nmod < numdatasets; nmod++)
4390 {
4391 if ((traindataNotMissing_ni[nmod])&&(includemarks[nmod]))
4392 {
4393 //we have observed the mark
4394 if (traindataObservedValues_ni[nmod])
4395 {
4396 dproduct *= emissionprobs_ni[nmod][1];
4397 }
4398 else
4399 {
4400 dproduct *= emissionprobs_ni[nmod][0];
4401 }
4402 }
4403 // otherwise treated as missing omitting from product
4404 }
4405 emissionproducts_ni[ns] = dproduct;
4406
4407 if (dproduct >= EPSILONEMISSIONS)
4408 {
4409 ballzero = false;
4410 }
4411 }
4412
4413 if (ballzero)
4414 {
4415 for (int ns = 0; ns < numstates; ns++)
4416 {
4417 emissionproducts_ni[ns] = EPSILONEMISSIONS;
4418 }
4419 }
4420 }
4421 }
4422
4423 //initial probability in state s is initial probability times emission probability at first position
4424 double[] alpha_nt = alpha[0];
4425 double dscale = 0;
4426 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex[0]];
4427 for (int ns = 0; ns < numstates; ns++)
4428 {
4429 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
4430 dscale += alpha_nt[ns];
4431 }
4432 scale[0] = dscale;
4433
4434 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
4435 //converts the alpha terms to probabilities
4436 if (bscalebeta)
4437 {
4438 if (dscale == 0)
4439 {
4440 for (int ns = 0; ns < numstates; ns++)
4441 {
4442 //added
4443 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
4444 {
4445 alpha_nt[ns] = EPSILONSTATE;
4446 dscale += EPSILONSTATE;
4447 }
4448 }
4449 scale[0] = dscale;
4450 }
4451
4452 for (int ns = 0; ns < numstates; ns++)
4453 {
4454 alpha_nt[ns] /= dscale;
4455
4456 if ((alpha_nt[ns] < EPSILONSTATE)&& (emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
4457 {
4458 alpha_nt[ns] = EPSILONSTATE;
4459 }
4460 }
4461 }
4462 else
4463 {
4464 for (int ns = 0; ns < numstates; ns++)
4465 {
4466 alpha_nt[ns] /= dscale;
4467 }
4468 }
4469 //for (int ni = 0; ni < numstates; ni++)
4470 //{
4471 // alpha_nt[ni] /= dscale;
4472 //}
4473
4474 //stores in coltransitionprobs the transpose of transitionprobs
4475 for (int ni = 0; ni < numstates; ni++)
4476 {
4477 double[] coltransitionprobs_ni = coltransitionprobs[ni];
4478 for (int nj = 0; nj < numstates; nj++)
4479 {
4480 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
4481 }
4482 }
4483
4484 //forward step
4485 int numtime_nseq = numtime[nordered_nseq];
4486 for (int nt = 1; nt < numtime_nseq; nt++)
4487 {
4488 //the actual observed combination at position t
4489 double[] alpha_ntm1 = alpha[nt-1];
4490 alpha_nt = alpha[nt];
4491
4492 dscale = 0;
4493 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex[nt]];
4494 for (int ns = 0; ns < numstates; ns++)
4495 {
4496 //going through each state
4497
4498 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
4499 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
4500 double[] coltransitionprobs_ns = coltransitionprobs[ns];
4501
4502 double dtempsum = 0;
4503 if (transitionprobsnumCol_ns < nsparsecutoff)
4504 {
4505 //if it is sparse enough then it is worth the extra array indirection here
4506 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
4507 {
4508 //for each next state computing inner sum of all previous alpha and the transition probability
4509 //for all non-zero transitions into the state
4510 int nmappedindex = transitionprobsindexCol_ns[nj];
4511 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
4512 }
4513 }
4514 else
4515 {
4516 for (int nj = 0; nj < numstates; nj++)
4517 {
4518 //for each next state computing inner sum of all previous alpha and the transition probability
4519 //for all transitions into the state
4520 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
4521 }
4522 }
4523
4524 //multiply the transition sum by the emission probability
4525 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
4526 alpha_nt[ns] = dalphaval;
4527 dscale += dalphaval;
4528 }
4529
4530 //rescaling alpha
4531 scale[nt] = dscale;
4532 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
4533
4534 if (bscalebeta)
4535 {
4536 if (dscale == 0)
4537 {
4538 for (int ns = 0; ns < numstates; ns++)
4539 {
4540 //added
4541 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
4542 {
4543 alpha_nt[ns] = EPSILONSTATE;
4544 dscale += EPSILONSTATE;
4545 }
4546 }
4547 scale[nt] = dscale;
4548 }
4549
4550 for (int ns = 0; ns < numstates; ns++)
4551 {
4552 alpha_nt[ns] /= dscale;
4553
4554 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
4555 {
4556 alpha_nt[ns] = EPSILONSTATE;
4557 }
4558 }
4559 }
4560 else
4561 {
4562 for (int ns = 0; ns < numstates; ns++)
4563 {
4564 alpha_nt[ns] /= dscale;
4565 }
4566 }
4567 //for (int ns = 0; ns < numstates; ns++)
4568 //{
4569 // alpha_nt[ns] /= dscale;
4570 //}
4571 }
4572
4573 //backward step
4574 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
4575 int nlastindex = numtime_nseq-1;
4576 double dinitval;
4577 if (bscalebeta)
4578 {
4579 dinitval = 1.0/numstates;
4580 }
4581 else
4582 {
4583 dinitval = 1.0/scale[nlastindex];
4584 }
4585
4586 for (int ns = 0; ns < numstates; ns++)
4587 {
4588 beta_ntp1[ns] = dinitval;
4589 }
4590 //double dinitval = 1.0/scale[nlastindex];
4591 //for (int ns = 0; ns < numstates; ns++)
4592 //{
4593 // beta_ntp1[ns] = dinitval;
4594 //}
4595
4596 int nmappedindexouter;
4597
4598 double ddenom = 0;
4599
4600 //gamma_nt - P(x=S| o_0,...,o_t)
4601 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,x_t=s|lambda)
4602 double[] gamma_nt = gamma[nlastindex];
4603 for (int ns = 0; ns < gamma_nt.length; ns++)
4604 {
4605 double dval = alpha[nlastindex][ns]*beta_ntp1[ns];
4606 ddenom += dval;
4607 gamma_nt[ns] = dval;
4608 }
4609
4610 if (ddenom > 0)
4611 {
4612 for (int ns = 0; ns < gamma_nt.length; ns++)
4613 {
4614 gamma_nt[ns] /= ddenom;
4615 }
4616 }
4617
4618
4619 for (int nt = nlastindex - 1; nt >= 0; nt--)
4620 {
4621 gamma_nt = gamma[nt];
4622 int ntp1 = (nt+1);
4623
4624 double[] emissionproducts_ncombo_ntp1 = emissionproducts[traindataObservedIndex[ntp1]];
4625 double dsumbeta = 0;
4626 double dscale_nt = scale[nt];
4627
4628 for (int ns = 0; ns < numstates; ns++)
4629 {
4630 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_ncombo_ntp1[ns];
4631 }
4632
4633 if (bscaleemissions)
4634 {
4635 //adding here to help numerical stability
4636 double dmaxval = 0;
4637 for (int ns = 0; ns < numstates; ns++)
4638 {
4639 if (tempproductbetaemiss[ns] > dmaxval)
4640 {
4641 dmaxval = tempproductbetaemiss[ns];
4642 }
4643 }
4644 for (int ns = 0; ns < numstates; ns++)
4645 {
4646 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
4647 }
4648 }
4649
4650 //double dscaleinv = 1.0/scale[nt];
4651 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
4652 for (int ni = 0; ni < numstates; ni++)
4653 {
4654 double dtempsum = 0;
4655 int[] transitionprobsindex_ni = transitionprobsindex[ni];
4656 double[] transitionprobs_ni = transitionprobs[ni];
4657 int transitionprobsnum_ni = transitionprobsnum[ni];
4658
4659 if (transitionprobsnum_ni < nsparsecutoff)
4660 {
4661 //if it is sparse enough then it is worth the extra array indirection here
4662 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
4663 {
4664 //for each state summing over transition probability to state j, emission probablity in j at next step
4665 //and probability of observing the remaining sequence
4666 nmappedindexouter = transitionprobsindex_ni[nj];
4667 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
4668 }
4669 }
4670 else
4671 {
4672 for (int nj = 0; nj < numstates; nj++)
4673 {
4674 //for each state summing over transition probability to state j, emission probablity in j at next step
4675 //and probability of observing the remaining sequence
4676 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
4677 }
4678 }
4679
4680 if (bscalebeta)
4681 {
4682 beta_nt[ni] = dtempsum;
4683 dsumbeta += dtempsum;
4684 }
4685 else
4686 {
4687 double dratio = dtempsum/dscale_nt;
4688 if (dratio > Double.MAX_VALUE)
4689 {
4690 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
4691 }
4692 else
4693 {
4694 beta_nt[ni] = dratio;
4695 }
4696 }
4697 //double dratio = dtempsum/dscale_nt;
4698 //if (dratio > Double.MAX_VALUE)
4699 //{
4700 // beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
4701 //}
4702 //else
4703 //{
4704 // beta_nt[ni] = dratio;// dtempsum/dscale_nt;
4705 //}
4706 }
4707
4708 if (bscalebeta)
4709 {
4710 for (int ni = 0; ni < numstates; ni++)
4711 {
4712 beta_nt[ni]/= dsumbeta;
4713
4714 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
4715 {
4716 beta_nt[ni] = EPSILONSTATE;
4717 }
4718 }
4719 }
4720
4721 ddenom = 0;
4722 alpha_nt = alpha[nt];
4723
4724 //gamma_nt - P(x=S| o_0,...,o_t)
4725 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
4726
4727 for (int ns = 0; ns < gamma_nt.length; ns++)
4728 {
4729 double dval = alpha_nt[ns]*beta_nt[ns];
4730
4731 ddenom += dval;
4732 gamma_nt[ns] = dval;
4733 }
4734
4735 if (ddenom > 0)
4736 {
4737 for (int ns = 0; ns < gamma_nt.length; ns++)
4738 {
4739 gamma_nt[ns]/=ddenom;
4740 }
4741 }
4742 beta_ntp1 = beta_nt;
4743 }
4744
4745
4746 for (int nt = 0; nt < numtime_nseq; nt++)
4747 {
4748
4749 gamma_nt = gamma[nt];
4750
4751 //handling the first line
4752 if ((breadsegment)||(breadstatebyline))
4753 {
4754 double dmaxval = 0;
4755 int nmaxstate = 0;
4756
4757 for (int ns = 0; ns < gamma_nt.length; ns++)
4758 {
4759 double dprob = gamma_nt[ns];
4760
4761 if (dprob > dmaxval)
4762 {
4763 //best one found so far
4764 dmaxval = dprob;
4765 nmaxstate = ns;
4766 }
4767 }
4768
4769 confusion[fullmax[nt]][nmaxstate]++;
4770 }
4771 else
4772 {
4773 double[] fullposterior_nt = fullposterior[nt];
4774 for (int nstate = 0; nstate < numstates; nstate++)
4775 {
4776 double dfullval = fullposterior_nt[nstate];
4777 double dpartialval = gamma_nt[nstate];
4778 if (dfullval >= dpartialval)
4779 {
4780 //assigned less to this state with the subset of the marks adding that amount to the decifict
4781 dstatesagree[nstate] += dpartialval;
4782 deficit[nstate] = dfullval - dpartialval;
4783 surplus[nstate] = 0;
4784 }
4785 else
4786 {
4787 //we have a surplus of posterior assigned to this state with a subset of marks
4788 dstatesagree[nstate] += dfullval;
4789 surplus[nstate] = dpartialval - dfullval;
4790 deficit[nstate] = 0;
4791 }
4792 }
4793
4794 double dsumdenom = 0;
4795 for (int nb = 0; nb < surplus.length; nb++)
4796 {
4797 dsumdenom += surplus[nb];
4798 }
4799 for (int nb = 0; nb < surplus.length; nb++)
4800 {
4801 //re-normalize surplus
4802 surplus[nb] /= dsumdenom;
4803 }
4804
4805 for (int nb = 0; nb < confusion.length; nb++)
4806 {
4807 double[] confusion_nb = confusion[nb];
4808 if (deficit[nb] > 0)
4809 {
4810 double ddeficit_nb = deficit[nb];
4811 for (int nc = 0; nc < confusion_nb.length; nc++)
4812 {
4813 confusion_nb[nc] += ddeficit_nb*surplus[nc];
4814 //there is a deficit for state nb with the subset of marks
4815 //allocating it to the states that proportionally have additional posterior
4816 }
4817 }
4818 }
4819
4820 for (int nb = 0; nb < confusion.length; nb++)
4821 {
4822 confusion[nb][nb] = dstatesagree[nb];
4823 }
4824 }
4825 }
4826 }
4827
4828 System.out.println("Writing to file "+szconfusionfileprefix+".txt");
4829 if (bprintimage)
4830 {
4831 System.out.println("Writing to file "+szconfusionfileprefix+".svg");
4832 System.out.println("Writing to file "+szconfusionfileprefix+".png");
4833 }
4834 PrintWriter pwconfusion = new PrintWriter(new FileWriter(szconfusionfileprefix+".txt",bappend));
4835 pwconfusion.print("EvalSubset\t"+szincludemarks);
4836 pwconfusion.println("\t"+szdatasets);
4837
4838 for (int na = 0; na < confusion.length; na++)
4839 {
4840 pwconfusion.print("\t"+chorder+(na+1));
4841 }
4842 pwconfusion.println();
4843
4844 for (int na = 0; na < confusion.length; na++)
4845 {
4846 pwconfusion.print(""+chorder+(na+1));
4847 double ddenom = 0;
4848 for (int nb = 0; nb < confusion[na].length; nb++)
4849 {
4850 ddenom += confusion[na][nb];
4851 }
4852
4853 for (int nb = 0; nb < confusion[na].length; nb++)
4854 {
4855 normalizedconfusion[na][nb] = confusion[na][nb]/(double) ddenom;
4856 pwconfusion.print("\t"+nf.format(normalizedconfusion[na][nb]));
4857 }
4858 pwconfusion.println();
4859 }
4860 pwconfusion.close();
4861 if (bprintimage)
4862 {
4863 printConfusionImage(normalizedconfusion, szconfusionfileprefix, szincludemarks);
4864 }
4865 }
4866
4867 ///////////////////////////////////////////////////////////////////////////////////////////
4868
4869 /**
4870 * Outputs the confusion matrix as a '.png' and '.svg'
4871 */
4872 public void printConfusionImage(double[][] confusion, String szconfusionfileprefix,
4873 String szincludemarks) throws IOException
4874 {
4875
4876 String[] rowlabels = new String[numstates];
4877
4878 for (int ni = 0; ni < numstates; ni++)
4879 {
4880 rowlabels[ni] = ""+(ni+1);
4881 String szsuffix;
4882
4883 //changing in v1.12 to be state labels for new state to match char ordering
4884 //if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(stateordering[ni]+1)))!=null)
4885 if ((szsuffix = (String) hmlabelExtend.get(""+chorder+(ni+1)))!=null)
4886 {
4887 rowlabels[ni]+= "_"+szsuffix;
4888 }
4889 }
4890
4891
4892 HeatChart map = new HeatChart(confusion);
4893
4894 map.setTitle("Confusion Matrix");
4895 map.setXAxisLabel("State Subset of Marks ("+szincludemarks+")");
4896 map.setAxisValuesFont(new Font("SansSerif",0,20));
4897 map.setAxisLabelsFont(new Font("SansSerif",0,22));
4898 map.setTitleFont(new Font("SansSerif",0,24));
4899 map.setYAxisLabel("State All Marks");
4900 if (confusion.length <=5)
4901 {
4902 map.setChartMargin(125);
4903 }
4904 else
4905 {
4906 map.setChartMargin(100);
4907 }
4908 map.setXValues(rowlabels);
4909 map.setYValues(rowlabels);
4910 map.setHighValueColour(theColor);
4911
4912
4913 Util.printImageToSVG(map, szconfusionfileprefix+".svg");
4914 map.saveToFile(new File(szconfusionfileprefix+".png"));
4915
4916 }
4917
4918
4919 //////////////////////////////////////////////////////////////////////////////////////////
4920
4921 /**
4922 * Takes an existing model and outputs information about the segmentation depending on the values of
4923 * bprintsegment, bprintstatebyline, bprintposterior
4924 */
4925 public void makeSegmentationWithLoad() throws IOException
4926 {
4927 NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH); //updated in 1.14 to Local.ENGLISH to ensure format of posterior values can be read in
4928 nf.setMaximumFractionDigits(4);
4929
4930 //number of non-zero transition required to be less than this at the more stringent cutoff
4931 //for trying to exploit sparsity in the transition matrix for efficiency gains
4932 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
4933
4934 //int[] numtime = new int[traindataObservedIndex.length];
4935
4936 //stores the maximum number of locations in any sequence and in each sequence
4937 int nmaxtime = 0;
4938 for (int nseq = 0; nseq < numtime.length; nseq++)
4939 {
4940 //numtime[nseq] = traindataObservedIndex[nseq].length;
4941 if (numtime[nseq] > nmaxtime)
4942 {
4943 nmaxtime = numtime[nseq];
4944 }
4945 }
4946
4947
4948 HashMap hmMaxCoord = null;
4949 if (szchromlengthfile != null)
4950 {
4951 hmMaxCoord = new HashMap();
4952 BufferedReader brchromlengthfile = Util.getBufferedReader(szchromlengthfile);
4953 String szLine;
4954 while ((szLine = brchromlengthfile.readLine())!=null)
4955 {
4956 StringTokenizer st = new StringTokenizer(szLine,"\t ");
4957 hmMaxCoord.put(st.nextToken(),Integer.valueOf(st.nextToken()));
4958 }
4959 brchromlengthfile.close();
4960 }
4961
4962 if (ChromHMM.BVERBOSE)
4963 {
4964 System.out.println("Maximum number of locations\t"+nmaxtime);
4965 }
4966
4967 //stores the emission probability for the i^th combination of marks in the j^th state
4968 double[][] emissionproducts = new double[nmaxtime][numstates]; //previously traindataObservedValues.length
4969
4970 //stores temporary product terms
4971 double[] tempproductbetaemiss = new double[numstates];
4972
4973 //This stores the alpha values at each time point and number of states
4974 double[][] alpha = new double[nmaxtime][numstates];
4975
4976 //Temporary storage of the gamma's for each state
4977 double[][] gamma = new double[nmaxtime][numstates];
4978
4979 //Temporary storage of the beta values for each state
4980 double[] beta_nt = new double[numstates];
4981
4982 //Temporary storage of the beta values for each state at the next time point
4983 double[] beta_ntp1 = new double[numstates];
4984
4985 //stores the scaling value for each time point
4986 double[] scale = new double[nmaxtime];
4987
4988 //stores the transition probabilities for each column
4989 double[][] coltransitionprobs = new double[numstates][numstates];
4990
4991 //stores the indicies of the data
4992 int[] traindataObservedIndex = new int[nmaxtime];
4993
4994 //saving the mapping of signatures and chromsome observed on
4995 //stores whether there is a present call at each location
4996 boolean[][] traindataObservedValues = new boolean[nmaxtime][numdatasets];
4997
4998 //stores whether the mark is not considered missing
4999 boolean[][] traindataNotMissing = new boolean[nmaxtime][numdatasets]; //usually nobserved
5000
5001
5002 //maps cell ID to printwriter objects
5003 HashMap hmcellToFourColPW = null;
5004 if (bprintsegment)
5005 {
5006 hmcellToFourColPW = new HashMap();
5007 }
5008
5009 RecIntString[] ordered = null;//new RecIntString[chromfiles.length];
5010 RecIntStringSplit[] orderedsplit = null;//new RecIntString[chromfiles.length];
5011
5012 if (bsplit)
5013 {
5014 orderedsplit = new RecIntStringSplit[chromfiles.length];
5015 for (int nindex = 0; nindex < orderedsplit.length; nindex++)
5016 {
5017 int nlastperiodindex = chromSeq[nindex].lastIndexOf('.');
5018
5019 if (nlastperiodindex == -1)
5020 {
5021 throw new IllegalArgumentException("No period found in chromosome "+chromSeq[nindex]+" despite split being specified");
5022 }
5023
5024 String szchromportion = chromSeq[nindex].substring(0, nlastperiodindex);
5025 int nsplitbinindex = Integer.parseInt(chromSeq[nindex].substring(nlastperiodindex+1));
5026 orderedsplit[nindex] = new RecIntStringSplit(nindex,cellSeq[nindex],szchromportion,nsplitbinindex);
5027 }
5028 Arrays.sort(orderedsplit,new RecIntStringSplitCompare());
5029 }
5030 else
5031 {
5032 ordered = new RecIntString[chromfiles.length];
5033 for (int nindex = 0; nindex < ordered.length; nindex++)
5034 {
5035 ordered[nindex] = new RecIntString(nindex,chromfiles[nindex]);
5036 }
5037 Arrays.sort(ordered,new RecIntStringCompare());
5038 }
5039
5040
5041 //RecIntString[] ordered = new RecIntString[chromfiles.length];
5042 //for (int nindex = 0; nindex < ordered.length; nindex++)
5043 //{
5044 // ordered[nindex] = new RecIntString(nindex,chromfiles[nindex]);
5045 //}
5046 //Arrays.sort(ordered,new RecIntStringCompare());
5047
5048 hsprefix = new HashSet();
5049
5050 GZIPOutputStream pwprobszip = null;
5051 GZIPOutputStream pwmaxzip = null;
5052 GZIPOutputStream pwbedzip = null;
5053 PrintWriter pwprobs = null;
5054 PrintWriter pwmax = null;
5055 PrintWriter pwbed = null;
5056
5057 int noffset = 0;
5058 boolean bclosefile = true;
5059 boolean bnewfile = true;
5060
5061
5062 //these can go across split files so defined out here
5063 int nstart = 0; //the start index of the current active interval
5064 int nmaxstateprev = -1;
5065 int nprevlinecount = 0;
5066 for (int nseq = 0; nseq < chromfiles.length; nseq++)
5067 {
5068 int nordered_nseq;// = ordered[nseq].nindex;
5069 String szactualchrom;
5070 if (bsplit)
5071 {
5072 nordered_nseq = orderedsplit[nseq].nindex;
5073 szactualchrom = orderedsplit[nseq].szchrom;
5074 }
5075 else
5076 {
5077 nordered_nseq = ordered[nseq].nindex;
5078 szactualchrom = chromSeq[nordered_nseq];
5079 }
5080
5081 if (bsplit)
5082 {
5083 //noffset = orderedsplit[nseq].nsplitbinindex * numsplitbins;
5084 //if (noffset == 0)
5085 if (orderedsplit[nseq].nsplitbinindex == 0)
5086 {
5087 noffset = 0;
5088 bnewfile = true;
5089 }
5090 else
5091 {
5092 noffset += nprevlinecount;
5093 if ((nseq >= 1) && (orderedsplit[nseq].nsplitbinindex != (orderedsplit[nseq-1].nsplitbinindex+1)))
5094 {
5095 throw new IllegalArgumentException("For "+orderedsplit[nseq].szcell+"_"+orderedsplit[nseq].szchrom+" found "+
5096 "a file with split index "+orderedsplit[nseq].nsplitbinindex+", but not "+
5097 (orderedsplit[nseq].nsplitbinindex-1));
5098 }
5099 bnewfile = false;
5100 }
5101 bclosefile = ((nseq + 1 == orderedsplit.length)||(orderedsplit[nseq+1].nsplitbinindex == 0));
5102 }
5103
5104
5105 //goes through each sequence
5106
5107 ///////////////////////////////////////////////////////////////////////////////
5108 //load data here
5109
5110 HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
5111
5112 int nobserved = 0;
5113
5114 if (ChromHMM.BVERBOSE)
5115 {
5116 System.out.println("reading\t"+szinputdir+" "+chromfiles[nordered_nseq]);
5117 }
5118 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nordered_nseq]); //fixed bug was chromfiles[nseq]
5119 String szLine;
5120 br.readLine(); //first line tells cell type and chromosome
5121 br.readLine();//flush mark header
5122 ArrayList aldata = new ArrayList();
5123 while ((szLine = br.readLine())!=null)
5124 {
5125 StringTokenizer st = new StringTokenizer(szLine,"\t ");
5126 StringBuffer sb = new StringBuffer();
5127
5128 for (int ncol = 0; ncol < numdatasets; ncol++)
5129 {
5130 if (!st.hasMoreTokens())
5131 {
5132 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nordered_nseq]);
5133 }
5134
5135 String sztoken = st.nextToken();
5136
5137 if (sztoken.equals("0"))
5138 {
5139 sb.append("0");
5140 }
5141 else if (sztoken.equals("1"))
5142 {
5143 sb.append("1");
5144 }
5145 else if (sztoken.equals("2"))
5146 {
5147 //this means missing
5148 sb.append("2");
5149 }
5150 else
5151 {
5152 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nordered_nseq]);
5153 }
5154 }
5155 aldata.add(sb.toString());
5156 }
5157 br.close();
5158
5159 int nsize = aldata.size();
5160 nprevlinecount = nsize;
5161 //traindataObservedIndex[nfile] = new int[nsize];
5162 //int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
5163
5164 for (int nrow = 0; nrow < nsize; nrow++)
5165 {
5166 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
5167 Integer theObservedInt = (Integer) hmObserved.get(theBigInteger);
5168 //boolean[] flagA;
5169
5170 if (theObservedInt == null)
5171 {
5172 //System.out.println(szmappingbyte.length());
5173 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
5174 hmObserved.put(theBigInteger, Integer.valueOf(nobserved));
5175
5176 //saving this observed index
5177 traindataObservedIndex[nrow] = nobserved;
5178
5179 //increments the number of observed combinations of marks
5180 nobserved++;
5181 }
5182 else
5183 {
5184 //storing the index of the flags associated with this row
5185 traindataObservedIndex[nrow] = ((Integer) theObservedInt).intValue();
5186 }
5187 }
5188
5189 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
5190 while (hmObservedIterator.hasNext())
5191 {
5192 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
5193 BigInteger theBigInteger = (BigInteger) pairs.getKey();
5194 String szmapping = theBigInteger.toString(3); //getting back the mapping string
5195
5196 //ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
5197 int ncurrindex = ((Integer) pairs.getValue()).intValue();// theObservedRec.nobserved;//this is an index on which obervation combination it is
5198
5199 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
5200 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
5201
5202 //if the mapping string is less than the number of data sets then
5203 //there are leading 0's will set for leading 0's not missing and absent
5204 int numch = szmapping.length();
5205 int numleading0 = numdatasets - numch;
5206 for (int nj = 0; nj < numleading0; nj++)
5207 {
5208 traindataObservedValues_ncurrindex[nj] = false;
5209 traindataNotMissing_ncurrindex[nj] = true;
5210 }
5211
5212 int nmappedindex = numleading0; //starting from the leading 0 position
5213 for (int nj = 0; nj < numch; nj++)
5214 {
5215 char ch = szmapping.charAt(nj);
5216
5217 if (ch == '0')
5218 {
5219 traindataObservedValues_ncurrindex[nmappedindex] = false;
5220 traindataNotMissing_ncurrindex[nmappedindex] = true;
5221 }
5222 else if (ch=='1')
5223 {
5224 traindataObservedValues_ncurrindex[nmappedindex] = true;
5225 traindataNotMissing_ncurrindex[nmappedindex] = true;
5226 }
5227 else
5228 {
5229 //missing data
5230 traindataObservedValues_ncurrindex[nmappedindex] = false;
5231 traindataNotMissing_ncurrindex[nmappedindex] = false;
5232 }
5233 nmappedindex++;
5234 }
5235 }
5236
5237 //////////////////////////////////////////////////////////////////////////////
5238
5239 //int[] traindataObservedIndex_nseq = traindataObservedIndex[nordered_nseq];
5240 //boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nordered_nseq];
5241
5242 if (bnewfile)
5243 {
5244 String szprefix = "";
5245 if (!cellSeq[nordered_nseq].equals(""))
5246 {
5247 szprefix += cellSeq[nordered_nseq]+"_";
5248 }
5249 szprefix += numstates;
5250 if (!szoutfileID.equals(""))
5251 {
5252 szprefix += "_"+szoutfileID;
5253 }
5254 hsprefix.add(szprefix);
5255
5256 //GZIPOutputStream pwprobszip = null;
5257 //PrintWriter pwprobs = null;
5258
5259 //GZIPOutputStream pwmaxzip = null;
5260 //PrintWriter pwmax = null;
5261
5262 //GZIPOutputStream pwbedzip = null;
5263 //PrintWriter pwbed = null;
5264
5265 if (bgzip)
5266 {
5267 //PrintWriter pwprobs = null;
5268 if (bprintposterior)
5269 {
5270 //creates the posterior file
5271
5272 //changed in v.1.18
5273 //String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+chromSeq[nordered_nseq]+ChromHMM.SZPOSTERIOREXTENSION+".gz";
5274 String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+szactualchrom+ChromHMM.SZPOSTERIOREXTENSION+".gz";
5275
5276 System.out.println("Writing to file "+szposterioroutfilename);
5277 pwprobszip = new GZIPOutputStream(new FileOutputStream(szposterioroutfilename));
5278 //pwprobs = new PrintWriter(szposterioroutfilename);
5279 String szout = cellSeq[nordered_nseq]+"\t"+szactualchrom+"\n";
5280
5281 byte[] btformat = szout.getBytes();
5282 pwprobszip.write(btformat,0,btformat.length);
5283
5284 StringBuffer sbout = new StringBuffer();
5285 //pwprobs.println(cellSeq[nordered_nseq]+"\t"+chromSeq[nordered_nseq]);
5286 for (int ni = 0; ni < numstates-1; ni++)
5287 {
5288 sbout.append(""+chorder+(ni+1)+"\t");
5289 //pwprobs.print(""+chorder+(ni+1)+"\t");
5290 }
5291 sbout.append(""+chorder+(numstates)+"\n");
5292 //pwprobs.println(""+chorder+(numstates));
5293 btformat = sbout.toString().getBytes();
5294 pwprobszip.write(btformat,0,btformat.length);
5295 }
5296
5297 //PrintWriter pwmax = null;
5298
5299 if (bprintstatebyline)
5300 {
5301 //creates a file which has the state with the maximum posterior probability
5302 String szmaxoutfilename = szoutputdir+"/STATEBYLINE/"+szprefix+"_"+szactualchrom+ChromHMM.SZSTATEBYLINEEXTENSION+".gz";
5303
5304 System.out.println("Writing to file "+szmaxoutfilename);
5305 //pwmax = new PrintWriter(szmaxoutfilename);
5306 pwmaxzip = new GZIPOutputStream(new FileOutputStream(szmaxoutfilename));
5307
5308 String szout = cellSeq[nordered_nseq]+"\t"+szactualchrom+"\n";
5309 byte[] btformat = szout.getBytes();
5310 pwmaxzip.write(btformat,0,btformat.length); //fix 1.23
5311 //pwmax.println(cellSeq[nordered_nseq]+"\t"+chromSeq[nordered_nseq]);
5312
5313 szout = "MaxState "+chorder+"\n";
5314 btformat = szout.getBytes();
5315 pwmaxzip.write(btformat,0,btformat.length); //fix 1.23
5316 //pwmax.println("MaxState "+chorder);
5317 }
5318
5319 //PrintWriter pwbed = null;
5320 //GZIPOutputStream pwbedzip = null;
5321
5322 if (bprintsegment)
5323 {
5324 //creates a file which has the maximum segmentation
5325 //we only have one file per cell type here
5326 pwbedzip = (GZIPOutputStream) hmcellToFourColPW.get(cellSeq[nordered_nseq]);
5327 // (PrintWriter) hmcellToFourColPW.get(cellSeq[nordered_nseq]);
5328
5329 if (pwbedzip == null)
5330 {
5331 //haven't seen this cell type
5332 String szsegmentoutfilename = szoutputdir+"/" + szprefix+SZSEGMENTEXTENSION+".gz";
5333
5334 pwbedzip = new GZIPOutputStream(new FileOutputStream(szsegmentoutfilename));
5335 //pwbed = new PrintWriter(szsegmentoutfilename);
5336 System.out.println("Writing to file "+szsegmentoutfilename);
5337
5338 hmcellToFourColPW.put(cellSeq[nordered_nseq],pwbedzip);
5339 }
5340 }
5341 }
5342 else
5343 {
5344
5345 if (bprintposterior)
5346 {
5347 //creates the posterior file
5348
5349 String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+szactualchrom+ChromHMM.SZPOSTERIOREXTENSION;
5350
5351 System.out.println("Writing to file "+szposterioroutfilename);
5352 pwprobs = new PrintWriter(szposterioroutfilename);
5353 pwprobs.println(cellSeq[nordered_nseq]+"\t"+szactualchrom);
5354 for (int ni = 0; ni < numstates-1; ni++)
5355 {
5356 pwprobs.print(""+chorder+(ni+1)+"\t");
5357 }
5358 pwprobs.println(""+chorder+(numstates));
5359 }
5360
5361 if (bprintstatebyline)
5362 {
5363 //creates a file which has the state with the maximum posterior probability
5364 String szmaxoutfilename = szoutputdir+"/STATEBYLINE/"+szprefix+"_"+szactualchrom+ChromHMM.SZSTATEBYLINEEXTENSION;
5365
5366 System.out.println("Writing to file "+szmaxoutfilename);
5367 pwmax = new PrintWriter(szmaxoutfilename);
5368 pwmax.println(cellSeq[nordered_nseq]+"\t"+szactualchrom);
5369 pwmax.println("MaxState "+chorder);
5370 }
5371
5372 //PrintWriter pwbed = null;
5373 if (bprintsegment)
5374 {
5375 //creates a file which has the maximum segmentation
5376 //we only have one file per cell type here
5377 pwbed = (PrintWriter) hmcellToFourColPW.get(cellSeq[nordered_nseq]);
5378
5379 if (pwbed == null)
5380 {
5381 //haven't seen this cell type
5382 String szsegmentoutfilename = szoutputdir+"/" + szprefix+SZSEGMENTEXTENSION;
5383
5384 pwbed = new PrintWriter(szsegmentoutfilename);
5385 System.out.println("Writing to file "+szsegmentoutfilename);
5386
5387 hmcellToFourColPW.put(cellSeq[nordered_nseq],pwbed);
5388 }
5389 }
5390 }
5391 }
5392
5393
5394 if (bscaleemissions)
5395 {
5396 for (int ni = 0; ni < nobserved; ni++)
5397 {
5398 //going through each combination of marks
5399 //if (traindataObservedSeqFlags_nseq[ni])
5400 //{
5401 //this signature of marks is observed on the current chromosome so
5402 //updating its emission probabilities
5403 double[] emissionproducts_ni = emissionproducts[ni];
5404 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
5405 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
5406
5407 for (int ns = 0; ns < numstates; ns++)
5408 {
5409 emissionproducts_ni[ns] = 1;
5410 }
5411
5412 for (int nmod = 0; nmod < numdatasets; nmod++)
5413 {
5414 for (int ns = 0; ns < numstates; ns++)
5415 {
5416 if (traindataNotMissing_ni[nmod])
5417 {
5418 //we are include this marks emission probability
5419 if (traindataObservedValues_ni[nmod])
5420 {
5421 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
5422 }
5423 else
5424 {
5425 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
5426 }
5427 }
5428 // otherwise treated as missing omitting from product
5429 }
5430
5431 double dmaxval = 0;
5432 for (int ns = 0; ns < numstates; ns++)
5433 {
5434 if (emissionproducts_ni[ns] > dmaxval)
5435 {
5436 dmaxval = emissionproducts_ni[ns];
5437 }
5438 }
5439
5440
5441 if (dmaxval <= 0)//EPSILONEMISSIONS)
5442 {
5443 for (int ns = 0; ns < numstates; ns++)
5444 {
5445 emissionproducts_ni[ns] = 1;
5446 }
5447 }
5448 else
5449 {
5450 for (int ns = 0; ns < numstates; ns++)
5451 {
5452 emissionproducts_ni[ns]/= dmaxval;
5453 }
5454 }
5455 }
5456 }
5457 }
5458 else
5459 {
5460 for (int ni = 0; ni < nobserved; ni++)
5461 {
5462 //going through each combination of marks
5463 //if (traindataObservedSeqFlags_nseq[ni])
5464 //{
5465 //this signature of marks is observed on the current chromosome so
5466 //updating its emission probabilities
5467 double[] emissionproducts_ni = emissionproducts[ni];
5468 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
5469 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
5470
5471 boolean ballzero = true;
5472
5473 for (int ns = 0; ns < numstates; ns++)
5474 {
5475 double dproduct = 1;
5476 double[][] emissionprobs_ni = emissionprobs[ns];
5477
5478 //going through all marks
5479 for (int nmod = 0; nmod < numdatasets; nmod++)
5480 {
5481 if (traindataNotMissing_ni[nmod])
5482 {
5483 //we have observed the mark
5484 if (traindataObservedValues_ni[nmod])
5485 {
5486 dproduct *= emissionprobs_ni[nmod][1];
5487 }
5488 else
5489 {
5490 dproduct *= emissionprobs_ni[nmod][0];
5491 }
5492 }
5493 // otherwise treated as missing omitting from product
5494 }
5495 emissionproducts_ni[ns] = dproduct;
5496
5497 if (dproduct >= EPSILONEMISSIONS)
5498 {
5499 ballzero = false;
5500 }
5501 }
5502
5503 if (ballzero)
5504 {
5505 for (int ns = 0; ns < numstates; ns++)
5506 {
5507 emissionproducts_ni[ns] = EPSILONEMISSIONS;
5508 }
5509 }
5510 }
5511 }
5512
5513 //initial probability in state s is initial probability times emission probability at first position
5514 double[] alpha_nt = alpha[0];
5515 double dscale = 0;
5516 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex[0]];
5517 for (int ns = 0; ns < numstates; ns++)
5518 {
5519 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
5520 dscale += alpha_nt[ns];
5521 }
5522 scale[0] = dscale;
5523
5524 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
5525 //converts the alpha terms to probabilities
5526 if (bscalebeta)
5527 {
5528 if (dscale == 0)
5529 {
5530 for (int ns = 0; ns < numstates; ns++)
5531 {
5532 //added
5533 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
5534 {
5535 alpha_nt[ns] = EPSILONSTATE;
5536 dscale += EPSILONSTATE;
5537 }
5538 }
5539 scale[0] = dscale;
5540 }
5541
5542 for (int ns = 0; ns < numstates; ns++)
5543 {
5544 alpha_nt[ns] /= dscale;
5545
5546 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
5547 {
5548 alpha_nt[ns] = EPSILONSTATE;
5549 }
5550 }
5551 }
5552 else
5553 {
5554 for (int ns = 0; ns < numstates; ns++)
5555 {
5556 alpha_nt[ns] /= dscale;
5557 }
5558 }
5559 //for (int ni = 0; ni < numstates; ni++)
5560 //{
5561 // alpha_nt[ni] /= dscale;
5562 //}
5563
5564 //stores in coltransitionprobs the transpose of transitionprobs
5565 for (int ni = 0; ni < numstates; ni++)
5566 {
5567 double[] coltransitionprobs_ni = coltransitionprobs[ni];
5568 for (int nj = 0; nj < numstates; nj++)
5569 {
5570 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
5571 }
5572 }
5573
5574 //forward step
5575 int numtime_nseq = numtime[nordered_nseq];
5576 for (int nt = 1; nt < numtime_nseq; nt++)
5577 {
5578 //the actual observed combination at position t
5579 double[] alpha_ntm1 = alpha[nt-1];
5580 alpha_nt = alpha[nt];
5581
5582 dscale = 0;
5583 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex[nt]];
5584 for (int ns = 0; ns < numstates; ns++)
5585 {
5586 //going through each state
5587 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
5588 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
5589 double[] coltransitionprobs_ns = coltransitionprobs[ns];
5590
5591 double dtempsum = 0;
5592 if (transitionprobsnumCol_ns < nsparsecutoff)
5593 {
5594 //if it is sparse enough then it is worth the extra array indirection here
5595 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
5596 {
5597 //for each next state computing inner sum of all previous alpha and the transition probability
5598 //for all non-zero transitions into the state
5599 int nmappedindex = transitionprobsindexCol_ns[nj];
5600 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
5601 }
5602 }
5603 else
5604 {
5605 for (int nj = 0; nj < numstates; nj++)
5606 {
5607 //for each next state computing inner sum of all previous alpha and the transition probability
5608 //for all transitions into the state
5609 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
5610 }
5611 }
5612
5613 //multiply the transition sum by the emission probability
5614 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
5615 alpha_nt[ns] = dalphaval;
5616 dscale += dalphaval;
5617 }
5618
5619 //rescaling alpha
5620 scale[nt] = dscale;
5621 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
5622
5623 if (bscalebeta)
5624 {
5625 if (dscale == 0)
5626 {
5627 for (int ns = 0; ns < numstates; ns++)
5628 {
5629 //added
5630 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
5631 {
5632 alpha_nt[ns] = EPSILONSTATE;
5633 dscale += EPSILONSTATE;
5634 }
5635 }
5636 scale[nt] = dscale;
5637 }
5638
5639 for (int ns = 0; ns < numstates; ns++)
5640 {
5641 alpha_nt[ns] /= dscale;
5642
5643 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
5644 {
5645 alpha_nt[ns] = EPSILONSTATE;
5646 }
5647 }
5648 }
5649 else
5650 {
5651 for (int ns = 0; ns < numstates; ns++)
5652 {
5653 alpha_nt[ns] /= dscale;
5654 }
5655 }
5656 //for (int ns = 0; ns < numstates; ns++)
5657 //{
5658 // alpha_nt[ns] /= dscale;
5659 //}
5660 }
5661
5662 //backward step
5663 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
5664 int nlastindex = numtime_nseq-1;
5665 double dinitval;
5666 if (bscalebeta)
5667 {
5668 dinitval = 1.0/numstates;
5669 }
5670 else
5671 {
5672 dinitval = 1.0/scale[nlastindex];
5673 }
5674
5675 for (int ns = 0; ns < numstates; ns++)
5676 {
5677 beta_ntp1[ns] = dinitval;
5678 }
5679 //double dinitval = 1.0/scale[nlastindex];
5680 //for (int ns = 0; ns < numstates; ns++)
5681 //{
5682 // beta_ntp1[ns] = dinitval;
5683 //}
5684
5685 int nmappedindexouter;
5686
5687 double ddenom = 0;
5688
5689 //gamma_nt - P(x=S| o_0,...,o_t)
5690 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,x_t=s|lambda)
5691 double[] gamma_nt = gamma[nlastindex];
5692 for (int ns = 0; ns < gamma_nt.length; ns++)
5693 {
5694 double dval = alpha[nlastindex][ns]*beta_ntp1[ns];
5695 ddenom += dval;
5696 gamma_nt[ns] = dval;
5697 }
5698
5699 if (ddenom > 0)
5700 {
5701 for (int ns = 0; ns < gamma_nt.length; ns++)
5702 {
5703 gamma_nt[ns] /= ddenom;
5704 }
5705 }
5706
5707
5708 for (int nt = nlastindex - 1; nt >= 0; nt--)
5709 {
5710 gamma_nt = gamma[nt];
5711 int ntp1 = (nt+1);
5712
5713 double[] emissionproducts_ncombo_ntp1 = emissionproducts[traindataObservedIndex[ntp1]];
5714 double dsumbeta = 0;
5715 double dscale_nt = scale[nt];
5716
5717 for (int ns = 0; ns < numstates; ns++)
5718 {
5719 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_ncombo_ntp1[ns];
5720 }
5721
5722 if (bscaleemissions)
5723 {
5724 //adding here to help numerical stability
5725 double dmaxval = 0;
5726 for (int ns = 0; ns < numstates; ns++)
5727 {
5728 if (tempproductbetaemiss[ns] > dmaxval)
5729 {
5730 dmaxval = tempproductbetaemiss[ns];
5731 }
5732 }
5733 for (int ns = 0; ns < numstates; ns++)
5734 {
5735 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
5736 }
5737 }
5738
5739 //double dscaleinv = 1.0/scale[nt];
5740 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
5741 for (int ni = 0; ni < numstates; ni++)
5742 {
5743 double dtempsum = 0;
5744 int[] transitionprobsindex_ni = transitionprobsindex[ni];
5745 double[] transitionprobs_ni = transitionprobs[ni];
5746 int transitionprobsnum_ni = transitionprobsnum[ni];
5747
5748 if (transitionprobsnum_ni < nsparsecutoff)
5749 {
5750 //if it is sparse enough then it is worth the extra array indirection here
5751 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
5752 {
5753 //for each state summing over transition probability to state j, emission probablity in j at next step
5754 //and probability of observing the remaining sequence
5755 nmappedindexouter = transitionprobsindex_ni[nj];
5756 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
5757 }
5758 }
5759 else
5760 {
5761 for (int nj = 0; nj < numstates; nj++)
5762 {
5763 //for each state summing over transition probability to state j, emission probablity in j at next step
5764 //and probability of observing the remaining sequence
5765 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
5766 }
5767 }
5768
5769 if (bscalebeta)
5770 {
5771 beta_nt[ni] = dtempsum;
5772 dsumbeta += dtempsum;
5773 }
5774 else
5775 {
5776 double dratio = dtempsum/dscale_nt;
5777 if (dratio > Double.MAX_VALUE)
5778 {
5779 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
5780 }
5781 else
5782 {
5783 beta_nt[ni] = dratio;
5784 }
5785 }
5786 //double dratio = dtempsum/dscale_nt;
5787 //if (dratio > Double.MAX_VALUE)
5788 //{
5789 // beta_nt[ni] = Double.MAX_VALUE;
5790 //}
5791 //else
5792 //{
5793 // beta_nt[ni] = dratio;//dtempsum/dscale_nt;
5794 //}
5795 }
5796
5797 if (bscalebeta)
5798 {
5799 for (int ni = 0; ni < numstates; ni++)
5800 {
5801 beta_nt[ni]/= dsumbeta;
5802
5803 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (emissionproducts_nobserveindex[ns]>0)))//(ni < numstates-1)))
5804 {
5805 beta_nt[ni] = EPSILONSTATE;
5806 }
5807 }
5808 }
5809
5810 ddenom = 0;
5811 alpha_nt = alpha[nt];
5812
5813 //gamma_nt - P(x=S| o_0,...,o_t)
5814 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
5815
5816 for (int ns = 0; ns < gamma_nt.length; ns++)
5817 {
5818 double dval = alpha_nt[ns]*beta_nt[ns];
5819
5820 ddenom += dval;
5821 gamma_nt[ns] = dval;
5822 }
5823
5824 if (ddenom > 0)
5825 {
5826 for (int ns = 0; ns < gamma_nt.length; ns++)
5827 {
5828 gamma_nt[ns]/=ddenom;
5829 }
5830 }
5831 beta_ntp1 = beta_nt;
5832 }
5833
5834 //int nstart = 0; //the start index of the current active interval
5835 gamma_nt = gamma[0];
5836
5837 double dmaxval = 0;
5838 int nmaxstate = 0;
5839
5840 int nt = 0;
5841
5842 if (bgzip)
5843 {
5844
5845 if (bnewfile)
5846 {
5847 //handling the first line
5848 for (int ns = 0; ns < gamma_nt.length; ns++)
5849 {
5850 int nmappedstate = stateordering[ns]; //maps new state to old
5851 double dprob = gamma_nt[nmappedstate];
5852 if (bprintposterior)
5853 {
5854 String szout;
5855 if (ns > 0)
5856 {
5857 //print with tab if not the first
5858 szout = "\t"+nf.format(dprob);
5859 //pwprobs.print("\t"+nf.format(dprob));
5860 }
5861 else
5862 {
5863 szout = nf.format(dprob);
5864 //pwprobs.print(nf.format(dprob));
5865 }
5866 byte[] btformat = szout.getBytes();
5867 pwprobszip.write(btformat,0,btformat.length);
5868 }
5869
5870 if (dprob > dmaxval)
5871 {
5872 //best one found so far
5873 dmaxval = dprob;
5874 nmaxstate = ns;
5875 }
5876 }
5877
5878 if (bprintposterior)
5879 {
5880 String szout = "\n";
5881 byte[] btformat = szout.getBytes();
5882 pwprobszip.write(btformat,0,btformat.length);
5883 //pwprobs.println();
5884 }
5885
5886 if (bprintstatebyline)
5887 {
5888 String szout = (nmaxstate+1)+"\n";
5889 byte[] btformat = szout.getBytes();
5890 pwmaxzip.write(btformat,0,btformat.length);
5891 //pwmax.println(""+(nmaxstate+1));
5892 }
5893
5894 nmaxstateprev = nmaxstate;
5895 nt = 1;
5896 nstart = 0;
5897 }
5898
5899 //this contains the best state of the previous interval
5900 //int nmaxstateprev = nmaxstate;
5901
5902 for (; nt < numtime_nseq; nt++)
5903 {
5904 gamma_nt = gamma[nt];
5905
5906 dmaxval = 0;
5907 nmaxstate = 0;
5908 for (int ns = 0; ns < gamma_nt.length; ns++)
5909 {
5910 int nmappedstate = stateordering[ns]; //maps new state to old
5911 double dprob = gamma_nt[nmappedstate];
5912 if (bprintposterior)
5913 {
5914 String szout;
5915 if (ns > 0)
5916 {
5917 //print with tab the first time
5918 szout = "\t"+nf.format(dprob);
5919 //pwprobs.print("\t"+nf.format(dprob));
5920 }
5921 else
5922 {
5923 szout = nf.format(dprob);
5924 //pwprobs.print(nf.format(dprob));
5925 }
5926 byte[] btformat = szout.getBytes();
5927 pwprobszip.write(btformat,0,btformat.length);
5928 }
5929
5930 if (dprob > dmaxval)
5931 {
5932 dmaxval = dprob;
5933 nmaxstate = ns;
5934 }
5935 }
5936
5937 if (bprintposterior)
5938 {
5939 String szout = "\n";
5940 byte[] btformat = szout.getBytes();
5941 pwprobszip.write(btformat,0,btformat.length);
5942 //pwprobs.println();
5943 }
5944
5945 if (bprintstatebyline)
5946 {
5947 String szout =""+(nmaxstate+1)+"\n";
5948 byte[] btformat = szout.getBytes();
5949 pwmaxzip.write(btformat,0,btformat.length);
5950 //pwmax.println(""+(nmaxstate+1));
5951 }
5952
5953 if (bprintsegment&&(nmaxstateprev != nmaxstate))
5954 {
5955 //print out last segment we are done with
5956 //pwbed.println(chromSeq[nordered_nseq]+"\t"+(nstart*nbinsize)+"\t"+(nt*nbinsize)+"\t"+chorder+(nmaxstateprev+1));
5957 String szout = szactualchrom+"\t"+(nstart*nbinsize)+"\t"+((nt+noffset)*nbinsize)+"\t"+chorder+(nmaxstateprev+1)+"\n";
5958 byte[] btformat = szout.getBytes();
5959 pwbedzip.write(btformat,0,btformat.length);
5960 //start a new segment now
5961 nstart = nt+noffset;
5962 nmaxstateprev = nmaxstate;
5963 }
5964 }
5965
5966 if (bclosefile)
5967 {
5968 if (bprintsegment)
5969 {
5970 int nlastcoordinate;
5971 Integer objMaxCoord = null;
5972 if (hmMaxCoord != null)
5973 {
5974 objMaxCoord = ((Integer) hmMaxCoord.get(szactualchrom));
5975 }
5976
5977 if (objMaxCoord != null)
5978 {
5979 nlastcoordinate = Math.min((numtime_nseq+noffset)*nbinsize,((Integer) objMaxCoord).intValue());
5980
5981 if (nstart*nbinsize >= nlastcoordinate)
5982 {
5983 //v1.26
5984 throw new IllegalArgumentException("Start of interval "+(nstart*nbinsize+1)+" (1-based) is past the end of the chromosome "+nlastcoordinate+
5985 "; Check if chromosome length file given to LearnModel is the same used for the binarization");
5986 }
5987 }
5988 else
5989 {
5990 nlastcoordinate = (numtime_nseq+noffset)*nbinsize;
5991 }
5992
5993 String szout = szactualchrom+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1)+"\n";
5994 byte[] btformat = szout.getBytes();
5995 pwbedzip.write(btformat,0,btformat.length);
5996
5997 //pwbed.println(chromSeq[nordered_nseq]+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1));
5998 }
5999
6000 //close out the max state file if that was requested
6001 if (bprintstatebyline)
6002 {
6003 pwmaxzip.finish();
6004 pwmaxzip.close();
6005 }
6006 //close out the posterior state file if that was requested
6007 if (bprintposterior)
6008 {
6009 pwprobszip.finish();
6010 pwprobszip.close();
6011 }
6012 }
6013 }
6014 else
6015 {
6016 if (bnewfile)
6017 {
6018 //handling the first line
6019 for (int ns = 0; ns < gamma_nt.length; ns++)
6020 {
6021 int nmappedstate = stateordering[ns]; //maps new state to old
6022 double dprob = gamma_nt[nmappedstate];
6023
6024 if (bprintposterior)
6025 {
6026 if (ns > 0)
6027 {
6028 pwprobs.print("\t"+nf.format(dprob));
6029 }
6030 else
6031 {
6032 pwprobs.print(nf.format(dprob));
6033 }
6034 }
6035
6036 if (dprob > dmaxval)
6037 {
6038 //best one found so far
6039 dmaxval = dprob;
6040 nmaxstate = ns;
6041 }
6042 }
6043
6044 if (bprintposterior)
6045 {
6046 pwprobs.println();
6047 }
6048
6049 if (bprintstatebyline)
6050 {
6051 pwmax.println(""+(nmaxstate+1));
6052 }
6053
6054 //this contains the best state of the previous interval
6055 nmaxstateprev = nmaxstate;
6056 nt = 1;
6057 nstart = 0;
6058 }
6059
6060 for ( ; nt < numtime_nseq; nt++)
6061 {
6062 gamma_nt = gamma[nt];
6063
6064 dmaxval = 0;
6065 nmaxstate = 0;
6066 for (int ns = 0; ns < gamma_nt.length; ns++)
6067 {
6068 int nmappedstate = stateordering[ns]; //maps new state to old
6069 double dprob = gamma_nt[nmappedstate];
6070 if (bprintposterior)
6071 {
6072 if (ns > 0)
6073 {
6074 //print with tab the first time
6075 pwprobs.print("\t"+nf.format(dprob));
6076 }
6077 else
6078 {
6079 pwprobs.print(nf.format(dprob));
6080 }
6081 }
6082
6083 if (dprob > dmaxval)
6084 {
6085 dmaxval = dprob;
6086 nmaxstate = ns;
6087 }
6088 }
6089
6090 if (bprintposterior)
6091 {
6092 pwprobs.println();
6093 }
6094
6095 if (bprintstatebyline)
6096 {
6097 pwmax.println(""+(nmaxstate+1));
6098 }
6099
6100 if (bprintsegment&&(nmaxstateprev != nmaxstate))
6101 {
6102 //print out last segment we are done with
6103 pwbed.println(szactualchrom+"\t"+(nstart*nbinsize)+"\t"+((nt+noffset)*nbinsize)+"\t"+chorder+(nmaxstateprev+1));
6104 //start a new segment now
6105 nstart = nt+noffset;
6106 nmaxstateprev = nmaxstate;
6107 }
6108 }
6109
6110 if (bclosefile)
6111 {
6112 if (bprintsegment)
6113 {
6114 int nlastcoordinate;
6115 Integer objMaxCoord = null;
6116 if (hmMaxCoord != null)
6117 {
6118 objMaxCoord = ((Integer) hmMaxCoord.get(szactualchrom));
6119 }
6120
6121 if (objMaxCoord != null)
6122 {
6123 nlastcoordinate = Math.min((numtime_nseq+noffset)*nbinsize,((Integer) objMaxCoord).intValue());
6124
6125 if (nstart*nbinsize >= nlastcoordinate)
6126 {
6127 //v1.26
6128 throw new IllegalArgumentException("Start of interval "+(nstart*nbinsize+1)+" (1-based) is past the end of the chromosome "+nlastcoordinate+
6129 "; Check if chromosome length file given to LearnModel is the same used for the binarization");
6130 }
6131 }
6132 else
6133 {
6134 nlastcoordinate = (numtime_nseq+noffset)*nbinsize;
6135 }
6136 pwbed.println(szactualchrom+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1));
6137 }
6138
6139 //close out the max state file if that was requested
6140 if (bprintstatebyline)
6141 {
6142 pwmax.close();
6143 }
6144 //close out the posterior state file if that was requested
6145 if (bprintposterior)
6146 {
6147 pwprobs.close();
6148 }
6149 }
6150 }
6151 }
6152
6153 //if segment print was requested then we are going to go close those printwriters
6154 if (bprintsegment)
6155 {
6156 Iterator itr = hmcellToFourColPW.values().iterator();
6157 if (bgzip)
6158 {
6159 while (itr.hasNext())
6160 {
6161 GZIPOutputStream pwzip = (GZIPOutputStream) itr.next();
6162 //PrintWriter pw = (PrintWriter) itr.next();
6163 pwzip.finish();
6164 pwzip.close();
6165 //pw.close();
6166 }
6167 }
6168 else
6169 {
6170 while (itr.hasNext())
6171 {
6172 PrintWriter pw = (PrintWriter) itr.next();
6173 pw.close();
6174 }
6175 }
6176 }
6177 }
6178
6179
6180
6181 ///////////////////////////////////////////////////////////////////////////////////////////
6182
6183 /**
6184 * Takes an existing model and outputs information about the segmentation depending on the values of
6185 * bprintsegment, bprintstatebyline, bprintposterior
6186 */
6187 public void makeSegmentation() throws IOException
6188 {
6189 NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH); //updated in 1.14 to Local.ENGLISH to ensure format of posterior values can be read in
6190 nf.setMaximumFractionDigits(4);
6191
6192 //number of non-zero transition required to be less than this at the more stringent cutoff
6193 //for trying to exploit sparsity in the transition matrix for efficiency gains
6194 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
6195
6196 int[] numtime = new int[traindataObservedIndex.length];
6197
6198 //stores the maximum number of locations in any sequence and in each sequence
6199 int nmaxtime = 0;
6200 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
6201 {
6202 numtime[nseq] = traindataObservedIndex[nseq].length;
6203 if (numtime[nseq] > nmaxtime)
6204 {
6205 nmaxtime = numtime[nseq];
6206 }
6207 }
6208
6209
6210 HashMap hmMaxCoord = null;
6211 if (szchromlengthfile != null)
6212 {
6213 hmMaxCoord = new HashMap();
6214 BufferedReader brchromlengthfile = Util.getBufferedReader(szchromlengthfile);
6215 String szLine;
6216 while ((szLine = brchromlengthfile.readLine())!=null)
6217 {
6218 StringTokenizer st = new StringTokenizer(szLine,"\t ");
6219 hmMaxCoord.put(st.nextToken(),Integer.valueOf(st.nextToken()));
6220 }
6221 brchromlengthfile.close();
6222 }
6223
6224 if (ChromHMM.BVERBOSE)
6225 {
6226 System.out.println("Maximum number of locations\t"+nmaxtime);
6227 }
6228
6229 //stores the emission probability for the i^th combination of marks in the j^th state
6230 double[][] emissionproducts = new double[traindataObservedValues.length][numstates];
6231
6232 //stores temporary product terms
6233 double[] tempproductbetaemiss = new double[numstates];
6234
6235 //This stores the alpha values at each time point and number of states
6236 double[][] alpha = new double[nmaxtime][numstates];
6237
6238 //Temporary storage of the gamma's for each state
6239 double[][] gamma = new double[nmaxtime][numstates];
6240
6241 //Temporary storage of the beta values for each state
6242 double[] beta_nt = new double[numstates];
6243
6244 //Temporary storage of the beta values for each state at the next time point
6245 double[] beta_ntp1 = new double[numstates];
6246
6247 //stores the scaling value for each time point
6248 double[] scale = new double[nmaxtime];
6249
6250 //stores the transition probabilities for each column
6251 double[][] coltransitionprobs = new double[numstates][numstates];
6252
6253 //maps cell ID to printwriter objects
6254 HashMap hmcellToFourColPW = null;
6255 if (bprintsegment)
6256 {
6257 hmcellToFourColPW = new HashMap();
6258 }
6259
6260 RecIntString[] ordered = null;//new RecIntString[chromfiles.length];
6261 RecIntStringSplit[] orderedsplit = null;//new RecIntString[chromfiles.length];
6262
6263 if (bsplit)
6264 {
6265 orderedsplit = new RecIntStringSplit[chromfiles.length];
6266 for (int nindex = 0; nindex < orderedsplit.length; nindex++)
6267 {
6268 int nlastperiodindex = chromSeq[nindex].lastIndexOf('.');
6269
6270 if (nlastperiodindex == -1)
6271 {
6272 throw new IllegalArgumentException("No period found in chromosome "+chromSeq[nindex]+" despite split being specified");
6273 }
6274
6275 String szchromportion = chromSeq[nindex].substring(0, nlastperiodindex);
6276 int nsplitbinindex = Integer.parseInt(chromSeq[nindex].substring(nlastperiodindex+1));
6277 orderedsplit[nindex] = new RecIntStringSplit(nindex,cellSeq[nindex],szchromportion,nsplitbinindex);
6278 }
6279 Arrays.sort(orderedsplit,new RecIntStringSplitCompare());
6280 }
6281 else
6282 {
6283 ordered = new RecIntString[chromfiles.length];
6284 for (int nindex = 0; nindex < ordered.length; nindex++)
6285 {
6286 ordered[nindex] = new RecIntString(nindex,chromfiles[nindex]);
6287 }
6288 Arrays.sort(ordered,new RecIntStringCompare());
6289 }
6290
6291 hsprefix = new HashSet();
6292
6293 GZIPOutputStream pwprobszip = null;
6294 GZIPOutputStream pwmaxzip = null;
6295 GZIPOutputStream pwbedzip = null;
6296 PrintWriter pwprobs = null;
6297 PrintWriter pwmax = null;
6298 PrintWriter pwbed = null;
6299
6300 int noffset = 0;
6301 boolean bclosefile = true;
6302 boolean bnewfile = true;
6303
6304 //these can go across split files so defined out here
6305 int nstart = 0; //the start index of the current active interval
6306 int nmaxstateprev = -1;
6307 int nprevlinecount = 0;
6308 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
6309 {
6310 int nordered_nseq;
6311 String szactualchrom;
6312 if (bsplit)
6313 {
6314 nordered_nseq = orderedsplit[nseq].nindex;
6315 szactualchrom = orderedsplit[nseq].szchrom;
6316 }
6317 else
6318 {
6319 nordered_nseq = ordered[nseq].nindex;
6320 szactualchrom = chromSeq[nordered_nseq];
6321 }
6322 //goes through each sequence
6323
6324 int[] traindataObservedIndex_nseq = traindataObservedIndex[nordered_nseq];
6325 boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nordered_nseq];
6326
6327
6328 if (bsplit)
6329 {
6330 //noffset = orderedsplit[nseq].nsplitbinindex * numsplitbins;
6331 if (orderedsplit[nseq].nsplitbinindex==0) //(noffset == 0)
6332 {
6333 noffset = 0;
6334 bnewfile = true;
6335 }
6336 else
6337 {
6338 noffset += nprevlinecount;
6339 if ((nseq >= 1) && (orderedsplit[nseq].nsplitbinindex != (orderedsplit[nseq-1].nsplitbinindex+1)))
6340 {
6341 throw new IllegalArgumentException("For "+orderedsplit[nseq].szcell+"_"+orderedsplit[nseq].szchrom+" found "+
6342 "a file with split index "+orderedsplit[nseq].nsplitbinindex+", but not "+
6343 (orderedsplit[nseq].nsplitbinindex-1));
6344 }
6345 bnewfile = false;
6346 }
6347 bclosefile = ((nseq + 1 == orderedsplit.length)||(orderedsplit[nseq+1].nsplitbinindex == 0));
6348 }
6349
6350
6351 if (bnewfile)
6352 {
6353
6354 String szprefix = "";
6355
6356 if (!cellSeq[nordered_nseq].equals(""))
6357 {
6358 szprefix += cellSeq[nordered_nseq]+"_";
6359 }
6360 szprefix += numstates;
6361 if (!szoutfileID.equals(""))
6362 {
6363 szprefix += "_"+szoutfileID;
6364 }
6365 hsprefix.add(szprefix);
6366
6367
6368 if (bgzip)
6369 {
6370 if (bprintposterior)
6371 {
6372 //creates the posterior file
6373 //v.1.18 replacing chromSeq[nordered_nseq] with szactualchrom
6374 //String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+chromSeq[nordered_nseq]+ChromHMM.SZPOSTERIOREXTENSION+".gz";
6375 String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+szactualchrom+ChromHMM.SZPOSTERIOREXTENSION+".gz";
6376
6377 System.out.println("Writing to file "+szposterioroutfilename);
6378 //pwprobs = new PrintWriter(szposterioroutfilename);
6379 pwprobszip = new GZIPOutputStream(new FileOutputStream(szposterioroutfilename));
6380 String szout = cellSeq[nordered_nseq]+"\t"+szactualchrom+"\n";
6381
6382 byte[] btformat = szout.getBytes();
6383 pwprobszip.write(btformat,0,btformat.length);
6384
6385 //pwprobs.println(cellSeq[nordered_nseq]+"\t"+chromSeq[nordered_nseq]);
6386 StringBuffer sbout = new StringBuffer();
6387 for (int ni = 0; ni < numstates-1; ni++)
6388 {
6389 sbout.append(""+chorder+(ni+1)+"\t");
6390 //pwprobs.print(""+chorder+(ni+1)+"\t");
6391 }
6392 sbout.append(""+chorder+(numstates)+"\n");
6393
6394 btformat = sbout.toString().getBytes();
6395 pwprobszip.write(btformat,0,btformat.length);
6396 //pwprobs.println(""+chorder+(numstates));
6397 }
6398
6399 if (bprintstatebyline)
6400 {
6401 //creates a file which has the state with the maximum posterior probability
6402 String szmaxoutfilename = szoutputdir+"/STATEBYLINE/"+szprefix+"_"+szactualchrom+ChromHMM.SZSTATEBYLINEEXTENSION+".gz";
6403 System.out.println("Writing to file "+szmaxoutfilename);
6404 pwmaxzip = new GZIPOutputStream(new FileOutputStream(szmaxoutfilename));
6405 //pwmax = new PrintWriter(szmaxoutfilename);
6406 String szout = cellSeq[nordered_nseq]+"\t"+szactualchrom +"\n";
6407 byte[] btformat = szout.getBytes();
6408 pwmaxzip.write(btformat,0,btformat.length);
6409
6410 szout = "MaxState "+chorder+"\n";
6411
6412 btformat = szout.getBytes();
6413 pwmaxzip.write(btformat,0,btformat.length);
6414 //pwmax.println(cellSeq[nordered_nseq]+"\t"+chromSeq[nordered_nseq]);
6415 //pwmax.println("MaxState "+chorder);
6416 }
6417
6418 if (bprintsegment)
6419 {
6420 //creates a file which has the maximum segmentation
6421 //we only have one file per cell type here
6422 pwbedzip = (GZIPOutputStream) hmcellToFourColPW.get(cellSeq[nordered_nseq]);
6423
6424 if (pwbedzip == null)
6425 {
6426 //haven't seen this cell type
6427 String szsegmentoutfilename = szoutputdir+"/" + szprefix+SZSEGMENTEXTENSION+".gz";
6428
6429 pwbedzip = new GZIPOutputStream(new FileOutputStream(szsegmentoutfilename));
6430 //pwbed = new PrintWriter(szsegmentoutfilename);
6431 System.out.println("Writing to file "+szsegmentoutfilename);
6432 hmcellToFourColPW.put(cellSeq[nordered_nseq],pwbedzip);
6433 }
6434 }
6435 }
6436 else
6437 {
6438 if (bprintposterior)
6439 {
6440 //creates the posterior file
6441
6442 String szposterioroutfilename = szoutputdir+"/POSTERIOR/"+szprefix+"_"+szactualchrom+ChromHMM.SZPOSTERIOREXTENSION;
6443
6444 System.out.println("Writing to file "+szposterioroutfilename);
6445 pwprobs = new PrintWriter(szposterioroutfilename);
6446 pwprobs.println(cellSeq[nordered_nseq]+"\t"+chromSeq[nordered_nseq]);
6447 for (int ni = 0; ni < numstates-1; ni++)
6448 {
6449 pwprobs.print(""+chorder+(ni+1)+"\t");
6450 }
6451 pwprobs.println(""+chorder+(numstates));
6452 }
6453
6454 if (bprintstatebyline)
6455 {
6456 //creates a file which has the state with the maximum posterior probability
6457 String szmaxoutfilename = szoutputdir+"/STATEBYLINE/"+szprefix+"_"+szactualchrom+ChromHMM.SZSTATEBYLINEEXTENSION;
6458 System.out.println("Writing to file "+szmaxoutfilename);
6459 pwmax = new PrintWriter(szmaxoutfilename);
6460 pwmax.println(cellSeq[nordered_nseq]+"\t"+szactualchrom);
6461 pwmax.println("MaxState "+chorder);
6462 }
6463
6464 //PrintWriter pwbed = null;
6465 if (bprintsegment)
6466 {
6467 //creates a file which has the maximum segmentation
6468 //we only have one file per cell type here
6469 pwbed = (PrintWriter) hmcellToFourColPW.get(cellSeq[nordered_nseq]);
6470
6471 if (pwbed == null)
6472 {
6473 //haven't seen this cell type
6474 String szsegmentoutfilename = szoutputdir+"/" + szprefix+SZSEGMENTEXTENSION;
6475
6476 pwbed = new PrintWriter(szsegmentoutfilename);
6477 System.out.println("Writing to file "+szsegmentoutfilename);
6478 hmcellToFourColPW.put(cellSeq[nordered_nseq],pwbed);
6479 }
6480 }
6481 }
6482 }
6483
6484
6485 if (bscaleemissions)
6486 {
6487 for (int ni = 0; ni < emissionproducts.length; ni++)
6488 {
6489 //going through each combination of marks
6490 if (traindataObservedSeqFlags_nseq[ni])
6491 {
6492 //this signature of marks is observed on the current chromosome so
6493 //updating its emission probabilities
6494 double[] emissionproducts_ni = emissionproducts[ni];
6495 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
6496 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
6497
6498 for (int ns = 0; ns < numstates; ns++)
6499 {
6500 emissionproducts_ni[ns] = 1;
6501 }
6502
6503 for (int nmod = 0; nmod < numdatasets; nmod++)
6504 {
6505 for (int ns = 0; ns < numstates; ns++)
6506 {
6507 if (traindataNotMissing_ni[nmod])
6508 {
6509 //we are include this marks emission probability
6510 if (traindataObservedValues_ni[nmod])
6511 {
6512 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
6513 }
6514 else
6515 {
6516 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
6517 }
6518 }
6519 // otherwise treated as missing omitting from product
6520 }
6521
6522 double dmaxval = 0;
6523 for (int ns = 0; ns < numstates; ns++)
6524 {
6525 if (emissionproducts_ni[ns] > dmaxval)
6526 {
6527 dmaxval = emissionproducts_ni[ns];
6528 }
6529 }
6530
6531 if (dmaxval <=0)
6532 {
6533 for (int ns = 0; ns < numstates; ns++)
6534 {
6535 emissionproducts_ni[ns] = 1;
6536 }
6537 }
6538 else
6539 {
6540 for (int ns = 0; ns < numstates; ns++)
6541 {
6542 emissionproducts_ni[ns]/= dmaxval;
6543 }
6544 }
6545 }
6546 }
6547 }
6548 }
6549 else
6550 {
6551 for (int ni = 0; ni < emissionproducts.length; ni++)
6552 {
6553 //going through each combination of marks
6554 if (traindataObservedSeqFlags_nseq[ni])
6555 {
6556 //this signature of marks is observed on the current chromosome so
6557 //updating its emission probabilities
6558 double[] emissionproducts_ni = emissionproducts[ni];
6559 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
6560 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
6561
6562 boolean ballzero = true;
6563
6564 for (int ns = 0; ns < numstates; ns++)
6565 {
6566 double dproduct = 1;
6567 double[][] emissionprobs_ni = emissionprobs[ns];
6568
6569 //going through all marks
6570 for (int nmod = 0; nmod < numdatasets; nmod++)
6571 {
6572 if (traindataNotMissing_ni[nmod])
6573 {
6574 //we have observed the mark
6575 if (traindataObservedValues_ni[nmod])
6576 {
6577 dproduct *= emissionprobs_ni[nmod][1];
6578 }
6579 else
6580 {
6581 dproduct *= emissionprobs_ni[nmod][0];
6582 }
6583 }
6584 // otherwise treated as missing omitting from product
6585 }
6586 emissionproducts_ni[ns] = dproduct;
6587
6588 if (dproduct >= EPSILONEMISSIONS)
6589 {
6590 ballzero = false;
6591 }
6592 }
6593
6594 if (ballzero)
6595 {
6596 for (int ns = 0; ns < numstates; ns++)
6597 {
6598 emissionproducts_ni[ns] = EPSILONEMISSIONS;
6599 }
6600 }
6601 }
6602 }
6603 }
6604
6605 //initial probability in state s is initial probability times emission probability at first position
6606 double[] alpha_nt = alpha[0];
6607 double dscale = 0;
6608 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex_nseq[0]];
6609 for (int ns = 0; ns < numstates; ns++)
6610 {
6611 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
6612 dscale += alpha_nt[ns];
6613 }
6614 scale[0] = dscale;
6615
6616 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
6617 //converts the alpha terms to probabilities
6618 if (bscalebeta)
6619 {
6620 if (dscale == 0)
6621 {
6622 for (int ns = 0; ns < numstates; ns++)
6623 {
6624 //added
6625 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
6626 {
6627 alpha_nt[ns] = EPSILONSTATE;
6628 dscale += EPSILONSTATE;
6629 }
6630 }
6631 scale[0] = dscale;
6632 }
6633
6634 for (int ns = 0; ns < numstates; ns++)
6635 {
6636 alpha_nt[ns] /= dscale;
6637
6638 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
6639 {
6640 alpha_nt[ns] = EPSILONSTATE;
6641 }
6642 }
6643 }
6644 else
6645 {
6646 for (int ns = 0; ns < numstates; ns++)
6647 {
6648 alpha_nt[ns] /= dscale;
6649 }
6650 }
6651 //for (int ni = 0; ni < numstates; ni++)
6652 //{
6653 //alpha_nt[ni] /= dscale;
6654 //}
6655
6656 //stores in coltransitionprobs the transpose of transitionprobs
6657 for (int ni = 0; ni < numstates; ni++)
6658 {
6659 double[] coltransitionprobs_ni = coltransitionprobs[ni];
6660 for (int nj = 0; nj < numstates; nj++)
6661 {
6662 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
6663 }
6664 }
6665
6666 //forward step
6667 int numtime_nseq = numtime[nordered_nseq];
6668
6669 nprevlinecount = numtime_nseq;
6670
6671 for (int nt = 1; nt < numtime_nseq; nt++)
6672 {
6673 //the actual observed combination at position t
6674 double[] alpha_ntm1 = alpha[nt-1];
6675 alpha_nt = alpha[nt];
6676
6677 dscale = 0;
6678 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex_nseq[nt]];
6679 for (int ns = 0; ns < numstates; ns++)
6680 {
6681 //going through each state
6682
6683 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
6684 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
6685 double[] coltransitionprobs_ns = coltransitionprobs[ns];
6686
6687 double dtempsum = 0;
6688 if (transitionprobsnumCol_ns < nsparsecutoff)
6689 {
6690 //if it is sparse enough then it is worth the extra array indirection here
6691 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
6692 {
6693 //for each next state computing inner sum of all previous alpha and the transition probability
6694 //for all non-zero transitions into the state
6695 int nmappedindex = transitionprobsindexCol_ns[nj];
6696 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
6697 }
6698 }
6699 else
6700 {
6701 for (int nj = 0; nj < numstates; nj++)
6702 {
6703 //for each next state computing inner sum of all previous alpha and the transition probability
6704 //for all transitions into the state
6705 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
6706 }
6707 }
6708
6709 //multiply the transition sum by the emission probability
6710 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
6711 alpha_nt[ns] = dalphaval;
6712 dscale += dalphaval;
6713 }
6714
6715 //rescaling alpha
6716 scale[nt] = dscale;
6717 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
6718
6719 if (bscalebeta)
6720 {
6721 if (dscale == 0)
6722 {
6723 for (int ns = 0; ns < numstates; ns++)
6724 {
6725 //added
6726 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
6727 {
6728 alpha_nt[ns] = EPSILONSTATE;
6729 dscale += EPSILONSTATE;
6730 }
6731 }
6732 scale[nt] = dscale;
6733 }
6734
6735 for (int ns = 0; ns < numstates; ns++)
6736 {
6737 alpha_nt[ns] /= dscale;
6738
6739 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
6740 {
6741 alpha_nt[ns] = EPSILONSTATE;
6742 }
6743 }
6744 }
6745 else
6746 {
6747 for (int ns = 0; ns < numstates; ns++)
6748 {
6749 alpha_nt[ns] /= dscale;
6750 }
6751 }
6752 // for (int ns = 0; ns < numstates; ns++)
6753 // {
6754 // alpha_nt[ns] /= dscale;
6755 //}
6756 }
6757
6758 //backward step
6759 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
6760 int nlastindex = numtime_nseq-1;
6761 double dinitval;
6762 if (bscalebeta)
6763 {
6764 dinitval = 1.0/numstates;
6765 }
6766 else
6767 {
6768 dinitval = 1.0/scale[nlastindex];
6769 }
6770
6771 for (int ns = 0; ns < numstates; ns++)
6772 {
6773 beta_ntp1[ns] = dinitval;
6774 }
6775 //double dinitval = 1.0/scale[nlastindex];
6776 //for (int ns = 0; ns < numstates; ns++)
6777 //{
6778 // beta_ntp1[ns] = dinitval;
6779 //}
6780
6781 int nmappedindexouter;
6782
6783 double ddenom = 0;
6784
6785 //gamma_nt - P(x=S| o_0,...,o_t)
6786 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,x_t=s|lambda)
6787 double[] gamma_nt = gamma[nlastindex];
6788 for (int ns = 0; ns < gamma_nt.length; ns++)
6789 {
6790 double dval = alpha[nlastindex][ns]*beta_ntp1[ns];
6791 ddenom += dval;
6792 gamma_nt[ns] = dval;
6793 }
6794
6795 if (ddenom > 0)
6796 {
6797 for (int ns = 0; ns < gamma_nt.length; ns++)
6798 {
6799 gamma_nt[ns] /= ddenom;
6800 }
6801 }
6802
6803
6804 for (int nt = nlastindex - 1; nt >= 0; nt--)
6805 {
6806 gamma_nt = gamma[nt];
6807 int ntp1 = (nt+1);
6808
6809 double[] emissionproducts_ncombo_ntp1 = emissionproducts[traindataObservedIndex_nseq[ntp1]];
6810 double dsumbeta = 0;
6811 double dscale_nt = scale[nt];
6812
6813 for (int ns = 0; ns < numstates; ns++)
6814 {
6815 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_ncombo_ntp1[ns];
6816 }
6817
6818 if (bscaleemissions)
6819 {
6820 //adding here to help numerical stability
6821 double dmaxval = 0;
6822 for (int ns = 0; ns < numstates; ns++)
6823 {
6824 if (tempproductbetaemiss[ns] > dmaxval)
6825 {
6826 dmaxval = tempproductbetaemiss[ns];
6827 }
6828 }
6829 for (int ns = 0; ns < numstates; ns++)
6830 {
6831 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
6832 }
6833 }
6834
6835 //double dscaleinv = 1.0/scale[nt];
6836 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
6837 for (int ni = 0; ni < numstates; ni++)
6838 {
6839 double dtempsum = 0;
6840 int[] transitionprobsindex_ni = transitionprobsindex[ni];
6841 double[] transitionprobs_ni = transitionprobs[ni];
6842 int transitionprobsnum_ni = transitionprobsnum[ni];
6843
6844 if (transitionprobsnum_ni < nsparsecutoff)
6845 {
6846 //if it is sparse enough then it is worth the extra array indirection here
6847 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
6848 {
6849 //for each state summing over transition probability to state j, emission probablity in j at next step
6850 //and probability of observing the remaining sequence
6851 nmappedindexouter = transitionprobsindex_ni[nj];
6852 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
6853 }
6854 }
6855 else
6856 {
6857 for (int nj = 0; nj < numstates; nj++)
6858 {
6859 //for each state summing over transition probability to state j, emission probablity in j at next step
6860 //and probability of observing the remaining sequence
6861 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
6862 }
6863 }
6864
6865 if (bscalebeta)
6866 {
6867 beta_nt[ni] = dtempsum;
6868 dsumbeta += dtempsum;
6869 }
6870 else
6871 {
6872 double dratio = dtempsum/dscale_nt;
6873 if (dratio > Double.MAX_VALUE)
6874 {
6875 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
6876 }
6877 else
6878 {
6879 beta_nt[ni] = dratio;
6880 }
6881 }
6882 //double dratio = dtempsum/dscale_nt;
6883 //if (dratio > Double.MAX_VALUE)
6884 //{
6885 // beta_nt[ni] = Double.MAX_VALUE;
6886 //}
6887 //else
6888 //{
6889 // beta_nt[ni] = dratio;//dtempsum/dscale_nt;
6890 //}
6891 }
6892
6893 if (bscalebeta)
6894 {
6895 for (int ni = 0; ni < numstates; ni++)
6896 {
6897 beta_nt[ni]/= dsumbeta;
6898
6899 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
6900 {
6901 beta_nt[ni] = EPSILONSTATE;
6902 }
6903 }
6904 }
6905
6906 ddenom = 0;
6907 alpha_nt = alpha[nt];
6908
6909 //gamma_nt - P(x=S| o_0,...,o_t)
6910 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
6911
6912 for (int ns = 0; ns < gamma_nt.length; ns++)
6913 {
6914 double dval = alpha_nt[ns]*beta_nt[ns];
6915
6916 ddenom += dval;
6917 gamma_nt[ns] = dval;
6918 }
6919
6920 if (ddenom > 0)
6921 {
6922 for (int ns = 0; ns < gamma_nt.length; ns++)
6923 {
6924 gamma_nt[ns]/=ddenom;
6925 }
6926 }
6927 beta_ntp1 = beta_nt;
6928 }
6929
6930
6931 gamma_nt = gamma[0];
6932
6933 double dmaxval = 0;
6934 int nmaxstate = 0;
6935
6936 int nt = 0;
6937
6938 if (bgzip)
6939 {
6940 //handling the first line
6941 if (bnewfile)
6942 {
6943 for (int ns = 0; ns < gamma_nt.length; ns++)
6944 {
6945 int nmappedstate = stateordering[ns]; //maps new state to old
6946 double dprob = gamma_nt[nmappedstate];
6947 if (bprintposterior)
6948 {
6949 String szout;
6950 if (ns > 0)
6951 {
6952 szout = "\t"+nf.format(dprob);
6953 //print with tab if not the first
6954 //pwprobs.print("\t"+nf.format(dprob));
6955 }
6956 else
6957 {
6958 szout = nf.format(dprob);
6959 //pwprobs.print(nf.format(dprob));
6960 }
6961
6962 byte[] btformat = szout.getBytes();
6963 pwprobszip.write(btformat,0,btformat.length);
6964 }
6965
6966 if (dprob > dmaxval)
6967 {
6968 //best one found so far
6969 dmaxval = dprob;
6970 nmaxstate = ns;
6971 }
6972 }
6973
6974 if (bprintposterior)
6975 {
6976 String szout = "\n";
6977 byte[] btformat = szout.getBytes();
6978 pwprobszip.write(btformat,0,btformat.length);
6979 //pwprobs.println();
6980 }
6981
6982 if (bprintstatebyline)
6983 {
6984 String szout = ""+(nmaxstate+1)+"\n";
6985 byte[] btformat = szout.getBytes();
6986 pwmaxzip.write(btformat,0,btformat.length);
6987 //pwmax.println(""+(nmaxstate+1));
6988 }
6989
6990 //this contains the best state of the previous interval
6991 nmaxstateprev = nmaxstate;
6992 nt = 1;
6993 nstart = 0;
6994 }
6995
6996
6997 for ( ; nt < numtime_nseq; nt++)
6998 {
6999 gamma_nt = gamma[nt];
7000
7001 dmaxval = 0;
7002 nmaxstate = 0;
7003 for (int ns = 0; ns < gamma_nt.length; ns++)
7004 {
7005 int nmappedstate = stateordering[ns]; //maps new state to old
7006 double dprob = gamma_nt[nmappedstate];
7007 if (bprintposterior)
7008 {
7009 String szout;
7010 if (ns > 0)
7011 {
7012 szout = "\t"+nf.format(dprob);
7013 //print with tab the first time
7014 //pwprobs.print("\t"+nf.format(dprob));
7015 }
7016 else
7017 {
7018 szout = nf.format(dprob);
7019 //pwprobs.print(nf.format(dprob));
7020 }
7021 byte[] btformat = szout.getBytes();
7022 pwprobszip.write(btformat,0,btformat.length);
7023 }
7024
7025 if (dprob > dmaxval)
7026 {
7027 dmaxval = dprob;
7028 nmaxstate = ns;
7029 }
7030 }
7031
7032 if (bprintposterior)
7033 {
7034 //pwprobs.println();
7035 String szout = "\n";
7036 byte[] btformat = szout.getBytes();
7037 pwprobszip.write(btformat,0,btformat.length);
7038 }
7039
7040 if (bprintstatebyline)
7041 {
7042 String szout = (nmaxstate+1)+"\n";
7043 byte[] btformat = szout.getBytes();
7044 pwmaxzip.write(btformat,0,btformat.length);
7045 //pwmax.println(""+(nmaxstate+1));
7046 }
7047
7048 if (bprintsegment&&(nmaxstateprev != nmaxstate))
7049 {
7050 //print out last segment we are done with
7051 //String szout = chromSeq[nordered_nseq]+"\t"+((nstart+noffset)*nbinsize)+"\t"+((nt+noffset)*nbinsize)+"\t"+chorder+(nmaxstateprev+1) +"\n";
7052 String szout = szactualchrom+"\t"+(nstart*nbinsize)+"\t"+((nt+noffset)*nbinsize)+"\t"+chorder+(nmaxstateprev+1) +"\n";
7053 //pwbed.println(chromSeq[nordered_nseq]+"\t"+(nstart*nbinsize)+"\t"+(nt*nbinsize)+"\t"+chorder+(nmaxstateprev+1));
7054 byte[] btformat = szout.getBytes();
7055 pwbedzip.write(btformat,0,btformat.length);
7056
7057 //start a new segment now
7058 nstart = nt+noffset;
7059 nmaxstateprev = nmaxstate;
7060 }
7061 }
7062
7063 if (bclosefile)
7064 {
7065 if (bprintsegment)
7066 {
7067 int nlastcoordinate;
7068 Integer objMaxCoord = null;
7069 if (hmMaxCoord != null)
7070 {
7071 //objMaxCoord = ((Integer) hmMaxCoord.get(chromSeq[nordered_nseq]));
7072 objMaxCoord = ((Integer) hmMaxCoord.get(szactualchrom));
7073 }
7074
7075 if (objMaxCoord != null)
7076 {
7077 nlastcoordinate = Math.min((numtime_nseq+noffset)*nbinsize,((Integer) objMaxCoord).intValue());
7078
7079 if (nstart*nbinsize >= nlastcoordinate)
7080 {
7081 //v1.26
7082 throw new IllegalArgumentException("Start of interval "+(nstart*nbinsize+1)+" (1-based) is past the end of the chromosome "+nlastcoordinate+
7083 "; Check if chromosome length file given to LearnModel is the same used for the binarization");
7084 }
7085 }
7086 else
7087 {
7088 nlastcoordinate = (numtime_nseq+noffset)*nbinsize;
7089 }
7090 //pwbed.println(chromSeq[nordered_nseq]+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1));
7091
7092 String szout = szactualchrom+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1)+"\n";
7093 byte[] btformat = szout.getBytes();
7094 pwbedzip.write(btformat,0,btformat.length);
7095 }
7096
7097 //close out the max state file if that was requested
7098 if (bprintstatebyline)
7099 {
7100 pwmaxzip.finish();
7101 pwmaxzip.close();
7102 }
7103 //close out the posterior state file if that was requested
7104 if (bprintposterior)
7105 {
7106 pwprobszip.finish();
7107 pwprobszip.close();
7108 }
7109 }
7110 }
7111 else
7112 {
7113 if (bnewfile)
7114 {
7115 //handling the first line
7116 for (int ns = 0; ns < gamma_nt.length; ns++)
7117 {
7118 int nmappedstate = stateordering[ns]; //maps new state to old
7119 double dprob = gamma_nt[nmappedstate];
7120 if (bprintposterior)
7121 {
7122 if (ns > 0)
7123 {
7124 //print with tab if not the first
7125 pwprobs.print("\t"+nf.format(dprob));
7126 }
7127 else
7128 {
7129 pwprobs.print(nf.format(dprob));
7130 }
7131 }
7132
7133 if (dprob > dmaxval)
7134 {
7135 //best one found so far
7136 dmaxval = dprob;
7137 nmaxstate = ns;
7138 }
7139 }
7140
7141 if (bprintposterior)
7142 {
7143 pwprobs.println();
7144 }
7145
7146 if (bprintstatebyline)
7147 {
7148 pwmax.println(""+(nmaxstate+1));
7149 }
7150
7151 //this contains the best state of the previous interval
7152 nmaxstateprev = nmaxstate;
7153 nt = 1;
7154 nstart = 0;
7155 }
7156
7157 for ( ; nt < numtime_nseq; nt++)
7158 {
7159 gamma_nt = gamma[nt];
7160
7161 dmaxval = 0;
7162 nmaxstate = 0;
7163 for (int ns = 0; ns < gamma_nt.length; ns++)
7164 {
7165 int nmappedstate = stateordering[ns]; //maps new state to old
7166 double dprob = gamma_nt[nmappedstate];
7167 if (bprintposterior)
7168 {
7169 if (ns > 0)
7170 {
7171 //print with tab the first time
7172 pwprobs.print("\t"+nf.format(dprob));
7173 }
7174 else
7175 {
7176 pwprobs.print(nf.format(dprob));
7177 }
7178 }
7179
7180 if (dprob > dmaxval)
7181 {
7182 dmaxval = dprob;
7183 nmaxstate = ns;
7184 }
7185 }
7186
7187 if (bprintposterior)
7188 {
7189 pwprobs.println();
7190 }
7191
7192 if (bprintstatebyline)
7193 {
7194 pwmax.println(""+(nmaxstate+1));
7195 }
7196
7197 if (bprintsegment&&(nmaxstateprev != nmaxstate))
7198 {
7199 //print out last segment we are done with
7200 pwbed.println(szactualchrom+"\t"+(nstart*nbinsize)+"\t"+((nt+noffset)*nbinsize)+"\t"+chorder+(nmaxstateprev+1));
7201 //start a new segment now
7202 nstart = nt + noffset;
7203 nmaxstateprev = nmaxstate;
7204 }
7205 }
7206
7207 if (bclosefile)
7208 {
7209 if (bprintsegment)
7210 {
7211 int nlastcoordinate;
7212 Integer objMaxCoord = null;
7213 if (hmMaxCoord != null)
7214 {
7215 objMaxCoord = ((Integer) hmMaxCoord.get(szactualchrom));
7216 }
7217
7218 if (objMaxCoord != null)
7219 {
7220 nlastcoordinate = Math.min((numtime_nseq+noffset)*nbinsize,((Integer) objMaxCoord).intValue());
7221
7222 if (nstart*nbinsize >= nlastcoordinate)
7223 {
7224 //v1.26
7225 throw new IllegalArgumentException("Start of interval "+(nstart*nbinsize+1)+" (1-based) is past the end of the chromosome "+nlastcoordinate+
7226 "; Check if chromosome length file given to LearnModel is the same used for the binarization");
7227 }
7228 }
7229 else
7230 {
7231 nlastcoordinate = (numtime_nseq+noffset)*nbinsize;
7232 }
7233
7234 pwbed.println(szactualchrom+"\t"+(nstart*nbinsize)+"\t"+nlastcoordinate+"\t"+chorder+(nmaxstateprev+1));
7235 }
7236
7237 //close out the max state file if that was requested
7238 if (bprintstatebyline)
7239 {
7240 pwmax.close();
7241 }
7242 //close out the posterior state file if that was requested
7243 if (bprintposterior)
7244 {
7245 pwprobs.close();
7246 }
7247 }
7248 }
7249 }
7250
7251 //if segment print was requested then we are going to go close those printwriters
7252 if (bprintsegment)
7253 {
7254 Iterator itr = hmcellToFourColPW.values().iterator();
7255 if (bgzip)
7256 {
7257 while (itr.hasNext())
7258 {
7259 GZIPOutputStream pwzip = (GZIPOutputStream) itr.next();
7260 pwzip.finish();
7261 pwzip.close();
7262 }
7263 }
7264 else
7265 {
7266 //if segment print was requested then we are going to go close those printwriters
7267 while (itr.hasNext())
7268 {
7269 PrintWriter pw = (PrintWriter) itr.next();
7270 pw.close();
7271 }
7272 }
7273 }
7274 }
7275
7276
7277 ///////////////////////////////////////////////////////////////////////////////////////////
7278
7279 /**
7280 * API call to compute max state at position npos (0-based) given input data
7281 */
7282 public int getMaxStateAtPos(int[][] data, int npos) throws IOException
7283 {
7284
7285 if ((npos < 0) || (npos >= data.length))
7286 {
7287 throw new IllegalArgumentException(npos+" is not in range of data");
7288 }
7289
7290 //number of non-zero transition required to be less than this at the more stringent cutoff
7291 //for trying to exploit sparsity in the transition matrix for efficiency gains
7292 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
7293
7294 //stores temporary product terms
7295 double[] tempproductbetaemiss = new double[numstates];
7296
7297 //This stores the alpha values at each time point and number of states
7298 double[][] alpha = new double[data.length][numstates];
7299
7300 //Temporary storage of the gamma's for each state
7301 //double[][] gamma = new double[data.length][numstates];
7302
7303 //Temporary storage of the beta values for each state
7304 double[] beta_nt = new double[numstates];
7305
7306 //Temporary storage of the beta values for each state at the next time point
7307 double[] beta_ntp1 = new double[numstates];
7308
7309 //stores the scaling value for each time point
7310 double[] scale = new double[data.length];
7311
7312 //stores the transition probabilities for each column
7313 double[][] coltransitionprobs = new double[numstates][numstates];
7314
7315
7316 //numdatasets is the number of marks we are integrating
7317 int numdatasets = data[0].length;
7318
7319 String[] szdataA = new String[data.length];
7320 for (int nrow = 0; nrow < data.length; nrow++)
7321 {
7322 StringBuffer sb = new StringBuffer();
7323
7324 int[] data_nrow = data[nrow];
7325 for (int ncol = 0; ncol < numdatasets; ncol++)
7326 {
7327 int nval = data_nrow[ncol];
7328
7329 if (nval == 0)
7330 {
7331 sb.append("0");
7332 }
7333 else if (nval == 1)
7334 {
7335 sb.append("1");
7336 }
7337 else if (nval == 2)
7338 {
7339 //this means missing
7340 sb.append("2");
7341 }
7342 else
7343 {
7344 throw new IllegalArgumentException("Unrecognized value "+nval+" in input data");
7345 }
7346 }
7347 szdataA[nrow] = sb.toString();
7348 }
7349
7350 traindataObservedIndex = new int[1][data.length];
7351 int[] traindataObservedIndex_nseq = traindataObservedIndex[0];
7352
7353 HashMap hmObserved = new HashMap();
7354 int nobserved = 0;
7355
7356 for (int nrow = 0; nrow < szdataA.length; nrow++)
7357 {
7358 BigInteger theBigInteger = new BigInteger(szdataA[nrow],3);
7359 ObservedRec theObservedRec = (ObservedRec) hmObserved.get(theBigInteger);
7360
7361 if (theObservedRec == null)
7362 {
7363 //System.out.println(szmappingbyte.length());
7364 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
7365 hmObserved.put(theBigInteger, new ObservedRec(nobserved,null));
7366
7367 //saving this observed index
7368 traindataObservedIndex_nseq[nrow] = nobserved;
7369
7370 //increments the number of observed combinations of marks
7371 nobserved++;
7372 }
7373 else
7374 {
7375 //storing the index of the flags associated with this row
7376 traindataObservedIndex_nseq[nrow] = theObservedRec.nobserved;
7377 }
7378 }
7379
7380 //saving the mapping of signatures and chromsome observed on
7381
7382 //stores whether there is a present call at each location
7383 traindataObservedValues = new boolean[nobserved][numdatasets];
7384 //stores the emission probability for the i^th combination of marks in the j^th state
7385 double[][] emissionproducts = new double[traindataObservedValues.length][numstates];
7386
7387
7388 //stores whether the mark is not considered missing
7389 traindataNotMissing = new boolean[nobserved][numdatasets];
7390
7391 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
7392 while (hmObservedIterator.hasNext())
7393 {
7394 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
7395 BigInteger theBigInteger = (BigInteger) pairs.getKey();
7396 String szmapping = theBigInteger.toString(3); //getting back the mapping string
7397
7398 ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
7399 int ncurrindex = theObservedRec.nobserved;//this is an index on which obervation combination it is
7400
7401 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
7402 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
7403
7404 //if the mapping string is less than the number of data sets then
7405 //there are leading 0's will set for leading 0's not missing and absent
7406 int numch = szmapping.length();
7407 int numleading0 = numdatasets - numch;
7408 for (int nj = 0; nj < numleading0; nj++)
7409 {
7410 traindataObservedValues_ncurrindex[nj] = false;
7411 traindataNotMissing_ncurrindex[nj] = true;
7412 }
7413
7414 int nmappedindex = numleading0; //starting from the leading 0 position
7415 for (int nj = 0; nj < numch; nj++)
7416 {
7417 char ch = szmapping.charAt(nj);
7418
7419 if (ch == '0')
7420 {
7421 traindataObservedValues_ncurrindex[nmappedindex] = false;
7422 traindataNotMissing_ncurrindex[nmappedindex] = true;
7423 }
7424 else if (ch=='1')
7425 {
7426 traindataObservedValues_ncurrindex[nmappedindex] = true;
7427 traindataNotMissing_ncurrindex[nmappedindex] = true;
7428 }
7429 else
7430 {
7431 //missing data
7432 traindataObservedValues_ncurrindex[nmappedindex] = false;
7433 traindataNotMissing_ncurrindex[nmappedindex] = false;
7434 }
7435 nmappedindex++;
7436 }
7437 }
7438
7439
7440
7441 if (bscaleemissions)
7442 {
7443 for (int ni = 0; ni < emissionproducts.length; ni++)
7444 {
7445 //this signature of marks is observed on the current chromosome so
7446 //updating its emission probabilities
7447 double[] emissionproducts_ni = emissionproducts[ni];
7448 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
7449 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
7450
7451 for (int ns = 0; ns < numstates; ns++)
7452 {
7453 emissionproducts_ni[ns] = 1;
7454 }
7455
7456 for (int nmod = 0; nmod < numdatasets; nmod++)
7457 {
7458 for (int ns = 0; ns < numstates; ns++)
7459 {
7460 if (traindataNotMissing_ni[nmod])
7461 {
7462 //we are include this marks emission probability
7463 if (traindataObservedValues_ni[nmod])
7464 {
7465 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
7466 }
7467 else
7468 {
7469 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
7470 }
7471 }
7472 // otherwise treated as missing omitting from product
7473 }
7474
7475 double dmaxval = 0;
7476 for (int ns = 0; ns < numstates; ns++)
7477 {
7478 if (emissionproducts_ni[ns] > dmaxval)
7479 {
7480 dmaxval = emissionproducts_ni[ns];
7481 }
7482 }
7483
7484 if (dmaxval <=0)
7485 {
7486 for (int ns = 0; ns < numstates; ns++)
7487 {
7488 emissionproducts_ni[ns] = 1;
7489 }
7490 }
7491 else
7492 {
7493 for (int ns = 0; ns < numstates; ns++)
7494 {
7495 emissionproducts_ni[ns]/= dmaxval;
7496 }
7497 }
7498 }
7499 }
7500 }
7501 else
7502 {
7503 for (int ni = 0; ni < emissionproducts.length; ni++)
7504 {
7505 //this signature of marks is observed on the current chromosome so
7506 //updating its emission probabilities
7507 double[] emissionproducts_ni = emissionproducts[ni];
7508 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
7509 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
7510
7511 boolean ballzero = true;
7512
7513 for (int ns = 0; ns < numstates; ns++)
7514 {
7515 double dproduct = 1;
7516 double[][] emissionprobs_ni = emissionprobs[ns];
7517
7518 //going through all marks
7519 for (int nmod = 0; nmod < numdatasets; nmod++)
7520 {
7521 if (traindataNotMissing_ni[nmod])
7522 {
7523 //we have observed the mark
7524 if (traindataObservedValues_ni[nmod])
7525 {
7526 dproduct *= emissionprobs_ni[nmod][1];
7527 }
7528 else
7529 {
7530 dproduct *= emissionprobs_ni[nmod][0];
7531 }
7532 }
7533 // otherwise treated as missing omitting from product
7534 }
7535 emissionproducts_ni[ns] = dproduct;
7536
7537 if (dproduct >= EPSILONEMISSIONS)
7538 {
7539 ballzero = false;
7540 }
7541 }
7542
7543 if (ballzero)
7544 {
7545 for (int ns = 0; ns < numstates; ns++)
7546 {
7547 emissionproducts_ni[ns] = EPSILONEMISSIONS;
7548 }
7549 }
7550 }
7551 }
7552
7553 //initial probability in state s is initial probability times emission probability at first position
7554 double[] alpha_nt = alpha[0];
7555 double dscale = 0;
7556 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex_nseq[0]];
7557 for (int ns = 0; ns < numstates; ns++)
7558 {
7559 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
7560 dscale += alpha_nt[ns];
7561 }
7562 scale[0] = dscale;
7563
7564 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
7565 //converts the alpha terms to probabilities
7566 if (bscalebeta)
7567 {
7568 if (dscale == 0)
7569 {
7570 for (int ns = 0; ns < numstates; ns++)
7571 {
7572 //added
7573 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
7574 {
7575 alpha_nt[ns] = EPSILONSTATE;
7576 dscale += EPSILONSTATE;
7577 }
7578 }
7579 scale[0] = dscale;
7580 }
7581
7582 for (int ns = 0; ns < numstates; ns++)
7583 {
7584 alpha_nt[ns] /= dscale;
7585
7586 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
7587 {
7588 alpha_nt[ns] = EPSILONSTATE;
7589 }
7590 }
7591 }
7592 else
7593 {
7594 for (int ns = 0; ns < numstates; ns++)
7595 {
7596 alpha_nt[ns] /= dscale;
7597 }
7598 }
7599
7600 //stores in coltransitionprobs the transpose of transitionprobs
7601 for (int ni = 0; ni < numstates; ni++)
7602 {
7603 double[] coltransitionprobs_ni = coltransitionprobs[ni];
7604 for (int nj = 0; nj < numstates; nj++)
7605 {
7606 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
7607 }
7608 }
7609
7610 //forward step
7611 int numtime_nseq = data.length;
7612
7613
7614 for (int nt = 1; nt < numtime_nseq; nt++)
7615 {
7616 //the actual observed combination at position t
7617 double[] alpha_ntm1 = alpha[nt-1];
7618 alpha_nt = alpha[nt];
7619
7620 dscale = 0;
7621 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex_nseq[nt]];
7622 for (int ns = 0; ns < numstates; ns++)
7623 {
7624 //going through each state
7625 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
7626 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
7627 double[] coltransitionprobs_ns = coltransitionprobs[ns];
7628
7629 double dtempsum = 0;
7630 if (transitionprobsnumCol_ns < nsparsecutoff)
7631 {
7632 //if it is sparse enough then it is worth the extra array indirection here
7633 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
7634 {
7635 //for each next state computing inner sum of all previous alpha and the transition probability
7636 //for all non-zero transitions into the state
7637 int nmappedindex = transitionprobsindexCol_ns[nj];
7638 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
7639 }
7640 }
7641 else
7642 {
7643 for (int nj = 0; nj < numstates; nj++)
7644 {
7645 //for each next state computing inner sum of all previous alpha and the transition probability
7646 //for all transitions into the state
7647 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
7648 }
7649 }
7650
7651 //multiply the transition sum by the emission probability
7652 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
7653 alpha_nt[ns] = dalphaval;
7654 dscale += dalphaval;
7655 }
7656
7657 //rescaling alpha
7658 scale[nt] = dscale;
7659 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
7660
7661 if (bscalebeta)
7662 {
7663 if (dscale == 0)
7664 {
7665 for (int ns = 0; ns < numstates; ns++)
7666 {
7667 //added
7668 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
7669 {
7670 alpha_nt[ns] = EPSILONSTATE;
7671 dscale += EPSILONSTATE;
7672 }
7673 }
7674 scale[nt] = dscale;
7675 }
7676
7677 for (int ns = 0; ns < numstates; ns++)
7678 {
7679 alpha_nt[ns] /= dscale;
7680
7681 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
7682 {
7683 alpha_nt[ns] = EPSILONSTATE;
7684 }
7685 }
7686 }
7687 else
7688 {
7689 for (int ns = 0; ns < numstates; ns++)
7690 {
7691 alpha_nt[ns] /= dscale;
7692 }
7693 }
7694 // for (int ns = 0; ns < numstates; ns++)
7695 // {
7696 // alpha_nt[ns] /= dscale;
7697 //}
7698 }
7699
7700 //backward step
7701 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
7702 int nlastindex = numtime_nseq-1;
7703 double dinitval;
7704 if (bscalebeta)
7705 {
7706 dinitval = 1.0/numstates;
7707 }
7708 else
7709 {
7710 dinitval = 1.0/scale[nlastindex];
7711 }
7712
7713 for (int ns = 0; ns < numstates; ns++)
7714 {
7715 beta_ntp1[ns] = dinitval;
7716 }
7717
7718
7719 int nmappedindexouter;
7720
7721
7722 //gamma_nt - P(x=S| o_0,...,o_t)
7723 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,x_t=s|lambda)
7724 //double[] gamma_nt = gamma[nlastindex];
7725 //for (int ns = 0; ns < gamma_nt.length; ns++)
7726 //{
7727 // double dval = alpha[nlastindex][ns]*beta_ntp1[ns];
7728 // ddenom += dval;
7729 // gamma_nt[ns] = dval;
7730 //}
7731
7732 //for (int ns = 0; ns < gamma_nt.length; ns++)
7733 //{
7734 // gamma_nt[ns] /= ddenom;
7735 //}
7736
7737
7738 for (int nt = nlastindex - 1; nt >= npos; nt--) //only goes to npos not 0
7739 {
7740 //gamma_nt = gamma[nt];
7741 int ntp1 = (nt+1);
7742
7743 double[] emissionproducts_ncombo_ntp1 = emissionproducts[traindataObservedIndex_nseq[ntp1]];
7744 double dsumbeta = 0;
7745 double dscale_nt = scale[nt];
7746
7747 for (int ns = 0; ns < numstates; ns++)
7748 {
7749 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_ncombo_ntp1[ns];
7750 }
7751
7752 if (bscaleemissions)
7753 {
7754 //adding here to help numerical stability
7755 double dmaxval = 0;
7756 for (int ns = 0; ns < numstates; ns++)
7757 {
7758 if (tempproductbetaemiss[ns] > dmaxval)
7759 {
7760 dmaxval = tempproductbetaemiss[ns];
7761 }
7762 }
7763 for (int ns = 0; ns < numstates; ns++)
7764 {
7765 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
7766 }
7767 }
7768
7769 //double dscaleinv = 1.0/scale[nt];
7770 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
7771 for (int ni = 0; ni < numstates; ni++)
7772 {
7773 double dtempsum = 0;
7774 int[] transitionprobsindex_ni = transitionprobsindex[ni];
7775 double[] transitionprobs_ni = transitionprobs[ni];
7776 int transitionprobsnum_ni = transitionprobsnum[ni];
7777
7778 if (transitionprobsnum_ni < nsparsecutoff)
7779 {
7780 //if it is sparse enough then it is worth the extra array indirection here
7781 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
7782 {
7783 //for each state summing over transition probability to state j, emission probablity in j at next step
7784 //and probability of observing the remaining sequence
7785 nmappedindexouter = transitionprobsindex_ni[nj];
7786 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
7787 }
7788 }
7789 else
7790 {
7791 for (int nj = 0; nj < numstates; nj++)
7792 {
7793 //for each state summing over transition probability to state j, emission probablity in j at next step
7794 //and probability of observing the remaining sequence
7795 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
7796 }
7797 }
7798
7799 if (bscalebeta)
7800 {
7801 beta_nt[ni] = dtempsum;
7802 dsumbeta += dtempsum;
7803 }
7804 else
7805 {
7806 double dratio = dtempsum/dscale_nt;
7807 if (dratio > Double.MAX_VALUE)
7808 {
7809 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
7810 }
7811 else
7812 {
7813 beta_nt[ni] = dratio;
7814 }
7815 }
7816 //double dratio = dtempsum/dscale_nt;
7817 //if (dratio > Double.MAX_VALUE)
7818 //{
7819 // beta_nt[ni] = Double.MAX_VALUE;
7820 //}
7821 //else
7822 //{
7823 // beta_nt[ni] = dratio;//dtempsum/dscale_nt;
7824 //}
7825 }
7826
7827 if (bscalebeta)
7828 {
7829 for (int ni = 0; ni < numstates; ni++)
7830 {
7831 beta_nt[ni]/= dsumbeta;
7832
7833 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
7834 {
7835 beta_nt[ni] = EPSILONSTATE;
7836 }
7837 }
7838 }
7839
7840 //ddenom = 0;
7841 //alpha_nt = alpha[nt];
7842 beta_ntp1 = beta_nt;
7843 }
7844
7845 //gamma_nt - P(x=S| o_0,...,o_t)
7846 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
7847
7848 //for (int ns = 0; ns < gamma_nt.length; ns++)
7849 //{
7850 // double dval = alpha_nt[ns]*beta_nt[ns];
7851 // ddenom += dval;
7852 // gamma_nt[ns] = dval;
7853 //}
7854
7855 //for (int ns = 0; ns < gamma_nt.length; ns++)
7856 //{
7857 // gamma_nt[ns]/=ddenom;
7858 //}
7859 //}
7860
7861 double dmaxval = 0;
7862 int nmaxstate = 0;
7863 double[] alpha_npos = alpha[npos];
7864 //double[] beta_npos = beta[npos];
7865 //double[] gamma_npos = gamma[npos];
7866
7867
7868 for (int ns = 0; ns < alpha_npos.length; ns++)
7869 {
7870 double dval = alpha_npos[ns]*beta_ntp1[ns];// gamma_npos[ns];
7871 if (dval > dmaxval)
7872 {
7873 //best one found so far
7874 dmaxval = dval;
7875 nmaxstate = ns;
7876 }
7877 }
7878
7879 return (nmaxstate+1);
7880 }
7881
7882 ///////////////////////////////////////////////////////////////////////////////////////////
7883 /**
7884 * This is the core procedure for learning the parameters of the model
7885 */
7886 public void trainParametersWithLoad() throws IOException
7887 {
7888
7889 NumberFormat nf3 = NumberFormat.getInstance();
7890 nf3.setMaximumFractionDigits(3);
7891 nf3.setGroupingUsed(false);
7892 nf3.setMinimumFractionDigits(3);
7893
7894 NumberFormat nf1 = NumberFormat.getInstance();
7895 nf1.setMaximumFractionDigits(1);
7896 nf1.setMinimumFractionDigits(1);
7897 nf1.setGroupingUsed(false);
7898
7899 int niteration = 1;
7900
7901 boolean bconverged = false;
7902
7903 double dzerotransitioncutoff = Math.pow(10,-nzerotransitionpower);
7904
7905 //number of non-zero transition for the
7906 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
7907
7908 //number of non-zero transition that need to be less than this at the looser cut-off
7909 int nsparsecutofflooser = (int) (numstates * ChromHMM.SPARSECUTOFFLOOSERRATIO);
7910
7911 double dprevloglike;
7912
7913 //stores the maximum number of locations in any sequence and in each sequence
7914 //int[] numtime = new int[traindataObservedIndex.length];
7915 int nmaxtime = 0;
7916 for (int nseq = 0; nseq < numtime.length; nseq++)
7917 {
7918 //numtime[nseq] = traindataObservedIndex[nseq].length;
7919 if (numtime[nseq] > nmaxtime)
7920 {
7921 nmaxtime = numtime[nseq];
7922 }
7923 }
7924
7925 if (ChromHMM.BVERBOSE)
7926 {
7927 System.out.println("Maximum number of locations\t"+nmaxtime);
7928 }
7929
7930 //stores the emission probability for the i^th combination of marks in the j^th state
7931 double[][] emissionproducts = new double[nmaxtime][numstates]; //changed to maxtime here
7932
7933 //stores the scale for the emission probability for the i^th combination of marks
7934 double[] emissionproducts_scale = null;
7935
7936 if (bscaleemissions)
7937 {
7938 emissionproducts_scale = new double[nmaxtime];
7939 }
7940
7941 //stores temporary product terms
7942 double[] tempproductbetaemiss = new double[numstates];
7943
7944 //This stores the alpha values at each time point and number of states
7945 double[][] alpha = new double[nmaxtime][numstates];
7946
7947 //Temporary storage of the gamma's for each state
7948 double[] gamma_nt = new double[numstates];
7949
7950 //Temporary storage of the beta values for each state
7951 double[] beta_nt = new double[numstates];
7952
7953 //Temporary storage of the beta values for each state at the next time point
7954 double[] beta_ntp1 = new double[numstates];
7955
7956 //stores the scaling value for each time point
7957 double[] scale = new double[nmaxtime];
7958
7959 //stores the transition probabilities for each column
7960 double[][] coltransitionprobs = new double[numstates][numstates];
7961
7962 //stores the sufficient statistic for the initital probability in each state for the last visit
7963 double[][] gammainitstore = new double[chromfiles.length][numstates];//changed from traindataObservedIndex.length
7964
7965 //stores the sufficient statistics for computing the transition probabilities cumulated for each iteration
7966 double[][][] sxistore = new double[chromfiles.length][numstates][numstates];
7967
7968 //stores the sufficient statistic for computing the emission probabilities
7969 double[][][][] gammaksumstore =
7970 new double[chromfiles.length][numstates][numdatasets][numbuckets];
7971
7972 //temporary storage in computation of sxi
7973 double[][] sumforsxi = new double[numstates][numstates];
7974
7975 //stores the sum of the gamma values associated with each combination in each state
7976 double[][] gammaObservedSum = new double[nmaxtime][numstates];//changed from traindataObservedValues.length
7977
7978 //stores the indicies of the data
7979 int[] traindataObservedIndex = new int[nmaxtime];
7980
7981 //saving the mapping of signatures and chromsome observed on
7982 //stores whether there is a present call at each location
7983 boolean[][] traindataObservedValues = new boolean[nmaxtime][numdatasets];
7984
7985 //stores whether the mark is not considered missing
7986 boolean[][] traindataNotMissing = new boolean[nmaxtime][numdatasets]; //usually nobserved
7987
7988 int nelim = 0;
7989 long ltimeitr= System.currentTimeMillis();
7990 dprevloglike = Double.NEGATIVE_INFINITY;
7991
7992 do
7993 {
7994 dloglike = 0;
7995
7996 //for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
7997 for (int nseq = 0; nseq < chromfiles.length; nseq++)
7998 {
7999 //going through each sequence
8000
8001
8002 ///////////////////////////////////////////////////////////
8003 //loading the data just for the current chromosome
8004
8005 HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
8006
8007 int nobserved = 0;
8008
8009 if (ChromHMM.BVERBOSE)
8010 {
8011 System.out.println("reading\t"+szinputdir+" "+chromfiles[nseq]);
8012 }
8013 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nseq]);
8014 String szLine;
8015 br.readLine(); //first line tells cell type and chromosome
8016 br.readLine();//flush mark header
8017 ArrayList aldata = new ArrayList();
8018 while ((szLine = br.readLine())!=null)
8019 {
8020 StringTokenizer st = new StringTokenizer(szLine,"\t ");
8021 StringBuffer sb = new StringBuffer();
8022
8023 for (int ncol = 0; ncol < numdatasets; ncol++)
8024 {
8025 if (!st.hasMoreTokens())
8026 {
8027 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nseq]);
8028 }
8029
8030 String sztoken = st.nextToken();//.trim();
8031
8032 if (sztoken.equals("0"))
8033 {
8034 sb.append("0");
8035 }
8036 else if (sztoken.equals("1"))
8037 {
8038 sb.append("1");
8039 }
8040 else if (sztoken.equals("2"))
8041 {
8042 //this means missing
8043 sb.append("2");
8044 }
8045 else
8046 {
8047 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nseq]);
8048 }
8049 }
8050 aldata.add(sb.toString());
8051 }
8052 br.close();
8053
8054 int nsize = aldata.size();
8055 //traindataObservedIndex[nfile] = new int[nsize];
8056 //int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
8057
8058 for (int nrow = 0; nrow < nsize; nrow++)
8059 {
8060 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
8061 Integer theObservedInt = (Integer) hmObserved.get(theBigInteger);
8062 //boolean[] flagA;
8063
8064 if (theObservedInt == null)
8065 {
8066 //System.out.println(szmappingbyte.length());
8067 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
8068 hmObserved.put(theBigInteger, Integer.valueOf(nobserved));
8069
8070 //saving this observed index
8071 traindataObservedIndex[nrow] = nobserved;
8072
8073 //increments the number of observed combinations of marks
8074 nobserved++;
8075 }
8076 else
8077 {
8078 //storing the index of the flags associated with this row
8079 traindataObservedIndex[nrow] = ((Integer) theObservedInt).intValue();
8080 }
8081 }
8082
8083
8084
8085
8086
8087 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
8088 while (hmObservedIterator.hasNext())
8089 {
8090 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
8091 BigInteger theBigInteger = (BigInteger) pairs.getKey();
8092 String szmapping = theBigInteger.toString(3); //getting back the mapping string
8093
8094 //ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
8095 int ncurrindex = ((Integer) pairs.getValue()).intValue();// theObservedRec.nobserved;//this is an index on which obervation combination it is
8096
8097 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
8098 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
8099
8100 //if the mapping string is less than the number of data sets then
8101 //there are leading 0's will set for leading 0's not missing and absent
8102 int numch = szmapping.length();
8103 int numleading0 = numdatasets - numch;
8104 for (int nj = 0; nj < numleading0; nj++)
8105 {
8106 traindataObservedValues_ncurrindex[nj] = false;
8107 traindataNotMissing_ncurrindex[nj] = true;
8108 }
8109
8110 int nmappedindex = numleading0; //starting from the leading 0 position
8111 for (int nj = 0; nj < numch; nj++)
8112 {
8113 char ch = szmapping.charAt(nj);
8114
8115 if (ch == '0')
8116 {
8117 traindataObservedValues_ncurrindex[nmappedindex] = false;
8118 traindataNotMissing_ncurrindex[nmappedindex] = true;
8119 }
8120 else if (ch=='1')
8121 {
8122 traindataObservedValues_ncurrindex[nmappedindex] = true;
8123 traindataNotMissing_ncurrindex[nmappedindex] = true;
8124 }
8125 else
8126 {
8127 //missing data
8128 traindataObservedValues_ncurrindex[nmappedindex] = false;
8129 traindataNotMissing_ncurrindex[nmappedindex] = false;
8130 }
8131 nmappedindex++;
8132 }
8133 }
8134
8135
8136
8137
8138 ///////////////////////////////////////////////////////////
8139 //int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
8140 //boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nseq];
8141
8142 double[][][] gammaksum_nseq = gammaksumstore[nseq];
8143
8144 for (int ns = 0; ns < gammaksum_nseq.length; ns++)
8145 {
8146 //resetting the gamma sufficient statistics in the current sequence
8147 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
8148 for (int nmark = 0; nmark < gammaksum_nseq_ns.length; nmark++)
8149 {
8150 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
8151 {
8152 gammaksum_nseq_ns[nmark][nbucket] = 0;
8153 }
8154 }
8155 }
8156
8157 double[][] sxi_nseq = sxistore[nseq];
8158 for (int ni = 0; ni < sxi_nseq.length; ni++)
8159 {
8160 //reseeting the sxi sufficient statistics in the current sequence
8161 double[] sxi_nseq_ni = sxi_nseq[ni];
8162 for (int nj = 0; nj < sxi_nseq_ni.length; nj++)
8163 {
8164 sxi_nseq_ni[nj] = 0;
8165 }
8166 }
8167
8168 //gammaObservedSum stores the weight for each combination of marks in each state
8169 //for (int ncombo = 0; ncombo < gammaObservedSum.length; ncombo++)
8170 for (int ncombo = 0; ncombo < nobserved; ncombo++)
8171 {
8172 //resetting that to 0
8173 double[] gammaObservedSum_ncombo = gammaObservedSum[ncombo];
8174 for (int ns = 0; ns < gammaObservedSum_ncombo.length; ns++)
8175 {
8176 gammaObservedSum_ncombo[ns] = 0;
8177 }
8178 }
8179
8180
8181 if (bscaleemissions)
8182 {
8183 //for (int ni = 0; ni < emissionproducts.length; ni++)
8184 for (int ni = 0; ni < nobserved; ni++)
8185 {
8186 //going through each combination of marks
8187 //if (traindataObservedSeqFlags_nseq[ni])
8188 //{
8189 //this signature of marks is observed on the current chromosome so
8190 //updating its emission probabilities
8191 double[] emissionproducts_ni = emissionproducts[ni];
8192 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
8193 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
8194
8195 for (int ns = 0; ns < numstates; ns++)
8196 {
8197 emissionproducts_ni[ns] = 1;
8198 }
8199 emissionproducts_scale[ni] = 0;
8200
8201 for (int nmod = 0; nmod < numdatasets; nmod++)
8202 {
8203 for (int ns = 0; ns < numstates; ns++)
8204 {
8205 if (traindataNotMissing_ni[nmod])
8206 {
8207 //we are include this marks emission probability
8208 if (traindataObservedValues_ni[nmod])
8209 {
8210 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
8211 }
8212 }
8213 // otherwise treated as missing omitting from product
8214 }
8215
8216 double dmaxval = 0;
8217 for (int ns = 0; ns < numstates; ns++)
8218 {
8219 if (emissionproducts_ni[ns] > dmaxval)
8220 {
8221 dmaxval = emissionproducts_ni[ns];
8222 }
8223 }
8224
8225 if (dmaxval <= 0)//EPSILONEMISSIONS)
8226 {
8227 for (int ns = 0; ns < numstates; ns++)
8228 {
8229 emissionproducts_ni[ns] = 1;
8230 }
8231 //approximating log-likelihood
8232 emissionproducts_scale[ni] += Math.log(EPSILONEMISSIONS);
8233 }
8234 else
8235 {
8236 for (int ns = 0; ns < numstates; ns++)
8237 {
8238 emissionproducts_ni[ns]/= dmaxval;
8239 }
8240 emissionproducts_scale[ni] += Math.log(dmaxval);
8241 }
8242 }
8243 }
8244 }
8245 else
8246 {
8247 //for (int ni = 0; ni < emissionproducts.length; ni++)
8248 for (int ni = 0; ni < nobserved; ni++)
8249 {
8250 //going through each combination of marks
8251 //if (traindataObservedSeqFlags_nseq[ni])
8252 //{
8253 //this signature of marks is observed on the current chromosome so
8254 //updating its emission probabilities
8255 double[] emissionproducts_ni = emissionproducts[ni];
8256 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
8257 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
8258
8259 boolean ballzero = true;
8260
8261 for (int ns = 0; ns < numstates; ns++)
8262 {
8263 double dproduct = 1;
8264 double[][] emissionprobs_ns = emissionprobs[ns];
8265
8266 for (int nmod = 0; nmod < numdatasets; nmod++)
8267 {
8268 if (traindataNotMissing_ni[nmod])
8269 {
8270 //we are include this marks emission probability
8271 if (traindataObservedValues_ni[nmod])
8272 {
8273 //System.out.println("positive\t"+ns+"\t"+nmod+"\t1\t"+emissionprobs_ns[nmod][1]);
8274 dproduct *= emissionprobs_ns[nmod][1];
8275 }
8276 else
8277 {
8278 ///System.out.println("negative\t"+ns+"\t"+nmod+"\t0\t"+emissionprobs_ns[nmod][0]);
8279 dproduct *= emissionprobs_ns[nmod][0];
8280 }
8281 }
8282 // otherwise treated as missing omitting from product
8283 }
8284 //System.out.println(ns+"\t"+dproduct);
8285 emissionproducts_ni[ns] = dproduct;
8286
8287 if (dproduct >= EPSILONEMISSIONS)
8288 {
8289 ballzero = false;
8290 }
8291 }
8292
8293 if (ballzero)
8294 {
8295 for (int ns = 0; ns < numstates; ns++)
8296 {
8297 emissionproducts_ni[ns] = EPSILONEMISSIONS;
8298 }
8299 }
8300 }
8301 }
8302
8303 //initial probability in state s is initial probability times emission probability at first position
8304 double[] alpha_nt = alpha[0];
8305 double dscale = 0;
8306 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex[0]];
8307 for (int ns = 0; ns < numstates; ns++)
8308 {
8309 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
8310 dscale += alpha_nt[ns];
8311 }
8312 scale[0] = dscale;
8313
8314 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
8315 //converts the alpha terms to probabilities
8316 if (bscalebeta)
8317 {
8318 if (dscale == 0)
8319 {
8320 for (int ns = 0; ns < numstates; ns++)
8321 {
8322 //added
8323 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
8324 {
8325 alpha_nt[ns] = EPSILONSTATE;
8326 dscale += EPSILONSTATE;
8327 }
8328 }
8329 scale[0] = dscale;
8330 }
8331
8332 for (int ns = 0; ns < numstates; ns++)
8333 {
8334 alpha_nt[ns] /= dscale;
8335
8336 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
8337 {
8338 alpha_nt[ns] = EPSILONSTATE;
8339 }
8340 }
8341 }
8342 else
8343 {
8344 for (int ns = 0; ns < numstates; ns++)
8345 {
8346 alpha_nt[ns] /= dscale;
8347 }
8348 }
8349 //for (int ni = 0; ni < numstates; ni++)
8350 //{
8351 // alpha_nt[ni] /= dscale;
8352 //}
8353 dloglike += Math.log(dscale);
8354
8355 if (bscaleemissions)
8356 {
8357 dloglike += emissionproducts_scale[traindataObservedIndex[0]];
8358 }
8359
8360 //stores in coltransitionprobs the transpose of transitionprobs
8361 for (int ni = 0; ni < numstates; ni++)
8362 {
8363 double[] coltransitionprobs_ni = coltransitionprobs[ni];
8364 for (int nj = 0; nj < numstates; nj++)
8365 {
8366 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
8367 }
8368 }
8369
8370 //forward step
8371 int numtime_nseq = numtime[nseq];
8372 for (int nt = 1; nt < numtime_nseq; nt++)
8373 {
8374 //the actual observed combination at position t
8375 double[] alpha_ntm1 = alpha[nt-1];
8376 alpha_nt = alpha[nt];
8377
8378 dscale = 0;
8379 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex[nt]];
8380 for (int ns = 0; ns < numstates; ns++)
8381 {
8382 //stores the emission product for each location on the chromosome
8383
8384 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
8385 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
8386 double[] coltransitionprobs_ns = coltransitionprobs[ns];
8387
8388 double dtempsum = 0;
8389 if (transitionprobsnumCol_ns < nsparsecutoff)
8390 {
8391 //number of transitions is sparse enough worth going through the extra redirection
8392 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
8393 {
8394 //for each next state computing inner sum of all previous alpha and the transition probability
8395 //for all non-zero transitions into the state
8396 int nmappedindex = transitionprobsindexCol_ns[nj];
8397 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
8398 }
8399 }
8400 else
8401 {
8402 //avoid the redirect and multiply by 0
8403 for (int nj = 0; nj < numstates; nj++)
8404 {
8405 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
8406 }
8407 }
8408 //multiply the transition sum by the emission probability
8409 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
8410 alpha_nt[ns] = dalphaval;
8411 //System.out.println(ns+"\t"+alpha_nt[ns]+"\t"+dtempsum+"\t"+emissionproducts_nobserveindex[ns]);
8412 dscale += dalphaval;
8413 }
8414
8415
8416 //rescaling alpha
8417 scale[nt] = dscale;
8418 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
8419
8420 if (bscalebeta)
8421 {
8422 if (dscale == 0)
8423 {
8424 for (int ns = 0; ns < numstates; ns++)
8425 {
8426 //added
8427 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
8428 {
8429 alpha_nt[ns] = EPSILONSTATE;
8430 dscale += EPSILONSTATE;
8431 }
8432 }
8433 scale[nt] = dscale;
8434 }
8435
8436 for (int ns = 0; ns < numstates; ns++)
8437 {
8438 alpha_nt[ns] /= dscale;
8439
8440 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
8441 {
8442 alpha_nt[ns] = EPSILONSTATE;
8443 }
8444 }
8445 }
8446 else
8447 {
8448 for (int ns = 0; ns < numstates; ns++)
8449 {
8450 alpha_nt[ns] /= dscale;
8451 }
8452 }
8453 //for (int ns = 0; ns < numstates; ns++)
8454 //{
8455 // alpha_nt[ns] /= dscale;
8456 //}
8457
8458 dloglike += Math.log(dscale);
8459
8460 if (bscaleemissions)
8461 {
8462 dloglike += emissionproducts_scale[traindataObservedIndex[nt]];
8463 }
8464 }
8465
8466 //backward step
8467 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
8468 int nlastindex = numtime_nseq-1;
8469 double dinitval;
8470 if (bscalebeta)
8471 {
8472 dinitval = 1.0/numstates;
8473 }
8474 else
8475 {
8476 dinitval = 1.0/scale[nlastindex];
8477 }
8478
8479 for (int ns = 0; ns < numstates; ns++)
8480 {
8481 beta_ntp1[ns] = dinitval;
8482 }
8483 //double dinitval = 1.0/scale[nlastindex];
8484 //for (int ns = 0; ns < numstates; ns++)
8485 //{
8486 // beta_ntp1[ns] = dinitval;
8487 //}
8488
8489 double ddenom = 0;
8490
8491 //gamma_nt - P(x=S| o_0,...,o_t)
8492 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
8493 alpha_nt = alpha[nlastindex];
8494 for (int ns = 0; ns < gamma_nt.length; ns++)
8495 {
8496 double dval = alpha_nt[ns]*beta_ntp1[ns];
8497 ddenom += dval;
8498 gamma_nt[ns] = dval;
8499 }
8500
8501 if (ddenom > 0)
8502 {
8503 for (int ns = 0; ns < gamma_nt.length; ns++)
8504 {
8505 gamma_nt[ns] /=ddenom;
8506 }
8507 }
8508
8509 double[] gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex[nlastindex]];
8510
8511 for (int ns = 0; ns < numstates; ns++)
8512 {
8513 //first sum gamma over all common signatures
8514 //updates probability of observing the signature when in the state
8515 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
8516 }
8517
8518 for (int nt = nlastindex - 1; nt >= 0; nt--)
8519 {
8520 int ntp1 = (nt+1);
8521
8522 double[] emissionproducts_combo_ntp1 = emissionproducts[traindataObservedIndex[ntp1]];
8523
8524 for (int ns = 0; ns < numstates; ns++)
8525 {
8526 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_combo_ntp1[ns];
8527 }
8528
8529 if (bscaleemissions)
8530 {
8531 //adding here to help numerical stability
8532 double dmaxval = 0;
8533 for (int ns = 0; ns < numstates; ns++)
8534 {
8535 if (tempproductbetaemiss[ns] > dmaxval)
8536 {
8537 dmaxval = tempproductbetaemiss[ns];
8538 }
8539 }
8540 for (int ns = 0; ns < numstates; ns++)
8541 {
8542 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
8543 }
8544 }
8545
8546 //double dscaleinv = 1.0/scale[nt];
8547 double dsumbeta = 0;
8548 double dscale_nt = scale[nt];
8549 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
8550
8551 for (int ni = 0; ni < numstates; ni++)
8552 {
8553 double dtempsum = 0;
8554 int[] transitionprobsindex_ni = transitionprobsindex[ni];
8555 double[] transitionprobs_ni = transitionprobs[ni];
8556 int transitionprobsnum_ni = transitionprobsnum[ni];
8557
8558 if (transitionprobsnum_ni < nsparsecutoff)
8559 {
8560 //sparse enought to pay the indirection penalty
8561 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
8562 {
8563 //for each state summing over transition probability to state j, emission probablity in j at next step
8564 //and probability of observing the remaining sequence
8565 int nmappedindexouter = transitionprobsindex_ni[nj];
8566 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
8567 }
8568 }
8569 else
8570 {
8571 //not trying to exploit sparsity here
8572 for (int nj = 0; nj < numstates; nj++)
8573 {
8574 //for each state summing over transition probability to state j, emission probablity in j at next step
8575 //and probability of observing the remaining sequence
8576 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
8577 }
8578 }
8579
8580 if (bscalebeta)
8581 {
8582 beta_nt[ni] = dtempsum;
8583 dsumbeta += dtempsum;
8584 }
8585 else
8586 {
8587 double dratio = dtempsum/dscale_nt;
8588 if (dratio > Double.MAX_VALUE)
8589 {
8590 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
8591 }
8592 else
8593 {
8594 beta_nt[ni] = dratio;
8595 }
8596 }
8597 //double dratio = dtempsum/dscale_nt;
8598 //if (dratio > Double.MAX_VALUE)
8599 //{
8600 // beta_nt[ni] = Double.MAX_VALUE;
8601 //}
8602 //else
8603 //{
8604 // beta_nt[ni] = dratio;
8605 //}
8606 }
8607
8608 if (bscalebeta)
8609 {
8610 for (int ni = 0; ni < numstates; ni++)
8611 {
8612 beta_nt[ni]/= dsumbeta;
8613
8614 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
8615 {
8616 beta_nt[ni] = EPSILONSTATE;
8617 }
8618 }
8619 }
8620
8621 ddenom = 0;
8622
8623 alpha_nt = alpha[nt];
8624
8625 //gamma_nt - P(x=S| o_0,...,o_t)
8626 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
8627
8628 for (int ns = 0; ns < gamma_nt.length; ns++)
8629 {
8630 double dval = alpha_nt[ns]*beta_nt[ns];
8631 ddenom += dval;
8632 gamma_nt[ns] = dval;
8633 }
8634
8635 if (ddenom > 0)
8636 {
8637 for (int ns = 0; ns < gamma_nt.length; ns++)
8638 {
8639 gamma_nt[ns] /= ddenom;
8640 }
8641 }
8642
8643 gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex[nt]];
8644
8645 for (int ns = 0; ns < numstates; ns++)
8646 {
8647 //first sum gamma over all common signatures
8648 //updates probability of observing the signature when in the state
8649 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
8650 }
8651
8652 double dsum = 0;
8653
8654 //this compues the numerator portion
8655 for (int ni = 0; ni < numstates; ni++)
8656 {
8657 double[] sumforsxi_ni = sumforsxi[ni]; //computing expected number of transition from state i
8658 int[] transitionprobsindex_ni = transitionprobsindex[ni]; //indicies of non-zero transitions from state i
8659 double[] transitionprobs_ni = transitionprobs[ni]; //probability of transitions from state i
8660 int ntransitionprobsnum_ni = transitionprobsnum[ni]; //number of non-zero transitions from state i
8661 double dalpha_nt_ni = alpha_nt[ni];
8662 //sxi is P(q_t = S_i, q_(t+1) = S_j | O)
8663
8664 if (ntransitionprobsnum_ni < nsparsecutofflooser)
8665 {
8666 //enough 0 transitionto use sparsity here
8667 //looser cut off since the indirection is less of the total time
8668 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
8669 {
8670 int nmappedindex = transitionprobsindex_ni[nj];
8671 //computes transition probability from state i to j
8672 double dtempval = transitionprobs_ni[nmappedindex] *dalpha_nt_ni*tempproductbetaemiss[nmappedindex];
8673 dsum += dtempval;
8674 sumforsxi_ni[nmappedindex] = dtempval;
8675 }
8676 }
8677 else
8678 {
8679 for (int nj = 0; nj < numstates; nj++)
8680 {
8681 //computes transition probability from state i to j
8682 double dtempval = transitionprobs_ni[nj]*dalpha_nt_ni*tempproductbetaemiss[nj];
8683 dsum += dtempval;
8684 sumforsxi_ni[nj] = dtempval;
8685 }
8686 }
8687 }
8688
8689 if (dsum > 0)
8690 {
8691 //normalizing the numerator by the sum of the denominator and updating this iterations value for it
8692 for (int ni = 0; ni < numstates; ni++)
8693 {
8694 int[] transitionprobsindex_ni = transitionprobsindex[ni];
8695 double[] sumforsxi_ni = sumforsxi[ni];
8696 double[] sxi_nseq_ni = sxi_nseq[ni];
8697 int ntransitionprobsnum_ni = transitionprobsnum[ni];
8698
8699 if (ntransitionprobsnum_ni < nsparsecutoff)
8700 {
8701 //guessing sparse enough to avoid the indirections
8702 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
8703 {
8704 int nmappedindex = transitionprobsindex_ni[nj];
8705 sxi_nseq_ni[nmappedindex] += sumforsxi_ni[nmappedindex]/dsum;
8706 }
8707 }
8708 else
8709 {
8710 for (int nj = 0; nj < numstates; nj++)
8711 {
8712 sxi_nseq_ni[nj] += sumforsxi_ni[nj]/dsum;
8713 }
8714 }
8715 }
8716 }
8717 beta_ntp1 = beta_nt; //updating beta_ntp1
8718 }
8719
8720 double[] gammainitstore_nseq = gammainitstore[nseq];
8721 for (int ns = 0; ns < numstates; ns++)
8722 {
8723 //storing the initial gamma from this iteration
8724 gammainitstore_nseq[ns] = gamma_nt[ns];
8725 }
8726
8727 //for (int nindex = 0; nindex < gammaObservedSum.length; nindex++)
8728 for (int nindex = 0; nindex < nobserved; nindex++)
8729 {
8730 //going through all the gamma sufficient statistic
8731
8732 //only update for those combinations that were observed on this sequnce
8733 //gets the observed combination and missing combination signatures
8734 boolean[] traindataObservedValues_nindex = traindataObservedValues[nindex];
8735 boolean[] traindataNotMissing_nindex = traindataNotMissing[nindex];
8736
8737
8738 double[] gammaObservedSum_nindex = gammaObservedSum[nindex];
8739
8740 for (int ns = 0; ns < numstates; ns++)
8741 {
8742 //going through each state
8743 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
8744 double gammaObservedSum_nindex_ns = gammaObservedSum_nindex[ns];
8745 for (int nmark = 0; nmark < numdatasets; nmark++)
8746 {
8747 //going through each mark
8748 if (traindataNotMissing_nindex[nmark])
8749 {
8750 //only update non-missing
8751 if (traindataObservedValues_nindex[nmark])
8752 {
8753 //updates the gamma sum for each mark when in state and observed 1
8754 gammaksum_nseq_ns[nmark][1] += gammaObservedSum_nindex_ns;
8755 }
8756 else
8757 {
8758 //updates the gamma sum for each mark when in state and observed 0
8759 gammaksum_nseq_ns[nmark][0] += gammaObservedSum_nindex_ns;
8760 }
8761 }
8762 }
8763 }
8764 }
8765
8766
8767
8768 //M step
8769 if ((niteration >1) ||(nseq==(chromfiles.length-1)))
8770 {
8771 //executes the M-step after any pass through a sequence after one pass has been made through all sequences
8772 double dsum = 0;
8773
8774 //updating the inital probabilities
8775 for (int ni = 0; ni < numstates; ni++)
8776 {
8777 double dgammainitsum = 0;
8778 for (int nitr = 0; nitr < chromfiles.length; nitr++)
8779 {
8780 dgammainitsum += gammainitstore[nitr][ni];
8781 }
8782
8783 if ((bpseudo)&&(!bnopseudolast))
8784 {
8785 dgammainitsum++;
8786 }
8787
8788 probinit[ni] = dgammainitsum;
8789 dsum += dgammainitsum;
8790 }
8791
8792 for (int ni = 0; ni < numstates; ni++)
8793 {
8794 probinit[ni] /= dsum;
8795 }
8796
8797 //this indicates if there is a change on the set of 0 probability transitions
8798 boolean bchange = false;
8799 for (int ni = 0; ni < transitionprobs.length; ni++)
8800 {
8801 dsum = 0;
8802 //computes the denominator for the transition probabilities
8803
8804 int[] transitionprobsindex_ni = transitionprobsindex[ni];
8805 double[] transitionprobs_ni = transitionprobs[ni];
8806 int transitionprobsnum_ni = transitionprobsnum[ni];
8807 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
8808 {
8809 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
8810 double dsxistoreitr = 0;
8811 for (int nitr = 0; nitr < chromfiles.length; nitr++)
8812 {
8813 dsxistoreitr += sxistore[nitr][ni][ntransitionprobsindex_ni_nj];
8814 }
8815
8816 if (bpseudo)
8817 {
8818 //pseudo-count to avoid divide by zero
8819 dsxistoreitr++;
8820 }
8821
8822 transitionprobs_ni[ntransitionprobsindex_ni_nj] = dsxistoreitr;
8823
8824 dsum += dsxistoreitr;
8825 }
8826
8827 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
8828 {
8829 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
8830 //computes the updated transition probabilities
8831 transitionprobs_ni[ntransitionprobsindex_ni_nj] /= dsum;
8832
8833 if ((transitionprobs_ni[ntransitionprobsindex_ni_nj] < dzerotransitioncutoff) && (ni != ntransitionprobsindex_ni_nj))
8834 {
8835 //if falls below threshold eliminate the transition probabilities
8836 elim[ni][ntransitionprobsindex_ni_nj] = true;
8837 bchange = true;
8838 nelim++;
8839 transitionprobs_ni[ntransitionprobsindex_ni_nj] = 0;
8840 }
8841 }
8842 }
8843
8844 if (bchange)
8845 {
8846 //a transition was eliminated we need to update the probabilities
8847 for (int ni = 0; ni < transitionprobs.length; ni++)
8848 {
8849 int nindex = 0;
8850 ddenom = 0;
8851 boolean[] elim_ni = elim[ni];
8852 double[] transitionprobs_ni = transitionprobs[ni];
8853 int[] transitionprobsindex_ni = transitionprobsindex[ni];
8854 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
8855 {
8856 if (!elim_ni[nj])
8857 {
8858 //we have not eliminated this transition
8859 //stores its index in order and add sum to denominator
8860 transitionprobsindex_ni[nindex] = nj;
8861 ddenom += transitionprobs_ni[nj];
8862 nindex++;
8863 }
8864 }
8865
8866 //renormalize the transition probabilities by the sum of the non-eliminated transitions
8867 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
8868 {
8869 transitionprobs_ni[nj] /= ddenom;
8870 }
8871 //update the number of valid transitions
8872 transitionprobsnum[ni] = nindex;
8873 }
8874
8875 for (int ni = 0; ni < transitionprobs.length; ni++)
8876 {
8877 int nindex =0;
8878 int[] transitionprobsindexCol_ni = transitionprobsindexCol[ni];
8879 for (int nj = 0; nj < transitionprobs[ni].length; nj++)
8880 {
8881 if (!elim[nj][ni])
8882 {
8883 //copy into the column of i the index of all non-eliminated transitions of i
8884 transitionprobsindexCol_ni[nindex] = nj;
8885 nindex++;
8886 }
8887 }
8888 //updates the number of non-zero transitions from column i
8889 transitionprobsnumCol[ni] = nindex;
8890 }
8891 }
8892
8893 //updating the emission parameters
8894 for (int ns = 0; ns < numstates; ns++)
8895 {
8896 double[][] emissionprobs_ns = emissionprobs[ns];
8897
8898 for (int nmark = 0; nmark < emissionprobs_ns.length; nmark++)
8899 {
8900 double[] emissionprobs_ns_nmark = emissionprobs_ns[nmark];
8901 //can't used a general gamma sum because of missing emission vals
8902 double dgammadenom = 0;
8903
8904 //updates gamma sum
8905 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
8906 {
8907 emissionprobs_ns_nmark[nbucket] = 0;
8908
8909 for (int nitr = 0; nitr < chromfiles.length; nitr++)
8910 {
8911 emissionprobs_ns_nmark[nbucket] += gammaksumstore[nitr][ns][nmark][nbucket];
8912 }
8913
8914 if ((bpseudo) && ((!bnopseudolast)||(nmark<emissionprobs_ns.length-1)))
8915 {
8916 emissionprobs_ns_nmark[nbucket]++;
8917 }
8918
8919 dgammadenom += emissionprobs_ns_nmark[nbucket];
8920 }
8921
8922
8923 //added to avoid NA values
8924 if (dgammadenom > 0)
8925 {
8926 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
8927 {
8928 emissionprobs_ns_nmark[nbucket] /= dgammadenom;
8929 }
8930 }
8931 }
8932 }
8933 }
8934
8935 if (ChromHMM.BVERBOSE)
8936 {
8937 System.out.println("\t"+niteration+"\t"+dloglike);
8938 }
8939 }
8940
8941 double ddiff =(dloglike-dprevloglike);
8942
8943 //dconvergediff is only enforced if greater thanor equal to 0
8944 dprevloglike = dloglike;
8945
8946 if (borderrows)
8947 {
8948 makeStateOrdering();
8949 }
8950
8951 if (bordercols)
8952 {
8953 makeColOrdering();
8954 }
8955 //updates after each iteration the current status of the search
8956 printTransitionTable(niteration);
8957 printEmissionTable(niteration);
8958 if (bprintimage)
8959 {
8960 printEmissionImage(niteration);
8961 printTransitionImage(niteration);
8962 }
8963 printParametersToFile(niteration);
8964
8965 //we just completed a full iteration
8966 long ltimefinal = System.currentTimeMillis();
8967 double dtimechange = (ltimefinal-ltimeitr)/(double) 1000;
8968 bconverged = (((niteration >= nmaxiterations)||((ddiff< dconvergediff)&&(dconvergediff>=0)))||((dtimechange>nmaxseconds)&&(nmaxseconds>=0)));
8969 if (ChromHMM.BVERBOSE)
8970 {
8971 System.out.println(niteration+"\tTime Iteration\t"+dtimechange+"\t"+"\tElim\t"+nelim);
8972 System.out.println("Full "+niteration+"\t"+dloglike+"\t"+dprevloglike+"\t"+ddiff);
8973 }
8974
8975
8976 if (niteration == 1)
8977 {
8978 System.out.format("%10s %25s %10s %20s%n","Iteration","Estimated Log Likelihood", "Change","Total Time (secs)");
8979 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),"-",""+nf1.format(dtimechange));
8980 }
8981 else
8982 {
8983 //System.out.format(niteration+" "+nf3.format(dloglike)+" "+nf3.format(ddiff)+" "+nf1.format(dtimechange));
8984 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),""+nf3.format(ddiff),""+nf1.format(dtimechange));
8985 }
8986 niteration++;
8987 }
8988 while (!bconverged);
8989 }
8990
8991 //////////////////////////////////////////////////////////////////////////////////////////
8992 /**
8993 * This is the core procedure for learning the parameters of the model
8994 */
8995 public void trainParameters() throws IOException
8996 {
8997 NumberFormat nf3 = NumberFormat.getInstance();
8998 nf3.setMaximumFractionDigits(3);
8999 nf3.setGroupingUsed(false);
9000 nf3.setMinimumFractionDigits(3);
9001
9002 NumberFormat nf1 = NumberFormat.getInstance();
9003 nf1.setMaximumFractionDigits(1);
9004 nf1.setMinimumFractionDigits(1);
9005 nf1.setGroupingUsed(false);
9006
9007 int niteration = 1;
9008
9009 boolean bconverged = false;
9010
9011 double dzerotransitioncutoff = Math.pow(10,-nzerotransitionpower);
9012
9013 //number of non-zero transition for the
9014 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
9015
9016 //number of non-zero transition that need to be less than this at the looser cut-off
9017 int nsparsecutofflooser = (int) (numstates * ChromHMM.SPARSECUTOFFLOOSERRATIO);
9018
9019 double dprevloglike;
9020
9021 //stores the maximum number of locations in any sequence and in each sequence
9022 int[] numtime = new int[traindataObservedIndex.length];
9023 int nmaxtime = 0;
9024 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
9025 {
9026 numtime[nseq] = traindataObservedIndex[nseq].length;
9027 if (numtime[nseq] > nmaxtime)
9028 {
9029 nmaxtime = numtime[nseq];
9030 }
9031 }
9032
9033 if (ChromHMM.BVERBOSE)
9034 {
9035 System.out.println("Maximum number of locations\t"+nmaxtime);
9036 }
9037
9038 //stores the emission probability for the i^th combination of marks in the j^th state
9039 double[][] emissionproducts = new double[traindataObservedValues.length][numstates];
9040
9041 //stores the scale for the emission probability for the i^th combination of marks
9042 double[] emissionproducts_scale = null;
9043
9044 if (bscaleemissions)
9045 {
9046 emissionproducts_scale = new double[traindataObservedValues.length];
9047 }
9048
9049 //stores temporary product terms
9050 double[] tempproductbetaemiss = new double[numstates];
9051
9052 //This stores the alpha values at each time point and number of states
9053 double[][] alpha = new double[nmaxtime][numstates];
9054
9055 //Temporary storage of the gamma's for each state
9056 double[] gamma_nt = new double[numstates];
9057
9058 //Temporary storage of the beta values for each state
9059 double[] beta_nt = new double[numstates];
9060
9061 //Temporary storage of the beta values for each state at the next time point
9062 double[] beta_ntp1 = new double[numstates];
9063
9064 //stores the scaling value for each time point
9065 double[] scale = new double[nmaxtime];
9066
9067 //stores the transition probabilities for each column
9068 double[][] coltransitionprobs = new double[numstates][numstates];
9069
9070 //stores the sufficient statistic for the initital probability in each state for the last visit
9071 double[][] gammainitstore = new double[traindataObservedIndex.length][numstates];
9072
9073 //stores the sufficient statistics for computing the transition probabilities cumulated for each iteration
9074 double[][][] sxistore = new double[traindataObservedIndex.length][numstates][numstates];
9075
9076 //stores the sufficient statistic for computing the emission probabilities
9077 double[][][][] gammaksumstore =
9078 new double[traindataObservedIndex.length][numstates][numdatasets][numbuckets];
9079
9080 //temporary storage in computation of sxi
9081 double[][] sumforsxi = new double[numstates][numstates];
9082
9083 //stores the sum of the gamma values associated with each combination in each state
9084 double[][] gammaObservedSum = new double[traindataObservedValues.length][numstates];
9085
9086 int nelim = 0;
9087 long ltimeitr= System.currentTimeMillis();
9088 dprevloglike = Double.NEGATIVE_INFINITY;
9089
9090 do
9091 {
9092 dloglike = 0;
9093
9094 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
9095 {
9096 //going through each sequence
9097
9098 int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
9099 boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nseq];
9100
9101 double[][][] gammaksum_nseq = gammaksumstore[nseq];
9102
9103 for (int ns = 0; ns < gammaksum_nseq.length; ns++)
9104 {
9105 //resetting the gamma sufficient statistics in the current sequence
9106 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
9107 for (int nmark = 0; nmark < gammaksum_nseq_ns.length; nmark++)
9108 {
9109 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
9110 {
9111 gammaksum_nseq_ns[nmark][nbucket] = 0;
9112 }
9113 }
9114 }
9115
9116 double[][] sxi_nseq = sxistore[nseq];
9117 for (int ni = 0; ni < sxi_nseq.length; ni++)
9118 {
9119 //reseeting the sxi sufficient statistics in the current sequence
9120 double[] sxi_nseq_ni = sxi_nseq[ni];
9121 for (int nj = 0; nj < sxi_nseq_ni.length; nj++)
9122 {
9123 sxi_nseq_ni[nj] = 0;
9124 }
9125 }
9126
9127 //gammaObservedSum stores the weight for each combination of marks in each state
9128 for (int ncombo = 0; ncombo < gammaObservedSum.length; ncombo++)
9129 {
9130 //resetting that to 0
9131 double[] gammaObservedSum_ncombo = gammaObservedSum[ncombo];
9132 for (int ns = 0; ns < gammaObservedSum_ncombo.length; ns++)
9133 {
9134 gammaObservedSum_ncombo[ns] = 0;
9135 }
9136 }
9137
9138 if (bscaleemissions)
9139 {
9140 for (int ni = 0; ni < emissionproducts.length; ni++)
9141 {
9142 //going through each combination of marks
9143 if (traindataObservedSeqFlags_nseq[ni])
9144 {
9145 //this signature of marks is observed on the current chromosome so
9146 //updating its emission probabilities
9147 double[] emissionproducts_ni = emissionproducts[ni];
9148 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
9149 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
9150
9151 for (int ns = 0; ns < numstates; ns++)
9152 {
9153 emissionproducts_ni[ns] = 1;
9154 }
9155 emissionproducts_scale[ni] = 0;
9156
9157 for (int nmod = 0; nmod < numdatasets; nmod++)
9158 {
9159 for (int ns = 0; ns < numstates; ns++)
9160 {
9161 if (traindataNotMissing_ni[nmod])
9162 {
9163 //we are include this marks emission probability
9164 if (traindataObservedValues_ni[nmod])
9165 {
9166 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
9167 }
9168 else
9169 {
9170 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
9171 }
9172 }
9173 // otherwise treated as missing omitting from product
9174 }
9175
9176 double dmaxval = 0;
9177 for (int ns = 0; ns < numstates; ns++)
9178 {
9179 if (emissionproducts_ni[ns] > dmaxval)
9180 {
9181 dmaxval = emissionproducts_ni[ns];
9182 }
9183 }
9184
9185 if (dmaxval <= 0)//EPSILONEMISSIONS)
9186 {
9187 for (int ns = 0; ns < numstates; ns++)
9188 {
9189 emissionproducts_ni[ns] = 1;
9190 }
9191 //approximating log-likelihood
9192 emissionproducts_scale[ni] += Math.log(EPSILONEMISSIONS);
9193 }
9194 else
9195 {
9196 for (int ns = 0; ns < numstates; ns++)
9197 {
9198 emissionproducts_ni[ns]/= dmaxval;
9199 }
9200 emissionproducts_scale[ni] += Math.log(dmaxval);
9201 }
9202 }
9203 }
9204 }
9205 }
9206 else
9207 {
9208 for (int ni = 0; ni < emissionproducts.length; ni++)
9209 {
9210 //going through each combination of marks
9211 if (traindataObservedSeqFlags_nseq[ni])
9212 {
9213 //this signature of marks is observed on the current chromosome so
9214 //updating its emission probabilities
9215 double[] emissionproducts_ni = emissionproducts[ni];
9216 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
9217 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
9218
9219 boolean ballzero = true;
9220
9221 for (int ns = 0; ns < numstates; ns++)
9222 {
9223 double dproduct = 1;
9224 double[][] emissionprobs_ns = emissionprobs[ns];
9225
9226 for (int nmod = 0; nmod < numdatasets; nmod++)
9227 {
9228 if (traindataNotMissing_ni[nmod])
9229 {
9230 //we are include this marks emission probability
9231 if (traindataObservedValues_ni[nmod])
9232 {
9233 //System.out.println("positive\t"+ns+"\t"+nmod+"\t1\t"+emissionprobs_ns[nmod][1]);
9234 dproduct *= emissionprobs_ns[nmod][1];
9235 }
9236 else
9237 {
9238 ///System.out.println("negative\t"+ns+"\t"+nmod+"\t0\t"+emissionprobs_ns[nmod][0]);
9239 dproduct *= emissionprobs_ns[nmod][0];
9240 }
9241 }
9242 // otherwise treated as missing omitting from product
9243 }
9244 //System.out.println(ns+"\t"+dproduct);
9245 emissionproducts_ni[ns] = dproduct;
9246
9247 if (dproduct >= EPSILONEMISSIONS)
9248 {
9249 ballzero = false;
9250 }
9251 }
9252
9253 if (ballzero)
9254 {
9255 for (int ns = 0; ns < numstates; ns++)
9256 {
9257 emissionproducts_ni[ns] = EPSILONEMISSIONS;
9258 }
9259 }
9260 }
9261 }
9262 }
9263
9264 //initial probability in state s is initial probability times emission probability at first position
9265 double[] alpha_nt = alpha[0];
9266 double dscale = 0;
9267 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex_nseq[0]];
9268
9269 for (int ns = 0; ns < numstates; ns++)
9270 {
9271 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
9272 dscale += alpha_nt[ns];
9273 }
9274
9275 scale[0] = dscale;
9276
9277 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
9278 //converts the alpha terms to probabilities
9279 if (bscalebeta)
9280 {
9281 if (dscale == 0)
9282 {
9283 for (int ns = 0; ns < numstates; ns++)
9284 {
9285 //added
9286 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
9287 {
9288 alpha_nt[ns] = EPSILONSTATE;
9289 dscale += EPSILONSTATE;
9290 }
9291 }
9292 scale[0] = dscale;
9293 }
9294
9295 for (int ns = 0; ns < numstates; ns++)
9296 {
9297 alpha_nt[ns] /= dscale;
9298
9299 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))// (ns < numstates-1)))
9300 {
9301 alpha_nt[ns] = EPSILONSTATE;
9302 }
9303 }
9304 }
9305 else
9306 {
9307 for (int ns = 0; ns < numstates; ns++)
9308 {
9309 alpha_nt[ns] /= dscale;
9310 }
9311 }
9312
9313
9314 dloglike += Math.log(dscale);
9315
9316 if (bscaleemissions)
9317 {
9318 dloglike += emissionproducts_scale[traindataObservedIndex_nseq[0]];
9319 }
9320
9321 //stores in coltransitionprobs the transpose of transitionprobs
9322 for (int ni = 0; ni < numstates; ni++)
9323 {
9324 double[] coltransitionprobs_ni = coltransitionprobs[ni];
9325 for (int nj = 0; nj < numstates; nj++)
9326 {
9327 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
9328 }
9329 }
9330
9331 //forward step
9332 int numtime_nseq = numtime[nseq];
9333 for (int nt = 1; nt < numtime_nseq; nt++)
9334 {
9335 //the actual observed combination at position t
9336 double[] alpha_ntm1 = alpha[nt-1];
9337 alpha_nt = alpha[nt];
9338
9339 dscale = 0;
9340 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex_nseq[nt]];
9341 for (int ns = 0; ns < numstates; ns++)
9342 {
9343 //stores the emission product for each location on the chromosome
9344
9345 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
9346 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
9347 double[] coltransitionprobs_ns = coltransitionprobs[ns];
9348
9349 double dtempsum = 0;
9350 if (transitionprobsnumCol_ns < nsparsecutoff)
9351 {
9352 //number of transitions is sparse enough worth going through the extra redirection
9353 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
9354 {
9355 //for each next state computing inner sum of all previous alpha and the transition probability
9356 //for all non-zero transitions into the state
9357 int nmappedindex = transitionprobsindexCol_ns[nj];
9358 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
9359 }
9360 }
9361 else
9362 {
9363 //avoid the redirect and multiply by 0
9364 for (int nj = 0; nj < numstates; nj++)
9365 {
9366 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
9367 }
9368 }
9369 //multiply the transition sum by the emission probability
9370 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
9371 alpha_nt[ns] = dalphaval;
9372 //System.out.println(ns+"\t"+alpha_nt[ns]+"\t"+dtempsum+"\t"+emissionproducts_nobserveindex[ns]);
9373 dscale += dalphaval;
9374 }
9375
9376
9377 //rescaling alpha
9378 scale[nt] = dscale;
9379 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
9380
9381 if (bscalebeta)
9382 {
9383 if (dscale == 0)
9384 {
9385 for (int ns = 0; ns < numstates; ns++)
9386 {
9387 //added
9388 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
9389 {
9390 alpha_nt[ns] = EPSILONSTATE;
9391 dscale += EPSILONSTATE;
9392 }
9393 }
9394 scale[nt] = dscale;
9395 }
9396
9397 for (int ns = 0; ns < numstates; ns++)
9398 {
9399 alpha_nt[ns] /= dscale;
9400
9401 //if ((alpha_nt[ns] < EPSILONSTATE)&&(!bdummy || (ns < numstates-1)))
9402 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))
9403 {
9404 alpha_nt[ns] = EPSILONSTATE;
9405 }
9406 }
9407 }
9408 else
9409 {
9410 for (int ns = 0; ns < numstates; ns++)
9411 {
9412 alpha_nt[ns] /= dscale;
9413 }
9414 }
9415
9416 dloglike += Math.log(dscale);
9417
9418 if (bscaleemissions)
9419 {
9420 dloglike += emissionproducts_scale[traindataObservedIndex_nseq[nt]];
9421 }
9422
9423 }
9424
9425
9426 //backward step
9427 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
9428 int nlastindex = numtime_nseq-1;
9429 double dinitval;
9430 if (bscalebeta)
9431 {
9432 dinitval = 1.0/numstates;
9433 }
9434 else
9435 {
9436 dinitval = 1.0/scale[nlastindex];
9437 }
9438
9439 for (int ns = 0; ns < numstates; ns++)
9440 {
9441 beta_ntp1[ns] = dinitval;
9442 }
9443
9444 double ddenom = 0;
9445
9446 //gamma_nt - P(x=S| o_0,...,o_t)
9447 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
9448 alpha_nt = alpha[nlastindex];
9449 for (int ns = 0; ns < gamma_nt.length; ns++)
9450 {
9451 double dval = alpha_nt[ns]*beta_ntp1[ns];
9452 ddenom += dval;
9453 gamma_nt[ns] = dval;
9454 }
9455
9456 if (ddenom > 0)
9457 {
9458 for (int ns = 0; ns < gamma_nt.length; ns++)
9459 {
9460 gamma_nt[ns] /=ddenom;
9461 }
9462 }
9463
9464 double[] gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex_nseq[nlastindex]];
9465
9466 for (int ns = 0; ns < numstates; ns++)
9467 {
9468 //first sum gamma over all common signatures
9469 //updates probability of observing the signature when in the state
9470 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
9471 }
9472
9473 for (int nt = nlastindex - 1; nt >= 0; nt--)
9474 {
9475 int ntp1 = (nt+1);
9476
9477 double[] emissionproducts_combo_ntp1 = emissionproducts[traindataObservedIndex_nseq[ntp1]];
9478
9479 for (int ns = 0; ns < numstates; ns++)
9480 {
9481 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_combo_ntp1[ns];
9482 }
9483
9484 if (bscaleemissions)
9485 {
9486 //adding here to help numerical stability
9487 double dmaxval = 0;
9488 for (int ns = 0; ns < numstates; ns++)
9489 {
9490 if (tempproductbetaemiss[ns] > dmaxval)
9491 {
9492 dmaxval = tempproductbetaemiss[ns];
9493 }
9494 }
9495 for (int ns = 0; ns < numstates; ns++)
9496 {
9497 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
9498 }
9499 }
9500
9501 //double dscaleinv = 1.0/scale[nt];
9502 double dsumbeta = 0;
9503 double dscale_nt = scale[nt];
9504 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
9505
9506 for (int ni = 0; ni < numstates; ni++)
9507 {
9508 double dtempsum = 0;
9509 int[] transitionprobsindex_ni = transitionprobsindex[ni];
9510 double[] transitionprobs_ni = transitionprobs[ni];
9511 int transitionprobsnum_ni = transitionprobsnum[ni];
9512
9513 if (transitionprobsnum_ni < nsparsecutoff)
9514 {
9515 //sparse enought to pay the indirection penalty
9516 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
9517 {
9518 //for each state summing over transition probability to state j, emission probablity in j at next step
9519 //and probability of observing the remaining sequence
9520 int nmappedindexouter = transitionprobsindex_ni[nj];
9521 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
9522 }
9523 }
9524 else
9525 {
9526 //not trying to exploit sparsity here
9527 for (int nj = 0; nj < numstates; nj++)
9528 {
9529 //for each state summing over transition probability to state j, emission probablity in j at next step
9530 //and probability of observing the remaining sequence
9531 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
9532 }
9533 }
9534
9535
9536
9537 if (bscalebeta)
9538 {
9539 beta_nt[ni] = dtempsum;
9540 dsumbeta += dtempsum;
9541 }
9542 else
9543 {
9544 double dratio = dtempsum/dscale_nt;
9545 if (dratio > Double.MAX_VALUE)
9546 {
9547 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
9548 }
9549 else
9550 {
9551 beta_nt[ni] = dratio;
9552 }
9553 }
9554 }
9555
9556
9557 if (bscalebeta)
9558 {
9559 for (int ni = 0; ni < numstates; ni++)
9560 {
9561 beta_nt[ni]/= dsumbeta;
9562
9563 if (beta_nt[ni] < EPSILONSTATE)//&& (!bdummy))// || !ballemisszero))// (!bdummy || (ni < numstates-1)))
9564 {
9565 beta_nt[ni] = EPSILONSTATE;
9566 }
9567 }
9568 }
9569
9570
9571 ddenom = 0;
9572
9573 alpha_nt = alpha[nt];
9574
9575 //gamma_nt - P(x=S| o_0,...,o_t)
9576 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
9577
9578 for (int ns = 0; ns < gamma_nt.length; ns++)
9579 {
9580 double dval = alpha_nt[ns]*beta_nt[ns];
9581 ddenom += dval;
9582 gamma_nt[ns] = dval;
9583 }
9584
9585 if (ddenom > 0)
9586 {
9587 for (int ns = 0; ns < gamma_nt.length; ns++)
9588 {
9589 gamma_nt[ns] /= ddenom;
9590 }
9591 }
9592
9593 gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex_nseq[nt]];
9594
9595 for (int ns = 0; ns < numstates; ns++)
9596 {
9597 //first sum gamma over all common signatures
9598 //updates probability of observing the signature when in the state
9599 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
9600 }
9601
9602 double dsum = 0;
9603
9604 //this compues the numerator portion
9605 for (int ni = 0; ni < numstates; ni++)
9606 {
9607 double[] sumforsxi_ni = sumforsxi[ni]; //computing expected number of transition from state i
9608 int[] transitionprobsindex_ni = transitionprobsindex[ni]; //indicies of non-zero transitions from state i
9609 double[] transitionprobs_ni = transitionprobs[ni]; //probability of transitions from state i
9610 int ntransitionprobsnum_ni = transitionprobsnum[ni]; //number of non-zero transitions from state i
9611 double dalpha_nt_ni = alpha_nt[ni];
9612 //sxi is P(q_t = S_i, q_(t+1) = S_j | O)
9613
9614 if (ntransitionprobsnum_ni < nsparsecutofflooser)
9615 {
9616 //enough 0 transitionto use sparsity here
9617 //looser cut off since the indirection is less of the total time
9618 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
9619 {
9620 int nmappedindex = transitionprobsindex_ni[nj];
9621 //computes transition probability from state i to j
9622 double dtempval = transitionprobs_ni[nmappedindex] *dalpha_nt_ni*tempproductbetaemiss[nmappedindex];
9623 dsum += dtempval;
9624 sumforsxi_ni[nmappedindex] = dtempval;
9625 }
9626 }
9627 else
9628 {
9629 for (int nj = 0; nj < numstates; nj++)
9630 {
9631 //computes transition probability from state i to j
9632 double dtempval = transitionprobs_ni[nj]*dalpha_nt_ni*tempproductbetaemiss[nj];
9633 dsum += dtempval;
9634 sumforsxi_ni[nj] = dtempval;
9635 }
9636 }
9637 }
9638
9639 if (dsum > 0)
9640 {
9641 //normalizing the numerator by the sum of the denominator and updating this iterations value for it
9642 for (int ni = 0; ni < numstates; ni++)
9643 {
9644 int[] transitionprobsindex_ni = transitionprobsindex[ni];
9645 double[] sumforsxi_ni = sumforsxi[ni];
9646 double[] sxi_nseq_ni = sxi_nseq[ni];
9647 int ntransitionprobsnum_ni = transitionprobsnum[ni];
9648
9649 if (ntransitionprobsnum_ni < nsparsecutoff)
9650 {
9651 //guessing sparse enough to avoid the indirections
9652 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
9653 {
9654 int nmappedindex = transitionprobsindex_ni[nj];
9655 sxi_nseq_ni[nmappedindex] += sumforsxi_ni[nmappedindex]/dsum;
9656 }
9657 }
9658 else
9659 {
9660 for (int nj = 0; nj < numstates; nj++)
9661 {
9662 sxi_nseq_ni[nj] += sumforsxi_ni[nj]/dsum;
9663 }
9664 }
9665 }
9666 }
9667 beta_ntp1 = beta_nt; //updating beta_ntp1
9668 }
9669
9670 double[] gammainitstore_nseq = gammainitstore[nseq];
9671 for (int ns = 0; ns < numstates; ns++)
9672 {
9673 //storing the initial gamma from this iteration
9674 gammainitstore_nseq[ns] = gamma_nt[ns];
9675 }
9676
9677 for (int nindex = 0; nindex < gammaObservedSum.length; nindex++)
9678 {
9679 //going through all the gamma sufficient statistic
9680 if (traindataObservedSeqFlags_nseq[nindex])
9681 {
9682 //only update for those combinations that were observed on this sequnce
9683 //gets the observed combination and missing combination signatures
9684 boolean[] traindataObservedValues_nindex = traindataObservedValues[nindex];
9685 boolean[] traindataNotMissing_nindex = traindataNotMissing[nindex];
9686
9687
9688 double[] gammaObservedSum_nindex = gammaObservedSum[nindex];
9689
9690 for (int ns = 0; ns < numstates; ns++)
9691 {
9692 //going through each state
9693 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
9694 double gammaObservedSum_nindex_ns = gammaObservedSum_nindex[ns];
9695 for (int nmark = 0; nmark < numdatasets; nmark++)
9696 {
9697 //going through each mark
9698 if (traindataNotMissing_nindex[nmark])
9699 {
9700 //only update non-missing
9701 if (traindataObservedValues_nindex[nmark])
9702 {
9703 //updates the gamma sum for each mark when in state and observed 1
9704 gammaksum_nseq_ns[nmark][1] += gammaObservedSum_nindex_ns;
9705 }
9706 else
9707 {
9708 //updates the gamma sum for each mark when in state and observed 0
9709 gammaksum_nseq_ns[nmark][0] += gammaObservedSum_nindex_ns;
9710 }
9711 }
9712 }
9713 }
9714 }
9715 }
9716
9717
9718 //M step
9719 if ((niteration >1) ||(nseq==(traindataObservedIndex.length-1)))
9720 {
9721 //executes the M-step after any pass through a sequence after one pass has been made through all sequences
9722 double dsum = 0;
9723
9724 //updating the inital probabilities
9725 for (int ni = 0; ni < numstates; ni++)
9726 {
9727 double dgammainitsum = 0;
9728 for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
9729 {
9730 dgammainitsum += gammainitstore[nitr][ni];
9731 }
9732
9733 if ((bpseudo)&&(!bnopseudolast))
9734 {
9735 dgammainitsum++;
9736 }
9737
9738 probinit[ni] = dgammainitsum;
9739 dsum += dgammainitsum;
9740 }
9741
9742 for (int ni = 0; ni < numstates; ni++)
9743 {
9744 probinit[ni] /= dsum;
9745 }
9746
9747 //this indicates if there is a change on the set of 0 probability transitions
9748 boolean bchange = false;
9749 for (int ni = 0; ni < transitionprobs.length; ni++)
9750 {
9751 dsum = 0;
9752 //computes the denominator for the transition probabilities
9753
9754 int[] transitionprobsindex_ni = transitionprobsindex[ni];
9755 double[] transitionprobs_ni = transitionprobs[ni];
9756 int transitionprobsnum_ni = transitionprobsnum[ni];
9757 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
9758 {
9759 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
9760 double dsxistoreitr = 0;
9761 for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
9762 {
9763 dsxistoreitr += sxistore[nitr][ni][ntransitionprobsindex_ni_nj];
9764 }
9765
9766 if (bpseudo)
9767 {
9768 //pseudo-count to avoid divide by zero
9769 dsxistoreitr++;
9770 }
9771
9772 transitionprobs_ni[ntransitionprobsindex_ni_nj] = dsxistoreitr;
9773
9774 dsum += dsxistoreitr;
9775 }
9776
9777 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
9778 {
9779 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
9780 //computes the updated transition probabilities
9781 transitionprobs_ni[ntransitionprobsindex_ni_nj] /= dsum;
9782
9783 if ((transitionprobs_ni[ntransitionprobsindex_ni_nj] < dzerotransitioncutoff) && (ni != ntransitionprobsindex_ni_nj))
9784 {
9785 //if falls below threshold eliminate the transition probabilities
9786 elim[ni][ntransitionprobsindex_ni_nj] = true;
9787 bchange = true;
9788 nelim++;
9789 transitionprobs_ni[ntransitionprobsindex_ni_nj] = 0;
9790 }
9791 }
9792 }
9793
9794 if (bchange)
9795 {
9796 //a transition was eliminated we need to update the probabilities
9797 for (int ni = 0; ni < transitionprobs.length; ni++)
9798 {
9799 int nindex = 0;
9800 ddenom = 0;
9801 boolean[] elim_ni = elim[ni];
9802 double[] transitionprobs_ni = transitionprobs[ni];
9803 int[] transitionprobsindex_ni = transitionprobsindex[ni];
9804 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
9805 {
9806 if (!elim_ni[nj])
9807 {
9808 //we have not eliminated this transition
9809 //stores its index in order and add sum to denominator
9810 transitionprobsindex_ni[nindex] = nj;
9811 ddenom += transitionprobs_ni[nj];
9812 nindex++;
9813 }
9814 }
9815
9816 //renormalize the transition probabilities by the sum of the non-eliminated transitions
9817 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
9818 {
9819 transitionprobs_ni[nj] /= ddenom;
9820 }
9821 //update the number of valid transitions
9822 transitionprobsnum[ni] = nindex;
9823 }
9824
9825 for (int ni = 0; ni < transitionprobs.length; ni++)
9826 {
9827 int nindex =0;
9828 int[] transitionprobsindexCol_ni = transitionprobsindexCol[ni];
9829 for (int nj = 0; nj < transitionprobs[ni].length; nj++)
9830 {
9831 if (!elim[nj][ni])
9832 {
9833 //copy into the column of i the index of all non-eliminated transitions of i
9834 transitionprobsindexCol_ni[nindex] = nj;
9835 nindex++;
9836 }
9837 }
9838 //updates the number of non-zero transitions from column i
9839 transitionprobsnumCol[ni] = nindex;
9840 }
9841 }
9842
9843 //updating the emission parameters
9844 for (int ns = 0; ns < numstates; ns++)
9845 {
9846 double[][] emissionprobs_ns = emissionprobs[ns];
9847
9848 for (int nmark = 0; nmark < emissionprobs_ns.length; nmark++)
9849 {
9850 double[] emissionprobs_ns_nmark = emissionprobs_ns[nmark];
9851 //can't used a general gamma sum because of missing emission vals
9852 double dgammadenom = 0;
9853
9854 //updates gamma sum
9855 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
9856 {
9857 emissionprobs_ns_nmark[nbucket] = 0;
9858
9859 for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
9860 {
9861 emissionprobs_ns_nmark[nbucket] += gammaksumstore[nitr][ns][nmark][nbucket];
9862 }
9863
9864
9865 if ((bpseudo) && ((!bnopseudolast)||(nmark<emissionprobs_ns.length-1)))
9866 {
9867 emissionprobs_ns_nmark[nbucket]++;
9868 }
9869 dgammadenom += emissionprobs_ns_nmark[nbucket];
9870 }
9871
9872 //added to avoid NA values
9873 if (dgammadenom > 0)
9874 {
9875 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
9876 {
9877 emissionprobs_ns_nmark[nbucket] /= dgammadenom;
9878 }
9879 }
9880 }
9881 }
9882 }
9883
9884 if (ChromHMM.BVERBOSE)
9885 {
9886 System.out.println("\t"+niteration+"\t"+dloglike);
9887 }
9888 }
9889
9890 double ddiff =(dloglike-dprevloglike);
9891
9892 //dconvergediff is only enforced if greater thanor equal to 0
9893 dprevloglike = dloglike;
9894
9895 if (borderrows)
9896 {
9897 makeStateOrdering();
9898 }
9899
9900 if (bordercols)
9901 {
9902 makeColOrdering();
9903 }
9904 //updates after each iteration the current status of the search
9905 printTransitionTable(niteration);
9906 printEmissionTable(niteration);
9907 if (bprintimage)
9908 {
9909 printEmissionImage(niteration);
9910 printTransitionImage(niteration);
9911 }
9912 printParametersToFile(niteration);
9913
9914 //we just completed a full iteration
9915 long ltimefinal = System.currentTimeMillis();
9916 double dtimechange = (ltimefinal-ltimeitr)/(double) 1000;
9917 bconverged = (((niteration >= nmaxiterations)||((ddiff< dconvergediff)&&(dconvergediff>=0)))||((dtimechange>nmaxseconds)&&(nmaxseconds>=0)));
9918 if (ChromHMM.BVERBOSE)
9919 {
9920 System.out.println(niteration+"\tTime Iteration\t"+dtimechange+"\t"+"\tElim\t"+nelim);
9921 System.out.println("Full "+niteration+"\t"+dloglike+"\t"+dprevloglike+"\t"+ddiff);
9922 }
9923
9924
9925 if (niteration == 1)
9926 {
9927 System.out.format("%10s %25s %10s %20s%n","Iteration","Estimated Log Likelihood", "Change","Total Time (secs)");
9928 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),"-",""+nf1.format(dtimechange));
9929 }
9930 else
9931 {
9932 //System.out.format(niteration+" "+nf3.format(dloglike)+" "+nf3.format(ddiff)+" "+nf1.format(dtimechange));
9933 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),""+nf3.format(ddiff),""+nf1.format(dtimechange));
9934 }
9935 niteration++;
9936 }
9937 while (!bconverged);
9938 }
9939
9940
9941 /////////////////////////////////////////////////////////////////////////////////////////////////////////
9942
9943 // Create a new thread.
9944 class NewThread implements Runnable
9945 {
9946
9947 int[] traindataObservedIndex_nseq;
9948 boolean[] traindataObservedSeqFlags_nseq;
9949 double[][][] gammaksum_nseq;
9950 double[][] sxi_nseq;
9951 int numtime_nseq;
9952 double[] gammainitstore_nseq;
9953 double[][][] gammaObservedSum_Pool;
9954 double[][][] alpha_Pool;
9955 double[][] emissionproducts;
9956 double[][] gamma_nt_Pool;
9957 double[][] coltransitionprobs;
9958 double[][] scale_Pool;
9959 double[][] beta_nt_Pool;
9960 double[][] beta_ntp1_Pool;
9961 double[][] tempproductbetaemiss_Pool;
9962 int nsparsecutoff;
9963 int nsparsecutofflooser;
9964 double[][][] sumforsxi_Pool;
9965 double[] dloglikeA;
9966 int nseq;
9967 double[] emissionproducts_scale;
9968
9969 NewThread(int[] traindataObservedIndex_nseq,
9970 boolean[] traindataObservedSeqFlags_nseq,
9971 double[][][] gammaksum_nseq,
9972 double[][] sxi_nseq,
9973 int numtime_nseq,
9974 double[] gammainitstore_nseq,
9975 double[][][] gammaObservedSum_Pool,
9976 double[][][] alpha_Pool,
9977 double[][] emissionproducts,
9978 double[][] gamma_nt_Pool,
9979 double[][] coltransitionprobs,
9980 double[][] scale_Pool,
9981 double[][] beta_nt_Pool,
9982 double[][] beta_ntp1_Pool,
9983 double[][] tempproductbetaemiss_Pool,
9984 double[][][] sumforsxi_Pool,
9985 int nsparsecutoff,
9986 int nsparsecutofflooser,
9987 double[] dloglikeA,
9988 int nseq,
9989 double[] emissionproducts_scale)
9990 {
9991 this.traindataObservedIndex_nseq = traindataObservedIndex_nseq;
9992 this.traindataObservedSeqFlags_nseq = traindataObservedSeqFlags_nseq;
9993 this.gammaksum_nseq = gammaksum_nseq;
9994 this.sxi_nseq = sxi_nseq;
9995 this.numtime_nseq = numtime_nseq;
9996 this.gammainitstore_nseq = gammainitstore_nseq;
9997 this.gammaObservedSum_Pool = gammaObservedSum_Pool;
9998 this.alpha_Pool = alpha_Pool;
9999 this.emissionproducts = emissionproducts;
10000 this.gamma_nt_Pool = gamma_nt_Pool;
10001 this.coltransitionprobs = coltransitionprobs;
10002 this.scale_Pool = scale_Pool;
10003 this.beta_nt_Pool = beta_nt_Pool;
10004 this.beta_ntp1_Pool = beta_ntp1_Pool;
10005 this.tempproductbetaemiss_Pool = tempproductbetaemiss_Pool;
10006 this.nsparsecutoff = nsparsecutoff;
10007 this.nsparsecutofflooser = nsparsecutofflooser;
10008 this.sumforsxi_Pool = sumforsxi_Pool;
10009 this.dloglikeA = dloglikeA;
10010 this.nseq = nseq;
10011 this.emissionproducts_scale = emissionproducts_scale;
10012 }
10013
10014 private int slotavailable()
10015 {
10016 for (int ni = 0; ni < threadslots.length; ni++)
10017 {
10018 if (!threadslots[ni])
10019 {
10020 threadslots[ni] = true;
10021 return ni;
10022 }
10023 }
10024 return -1;
10025 }
10026
10027 // This is the entry point for the second thread.
10028 public void run()
10029 {
10030 int nprocess;
10031
10032 synchronized (objlock)
10033 {
10034 while ((nprocess=slotavailable())==-1)
10035 {
10036 try
10037 {
10038 objlock.wait();
10039 }
10040 catch (InterruptedException ex) {}
10041 }
10042 }
10043
10044 estep(gammaObservedSum_Pool[nprocess],
10045 alpha_Pool[nprocess],
10046 gamma_nt_Pool[nprocess],
10047 scale_Pool[nprocess],
10048 beta_nt_Pool[nprocess],
10049 beta_ntp1_Pool[nprocess],
10050 tempproductbetaemiss_Pool[nprocess],
10051 sumforsxi_Pool[nprocess]);
10052
10053 synchronized(objlock)
10054 {
10055 nlaunched--;
10056 threadslots[nprocess] = false;
10057 objlock.notifyAll();
10058 }
10059
10060 }
10061
10062 public void estep(
10063 double[][] gammaObservedSum,
10064 double[][] alpha,
10065 double[] gamma_nt,
10066 double[] scale,
10067 double[] beta_nt,
10068 double[] beta_ntp1,
10069 double[] tempproductbetaemiss,
10070 double[][] sumforsxi)
10071 {
10072 //going through each sequence
10073
10074 double dloglikeseq = 0;
10075
10076 for (int ns = 0; ns < gammaksum_nseq.length; ns++)
10077 {
10078 //resetting the gamma sufficient statistics in the current sequence
10079 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
10080 for (int nmark = 0; nmark < gammaksum_nseq_ns.length; nmark++)
10081 {
10082 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
10083 {
10084 gammaksum_nseq_ns[nmark][nbucket] = 0;
10085 }
10086 }
10087 }
10088
10089 for (int ni = 0; ni < sxi_nseq.length; ni++)
10090 {
10091 //reseeting the sxi sufficient statistics in the current sequence
10092 double[] sxi_nseq_ni = sxi_nseq[ni];
10093 for (int nj = 0; nj < sxi_nseq_ni.length; nj++)
10094 {
10095 sxi_nseq_ni[nj] = 0;
10096 }
10097 }
10098
10099 //gammaObservedSum stores the weight for each combination of marks in each state
10100 for (int ncombo = 0; ncombo < gammaObservedSum.length; ncombo++)
10101 {
10102 //resetting that to 0
10103 double[] gammaObservedSum_ncombo = gammaObservedSum[ncombo];
10104 for (int ns = 0; ns < gammaObservedSum_ncombo.length; ns++)
10105 {
10106 gammaObservedSum_ncombo[ns] = 0;
10107 }
10108 }
10109
10110 //initial probability in state s is initial probability times emission probability at first position
10111 double[] alpha_nt = alpha[0];
10112 double dscale = 0;
10113 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex_nseq[0]];
10114 for (int ns = 0; ns < numstates; ns++)
10115 {
10116 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
10117 dscale += alpha_nt[ns];
10118
10119 }
10120 scale[0] = dscale;
10121
10122 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
10123 //converts the alpha terms to probabilities
10124
10125 if (bscalebeta)
10126 {
10127 if (dscale == 0)
10128 {
10129 for (int ns = 0; ns < numstates; ns++)
10130 {
10131 //added
10132 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
10133 {
10134 alpha_nt[ns] = EPSILONSTATE;
10135 dscale += EPSILONSTATE;
10136 }
10137 }
10138 scale[0] = dscale;
10139 }
10140
10141 for (int ns = 0; ns < numstates; ns++)
10142 {
10143 alpha_nt[ns] /= dscale;
10144
10145 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
10146 {
10147 alpha_nt[ns] = EPSILONSTATE;
10148 }
10149 }
10150 }
10151 else
10152 {
10153 for (int ns = 0; ns < numstates; ns++)
10154 {
10155 alpha_nt[ns] /= dscale;
10156 }
10157 }
10158 //for (int ni = 0; ni < numstates; ni++)
10159 //{
10160 // alpha_nt[ni] /= dscale;
10161 //}
10162
10163 dloglikeseq += Math.log(dscale);
10164
10165 if (bscaleemissions)
10166 {
10167 dloglikeseq += emissionproducts_scale[traindataObservedIndex_nseq[0]];
10168 }
10169
10170 //forward step
10171 //int numtime_nseq = numtime[nseq];
10172 for (int nt = 1; nt < numtime_nseq; nt++)
10173 {
10174 //the actual observed combination at position t
10175 double[] alpha_ntm1 = alpha[nt-1];
10176 alpha_nt = alpha[nt];
10177
10178
10179 dscale = 0;
10180 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex_nseq[nt]];
10181 for (int ns = 0; ns < numstates; ns++)
10182 {
10183 //stores the emission product for each location on the chromosome
10184
10185 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
10186 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
10187 double[] coltransitionprobs_ns = coltransitionprobs[ns];
10188
10189 double dtempsum = 0;
10190 if (transitionprobsnumCol_ns < nsparsecutoff)
10191 {
10192 //number of transitions is sparse enough worth going through the extra redirection
10193 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
10194 {
10195 //for each next state computing inner sum of all previous alpha and the transition probability
10196 //for all non-zero transitions into the state
10197 int nmappedindex = transitionprobsindexCol_ns[nj];
10198 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
10199 }
10200 }
10201 else
10202 {
10203 //avoid the redirect and multiply by 0
10204 for (int nj = 0; nj < numstates; nj++)
10205 {
10206 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
10207 }
10208 }
10209 //multiply the transition sum by the emission probability
10210 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
10211 alpha_nt[ns] = dalphaval;
10212 //System.out.println(ns+"\t"+alpha_nt[ns]+"\t"+dtempsum+"\t"+emissionproducts_nobserveindex[ns]);
10213 dscale += dalphaval;
10214 }
10215
10216 //rescaling alpha
10217 scale[nt] = dscale;
10218 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
10219
10220 if (bscalebeta)
10221 {
10222 if (dscale == 0)
10223 {
10224 for (int ns = 0; ns < numstates; ns++)
10225 {
10226 //added
10227 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
10228 {
10229 alpha_nt[ns] = EPSILONSTATE;
10230 dscale += EPSILONSTATE;
10231 }
10232 }
10233 scale[nt] = dscale;
10234 }
10235
10236 for (int ns = 0; ns < numstates; ns++)
10237 {
10238 alpha_nt[ns] /= dscale;
10239
10240 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
10241 {
10242 alpha_nt[ns] = EPSILONSTATE;
10243 }
10244 }
10245 }
10246 else
10247 {
10248 for (int ns = 0; ns < numstates; ns++)
10249 {
10250 alpha_nt[ns] /= dscale;
10251 }
10252 }
10253 dloglikeseq += Math.log(dscale);
10254
10255 if (bscaleemissions)
10256 {
10257 dloglikeseq += emissionproducts_scale[traindataObservedIndex_nseq[nt]];
10258 }
10259
10260 }
10261
10262 //backward step
10263 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
10264 int nlastindex = numtime_nseq-1;
10265 double dinitval;
10266
10267 if (bscalebeta)
10268 {
10269 dinitval = 1.0/numstates;
10270 }
10271 else
10272 {
10273 dinitval = 1.0/scale[nlastindex];
10274 }
10275
10276 for (int ns = 0; ns < numstates; ns++)
10277 {
10278 beta_ntp1[ns] = dinitval;
10279 }
10280
10281 double ddenom = 0;
10282
10283 //gamma_nt - P(x=S| o_0,...,o_t)
10284 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
10285 alpha_nt = alpha[nlastindex];
10286 for (int ns = 0; ns < gamma_nt.length; ns++)
10287 {
10288 double dval = alpha_nt[ns]*beta_ntp1[ns];
10289 ddenom += dval;
10290 gamma_nt[ns] = dval;
10291 }
10292
10293 if (ddenom > 0)
10294 {
10295 for (int ns = 0; ns < gamma_nt.length; ns++)
10296 {
10297 gamma_nt[ns] /=ddenom;
10298 }
10299 }
10300
10301 double[] gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex_nseq[nlastindex]];
10302
10303 for (int ns = 0; ns < numstates; ns++)
10304 {
10305 //first sum gamma over all common signatures
10306 //updates probability of observing the signature when in the state
10307 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
10308 }
10309
10310 for (int nt = nlastindex - 1; nt >= 0; nt--)
10311 {
10312 int ntp1 = (nt+1);
10313
10314 double[] emissionproducts_combo_ntp1 = emissionproducts[traindataObservedIndex_nseq[ntp1]];
10315
10316 for (int ns = 0; ns < numstates; ns++)
10317 {
10318 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_combo_ntp1[ns];
10319 }
10320
10321 if (bscaleemissions)
10322 {
10323 //adding here to help numerical stability
10324 double dmaxval = 0;
10325 for (int ns = 0; ns < numstates; ns++)
10326 {
10327 if (tempproductbetaemiss[ns] > dmaxval)
10328 {
10329 dmaxval = tempproductbetaemiss[ns];
10330 }
10331 }
10332 for (int ns = 0; ns < numstates; ns++)
10333 {
10334 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
10335 }
10336 }
10337
10338 double dsumbeta = 0;
10339 //double dscaleinv = 1.0/scale[nt];
10340 double dscale_nt = scale[nt];
10341 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
10342 for (int ni = 0; ni < numstates; ni++)
10343 {
10344 double dtempsum = 0;
10345 int[] transitionprobsindex_ni = transitionprobsindex[ni];
10346 double[] transitionprobs_ni = transitionprobs[ni];
10347 int transitionprobsnum_ni = transitionprobsnum[ni];
10348
10349 if (transitionprobsnum_ni < nsparsecutoff)
10350 {
10351 //sparse enought to pay the indirection penalty
10352 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
10353 {
10354 //for each state summing over transition probability to state j, emission probablity in j at next step
10355 //and probability of observing the remaining sequence
10356 int nmappedindexouter = transitionprobsindex_ni[nj];
10357 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
10358 }
10359 }
10360 else
10361 {
10362 //not trying to exploit sparsity here
10363 for (int nj = 0; nj < numstates; nj++)
10364 {
10365 //for each state summing over transition probability to state j, emission probablity in j at next step
10366 //and probability of observing the remaining sequence
10367 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
10368 }
10369 }
10370
10371 if (bscalebeta)
10372 {
10373 beta_nt[ni] = dtempsum;
10374 dsumbeta += dtempsum;
10375 }
10376 else
10377 {
10378 double dratio = dtempsum/dscale_nt;
10379
10380 if (dratio > Double.MAX_VALUE)
10381 {
10382 beta_nt[ni] = Double.MAX_VALUE;// dtempsum/dscale_nt;
10383 }
10384 else
10385 {
10386 beta_nt[ni] = dratio;// dtempsum/dscale_nt;
10387 }
10388 }
10389 }
10390
10391 if (bscalebeta)
10392 {
10393 for (int ni = 0; ni < numstates; ni++)
10394 {
10395 beta_nt[ni]/= dsumbeta;
10396
10397 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
10398 {
10399 beta_nt[ni] = EPSILONSTATE;
10400 }
10401 }
10402 }
10403
10404 ddenom = 0;
10405
10406 alpha_nt = alpha[nt];
10407
10408 //gamma_nt - P(x=S| o_0,...,o_t)
10409 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
10410
10411 for (int ns = 0; ns < gamma_nt.length; ns++)
10412 {
10413 double dval = alpha_nt[ns]*beta_nt[ns];
10414 ddenom += dval;
10415 gamma_nt[ns] = dval;
10416 }
10417
10418 if (ddenom > 0)
10419 {
10420 for (int ns = 0; ns < gamma_nt.length; ns++)
10421 {
10422 gamma_nt[ns] /= ddenom;
10423 }
10424 }
10425
10426 gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex_nseq[nt]];
10427
10428 for (int ns = 0; ns < numstates; ns++)
10429 {
10430 //first sum gamma over all common signatures
10431 //updates probability of observing the signature when in the state
10432 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
10433 }
10434
10435 double dsum = 0;
10436
10437 //this compues the numerator portion
10438 for (int ni = 0; ni < numstates; ni++)
10439 {
10440 double[] sumforsxi_ni = sumforsxi[ni]; //computing expected number of transition from state i
10441 int[] transitionprobsindex_ni = transitionprobsindex[ni]; //indicies of non-zero transitions from state i
10442 double[] transitionprobs_ni = transitionprobs[ni]; //probability of transitions from state i
10443 int ntransitionprobsnum_ni = transitionprobsnum[ni]; //number of non-zero transitions from state i
10444 double dalpha_nt_ni = alpha_nt[ni];
10445 //sxi is P(q_t = S_i, q_(t+1) = S_j | O)
10446
10447 if (ntransitionprobsnum_ni < nsparsecutofflooser)
10448 {
10449 //enough 0 transitionto use sparsity here
10450 //looser cut off since the indirection is less of the total time
10451 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
10452 {
10453 int nmappedindex = transitionprobsindex_ni[nj];
10454 //computes transition probability from state i to j
10455 double dtempval = transitionprobs_ni[nmappedindex] *dalpha_nt_ni*tempproductbetaemiss[nmappedindex];
10456 dsum += dtempval;
10457 sumforsxi_ni[nmappedindex] = dtempval;
10458 }
10459 }
10460 else
10461 {
10462 for (int nj = 0; nj < numstates; nj++)
10463 {
10464 //computes transition probability from state i to j
10465 double dtempval = transitionprobs_ni[nj]*dalpha_nt_ni*tempproductbetaemiss[nj];
10466 dsum += dtempval;
10467 sumforsxi_ni[nj] = dtempval;
10468 }
10469 }
10470 }
10471
10472 if (dsum > 0)
10473 {
10474 //normalizing the numerator by the sum of the denominator and updating this iterations value for it
10475 for (int ni = 0; ni < numstates; ni++)
10476 {
10477 int[] transitionprobsindex_ni = transitionprobsindex[ni];
10478 double[] sumforsxi_ni = sumforsxi[ni];
10479 double[] sxi_nseq_ni = sxi_nseq[ni];
10480 int ntransitionprobsnum_ni = transitionprobsnum[ni];
10481
10482 if (ntransitionprobsnum_ni < nsparsecutoff)
10483 {
10484 //guessing sparse enough to avoid the indirections
10485 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
10486 {
10487 int nmappedindex = transitionprobsindex_ni[nj];
10488 sxi_nseq_ni[nmappedindex] += sumforsxi_ni[nmappedindex]/dsum;
10489 }
10490 }
10491 else
10492 {
10493 for (int nj = 0; nj < numstates; nj++)
10494 {
10495 sxi_nseq_ni[nj] += sumforsxi_ni[nj]/dsum;
10496 }
10497 }
10498 }
10499 }
10500 beta_ntp1 = beta_nt; //updating beta_ntp1
10501 }
10502
10503 //double[] gammainitstore_nseq = gammainitstore[nseq];
10504 for (int ns = 0; ns < numstates; ns++)
10505 {
10506 //storing the initial gamma from this iteration
10507 gammainitstore_nseq[ns] = gamma_nt[ns];
10508 }
10509
10510 for (int nindex = 0; nindex < gammaObservedSum.length; nindex++)
10511 {
10512 //going through all the gamma sufficient statistic
10513 if (traindataObservedSeqFlags_nseq[nindex])
10514 {
10515 //only update for those combinations that were observed on this sequnce
10516 //gets the observed combination and missing combination signatures
10517 boolean[] traindataObservedValues_nindex = traindataObservedValues[nindex];
10518 boolean[] traindataNotMissing_nindex = traindataNotMissing[nindex];
10519
10520 double[] gammaObservedSum_nindex = gammaObservedSum[nindex];
10521
10522 for (int ns = 0; ns < numstates; ns++)
10523 {
10524 //going through each state
10525 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
10526 double gammaObservedSum_nindex_ns = gammaObservedSum_nindex[ns];
10527 for (int nmark = 0; nmark < numdatasets; nmark++)
10528 {
10529 //going through each mark
10530 if (traindataNotMissing_nindex[nmark])
10531 {
10532 //only update non-missing
10533 if (traindataObservedValues_nindex[nmark])
10534 {
10535 //updates the gamma sum for each mark when in state and observed 1
10536 gammaksum_nseq_ns[nmark][1] += gammaObservedSum_nindex_ns;
10537 }
10538 else
10539 {
10540 //updates the gamma sum for each mark when in state and observed 0
10541 gammaksum_nseq_ns[nmark][0] += gammaObservedSum_nindex_ns;
10542 }
10543 }
10544 }
10545 }
10546 }
10547 }
10548 dloglikeA[nseq] = dloglikeseq;
10549 }
10550 }
10551
10552 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
10553
10554
10555
10556
10557 /////////////////////////////////////////////////////////////////////////////////////////////////////////
10558
10559 // Create a new thread.
10560 class NewThreadWithLoad implements Runnable
10561 {
10562
10563 //int[] traindataObservedIndex_nseq;
10564 //boolean[] traindataObservedSeqFlags_nseq;
10565 double[][][] gammaksum_nseq;
10566 double[][] sxi_nseq;
10567 int numtime_nseq;
10568 String chromfiles_nseq;
10569 double[] gammainitstore_nseq;
10570 double[][][] gammaObservedSum_Pool;
10571 double[][][] alpha_Pool;
10572 //double[][] emissionproducts;
10573 double[][] gamma_nt_Pool;
10574 double[][] coltransitionprobs;
10575 double[][] scale_Pool;
10576 double[][] beta_nt_Pool;
10577 double[][] beta_ntp1_Pool;
10578 double[][] tempproductbetaemiss_Pool;
10579 int nsparsecutoff;
10580 int nsparsecutofflooser;
10581 double[][][] sumforsxi_Pool;
10582 double[] dloglikeA;
10583 int nseq;
10584
10585 int[][] traindataObservedIndex_Pool;
10586 boolean[][][] traindataObservedValues_Pool;
10587 boolean[][][] traindataNotMissing_Pool;
10588 double[][][] emissionproducts_Pool;
10589 double[][] emissionproducts_scale_Pool;
10590
10591
10592 NewThreadWithLoad(
10593 String chromfiles_nseq,
10594 int[][] traindataObservedIndex_Pool,
10595 boolean[][][] traindataObservedValues_Pool,
10596 boolean[][][] traindataNotMissing_Pool,
10597 //boolean[] traindataObservedSeqFlags_nseq,
10598 double[][][] gammaksum_nseq,
10599 double[][] sxi_nseq,
10600 int numtime_nseq,
10601 double[] gammainitstore_nseq,
10602 double[][][] gammaObservedSum_Pool,
10603 double[][][] alpha_Pool,
10604 double[][][] emissionproducts_Pool,
10605 double[][] gamma_nt_Pool,
10606 double[][] coltransitionprobs,
10607 double[][] scale_Pool,
10608 double[][] beta_nt_Pool,
10609 double[][] beta_ntp1_Pool,
10610 double[][] tempproductbetaemiss_Pool,
10611 double[][][] sumforsxi_Pool,
10612 int nsparsecutoff,
10613 int nsparsecutofflooser,
10614 double[] dloglikeA,
10615 int nseq,
10616 double[][] emissionproducts_scale_Pool)
10617 {
10618 this.emissionproducts_Pool = emissionproducts_Pool;
10619 this.emissionproducts_scale_Pool = emissionproducts_scale_Pool;
10620 this.chromfiles_nseq = chromfiles_nseq;
10621 this.traindataObservedIndex_Pool = traindataObservedIndex_Pool;
10622 this.traindataObservedValues_Pool = traindataObservedValues_Pool;
10623 this.traindataNotMissing_Pool = traindataNotMissing_Pool;
10624 //this.traindataObservedIndex_nseq = traindataObservedIndex_nseq;
10625 //this.traindataObservedSeqFlags_nseq = traindataObservedSeqFlags_nseq;
10626 this.gammaksum_nseq = gammaksum_nseq;
10627 this.sxi_nseq = sxi_nseq;
10628 this.numtime_nseq = numtime_nseq;
10629 this.gammainitstore_nseq = gammainitstore_nseq;
10630 this.gammaObservedSum_Pool = gammaObservedSum_Pool;
10631 this.alpha_Pool = alpha_Pool;
10632 //this.emissionproducts = emissionproducts;
10633 this.gamma_nt_Pool = gamma_nt_Pool;
10634 this.coltransitionprobs = coltransitionprobs;
10635 this.scale_Pool = scale_Pool;
10636 this.beta_nt_Pool = beta_nt_Pool;
10637 this.beta_ntp1_Pool = beta_ntp1_Pool;
10638 this.tempproductbetaemiss_Pool = tempproductbetaemiss_Pool;
10639 this.nsparsecutoff = nsparsecutoff;
10640 this.nsparsecutofflooser = nsparsecutofflooser;
10641 this.sumforsxi_Pool = sumforsxi_Pool;
10642 this.dloglikeA = dloglikeA;
10643 this.nseq = nseq;
10644 }
10645
10646 private int slotavailable()
10647 {
10648 for (int ni = 0; ni < threadslots.length; ni++)
10649 {
10650 if (!threadslots[ni])
10651 {
10652 threadslots[ni] = true;
10653 return ni;
10654 }
10655 }
10656 return -1;
10657 }
10658
10659 // This is the entry point for the second thread.
10660 public void run()
10661 {
10662 int nprocess;
10663
10664 synchronized (objlock)
10665 {
10666 while ((nprocess=slotavailable())==-1)
10667 {
10668 try
10669 {
10670 objlock.wait();
10671 }
10672 catch (InterruptedException ex) {}
10673 }
10674 }
10675
10676 try
10677 {
10678
10679 estep(
10680 emissionproducts_Pool[nprocess],
10681 traindataObservedIndex_Pool[nprocess],
10682 traindataObservedValues_Pool[nprocess],
10683 traindataNotMissing_Pool[nprocess],
10684 gammaObservedSum_Pool[nprocess],
10685 alpha_Pool[nprocess],
10686 gamma_nt_Pool[nprocess],
10687 scale_Pool[nprocess],
10688 beta_nt_Pool[nprocess],
10689 beta_ntp1_Pool[nprocess],
10690 tempproductbetaemiss_Pool[nprocess],
10691 sumforsxi_Pool[nprocess],
10692 emissionproducts_scale_Pool[nprocess]);
10693 }
10694 catch (IOException ioex)
10695 {
10696 ioex.printStackTrace(System.out);
10697 }
10698
10699 synchronized(objlock)
10700 {
10701 nlaunched--;
10702 threadslots[nprocess] = false;
10703 objlock.notifyAll();
10704 }
10705 }
10706
10707 public void estep(
10708 double[][] emissionproducts,
10709 int[] traindataObservedIndex,
10710 boolean[][] traindataObservedValues,
10711 boolean[][] traindataNotMissing,
10712 double[][] gammaObservedSum,
10713 double[][] alpha,
10714 double[] gamma_nt,
10715 double[] scale,
10716 double[] beta_nt,
10717 double[] beta_ntp1,
10718 double[] tempproductbetaemiss,
10719 double[][] sumforsxi,
10720 double[] emissionproducts_scale) throws IOException
10721 {
10722 //going through each sequence
10723
10724 ///////////////////////////////////////////////////////////
10725 //loading the data just for the current chromosome
10726
10727 HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
10728
10729 int nobserved = 0;
10730
10731 if (ChromHMM.BVERBOSE)
10732 {
10733 System.out.println("reading\t"+szinputdir+" "+chromfiles_nseq);
10734 }
10735
10736 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles_nseq);
10737 String szLine;
10738 br.readLine(); //first line tells cell type and chromosome
10739 br.readLine();//flush mark header
10740 ArrayList aldata = new ArrayList();
10741 while ((szLine = br.readLine())!=null)
10742 {
10743 StringTokenizer st = new StringTokenizer(szLine,"\t ");
10744 StringBuffer sb = new StringBuffer();
10745
10746 for (int ncol = 0; ncol < numdatasets; ncol++)
10747 {
10748 if (!st.hasMoreTokens())
10749 {
10750 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles_nseq);
10751 }
10752
10753 String sztoken = st.nextToken();//.trim();
10754
10755 if (sztoken.equals("0"))
10756 {
10757 sb.append("0");
10758 }
10759 else if (sztoken.equals("1"))
10760 {
10761 sb.append("1");
10762 }
10763 else if (sztoken.equals("2"))
10764 {
10765 //this means missing
10766 sb.append("2");
10767 }
10768 else
10769 {
10770 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles_nseq);
10771 }
10772 }
10773 aldata.add(sb.toString());
10774 }
10775 br.close();
10776
10777 int nsize = aldata.size();
10778 //traindataObservedIndex[nfile] = new int[nsize];
10779 //int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
10780
10781 for (int nrow = 0; nrow < nsize; nrow++)
10782 {
10783 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
10784 Integer theObservedInt = (Integer) hmObserved.get(theBigInteger);
10785 //boolean[] flagA;
10786
10787 if (theObservedInt == null)
10788 {
10789 //System.out.println(szmappingbyte.length());
10790 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
10791 hmObserved.put(theBigInteger, Integer.valueOf(nobserved));
10792
10793 //saving this observed index
10794 traindataObservedIndex[nrow] = nobserved;
10795
10796 //increments the number of observed combinations of marks
10797 nobserved++;
10798 }
10799 else
10800 {
10801 //storing the index of the flags associated with this row
10802 traindataObservedIndex[nrow] = ((Integer) theObservedInt).intValue();
10803 }
10804 }
10805
10806
10807
10808 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
10809 while (hmObservedIterator.hasNext())
10810 {
10811 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
10812 BigInteger theBigInteger = (BigInteger) pairs.getKey();
10813 String szmapping = theBigInteger.toString(3); //getting back the mapping string
10814
10815 //ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
10816
10817 int ncurrindex = ((Integer) pairs.getValue()).intValue();// theObservedRec.nobserved;//this is an index on which obervation combination it is
10818
10819 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
10820 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
10821
10822 //if the mapping string is less than the number of data sets then
10823 //there are leading 0's will set for leading 0's not missing and absent
10824 int numch = szmapping.length();
10825 int numleading0 = numdatasets - numch;
10826 for (int nj = 0; nj < numleading0; nj++)
10827 {
10828 traindataObservedValues_ncurrindex[nj] = false;
10829 traindataNotMissing_ncurrindex[nj] = true;
10830 }
10831
10832 int nmappedindex = numleading0; //starting from the leading 0 position
10833 for (int nj = 0; nj < numch; nj++)
10834 {
10835 char ch = szmapping.charAt(nj);
10836
10837 if (ch == '0')
10838 {
10839 traindataObservedValues_ncurrindex[nmappedindex] = false;
10840 traindataNotMissing_ncurrindex[nmappedindex] = true;
10841 }
10842 else if (ch=='1')
10843 {
10844 traindataObservedValues_ncurrindex[nmappedindex] = true;
10845 traindataNotMissing_ncurrindex[nmappedindex] = true;
10846 }
10847 else
10848 {
10849 //missing data
10850 traindataObservedValues_ncurrindex[nmappedindex] = false;
10851 traindataNotMissing_ncurrindex[nmappedindex] = false;
10852 }
10853 nmappedindex++;
10854 }
10855 }
10856
10857 if (bscaleemissions)
10858 {
10859 for (int ni = 0; ni < nobserved; ni++)
10860 {
10861 //going through each combination of marks
10862 //if (traindataObservedSeqFlags_nseq[ni])
10863 //{
10864 //this signature of marks is observed on the current chromosome so
10865 //updating its emission probabilities
10866 double[] emissionproducts_ni = emissionproducts[ni];
10867 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
10868 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
10869
10870 for (int ns = 0; ns < numstates; ns++)
10871 {
10872 emissionproducts_ni[ns] = 1;
10873 }
10874 emissionproducts_scale[ni] = 0;
10875
10876 for (int nmod = 0; nmod < numdatasets; nmod++)
10877 {
10878 for (int ns = 0; ns < numstates; ns++)
10879 {
10880 if (traindataNotMissing_ni[nmod])
10881 {
10882 //we are include this marks emission probability
10883 if (traindataObservedValues_ni[nmod])
10884 {
10885 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
10886 }
10887 else
10888 {
10889 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
10890 }
10891 }
10892 // otherwise treated as missing omitting from product
10893 }
10894
10895
10896 double dmaxval = 0;
10897 for (int ns = 0; ns < numstates; ns++)
10898 {
10899 if (emissionproducts_ni[ns] > dmaxval)
10900 {
10901 dmaxval = emissionproducts_ni[ns];
10902 }
10903 }
10904
10905 if (dmaxval <=0)///EPSILONEMISSIONS)
10906 {
10907 for (int ns = 0; ns < numstates; ns++)
10908 {
10909 emissionproducts_ni[ns] = 1;
10910 }
10911 //approximating log-likelihood
10912 emissionproducts_scale[ni] += Math.log(EPSILONEMISSIONS);
10913 }
10914 else
10915 {
10916 for (int ns = 0; ns < numstates; ns++)
10917 {
10918 emissionproducts_ni[ns]/= dmaxval;
10919 }
10920 emissionproducts_scale[ni] += Math.log(dmaxval);
10921 }
10922 }
10923 }
10924 }
10925 else
10926 {
10927 for (int ni = 0; ni < nobserved; ni++)
10928 {
10929 //going through each combination of marks
10930 //if (traindataObservedSeqFlags_nseq[ni])
10931 //{
10932 //this signature of marks is observed on the current chromosome so
10933 //updating its emission probabilities
10934 double[] emissionproducts_ni = emissionproducts[ni];
10935 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
10936 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
10937
10938 boolean ballzero = true;
10939
10940 for (int ns = 0; ns < numstates; ns++)
10941 {
10942 double dproduct = 1;
10943 double[][] emissionprobs_ns = emissionprobs[ns];
10944
10945 for (int nmod = 0; nmod < numdatasets; nmod++)
10946 {
10947 if (traindataNotMissing_ni[nmod])
10948 {
10949 //we are include this marks emission probability
10950 if (traindataObservedValues_ni[nmod])
10951 {
10952 //System.out.println("positive\t"+ns+"\t"+nmod+"\t1\t"+emissionprobs_ns[nmod][1]);
10953 dproduct *= emissionprobs_ns[nmod][1];
10954 }
10955 else
10956 {
10957 ///System.out.println("negative\t"+ns+"\t"+nmod+"\t0\t"+emissionprobs_ns[nmod][0]);
10958 dproduct *= emissionprobs_ns[nmod][0];
10959 }
10960 }
10961 // otherwise treated as missing omitting from product
10962 }
10963 //System.out.println(ns+"\t"+dproduct);
10964 emissionproducts_ni[ns] = dproduct;
10965
10966 if (dproduct >= EPSILONEMISSIONS)
10967 {
10968 ballzero = false;
10969 }
10970 }
10971
10972 if (ballzero)
10973 {
10974 for (int ns = 0; ns < numstates; ns++)
10975 {
10976 emissionproducts_ni[ns] = EPSILONEMISSIONS;
10977 }
10978 }
10979 }
10980 }
10981
10982
10983
10984 double dloglikeseq = 0;
10985
10986 for (int ns = 0; ns < gammaksum_nseq.length; ns++)
10987 {
10988 //resetting the gamma sufficient statistics in the current sequence
10989 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
10990 for (int nmark = 0; nmark < gammaksum_nseq_ns.length; nmark++)
10991 {
10992 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
10993 {
10994 gammaksum_nseq_ns[nmark][nbucket] = 0;
10995 }
10996 }
10997 }
10998
10999 for (int ni = 0; ni < sxi_nseq.length; ni++)
11000 {
11001 //reseeting the sxi sufficient statistics in the current sequence
11002 double[] sxi_nseq_ni = sxi_nseq[ni];
11003 for (int nj = 0; nj < sxi_nseq_ni.length; nj++)
11004 {
11005 sxi_nseq_ni[nj] = 0;
11006 }
11007 }
11008
11009 //gammaObservedSum stores the weight for each combination of marks in each stat
11010 //for (int ncombo = 0; ncombo < gammaObservedSum.length; ncombo++)
11011 for (int ncombo = 0; ncombo < nobserved; ncombo++)
11012 {
11013 //resetting that to 0
11014 double[] gammaObservedSum_ncombo = gammaObservedSum[ncombo];
11015 for (int ns = 0; ns < gammaObservedSum_ncombo.length; ns++)
11016 {
11017 gammaObservedSum_ncombo[ns] = 0;
11018 }
11019 }
11020
11021 //initial probability in state s is initial probability times emission probability at first position
11022 double[] alpha_nt = alpha[0];
11023 double dscale = 0;
11024 double[] emissionproducts_nobserveindex =emissionproducts[traindataObservedIndex[0]];
11025 for (int ns = 0; ns < numstates; ns++)
11026 {
11027 alpha_nt[ns] = probinit[ns] * emissionproducts_nobserveindex[ns];
11028 //System.out.println(ns+"\t"+alpha_nt[ns]);
11029 dscale += alpha_nt[ns];
11030 }
11031 scale[0] = dscale;
11032
11033 //alpha_t(s)=P(o_0,...,o_t,x_t=s|lambda)
11034 //converts the alpha terms to probabilities
11035 if (bscalebeta)
11036 {
11037 if (dscale == 0)
11038 {
11039 for (int ns = 0; ns < numstates; ns++)
11040 {
11041 //added
11042 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
11043 {
11044 alpha_nt[ns] = EPSILONSTATE;
11045 dscale += EPSILONSTATE;
11046 }
11047 }
11048 scale[0] = dscale;
11049 }
11050
11051 for (int ns = 0; ns < numstates; ns++)
11052 {
11053 alpha_nt[ns] /= dscale;
11054
11055 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
11056 {
11057 alpha_nt[ns] = EPSILONSTATE;
11058 }
11059 }
11060 }
11061 else
11062 {
11063 for (int ns = 0; ns < numstates; ns++)
11064 {
11065 alpha_nt[ns] /= dscale;
11066 }
11067 }
11068
11069
11070
11071 dloglikeseq += Math.log(dscale);
11072
11073 if (bscaleemissions)
11074 {
11075 dloglikeseq += emissionproducts_scale[traindataObservedIndex[0]];
11076 }
11077
11078 //forward step
11079 //int numtime_nseq = numtime[nseq];
11080 for (int nt = 1; nt < numtime_nseq; nt++)
11081 {
11082 //the actual observed combination at position t
11083 double[] alpha_ntm1 = alpha[nt-1];
11084 alpha_nt = alpha[nt];
11085
11086 dscale = 0;
11087 emissionproducts_nobserveindex = emissionproducts[traindataObservedIndex[nt]];
11088
11089 for (int ns = 0; ns < numstates; ns++)
11090 {
11091 //stores the emission product for each location on the chromosome
11092
11093 int transitionprobsnumCol_ns = transitionprobsnumCol[ns];
11094 int[] transitionprobsindexCol_ns = transitionprobsindexCol[ns];
11095 double[] coltransitionprobs_ns = coltransitionprobs[ns];
11096
11097 double dtempsum = 0;
11098 if (transitionprobsnumCol_ns < nsparsecutoff)
11099 {
11100 //number of transitions is sparse enough worth going through the extra redirection
11101 for (int nj = 0; nj < transitionprobsnumCol_ns; nj++)
11102 {
11103 //for each next state computing inner sum of all previous alpha and the transition probability
11104 //for all non-zero transitions into the state
11105 int nmappedindex = transitionprobsindexCol_ns[nj];
11106 dtempsum += coltransitionprobs_ns[nmappedindex]*alpha_ntm1[nmappedindex];
11107 }
11108 }
11109 else
11110 {
11111 //avoid the redirect and multiply by 0
11112 for (int nj = 0; nj < numstates; nj++)
11113 {
11114 dtempsum += coltransitionprobs_ns[nj]*alpha_ntm1[nj];
11115 }
11116 }
11117 //multiply the transition sum by the emission probability
11118 double dalphaval = dtempsum*emissionproducts_nobserveindex[ns];
11119 alpha_nt[ns] = dalphaval;
11120 //System.out.println(ns+"\t"+alpha_nt[ns]+"\t"+dtempsum+"\t"+emissionproducts_nobserveindex[ns]);
11121 dscale += dalphaval;
11122 }
11123
11124
11125 //rescaling alpha
11126 scale[nt] = dscale;
11127 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
11128
11129 if (bscalebeta)
11130 {
11131 if (dscale == 0)
11132 {
11133 for (int ns = 0; ns < numstates; ns++)
11134 {
11135 //added
11136 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
11137 {
11138 alpha_nt[ns] = EPSILONSTATE;
11139 dscale += EPSILONSTATE;
11140 }
11141 }
11142 scale[nt] = dscale;
11143 }
11144
11145 // else
11146 //{
11147 for (int ns = 0; ns < numstates; ns++)
11148 {
11149 alpha_nt[ns] /= dscale;
11150
11151 if ((alpha_nt[ns] < EPSILONSTATE)&&(emissionproducts_nobserveindex[ns]>0))//(ns < numstates-1)))
11152 {
11153 alpha_nt[ns] = EPSILONSTATE;
11154 }
11155 }
11156 //}
11157 }
11158 else
11159 {
11160 for (int ns = 0; ns < numstates; ns++)
11161 {
11162 alpha_nt[ns] /= dscale;
11163 }
11164 }
11165 //for (int ns = 0; ns < numstates; ns++)
11166 //{
11167 // alpha_nt[ns] /= dscale;
11168 //}
11169
11170 dloglikeseq += Math.log(dscale);
11171
11172 if (bscaleemissions)
11173 {
11174 dloglikeseq += emissionproducts_scale[traindataObservedIndex[nt]];
11175 }
11176 }
11177
11178 //backward step
11179 //beta_t(s)=P(o_t+1,...,o_T|x_t=s,lambda)
11180 int nlastindex = numtime_nseq-1;
11181 double dinitval;
11182 if (bscalebeta)
11183 {
11184 dinitval = 1.0/numstates;
11185 }
11186 else
11187 {
11188 dinitval = 1.0/scale[nlastindex];
11189 }
11190
11191 for (int ns = 0; ns < numstates; ns++)
11192 {
11193 beta_ntp1[ns] = dinitval;
11194 }
11195 //double dinitval = 1.0/scale[nlastindex];
11196 //for (int ns = 0; ns < numstates; ns++)
11197 //{
11198 // beta_ntp1[ns] = dinitval;
11199 //}
11200
11201 double ddenom = 0;
11202
11203 //gamma_nt - P(x=S| o_0,...,o_t)
11204 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
11205 alpha_nt = alpha[nlastindex];
11206 for (int ns = 0; ns < gamma_nt.length; ns++)
11207 {
11208 double dval = alpha_nt[ns]*beta_ntp1[ns];
11209 ddenom += dval;
11210 gamma_nt[ns] = dval;
11211 }
11212
11213 if (ddenom > 0)
11214 {
11215 for (int ns = 0; ns < gamma_nt.length; ns++)
11216 {
11217 gamma_nt[ns] /=ddenom;
11218 }
11219 }
11220
11221 double[] gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex[nlastindex]];
11222
11223 for (int ns = 0; ns < numstates; ns++)
11224 {
11225 //first sum gamma over all common signatures
11226 //updates probability of observing the signature when in the state
11227 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
11228 }
11229
11230 for (int nt = nlastindex - 1; nt >= 0; nt--)
11231 {
11232 int ntp1 = (nt+1);
11233
11234 double[] emissionproducts_combo_ntp1 = emissionproducts[traindataObservedIndex[ntp1]];
11235
11236 for (int ns = 0; ns < numstates; ns++)
11237 {
11238 tempproductbetaemiss[ns] = beta_ntp1[ns]*emissionproducts_combo_ntp1[ns];
11239 }
11240
11241 if (bscaleemissions)
11242 {
11243 //adding here to help numerical stability
11244 double dmaxval = 0;
11245 for (int ns = 0; ns < numstates; ns++)
11246 {
11247 if (tempproductbetaemiss[ns] > dmaxval)
11248 {
11249 dmaxval = tempproductbetaemiss[ns];
11250 }
11251 }
11252 for (int ns = 0; ns < numstates; ns++)
11253 {
11254 tempproductbetaemiss[ns] = tempproductbetaemiss[ns]/dmaxval;
11255 }
11256 }
11257
11258 double dsumbeta = 0;
11259
11260 //double dscaleinv = 1.0/scale[nt];
11261 double dscale_nt = scale[nt];
11262 //scale_t(s)=P(o_0,...,o_t|lambda) summed over all states
11263 for (int ni = 0; ni < numstates; ni++)
11264 {
11265 double dtempsum = 0;
11266 int[] transitionprobsindex_ni = transitionprobsindex[ni];
11267 double[] transitionprobs_ni = transitionprobs[ni];
11268 int transitionprobsnum_ni = transitionprobsnum[ni];
11269
11270 if (transitionprobsnum_ni < nsparsecutoff)
11271 {
11272 //sparse enought to pay the indirection penalty
11273 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
11274 {
11275 //for each state summing over transition probability to state j, emission probablity in j at next step
11276 //and probability of observing the remaining sequence
11277 int nmappedindexouter = transitionprobsindex_ni[nj];
11278 dtempsum += transitionprobs_ni[nmappedindexouter]*tempproductbetaemiss[nmappedindexouter];
11279 }
11280 }
11281 else
11282 {
11283 //not trying to exploit sparsity here
11284 for (int nj = 0; nj < numstates; nj++)
11285 {
11286 //for each state summing over transition probability to state j, emission probablity in j at next step
11287 //and probability of observing the remaining sequence
11288 dtempsum += transitionprobs_ni[nj]*tempproductbetaemiss[nj];
11289 }
11290 }
11291
11292 if (bscalebeta)
11293 {
11294 beta_nt[ni] = dtempsum;
11295 dsumbeta += dtempsum;
11296 }
11297 else
11298 {
11299 double dratio = dtempsum/dscale_nt;
11300 if (dratio > Double.MAX_VALUE)
11301 {
11302 beta_nt[ni] = Double.MAX_VALUE;//dtempsum/dscale_nt;
11303 }
11304 else
11305 {
11306 beta_nt[ni] = dratio;
11307 }
11308 }
11309 //double dratio = dtempsum/dscale_nt;
11310
11311 //if (dratio > Double.MAX_VALUE)
11312 //{
11313 // beta_nt[ni] = Double.MAX_VALUE;// dtempsum/dscale_nt;
11314 //}
11315 //else
11316 //{
11317 // beta_nt[ni] = dratio;//dtempsum/dscale_nt;
11318 //}
11319 }
11320
11321 if (bscalebeta)
11322 {
11323 for (int ni = 0; ni < numstates; ni++)
11324 {
11325 beta_nt[ni]/= dsumbeta;
11326
11327 if (beta_nt[ni] < EPSILONSTATE)//&&(!bdummy))// || (ni < numstates-1)))
11328 {
11329 beta_nt[ni] = EPSILONSTATE;
11330 }
11331 }
11332 }
11333
11334 ddenom = 0;
11335
11336 alpha_nt = alpha[nt];
11337
11338 //gamma_nt - P(x=S| o_0,...,o_t)
11339 //P(o_t+1,...,o_T|x_t=s,lambda) * P(o_0,...,o_t,xt=s|lambda)
11340
11341 for (int ns = 0; ns < gamma_nt.length; ns++)
11342 {
11343 double dval = alpha_nt[ns]*beta_nt[ns];
11344 ddenom += dval;
11345 gamma_nt[ns] = dval;
11346 }
11347
11348 if (ddenom > 0)
11349 {
11350 for (int ns = 0; ns < gamma_nt.length; ns++)
11351 {
11352 gamma_nt[ns] /= ddenom;
11353 }
11354 }
11355
11356 gammaObservedSum_combo_nt = gammaObservedSum[traindataObservedIndex[nt]];
11357
11358 for (int ns = 0; ns < numstates; ns++)
11359 {
11360 //first sum gamma over all common signatures
11361 //updates probability of observing the signature when in the state
11362 gammaObservedSum_combo_nt[ns] += gamma_nt[ns];
11363 }
11364
11365 double dsum = 0;
11366
11367 //this compues the numerator portion
11368 for (int ni = 0; ni < numstates; ni++)
11369 {
11370 double[] sumforsxi_ni = sumforsxi[ni]; //computing expected number of transition from state i
11371 int[] transitionprobsindex_ni = transitionprobsindex[ni]; //indicies of non-zero transitions from state i
11372 double[] transitionprobs_ni = transitionprobs[ni]; //probability of transitions from state i
11373 int ntransitionprobsnum_ni = transitionprobsnum[ni]; //number of non-zero transitions from state i
11374 double dalpha_nt_ni = alpha_nt[ni];
11375 //sxi is P(q_t = S_i, q_(t+1) = S_j | O)
11376
11377 if (ntransitionprobsnum_ni < nsparsecutofflooser)
11378 {
11379 //enough 0 transitionto use sparsity here
11380 //looser cut off since the indirection is less of the total time
11381 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
11382 {
11383 int nmappedindex = transitionprobsindex_ni[nj];
11384 //computes transition probability from state i to j
11385 double dtempval = transitionprobs_ni[nmappedindex] *dalpha_nt_ni*tempproductbetaemiss[nmappedindex];
11386 dsum += dtempval;
11387
11388 sumforsxi_ni[nmappedindex] = dtempval;
11389 }
11390 }
11391 else
11392 {
11393 for (int nj = 0; nj < numstates; nj++)
11394 {
11395 //computes transition probability from state i to j
11396 double dtempval = transitionprobs_ni[nj]*dalpha_nt_ni*tempproductbetaemiss[nj];
11397 dsum += dtempval;
11398 sumforsxi_ni[nj] = dtempval;
11399 }
11400 }
11401 }
11402
11403
11404 if (dsum > 0)
11405 {
11406 //added to avoid numerical errors
11407 //normalizing the numerator by the sum of the denominator and updating this iterations value for it
11408 for (int ni = 0; ni < numstates; ni++)
11409 {
11410 int[] transitionprobsindex_ni = transitionprobsindex[ni];
11411 double[] sumforsxi_ni = sumforsxi[ni];
11412 double[] sxi_nseq_ni = sxi_nseq[ni];
11413 int ntransitionprobsnum_ni = transitionprobsnum[ni];
11414
11415 if (ntransitionprobsnum_ni < nsparsecutoff)
11416 {
11417 //guessing sparse enough to avoid the indirections
11418 for (int nj = 0; nj < ntransitionprobsnum_ni; nj++)
11419 {
11420 int nmappedindex = transitionprobsindex_ni[nj];
11421 sxi_nseq_ni[nmappedindex] += sumforsxi_ni[nmappedindex]/dsum;
11422 }
11423 }
11424 else
11425 {
11426 for (int nj = 0; nj < numstates; nj++)
11427 {
11428 sxi_nseq_ni[nj] += sumforsxi_ni[nj]/dsum;
11429 }
11430 }
11431 }
11432 }
11433 beta_ntp1 = beta_nt; //updating beta_ntp1
11434 }
11435
11436 //double[] gammainitstore_nseq = gammainitstore[nseq];
11437 for (int ns = 0; ns < numstates; ns++)
11438 {
11439 //storing the initial gamma from this iteration
11440 gammainitstore_nseq[ns] = gamma_nt[ns];
11441 }
11442
11443 //for (int nindex = 0; nindex < gammaObservedSum.length; nindex++)
11444 for (int nindex = 0; nindex < nobserved; nindex++)
11445 {
11446 //going through all the gamma sufficient statistic
11447 //if (traindataObservedSeqFlags_nseq[nindex])
11448 {
11449 //only update for those combinations that were observed on this sequence
11450 //gets the observed combination and missing combination signatures
11451 boolean[] traindataObservedValues_nindex = traindataObservedValues[nindex];
11452 boolean[] traindataNotMissing_nindex = traindataNotMissing[nindex];
11453
11454 double[] gammaObservedSum_nindex = gammaObservedSum[nindex];
11455
11456 for (int ns = 0; ns < numstates; ns++)
11457 {
11458 //going through each state
11459 double[][] gammaksum_nseq_ns = gammaksum_nseq[ns];
11460 double gammaObservedSum_nindex_ns = gammaObservedSum_nindex[ns];
11461 for (int nmark = 0; nmark < numdatasets; nmark++)
11462 {
11463 //going through each mark
11464 if (traindataNotMissing_nindex[nmark])
11465 {
11466 //only update non-missing
11467 if (traindataObservedValues_nindex[nmark])
11468 {
11469 //updates the gamma sum for each mark when in state and observed 1
11470 gammaksum_nseq_ns[nmark][1] += gammaObservedSum_nindex_ns;
11471 }
11472 else
11473 {
11474 //updates the gamma sum for each mark when in state and observed 0
11475 gammaksum_nseq_ns[nmark][0] += gammaObservedSum_nindex_ns;
11476 }
11477 }
11478 }
11479 }
11480 }
11481 }
11482 //System.out.println("==>"+nseq+"\t"+dloglikeseq);
11483 dloglikeA[nseq] = dloglikeseq;
11484 }
11485 }
11486
11487
11488 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510 boolean[] threadslots;
11511
11512 Object objlock = new Object();
11513 int nlaunched;
11514
11515
11516 ///////////////////////////////////////////////////////////////////////////////////////////////////////
11517 /**
11518 * This is the core procedure for learning the parameters of the model loading from data
11519 */
11520 public void trainParametersParallelWithLoad() throws IOException
11521 {
11522 NumberFormat nf3 = NumberFormat.getInstance();
11523 nf3.setMaximumFractionDigits(3);
11524 nf3.setGroupingUsed(false);
11525 nf3.setMinimumFractionDigits(3);
11526
11527 NumberFormat nf1 = NumberFormat.getInstance();
11528 nf1.setMaximumFractionDigits(1);
11529 nf1.setMinimumFractionDigits(1);
11530 nf1.setGroupingUsed(false);
11531
11532 int niteration = 1;
11533
11534 boolean bconverged = false;
11535
11536 double dzerotransitioncutoff = Math.pow(10,-nzerotransitionpower);
11537
11538 //number of non-zero transition for the
11539 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
11540
11541 //number of non-zero transition that need to be less than this at the looser cut-off
11542 int nsparsecutofflooser = (int) (numstates * ChromHMM.SPARSECUTOFFLOOSERRATIO);
11543
11544 double dprevloglike;
11545
11546 //stores the maximum number of locations in any sequence and in each sequence
11547 //int[] numtime = new int[chromfiles.length];//traindataObservedIndex.length];
11548 int nmaxtime = 0;
11549 for (int nseq = 0; nseq < numtime.length; nseq++) //traindataObservedIndex.length;
11550 {
11551 //numtime[nseq] = traindataObservedIndex[nseq].length;
11552 if (numtime[nseq] > nmaxtime)
11553 {
11554 nmaxtime = numtime[nseq];
11555 }
11556 }
11557
11558 if (ChromHMM.BVERBOSE)
11559 {
11560 System.out.println("Maximum number of locations\t"+nmaxtime);
11561 }
11562
11563
11564 int numprocessors;
11565 // for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
11566
11567 if (nmaxprocessors <= 0)
11568 {
11569 numprocessors = Math.min(numtime.length,Runtime.getRuntime().availableProcessors()); //changed from traindataObservedIndex.length;
11570 }
11571 else
11572 {
11573 numprocessors = Math.min(numtime.length, //changed from traindataObservedIndex.length;
11574 Math.min(nmaxprocessors,Runtime.getRuntime().availableProcessors()));
11575 }
11576
11577 //if (ChromHMM.BVERBOSE)
11578 {
11579 if (numprocessors == 1)
11580 System.out.println("Using "+numprocessors+" thread for Baum-Welch training");
11581 else
11582 System.out.println("Using "+numprocessors+" threads for Baum-Welch training");
11583 }
11584 threadslots = new boolean[numprocessors];
11585
11586 int ncurrnumincludeseq;
11587 int[] samples= null;
11588 if (numincludeseq >= 1)
11589 {
11590 ncurrnumincludeseq = Math.min(numincludeseq, chromfiles.length);
11591 samples = new int[ncurrnumincludeseq];
11592 }
11593 else
11594 {
11595 ncurrnumincludeseq = chromfiles.length;
11596 }
11597
11598 //stores the emission probability for the i^th combination of marks in the j^th state
11599 double[][][] emissionproducts_Pool = new double[numprocessors][nmaxtime][numstates]; //traindataObservedValues.length
11600
11601 //stores the scale for the emission probability for the i^th combination of marks
11602 double[][] emissionproducts_scale_Pool;
11603
11604 if (bscaleemissions)
11605 {
11606 emissionproducts_scale_Pool = new double[numprocessors][nmaxtime];
11607 }
11608 else
11609 {
11610 emissionproducts_scale_Pool = new double[numprocessors][];
11611 }
11612
11613
11614 //stores temporary product terms
11615 double[][] tempproductbetaemiss_Pool = new double[numprocessors][numstates];
11616
11617 //This stores the alpha values at each time point and number of states
11618 double[][][] alpha_Pool = new double[numprocessors][nmaxtime][numstates];
11619
11620 //Temporary storage of the gamma's for each state
11621 double[][] gamma_nt_Pool = new double[numprocessors][numstates];
11622
11623 //Temporary storage of the beta values for each state
11624 double[][] beta_nt_Pool = new double[numprocessors][numstates];
11625
11626 //Temporary storage of the beta values for each state at the next time point
11627 double[][] beta_ntp1_Pool = new double[numprocessors][numstates];
11628
11629 //stores the scaling value for each time point
11630 double[][] scale_Pool = new double[numprocessors][nmaxtime];
11631
11632 //stores the transition probabilities for each column
11633 double[][] coltransitionprobs = new double[numstates][numstates];
11634
11635 //stores the sufficient statistic for the initital probability in each state for the last visit
11636 //double[][] gammainitstore = new double[chromfiles.length][numstates];
11637 double[][] gammainitstore = new double[ncurrnumincludeseq][numstates];
11638
11639 //stores the sufficient statistics for computing the transition probabilities cumulated for each iteration
11640 double[][][] sxistore = new double[ncurrnumincludeseq][numstates][numstates];
11641 //double[][][] sxistore = new double[chromfiles.length][numstates][numstates];
11642
11643 //stores the sufficient statistic for computing the emission probabilities
11644 double[][][][] gammaksumstore =
11645 //new double[chromfiles.length][numstates][numdatasets][numbuckets];
11646 new double[ncurrnumincludeseq][numstates][numdatasets][numbuckets];
11647
11648 //temporary storage in computation of sxi
11649 double[][][] sumforsxi_Pool = new double[numprocessors][numstates][numstates];
11650
11651 //stores the sum of the gamma values associated with each combination in each state
11652 double[][][] gammaObservedSum_Pool = new double[numprocessors][nmaxtime][numstates]; //nmaxtime instead of traindataObservedValues.length
11653
11654 //stores the indicies of the data
11655 int[][] traindataObservedIndex_Pool = new int[numprocessors][nmaxtime];
11656
11657 //saving the mapping of signatures and chromsome observed on
11658 //stores whether there is a present call at each location
11659 boolean[][][] traindataObservedValues_Pool = new boolean[numprocessors][nmaxtime][numdatasets];
11660
11661 //stores whether the mark is not considered missing
11662 boolean[][][] traindataNotMissing_Pool = new boolean[numprocessors][nmaxtime][numdatasets]; //usually nobserved
11663
11664
11665 double[] dloglikeA = new double[ncurrnumincludeseq];//chromfiles.length];
11666
11667 int nelim = 0;
11668 long ltimeitr= System.currentTimeMillis();
11669 dprevloglike = Double.NEGATIVE_INFINITY;
11670
11671
11672
11673
11674
11675 boolean[] bincludeseq = new boolean[chromfiles.length];
11676 for (int nk = 0; nk < bincludeseq.length; nk++)
11677 {
11678 bincludeseq[nk] = true;
11679 }
11680
11681 do
11682 {
11683
11684 if (numincludeseq >=1)
11685 {
11686 for (int ni = 0; ni < samples.length; ni++)
11687 {
11688 samples[ni] = ni;
11689 }
11690
11691 //Random theRandom2 = new Random(412);//433
11692
11693 //sampling without replacement data locations wanted
11694 for (int ni = ncurrnumincludeseq; ni < chromfiles.length; ni++)
11695 {
11696 if (theRandom.nextDouble() < ncurrnumincludeseq/((double) ni +1))
11697 {
11698 samples[theRandom.nextInt(ncurrnumincludeseq)] = ni;
11699 }
11700 }
11701
11702 for (int nk = 0; nk < bincludeseq.length; nk++)
11703 {
11704 bincludeseq[nk] = false;
11705 }
11706
11707 for (int nk = 0; nk < samples.length; nk++)
11708 {
11709 bincludeseq[samples[nk]] = true;
11710 //System.out.println("including\t"+samples[nk]+"\t"+bincludeseq[samples[nk]]);
11711 }
11712 }
11713
11714 //dloglike= 0;
11715
11716 /*
11717 //for (int ni = 0; ni < emissionproducts.length; ni++)
11718 for (int ni = 0; ni < emissionproducts.length; ni++)
11719 {
11720 //going through each combination of marks
11721 //this signature of marks is observed on the current chromosome so
11722 //updating its emission probabilities
11723 double[] emissionproducts_ni = emissionproducts[ni];
11724 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
11725 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
11726
11727 boolean ballzero = true;
11728
11729 for (int ns = 0; ns < numstates; ns++)
11730 {
11731 double dproduct = 1;
11732 double[][] emissionprobs_ns = emissionprobs[ns];
11733
11734 for (int nmod = 0; nmod < numdatasets; nmod++)
11735 {
11736 if (traindataNotMissing_ni[nmod])
11737 {
11738 //we are include this marks emission probability
11739 if (traindataObservedValues_ni[nmod])
11740 {
11741 //System.out.println("positive\t"+ns+"\t"+nmod+"\t1\t"+emissionprobs_ns[nmod][1]);
11742 dproduct *= emissionprobs_ns[nmod][1];
11743 }
11744 else
11745 {
11746 ///System.out.println("negative\t"+ns+"\t"+nmod+"\t0\t"+emissionprobs_ns[nmod][0]);
11747 dproduct *= emissionprobs_ns[nmod][0];
11748 }
11749 }
11750 // otherwise treated as missing omitting from product
11751 }
11752 //System.out.println(ns+"\t"+dproduct);
11753 emissionproducts_ni[ns] = dproduct;
11754
11755 if (dproduct >= EPSILONEMISSIONS)
11756 {
11757 ballzero = false;
11758 }
11759 }
11760
11761 if (ballzero)
11762 {
11763 for (int ns = 0; ns < numstates; ns++)
11764 {
11765 emissionproducts_ni[ns] = EPSILONEMISSIONS;
11766 }
11767 }
11768 }
11769 */
11770
11771 //stores in coltransitionprobs the transpose of transitionprobs
11772 for (int ni = 0; ni < numstates; ni++)
11773 {
11774 double[] coltransitionprobs_ni = coltransitionprobs[ni];
11775 for (int nj = 0; nj < numstates; nj++)
11776 {
11777 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
11778 }
11779 }
11780
11781 synchronized (objlock)
11782 {
11783 nlaunched = ncurrnumincludeseq;// chromfiles.length;// traindataObservedIndex.length;
11784 }
11785
11786 //for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
11787 int nincludeindex = 0;
11788 for (int nseq = 0; nseq < chromfiles.length; nseq++)
11789 {
11790
11791 if (bincludeseq[nseq])
11792 {
11793 double[][] sxi_nseq = sxistore[nincludeindex];//nseq];
11794 int numtime_nseq = numtime[nseq];
11795 String chromfiles_nseq = chromfiles[nseq];
11796 //int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
11797 //boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nseq];
11798 double[][][] gammaksum_nseq = gammaksumstore[nincludeindex];//nseq];
11799 double[] gammainitstore_nseq = gammainitstore[nincludeindex];//nseq];
11800
11801 NewThreadWithLoad myNewThreadWithLoad = new NewThreadWithLoad(
11802 chromfiles_nseq,
11803 traindataObservedIndex_Pool,
11804 traindataObservedValues_Pool,
11805 traindataNotMissing_Pool,
11806 //traindataObservedIndex_nseq,
11807 //traindataObservedSeqFlags_nseq,
11808 gammaksum_nseq,
11809 sxi_nseq,
11810 numtime_nseq,
11811 gammainitstore_nseq,
11812 gammaObservedSum_Pool,
11813 alpha_Pool,
11814 emissionproducts_Pool,
11815 gamma_nt_Pool,
11816 coltransitionprobs,
11817 scale_Pool,
11818 beta_nt_Pool,
11819 beta_ntp1_Pool,
11820 tempproductbetaemiss_Pool,
11821 sumforsxi_Pool,
11822 nsparsecutoff,
11823 nsparsecutofflooser,
11824 dloglikeA,
11825 nincludeindex,
11826 emissionproducts_scale_Pool);
11827 nincludeindex++;
11828
11829 new Thread(myNewThreadWithLoad).start();
11830 }
11831 }
11832
11833
11834 synchronized(objlock)
11835 {
11836 while (nlaunched > 0)
11837 {
11838 try
11839 {
11840 objlock.wait();
11841 }
11842 catch (InterruptedException ex) {}
11843 }
11844 }
11845
11846
11847 //normal EM
11848 //executes the M-step after any pass through a sequence after one pass has been made through all sequences
11849 double dsum = 0;
11850
11851 //updating the initial probabilities
11852 for (int ni = 0; ni < numstates; ni++)
11853 {
11854 double dgammainitsum = 0;
11855 //for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
11856 //for (int nitr = 0; nitr < chromfiles.length; nitr++)
11857 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++)
11858 {
11859 dgammainitsum += gammainitstore[nitr][ni];
11860 }
11861
11862 if ((bpseudo)&&(!bnopseudolast))
11863 {
11864 dgammainitsum++;
11865 }
11866 probinit[ni] = dgammainitsum;
11867 dsum += dgammainitsum;
11868 }
11869
11870 for (int ni = 0; ni < numstates; ni++)
11871 {
11872 probinit[ni] /= dsum;
11873 }
11874
11875 //this indicates if there is a change on the set of 0 probability transitions
11876 boolean bchange = false;
11877 for (int ni = 0; ni < transitionprobs.length; ni++)
11878 {
11879 dsum = 0;
11880 //computes the denominator for the transition probabilities
11881
11882 int[] transitionprobsindex_ni = transitionprobsindex[ni];
11883 double[] transitionprobs_ni = transitionprobs[ni];
11884 int transitionprobsnum_ni = transitionprobsnum[ni];
11885 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
11886 {
11887 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
11888 double dsxistoreitr = 0;
11889 //for (int nitr = 0; nitr < chromfiles.length; nitr++) //traindataObservedIndex.length
11890 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++) //traindataObservedIndex.length
11891 {
11892 //if (bincludeseq[nitr])
11893 {
11894 dsxistoreitr += sxistore[nitr][ni][ntransitionprobsindex_ni_nj];
11895 }
11896 }
11897
11898 if (bpseudo)
11899 {
11900 //pseudo-count to avoid divide by zero
11901 dsxistoreitr++;
11902 }
11903 transitionprobs_ni[ntransitionprobsindex_ni_nj] = dsxistoreitr;
11904
11905 dsum += dsxistoreitr;
11906 }
11907
11908 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
11909 {
11910 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
11911 //computes the updated transition probabilities
11912
11913 transitionprobs_ni[ntransitionprobsindex_ni_nj] /= dsum;
11914
11915 if ((transitionprobs_ni[ntransitionprobsindex_ni_nj] < dzerotransitioncutoff) && (ni != ntransitionprobsindex_ni_nj))
11916 {
11917 //if falls below threshold eliminate the transition probabilities
11918 elim[ni][ntransitionprobsindex_ni_nj] = true;
11919 bchange = true;
11920 nelim++;
11921 transitionprobs_ni[ntransitionprobsindex_ni_nj] = 0;
11922 }
11923 }
11924 }
11925
11926
11927 if (bchange)
11928 {
11929 //a transition was eliminated we need to update the probabilities
11930 for (int ni = 0; ni < transitionprobs.length; ni++)
11931 {
11932 int nindex = 0;
11933 double ddenom = 0;
11934 boolean[] elim_ni = elim[ni];
11935 double[] transitionprobs_ni = transitionprobs[ni];
11936 int[] transitionprobsindex_ni = transitionprobsindex[ni];
11937 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
11938 {
11939 if (!elim_ni[nj])
11940 {
11941 //we have not eliminated this transition
11942 //stores its index in order and add sum to denominator
11943 transitionprobsindex_ni[nindex] = nj;
11944 ddenom += transitionprobs_ni[nj];
11945 nindex++;
11946 }
11947 }
11948
11949 //renormalize the transition probabilities by the sum of the non-eliminated transitions
11950 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
11951 {
11952 transitionprobs_ni[nj] /= ddenom;
11953 }
11954 //update the number of valid transitions
11955 transitionprobsnum[ni] = nindex;
11956 }
11957
11958 for (int ni = 0; ni < transitionprobs.length; ni++)
11959 {
11960 int nindex =0;
11961 int[] transitionprobsindexCol_ni = transitionprobsindexCol[ni];
11962 for (int nj = 0; nj < transitionprobs[ni].length; nj++)
11963 {
11964 if (!elim[nj][ni])
11965 {
11966 //copy into the column of i the index of all non-eliminated transitions of i
11967 transitionprobsindexCol_ni[nindex] = nj;
11968 nindex++;
11969 }
11970 }
11971 //updates the number of non-zero transitions from column i
11972 transitionprobsnumCol[ni] = nindex;
11973 }
11974 }
11975
11976 //updating the emission parameters
11977 for (int ns = 0; ns < numstates; ns++)
11978 {
11979 double[][] emissionprobs_ns = emissionprobs[ns];
11980
11981
11982 for (int nmark = 0; nmark < emissionprobs_ns.length; nmark++)
11983 {
11984 double[] emissionprobs_ns_nmark = emissionprobs_ns[nmark];
11985 //can't used a general gamma sum because of missing emission vals
11986 double dgammadenom = 0;
11987
11988 //updates gamma sum
11989 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
11990 {
11991 emissionprobs_ns_nmark[nbucket] = 0;
11992 //ncurrnumincludeseq
11993 //for (int nitr = 0; nitr < chromfiles.length; nitr++) //was traindataobserved length
11994 //double dtempsum = 0;
11995 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++) //was traindataobserved length
11996 {
11997 //if (bincludeseq[nitr])
11998 //{
11999 emissionprobs_ns_nmark[nbucket] += gammaksumstore[nitr][ns][nmark][nbucket];
12000 //}
12001 }
12002
12003 if ((bpseudo) && ((!bnopseudolast)||(nmark<emissionprobs_ns.length-1)))
12004 {
12005 emissionprobs_ns_nmark[nbucket]++;
12006 }
12007 dgammadenom += emissionprobs_ns_nmark[nbucket];
12008 }
12009
12010 //added to avoid NA
12011 if (dgammadenom > 0)
12012 {
12013 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
12014 {
12015 emissionprobs_ns_nmark[nbucket] /= dgammadenom;
12016 }
12017 }
12018 }
12019 }
12020
12021
12022 if (ChromHMM.BVERBOSE)
12023 {
12024 System.out.println("\t"+niteration+"\t"+dloglike);
12025 }
12026
12027
12028 dloglike = 0;
12029 for (int nindex = 0; nindex < dloglikeA.length; nindex++)
12030 {
12031 //if (bincludeseq[nindex])
12032 {
12033 dloglike += dloglikeA[nindex];
12034 }
12035 }
12036
12037 double ddiff =(dloglike-dprevloglike);
12038
12039
12040 //dconvergediff is only enforced if greater thanor equal to 0
12041 dprevloglike = dloglike;
12042
12043 if (borderrows)
12044 {
12045 makeStateOrdering();
12046 }
12047
12048 if (bordercols)
12049 {
12050 makeColOrdering();
12051 }
12052 //updates after each iteration the current status of the search
12053 printTransitionTable(niteration);
12054 printEmissionTable(niteration);
12055
12056 if (bprintimage)
12057 {
12058 printEmissionImage(niteration);
12059 printTransitionImage(niteration);
12060 }
12061 printParametersToFile(niteration);
12062
12063 //we just completed a full iteration
12064 long ltimefinal = System.currentTimeMillis();
12065 double dtimechange = (ltimefinal-ltimeitr)/(double) 1000;
12066 bconverged = (((niteration >= nmaxiterations)||((ddiff< dconvergediff)&&(dconvergediff>=0)))||((dtimechange>nmaxseconds)&&(nmaxseconds>=0)));
12067 if (ChromHMM.BVERBOSE)
12068 {
12069 System.out.println(niteration+"\tTime Iteration\t"+dtimechange+"\t"+"\tElim\t"+nelim);
12070 System.out.println("Full "+niteration+"\t"+dloglike+"\t"+dprevloglike+"\t"+ddiff);
12071 }
12072
12073
12074 if (niteration == 1)
12075 {
12076 System.out.format("%10s %25s %10s %20s%n","Iteration","Estimated Log Likelihood", "Change","Total Time (secs)");
12077 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),"-",""+nf1.format(dtimechange));
12078 }
12079 else
12080 {
12081 //System.out.format(niteration+" "+nf3.format(dloglike)+" "+nf3.format(ddiff)+" "+nf1.format(dtimechange));
12082 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),""+nf3.format(ddiff),""+nf1.format(dtimechange));
12083 }
12084 niteration++;
12085 }
12086 while (!bconverged);
12087 }
12088
12089 ////////////////////////////////////////////////////////////////////////////////////////////////////////
12090 /**
12091 * This is the core procedure for learning the parameters of the model
12092 */
12093 public void trainParametersParallel() throws IOException
12094 {
12095 NumberFormat nf3 = NumberFormat.getInstance();
12096 nf3.setMaximumFractionDigits(3);
12097 nf3.setGroupingUsed(false);
12098 nf3.setMinimumFractionDigits(3);
12099
12100 NumberFormat nf1 = NumberFormat.getInstance();
12101 nf1.setMaximumFractionDigits(1);
12102 nf1.setMinimumFractionDigits(1);
12103 nf1.setGroupingUsed(false);
12104
12105 int niteration = 1;
12106
12107 boolean bconverged = false;
12108
12109 double dzerotransitioncutoff = Math.pow(10,-nzerotransitionpower);
12110
12111 //number of non-zero transition for the
12112 int nsparsecutoff = (int) (numstates * ChromHMM.SPARSECUTOFFRATIO);
12113
12114 //number of non-zero transition that need to be less than this at the looser cut-off
12115 int nsparsecutofflooser = (int) (numstates * ChromHMM.SPARSECUTOFFLOOSERRATIO);
12116
12117 double dprevloglike;
12118
12119 //stores the maximum number of locations in any sequence and in each sequence
12120 int[] numtime = new int[traindataObservedIndex.length];
12121 int nmaxtime = 0;
12122 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
12123 {
12124 numtime[nseq] = traindataObservedIndex[nseq].length;
12125 if (numtime[nseq] > nmaxtime)
12126 {
12127 nmaxtime = numtime[nseq];
12128 }
12129 }
12130
12131 if (ChromHMM.BVERBOSE)
12132 {
12133 System.out.println("Maximum number of locations\t"+nmaxtime);
12134 }
12135
12136
12137 int numprocessors;
12138 // for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
12139
12140 if (nmaxprocessors <= 0)
12141 {
12142 numprocessors = Math.min(traindataObservedIndex.length,Runtime.getRuntime().availableProcessors());
12143 }
12144 else
12145 {
12146 numprocessors = Math.min(traindataObservedIndex.length,
12147 Math.min(nmaxprocessors,Runtime.getRuntime().availableProcessors()));
12148 }
12149
12150 //if (ChromHMM.BVERBOSE)
12151 {
12152 if (numprocessors == 1)
12153 System.out.println("Using "+numprocessors+" thread for Baum-Welch training");
12154 else
12155 System.out.println("Using "+numprocessors+" threads for Baum-Welch training");
12156 }
12157 threadslots = new boolean[numprocessors];
12158
12159 int ncurrnumincludeseq;
12160 int[] samples= null;
12161 if (numincludeseq >= 1)
12162 {
12163 ncurrnumincludeseq = Math.min(numincludeseq, chromfiles.length);
12164 samples = new int[ncurrnumincludeseq];
12165 }
12166 else
12167 {
12168 ncurrnumincludeseq = chromfiles.length;
12169 }
12170
12171 //stores the emission probability for the i^th combination of marks in the j^th state
12172 double[][] emissionproducts = new double[traindataObservedValues.length][numstates];
12173
12174
12175 //stores the scale for the emission probability for the i^th combination of marks
12176 double[] emissionproducts_scale = null;
12177
12178 if (bscaleemissions)
12179 {
12180 emissionproducts_scale = new double[traindataObservedValues.length];
12181 }
12182
12183 //stores temporary product terms
12184 double[][] tempproductbetaemiss_Pool = new double[numprocessors][numstates];
12185
12186 //This stores the alpha values at each time point and number of states
12187 double[][][] alpha_Pool = new double[numprocessors][nmaxtime][numstates];
12188
12189 //Temporary storage of the gamma's for each state
12190 double[][] gamma_nt_Pool = new double[numprocessors][numstates];
12191
12192 //Temporary storage of the beta values for each state
12193 double[][] beta_nt_Pool = new double[numprocessors][numstates];
12194
12195 //Temporary storage of the beta values for each state at the next time point
12196 double[][] beta_ntp1_Pool = new double[numprocessors][numstates];
12197
12198 //stores the scaling value for each time point
12199 double[][] scale_Pool = new double[numprocessors][nmaxtime];
12200
12201 //stores the transition probabilities for each column
12202 double[][] coltransitionprobs = new double[numstates][numstates];
12203
12204 //stores the sufficient statistic for the initital probability in each state for the last visit
12205 double[][] gammainitstore = //new double[traindataObservedIndex.length][numstates];
12206 new double[ncurrnumincludeseq][numstates];
12207
12208 //stores the sufficient statistics for computing the transition probabilities cumulated for each iteration
12209 double[][][] sxistore = //new double[traindataObservedIndex.length][numstates][numstates];
12210 new double[ncurrnumincludeseq][numstates][numstates];
12211
12212 //stores the sufficient statistic for computing the emission probabilities
12213 double[][][][] gammaksumstore =
12214 new double[ncurrnumincludeseq][numstates][numdatasets][numbuckets];
12215 //new double[traindataObservedIndex.length][numstates][numdatasets][numbuckets];
12216
12217 //temporary storage in computation of sxi
12218 double[][][] sumforsxi_Pool = new double[numprocessors][numstates][numstates];
12219
12220 //stores the sum of the gamma values associated with each combination in each state
12221 double[][][] gammaObservedSum_Pool = new double[numprocessors][traindataObservedValues.length][numstates];
12222
12223
12224 double[] dloglikeA = new double[ncurrnumincludeseq];
12225 //new double[traindataObservedIndex.length];
12226
12227 int nelim = 0;
12228 long ltimeitr= System.currentTimeMillis();
12229 dprevloglike = Double.NEGATIVE_INFINITY;
12230
12231
12232 boolean[] bincludeseq = new boolean[chromfiles.length];
12233 for (int nk = 0; nk < bincludeseq.length; nk++)
12234 {
12235 bincludeseq[nk] = true;
12236 }
12237
12238
12239 do
12240 {
12241 //dloglike= 0;
12242
12243 if (numincludeseq >=1)
12244 {
12245 for (int ni = 0; ni < samples.length; ni++)
12246 {
12247 samples[ni] = ni;
12248 }
12249
12250 //Random theRandom2 = new Random(412);//433
12251
12252 //sampling without replacement data locations wanted
12253 for (int ni = ncurrnumincludeseq; ni < chromfiles.length; ni++)
12254 {
12255 if (theRandom.nextDouble() < ncurrnumincludeseq/((double) ni +1))
12256 {
12257 samples[theRandom.nextInt(ncurrnumincludeseq)] = ni;
12258 }
12259 }
12260
12261 for (int nk = 0; nk < bincludeseq.length; nk++)
12262 {
12263 bincludeseq[nk] = false;
12264 }
12265
12266 for (int nk = 0; nk < samples.length; nk++)
12267 {
12268 bincludeseq[samples[nk]] = true;
12269 //System.out.println("including\t"+samples[nk]+"\t"+bincludeseq[samples[nk]]);
12270 }
12271 }
12272
12273
12274 if (bscaleemissions)
12275 {
12276 for (int ni = 0; ni < emissionproducts.length; ni++)
12277 {
12278 //going through each combination of marks
12279 //this signature of marks is observed on the current chromosome so
12280 //updating its emission probabilities
12281 double[] emissionproducts_ni = emissionproducts[ni];
12282 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
12283 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
12284
12285 for (int ns = 0; ns < numstates; ns++)
12286 {
12287 emissionproducts_ni[ns] = 1;
12288 }
12289 emissionproducts_scale[ni] = 0;
12290
12291 for (int nmod = 0; nmod < numdatasets; nmod++)
12292 {
12293 for (int ns = 0; ns < numstates; ns++)
12294 {
12295 if (traindataNotMissing_ni[nmod])
12296 {
12297 //we are include this marks emission probability
12298 if (traindataObservedValues_ni[nmod])
12299 {
12300 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][1];
12301 }
12302 else
12303 {
12304 emissionproducts_ni[ns] *= emissionprobs[ns][nmod][0];
12305 }
12306 }
12307 // otherwise treated as missing omitting from product
12308 }
12309
12310 double dmaxval = 0;
12311 for (int ns = 0; ns < numstates; ns++)
12312 {
12313 if (emissionproducts_ni[ns] > dmaxval)
12314 {
12315 dmaxval = emissionproducts_ni[ns];
12316 }
12317 }
12318
12319 if (dmaxval <= 0)//EPSILONEMISSIONS)
12320 {
12321 for (int ns = 0; ns < numstates; ns++)
12322 {
12323 emissionproducts_ni[ns] = 1;
12324 }
12325 //approximating log-likelihood
12326 emissionproducts_scale[ni] += Math.log(EPSILONEMISSIONS);
12327 }
12328 else
12329 {
12330 for (int ns = 0; ns < numstates; ns++)
12331 {
12332 emissionproducts_ni[ns]/= dmaxval;
12333 }
12334 emissionproducts_scale[ni] += Math.log(dmaxval);
12335 }
12336 }
12337 }
12338 }
12339 else
12340 {
12341 for (int ni = 0; ni < emissionproducts.length; ni++)
12342 {
12343 //going through each combination of marks
12344 //this signature of marks is observed on the current chromosome so
12345 //updating its emission probabilities
12346 double[] emissionproducts_ni = emissionproducts[ni];
12347 boolean[] traindataObservedValues_ni = traindataObservedValues[ni];
12348 boolean[] traindataNotMissing_ni = traindataNotMissing[ni];
12349
12350 boolean ballzero = true;
12351
12352 for (int ns = 0; ns < numstates; ns++)
12353 {
12354 double dproduct = 1;
12355 double[][] emissionprobs_ns = emissionprobs[ns];
12356
12357 for (int nmod = 0; nmod < numdatasets; nmod++)
12358 {
12359 if (traindataNotMissing_ni[nmod])
12360 {
12361 //we are include this marks emission probability
12362 if (traindataObservedValues_ni[nmod])
12363 {
12364 //System.out.println("positive\t"+ns+"\t"+nmod+"\t1\t"+emissionprobs_ns[nmod][1]);
12365 dproduct *= emissionprobs_ns[nmod][1];
12366 }
12367 else
12368 {
12369 ///System.out.println("negative\t"+ns+"\t"+nmod+"\t0\t"+emissionprobs_ns[nmod][0]);
12370 dproduct *= emissionprobs_ns[nmod][0];
12371 }
12372 }
12373 // otherwise treated as missing omitting from product
12374 }
12375 //System.out.println(ns+"\t"+dproduct);
12376 emissionproducts_ni[ns] = dproduct;
12377
12378 if (dproduct >= EPSILONEMISSIONS)
12379 {
12380 ballzero = false;
12381 }
12382 }
12383
12384 if (ballzero)
12385 {
12386 for (int ns = 0; ns < numstates; ns++)
12387 {
12388 emissionproducts_ni[ns] = EPSILONEMISSIONS;
12389 }
12390 }
12391 }
12392 }
12393
12394
12395 //stores in coltransitionprobs the transpose of transitionprobs
12396 for (int ni = 0; ni < numstates; ni++)
12397 {
12398 double[] coltransitionprobs_ni = coltransitionprobs[ni];
12399 for (int nj = 0; nj < numstates; nj++)
12400 {
12401 coltransitionprobs_ni[nj] = transitionprobs[nj][ni];
12402 }
12403 }
12404
12405 synchronized (objlock)
12406 {
12407 nlaunched = ncurrnumincludeseq;//traindataObservedIndex.length;
12408 }
12409
12410
12411 int nincludeindex = 0;
12412 for (int nseq = 0; nseq < traindataObservedIndex.length; nseq++)
12413 {
12414 //System.out.println(nseq+"\t"+bincludeseq[nseq]);
12415 if (bincludeseq[nseq])
12416 {
12417 double[][] sxi_nseq = sxistore[nincludeindex];//[nseq]; //bug fixed here in v1.15 when using -n option with lowmem
12418 int numtime_nseq = numtime[nseq];
12419 int[] traindataObservedIndex_nseq = traindataObservedIndex[nseq];
12420 boolean[] traindataObservedSeqFlags_nseq = traindataObservedSeqFlags[nseq];
12421 double[][][] gammaksum_nseq = gammaksumstore[nincludeindex];// gammaksumstore[nseq];
12422 double[] gammainitstore_nseq = gammainitstore[nincludeindex];// gammainitstore[nseq];
12423
12424 NewThread myNewThread = new NewThread(traindataObservedIndex_nseq,
12425 traindataObservedSeqFlags_nseq,
12426 gammaksum_nseq,
12427 sxi_nseq,
12428 numtime_nseq,
12429 gammainitstore_nseq,
12430 gammaObservedSum_Pool,
12431 alpha_Pool,
12432 emissionproducts,
12433 gamma_nt_Pool,
12434 coltransitionprobs,
12435 scale_Pool,
12436 beta_nt_Pool,
12437 beta_ntp1_Pool,
12438 tempproductbetaemiss_Pool,
12439 sumforsxi_Pool,
12440 nsparsecutoff,
12441 nsparsecutofflooser,
12442 dloglikeA,
12443 nincludeindex,
12444 emissionproducts_scale);
12445 //nseq);
12446 nincludeindex++;
12447 new Thread(myNewThread).start();
12448 }
12449 }
12450
12451
12452 synchronized(objlock)
12453 {
12454 while (nlaunched > 0)
12455 {
12456 try
12457 {
12458 objlock.wait();
12459 }
12460 catch (InterruptedException ex) {}
12461 }
12462 }
12463
12464 //normal EM
12465 //executes the M-step after any pass through a sequence after one pass has been made through all sequences
12466 double dsum = 0;
12467
12468 //updating the inital probabilities
12469 for (int ni = 0; ni < numstates; ni++)
12470 {
12471 double dgammainitsum = 0;
12472 //for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
12473 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++)
12474 {
12475 //if (bincludeseq[nitr])
12476 {
12477 dgammainitsum += gammainitstore[nitr][ni];
12478 }
12479 }
12480
12481 if ((bpseudo)&&(!bnopseudolast))
12482 {
12483 dgammainitsum++;
12484 }
12485 probinit[ni] = dgammainitsum;
12486 dsum += dgammainitsum;
12487 }
12488
12489 for (int ni = 0; ni < numstates; ni++)
12490 {
12491 probinit[ni] /= dsum;
12492 }
12493
12494 //this indicates if there is a change on the set of 0 probability transitions
12495 boolean bchange = false;
12496 for (int ni = 0; ni < transitionprobs.length; ni++)
12497 {
12498 dsum = 0;
12499 //computes the denominator for the transition probabilities
12500
12501 int[] transitionprobsindex_ni = transitionprobsindex[ni];
12502 double[] transitionprobs_ni = transitionprobs[ni];
12503 int transitionprobsnum_ni = transitionprobsnum[ni];
12504 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
12505 {
12506 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
12507 double dsxistoreitr = 0;
12508 //for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
12509 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++)
12510 {
12511 //if (bincludeseq[nitr])
12512 {
12513 dsxistoreitr += sxistore[nitr][ni][ntransitionprobsindex_ni_nj];
12514 }
12515 }
12516
12517 if (bpseudo)
12518 {
12519 //pseudo-count to avoid divide by zero
12520 dsxistoreitr++;
12521 }
12522 transitionprobs_ni[ntransitionprobsindex_ni_nj] = dsxistoreitr;
12523
12524 dsum += dsxistoreitr;
12525 }
12526
12527 for (int nj = 0; nj < transitionprobsnum_ni; nj++)
12528 {
12529 int ntransitionprobsindex_ni_nj = transitionprobsindex_ni[nj];
12530 //computes the updated transition probabilities
12531 transitionprobs_ni[ntransitionprobsindex_ni_nj] /= dsum;
12532
12533 if ((transitionprobs_ni[ntransitionprobsindex_ni_nj] < dzerotransitioncutoff) && (ni != ntransitionprobsindex_ni_nj))
12534 {
12535 //if falls below threshold eliminate the transition probabilities
12536 elim[ni][ntransitionprobsindex_ni_nj] = true;
12537 bchange = true;
12538 nelim++;
12539 transitionprobs_ni[ntransitionprobsindex_ni_nj] = 0;
12540 }
12541 }
12542 }
12543
12544
12545 if (bchange)
12546 {
12547 //a transition was eliminated we need to update the probabilities
12548 for (int ni = 0; ni < transitionprobs.length; ni++)
12549 {
12550 int nindex = 0;
12551 double ddenom = 0;
12552 boolean[] elim_ni = elim[ni];
12553 double[] transitionprobs_ni = transitionprobs[ni];
12554 int[] transitionprobsindex_ni = transitionprobsindex[ni];
12555 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
12556 {
12557 if (!elim_ni[nj])
12558 {
12559 //we have not eliminated this transition
12560 //stores its index in order and add sum to denominator
12561 transitionprobsindex_ni[nindex] = nj;
12562 ddenom += transitionprobs_ni[nj];
12563 nindex++;
12564 }
12565 }
12566
12567 //renormalize the transition probabilities by the sum of the non-eliminated transitions
12568 for (int nj = 0; nj < transitionprobs_ni.length; nj++)
12569 {
12570 transitionprobs_ni[nj] /= ddenom;
12571 }
12572 //update the number of valid transitions
12573 transitionprobsnum[ni] = nindex;
12574 }
12575
12576 for (int ni = 0; ni < transitionprobs.length; ni++)
12577 {
12578 int nindex =0;
12579 int[] transitionprobsindexCol_ni = transitionprobsindexCol[ni];
12580 for (int nj = 0; nj < transitionprobs[ni].length; nj++)
12581 {
12582 if (!elim[nj][ni])
12583 {
12584 //copy into the column of i the index of all non-eliminated transitions of i
12585 transitionprobsindexCol_ni[nindex] = nj;
12586 nindex++;
12587 }
12588 }
12589 //updates the number of non-zero transitions from column i
12590 transitionprobsnumCol[ni] = nindex;
12591 }
12592 }
12593
12594 //updating the emission parameters
12595 for (int ns = 0; ns < numstates; ns++)
12596 {
12597 double[][] emissionprobs_ns = emissionprobs[ns];
12598
12599 for (int nmark = 0; nmark < emissionprobs_ns.length; nmark++)
12600 {
12601 double[] emissionprobs_ns_nmark = emissionprobs_ns[nmark];
12602 //can't used a general gamma sum because of missing emission vals
12603 double dgammadenom = 0;
12604
12605 //updates gamma sum
12606 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
12607 {
12608 emissionprobs_ns_nmark[nbucket] = 0;
12609
12610 //for (int nitr = 0; nitr < traindataObservedIndex.length; nitr++)
12611 for (int nitr = 0; nitr < ncurrnumincludeseq; nitr++)
12612 {
12613 //if (bincludeseq[nitr])
12614 {
12615 emissionprobs_ns_nmark[nbucket] += gammaksumstore[nitr][ns][nmark][nbucket];
12616 }
12617 }
12618
12619 if ((bpseudo) && ((!bnopseudolast)||(nmark<emissionprobs_ns.length-1)))
12620 {
12621 emissionprobs_ns_nmark[nbucket]++;
12622 }
12623 dgammadenom += emissionprobs_ns_nmark[nbucket];
12624 }
12625
12626 //added to avoid NA
12627 if (dgammadenom > 0)
12628 {
12629 for (int nbucket = 0; nbucket < numbuckets; nbucket++)
12630 {
12631 emissionprobs_ns_nmark[nbucket] /= dgammadenom;
12632 }
12633 }
12634 }
12635 }
12636
12637
12638 if (ChromHMM.BVERBOSE)
12639 {
12640 System.out.println("\t"+niteration+"\t"+dloglike);
12641 }
12642
12643
12644 dloglike = 0;
12645 for (int nindex = 0; nindex < dloglikeA.length; nindex++)
12646 {
12647 //if (bincludeseq[nindex])
12648 {
12649 dloglike += dloglikeA[nindex];
12650 }
12651 }
12652
12653 double ddiff =(dloglike-dprevloglike);
12654
12655
12656 //dconvergediff is only enforced if greater thanor equal to 0
12657 dprevloglike = dloglike;
12658
12659 if (borderrows)
12660 {
12661 makeStateOrdering();
12662 }
12663
12664 if (bordercols)
12665 {
12666 makeColOrdering();
12667 }
12668 //updates after each iteration the current status of the search
12669 printTransitionTable(niteration);
12670 printEmissionTable(niteration);
12671 if (bprintimage)
12672 {
12673 printEmissionImage(niteration);
12674 printTransitionImage(niteration);
12675 }
12676 printParametersToFile(niteration);
12677
12678 //we just completed a full iteration
12679 long ltimefinal = System.currentTimeMillis();
12680 double dtimechange = (ltimefinal-ltimeitr)/(double) 1000;
12681 bconverged = (((niteration >= nmaxiterations)||((ddiff< dconvergediff)&&(dconvergediff>=0)))||((dtimechange>nmaxseconds)&&(nmaxseconds>=0)));
12682 if (ChromHMM.BVERBOSE)
12683 {
12684 System.out.println(niteration+"\tTime Iteration\t"+dtimechange+"\t"+"\tElim\t"+nelim);
12685 System.out.println("Full "+niteration+"\t"+dloglike+"\t"+dprevloglike+"\t"+ddiff);
12686 }
12687
12688
12689 if (niteration == 1)
12690 {
12691 System.out.format("%10s %25s %10s %20s%n","Iteration","Estimated Log Likelihood", "Change","Total Time (secs)");
12692 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),"-",""+nf1.format(dtimechange));
12693 }
12694 else
12695 {
12696 //System.out.format(niteration+" "+nf3.format(dloglike)+" "+nf3.format(ddiff)+" "+nf1.format(dtimechange));
12697 System.out.format("%10s %25s %10s %20s%n",""+niteration,""+nf3.format(dloglike),""+nf3.format(ddiff),""+nf1.format(dtimechange));
12698 }
12699 niteration++;
12700 }
12701 while (!bconverged);
12702 }
12703
12704
12705 ////////////////////////////////////////////////////////////////////////////////////////////////////////
12706 /**
12707 * Loads in the input data
12708 * If there are multiple cell type associated with the files that should be
12709 * indicated by a prefix before an '_'
12710 */
12711 public void loadDataFileStubs() throws IOException
12712 {
12713
12714 if (szinputfilelist == null)
12715 {
12716 //takes all files in the directory with a _binary
12717 File dir = new File(szinputdir);
12718 String[] chromfilesall = dir.list();
12719 if (chromfilesall == null)
12720 {
12721 throw new IllegalArgumentException(szinputdir+" is not a valid directory!");
12722 }
12723 ArrayList alfiles = new ArrayList();
12724 for (int nfile = 0; nfile < chromfilesall.length; nfile++)
12725 {
12726 if ((chromfilesall[nfile].contains("_binary"))&&(!(new File(chromfilesall[nfile])).isHidden()))
12727 {
12728 //added hidden check in v.1.11
12729 alfiles.add(chromfilesall[nfile]);
12730 }
12731 }
12732
12733 if (alfiles.size() == 0)
12734 {
12735 throw new IllegalArgumentException("No files found in "+szinputdir+" containing '_binary' that are not Hidden");
12736 }
12737
12738 //stores them in chromfiles
12739 chromfiles = new String[alfiles.size()];
12740 for (int nfile = 0; nfile < chromfiles.length; nfile++)
12741 {
12742 chromfiles[nfile] = (String) alfiles.get(nfile);
12743 }
12744 }
12745 else
12746 {
12747 //loads in the input coords list
12748 BufferedReader brfiles = Util.getBufferedReader(szinputfilelist);
12749
12750 ArrayList alfiles = new ArrayList();
12751 String szLine;
12752 while ((szLine = brfiles.readLine())!=null)
12753 {
12754 alfiles.add(szLine);
12755 }
12756 brfiles.close();
12757
12758 //stores them in chromfiles
12759 chromfiles = new String[alfiles.size()];
12760 for (int nfile = 0; nfile < chromfiles.length; nfile++)
12761 {
12762 chromfiles[nfile] = (String) alfiles.get(nfile);
12763 }
12764 }
12765
12766 Arrays.sort(chromfiles);//gives a deterministic reproducible starting order to the chromfiles
12767
12768 //randomly orders the chromosome files to visit
12769 RecIntDouble[] recA = new RecIntDouble[chromfiles.length];
12770 String[] tempchromfiles = new String[chromfiles.length];
12771
12772 //now going to randomize the order of chromosomes if theRandom is not null
12773 //the order of chromosome matters when doing an incremental expectation maximization
12774 for (int ni = 0; ni < chromfiles.length; ni++)
12775 {
12776 tempchromfiles[ni] = chromfiles[ni];
12777 if (theRandom == null)
12778 {
12779 recA[ni] = new RecIntDouble(ni, ni);
12780 }
12781 else
12782 {
12783 recA[ni] = new RecIntDouble(ni,theRandom.nextDouble());
12784 }
12785 }
12786
12787 if (theRandom != null)
12788 {
12789 //already in order if random is null
12790 Arrays.sort(recA,new RecIntDoubleCompare());
12791 }
12792
12793 cellSeq = new String[chromfiles.length];
12794 chromSeq = new String[chromfiles.length];
12795
12796 for (int ni = 0; ni < chromfiles.length; ni++)
12797 {
12798 //swapping into chromfiles the sorted chromosome ordering
12799 chromfiles[ni] = tempchromfiles[recA[ni].nindex];
12800 }
12801
12802 traindataObservedIndex = new int[chromfiles.length][]; //number of columns depends on number of lines in file
12803 numtime = new int[chromfiles.length];
12804
12805 //HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
12806
12807 int nobserved = 0;
12808 //PrintWriter pw = null;
12809
12810 for (int nfile = 0; nfile < chromfiles.length; nfile++)
12811 {
12812 if (ChromHMM.BVERBOSE)
12813 {
12814 System.out.println("reading\t"+szinputdir+" "+chromfiles[nfile]);
12815 }
12816 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nfile]);
12817 String szLine = br.readLine(); //first line tells cell type and chromosome
12818 if (szLine == null)
12819 {
12820 throw new IllegalArgumentException(szinputdir+"/"+chromfiles[nfile]+" is empty!");
12821 }
12822 StringTokenizer st = new StringTokenizer(szLine,"\t");
12823 if (!st.hasMoreTokens())
12824 {
12825 throw new IllegalArgumentException("First line must contain cell type and chromosome. No entries found.");
12826 }
12827
12828 cellSeq[nfile] = st.nextToken().trim();//added trim in version 1.23
12829 if (!st.hasMoreTokens())
12830 {
12831 throw new IllegalArgumentException("First line must contain cell type and chromosome. Only one entry found.");
12832 }
12833 chromSeq[nfile] = st.nextToken().trim();//added trim in version 1.23
12834
12835 if (st.hasMoreTokens())
12836 {
12837 throw new IllegalArgumentException("First line should only contain cell type and chromosome");
12838 }
12839 szLine = br.readLine(); //reading header
12840 //to output binary
12841 if (szLine == null)
12842 {
12843 throw new IllegalArgumentException(szinputdir+"/"+chromfiles[nfile]+" only has one line!");
12844 }
12845 st = new StringTokenizer(szLine,"\t");
12846 int numtokens = st.countTokens();
12847 if (nfile == 0)
12848 {
12849 //first time reading header taking tokens
12850 datasets = new String[numtokens];
12851 int ntoken = 0;
12852 while (st.hasMoreTokens())
12853 {
12854 datasets[ntoken] = st.nextToken().trim();
12855 ntoken++;
12856 }
12857 //numdatasets is the number of marks we are integrating
12858 numdatasets = datasets.length;
12859 }
12860 else
12861 {
12862 //Requires number of tokens to match
12863 if (numtokens != datasets.length)
12864 {
12865 throw new IllegalArgumentException(" found a file with header with "+numtokens+" entries, which does not match another with "+datasets.length); //updated in v1.20 to be more informative
12866 }
12867
12868 int ntoken = 0;
12869 //Gives warning if a header column does not match
12870 while (st.hasMoreTokens())
12871 {
12872 String sztoken = st.nextToken().trim();
12873 if (!datasets[ntoken].equals(sztoken))
12874 {
12875 System.out.println("WARNING headers do not match between "+chromfiles[nfile]+" and "+chromfiles[0]);
12876 }
12877 ntoken++;
12878 }
12879 }
12880
12881
12882
12883 // LineNumberReader lnr = new LineNumberReader(br);//new FileReader(new File("File1")));
12884 //while (lnr.skip(Long.MAX_VALUE) > 0);
12885 //int nlinecount = lnr.getLineNumber();
12886
12887
12888
12889 int nlinecount = 0;
12890 while ((szLine = br.readLine())!=null)
12891 {
12892 nlinecount++;
12893 }
12894
12895 //System.out.println("num lines is\t"+nlinecount+"\t"+nfile);
12896 br.close();
12897 //lnr.close();
12898 numtime[nfile] = nlinecount;
12899
12900
12901 }
12902 }
12903
12904
12905 /*
12906 ArrayList aldata = new ArrayList();
12907 while ((szLine = br.readLine())!=null)
12908 {
12909 st = new StringTokenizer(szLine,"\t");
12910 StringBuffer sb = new StringBuffer();
12911
12912 for (int ncol = 0; ncol < numdatasets; ncol++)
12913 {
12914
12915 if (!st.hasMoreTokens())
12916 {
12917 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nfile]);
12918 }
12919
12920 String sztoken = st.nextToken();
12921
12922 if (sztoken.equals("0"))
12923 {
12924 sb.append("0");
12925 }
12926 else if (sztoken.equals("1"))
12927 {
12928 sb.append("1");
12929 }
12930 else if (sztoken.equals("2"))
12931 {
12932 //this means missing
12933 sb.append("2");
12934 }
12935 else
12936 {
12937 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nfile]);
12938 }
12939 }
12940
12941 aldata.add(sb.toString());
12942 }
12943 br.close();
12944
12945 int nsize = aldata.size();
12946 traindataObservedIndex[nfile] = new int[nsize];
12947 int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
12948
12949 for (int nrow = 0; nrow < nsize; nrow++)
12950 {
12951 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
12952 ObservedRec theObservedRec = (ObservedRec) hmObserved.get(theBigInteger);
12953 boolean[] flagA;
12954
12955 if (theObservedRec == null)
12956 {
12957 //this is the first time we encountered this combination of marks
12958 flagA = new boolean[chromfiles.length];
12959 //recording which chromsomes this mark combination was observed
12960 flagA[nfile] =true;
12961
12962 //System.out.println(szmappingbyte.length());
12963 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
12964 hmObserved.put(theBigInteger, new ObservedRec(nobserved,flagA));
12965
12966 //saving this observed index
12967 traindataObservedIndex[nfile][nrow] = nobserved;
12968
12969 //increments the number of observed combinations of marks
12970 nobserved++;
12971 }
12972 else
12973 {
12974 //updating that this signature was observed on this chromosome
12975 theObservedRec.flagA[nfile] = true;
12976 //storing the index of the flags associated with this row
12977 traindataObservedIndex_nfile[nrow] = theObservedRec.nobserved;
12978 }
12979 }
12980 }
12981
12982 //saving the mapping of signatures and chromsome observed on
12983
12984 //stores whether there is a present call at each location
12985 traindataObservedValues = new boolean[nobserved][numdatasets];
12986
12987 //stores whether the mark is not considered missing
12988 traindataNotMissing = new boolean[nobserved][numdatasets];
12989
12990 //stores whether this sequence combination appears on the chromosome
12991 traindataObservedSeqFlags = new boolean[chromfiles.length][traindataObservedValues.length];
12992
12993 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
12994 while (hmObservedIterator.hasNext())
12995 {
12996 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
12997 BigInteger theBigInteger = (BigInteger) pairs.getKey();
12998 String szmapping = theBigInteger.toString(3); //getting back the mapping string
12999
13000 ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
13001 int ncurrindex = theObservedRec.nobserved;//this is an index on which obervation combination it is
13002
13003 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
13004 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
13005
13006 //if the mapping string is less than the number of data sets then
13007 //there are leading 0's will set for leading 0's not missing and absent
13008 int numch = szmapping.length();
13009 int numleading0 = numdatasets - numch;
13010 for (int nj = 0; nj < numleading0; nj++)
13011 {
13012 traindataObservedValues_ncurrindex[nj] = false;
13013 traindataNotMissing_ncurrindex[nj] = true;
13014 }
13015
13016 int nmappedindex = numleading0; //starting from the leading 0 position
13017 for (int nj = 0; nj < numch; nj++)
13018 {
13019 char ch = szmapping.charAt(nj);
13020
13021 if (ch == '0')
13022 {
13023 traindataObservedValues_ncurrindex[nmappedindex] = false;
13024 traindataNotMissing_ncurrindex[nmappedindex] = true;
13025 }
13026 else if (ch=='1')
13027 {
13028 traindataObservedValues_ncurrindex[nmappedindex] = true;
13029 traindataNotMissing_ncurrindex[nmappedindex] = true;
13030 }
13031 else
13032 {
13033 //missing data
13034 traindataObservedValues_ncurrindex[nmappedindex] = false;
13035 traindataNotMissing_ncurrindex[nmappedindex] = false;
13036 }
13037 nmappedindex++;
13038 }
13039
13040 boolean[] currFlags = theObservedRec.flagA;
13041 for (int nj = 0; nj < chromfiles.length; nj++)
13042 {
13043 //storing at this observation whether it is found for each chromosome
13044 traindataObservedSeqFlags[nj][ncurrindex] = currFlags[nj];
13045 }
13046 }
13047 */
13048
13049
13050
13051
13052 ///////////////////////////////////////////////////////////////////////////////////////////////////////
13053
13054 /**
13055 * Loads in the input data
13056 * If there are multiple cell type associated with the files that should be
13057 * indicated by a prefix before an '_'
13058 */
13059 public void loadData() throws IOException
13060 {
13061 if (szinputfilelist == null)
13062 {
13063 //takes all files in the directory with a _binary
13064 File dir = new File(szinputdir);
13065 String[] chromfilesall = dir.list();
13066 if (chromfilesall == null)
13067 {
13068 throw new IllegalArgumentException(szinputdir+" is not a valid directory!");
13069 }
13070 ArrayList alfiles = new ArrayList();
13071 for (int nfile = 0; nfile < chromfilesall.length; nfile++)
13072 {
13073 if ((chromfilesall[nfile].contains("_binary"))&&(!(new File(chromfilesall[nfile])).isHidden()))
13074 {
13075 //added hidden check in v.1.11
13076 alfiles.add(chromfilesall[nfile]);
13077 }
13078 }
13079
13080 if (alfiles.size() == 0)
13081 {
13082 throw new IllegalArgumentException("No files found in "+szinputdir+" containing '_binary' that are not Hidden");
13083 }
13084
13085 //stores them in chromfiles
13086 chromfiles = new String[alfiles.size()];
13087 for (int nfile = 0; nfile < chromfiles.length; nfile++)
13088 {
13089 chromfiles[nfile] = (String) alfiles.get(nfile);
13090 }
13091 }
13092 else
13093 {
13094 //loads in the input coords list
13095 BufferedReader brfiles = Util.getBufferedReader(szinputfilelist);
13096
13097 ArrayList alfiles = new ArrayList();
13098 String szLine;
13099 while ((szLine = brfiles.readLine())!=null)
13100 {
13101 alfiles.add(szLine);
13102 }
13103 brfiles.close();
13104
13105 //stores them in chromfiles
13106 chromfiles = new String[alfiles.size()];
13107 for (int nfile = 0; nfile < chromfiles.length; nfile++)
13108 {
13109 chromfiles[nfile] = (String) alfiles.get(nfile);
13110 }
13111 }
13112
13113 Arrays.sort(chromfiles);//gives a deterministic reproducible starting order to the chromfiles
13114
13115 //randomly orders the chromosome files to visit
13116 RecIntDouble[] recA = new RecIntDouble[chromfiles.length];
13117 String[] tempchromfiles = new String[chromfiles.length];
13118
13119 //now going to randomize the order of chromosomes if theRandom is not null
13120 //the order of chromosome matters when doing an incremental expectation maximization
13121 for (int ni = 0; ni < chromfiles.length; ni++)
13122 {
13123 tempchromfiles[ni] = chromfiles[ni];
13124 if (theRandom == null)
13125 {
13126 recA[ni] = new RecIntDouble(ni, ni);
13127 }
13128 else
13129 {
13130 recA[ni] = new RecIntDouble(ni,theRandom.nextDouble());
13131 }
13132 }
13133
13134 if (theRandom != null)
13135 {
13136 //already in order if random is null
13137 Arrays.sort(recA,new RecIntDoubleCompare());
13138 }
13139
13140 cellSeq = new String[chromfiles.length];
13141 chromSeq = new String[chromfiles.length];
13142
13143 for (int ni = 0; ni < chromfiles.length; ni++)
13144 {
13145 //swapping into chromfiles the sorted chromosome ordering
13146 chromfiles[ni] = tempchromfiles[recA[ni].nindex];
13147 }
13148
13149 traindataObservedIndex = new int[chromfiles.length][]; //number of columns depends on number of lines in file
13150
13151 HashMap hmObserved = new HashMap(); //maps an observation string to an index and set of flags
13152
13153 int nobserved = 0;
13154 //PrintWriter pw = null;
13155
13156 for (int nfile = 0; nfile < chromfiles.length; nfile++)
13157 {
13158 if (ChromHMM.BVERBOSE)
13159 {
13160 System.out.println("reading\t"+szinputdir+" "+chromfiles[nfile]);
13161 }
13162 BufferedReader br = Util.getBufferedReader(szinputdir+"/"+chromfiles[nfile]);
13163 String szLine = br.readLine(); //first line tells cell type and chromosome
13164 if (szLine == null)
13165 {
13166 throw new IllegalArgumentException(szinputdir+"/"+chromfiles[nfile]+" is empty!");
13167 }
13168 StringTokenizer st = new StringTokenizer(szLine,"\t");
13169 if (!st.hasMoreTokens())
13170 {
13171 throw new IllegalArgumentException("First line must contain cell type and chromosome. No entries found.");
13172 }
13173
13174 cellSeq[nfile] = st.nextToken().trim(); //added trim in version 1.23
13175 if (!st.hasMoreTokens())
13176 {
13177 throw new IllegalArgumentException("First line must contain cell type and chromosome. Only one entry found.");
13178 }
13179 chromSeq[nfile] = st.nextToken().trim(); //added trim in version 1.23
13180
13181 if (st.hasMoreTokens())
13182 {
13183 throw new IllegalArgumentException("First line should only contain cell type and chromosome");
13184 }
13185 szLine = br.readLine(); //reading header
13186 //to output binary
13187 if (szLine == null)
13188 {
13189 throw new IllegalArgumentException(szinputdir+"/"+chromfiles[nfile]+" only has one line!");
13190 }
13191 st = new StringTokenizer(szLine,"\t");
13192 int numtokens = st.countTokens();
13193 if (nfile == 0)
13194 {
13195 //first time reading header taking tokens
13196 datasets = new String[numtokens];
13197 int ntoken = 0;
13198 while (st.hasMoreTokens())
13199 {
13200 datasets[ntoken] = st.nextToken().trim();
13201 ntoken++;
13202 }
13203 }
13204 else
13205 {
13206 //Requires number of tokens to match
13207 if (numtokens != datasets.length)
13208 {
13209 throw new IllegalArgumentException(" found a file with header with "+numtokens+" entries, which does not match another with "+datasets.length); //updated in v1.20 to be more informative
13210 }
13211
13212 int ntoken = 0;
13213 //Gives warning if a header column does not match
13214 while (st.hasMoreTokens())
13215 {
13216 String sztoken = st.nextToken().trim();
13217 if (!datasets[ntoken].equals(sztoken))
13218 {
13219 System.out.println("WARNING headers do not match between "+chromfiles[nfile]+" and "+chromfiles[0]);
13220 }
13221 ntoken++;
13222 }
13223 }
13224
13225 //numdatasets is the number of marks we are integrating
13226 numdatasets = datasets.length;
13227
13228 ArrayList aldata = new ArrayList();
13229 while ((szLine = br.readLine())!=null)
13230 {
13231 st = new StringTokenizer(szLine,"\t ");
13232 StringBuffer sb = new StringBuffer();
13233
13234 for (int ncol = 0; ncol < numdatasets; ncol++)
13235 {
13236
13237 if (!st.hasMoreTokens())
13238 {
13239 throw new IllegalArgumentException("Found line without "+numdatasets+" values in file "+chromfiles[nfile]);
13240 }
13241
13242 String sztoken = st.nextToken();//.trim();
13243
13244 if (sztoken.equals("0"))
13245 {
13246 sb.append("0");
13247 }
13248 else if (sztoken.equals("1"))
13249 {
13250 sb.append("1");
13251 }
13252 else if (sztoken.equals("2"))
13253 {
13254 //this means missing
13255 sb.append("2");
13256 }
13257 else
13258 {
13259 throw new IllegalArgumentException("Unrecognized value "+sztoken+" found in "+szinputdir+"/"+chromfiles[nfile]);
13260 }
13261 }
13262
13263 aldata.add(sb.toString());
13264 }
13265 br.close();
13266
13267 int nsize = aldata.size();
13268 traindataObservedIndex[nfile] = new int[nsize];
13269 int[] traindataObservedIndex_nfile = traindataObservedIndex[nfile];
13270
13271 for (int nrow = 0; nrow < nsize; nrow++)
13272 {
13273 BigInteger theBigInteger = new BigInteger((String) aldata.get(nrow),3);
13274 ObservedRec theObservedRec = (ObservedRec) hmObserved.get(theBigInteger);
13275 boolean[] flagA;
13276
13277 if (theObservedRec == null)
13278 {
13279 //this is the first time we encountered this combination of marks
13280 flagA = new boolean[chromfiles.length];
13281 //recording which chromsomes this mark combination was observed
13282 flagA[nfile] =true;
13283
13284 //System.out.println(szmappingbyte.length());
13285 //storing a mapping from observed byte string to an integer index in alFlags and alObserved
13286 hmObserved.put(theBigInteger, new ObservedRec(nobserved,flagA));
13287
13288 //saving this observed index
13289 traindataObservedIndex_nfile[nrow] = nobserved; //change in 1.20 for efficiency to be_nfile
13290
13291 //increments the number of observed combinations of marks
13292 nobserved++;
13293 }
13294 else
13295 {
13296 //updating that this signature was observed on this chromosome
13297 theObservedRec.flagA[nfile] = true;
13298 //storing the index of the flags associated with this row
13299 traindataObservedIndex_nfile[nrow] = theObservedRec.nobserved;
13300 }
13301 }
13302 }
13303
13304 //saving the mapping of signatures and chromsome observed on
13305
13306 //stores whether there is a present call at each location
13307 traindataObservedValues = new boolean[nobserved][numdatasets];
13308
13309 //stores whether the mark is not considered missing
13310 traindataNotMissing = new boolean[nobserved][numdatasets];
13311
13312 //stores whether this sequence combination appears on the chromosome
13313 traindataObservedSeqFlags = new boolean[chromfiles.length][traindataObservedValues.length];
13314
13315 Iterator hmObservedIterator = hmObserved.entrySet().iterator();
13316 while (hmObservedIterator.hasNext())
13317 {
13318 Map.Entry pairs = (Map.Entry) hmObservedIterator.next();
13319 BigInteger theBigInteger = (BigInteger) pairs.getKey();
13320 String szmapping = theBigInteger.toString(3); //getting back the mapping string
13321
13322 ObservedRec theObservedRec = (ObservedRec) pairs.getValue();
13323 int ncurrindex = theObservedRec.nobserved;//this is an index on which obervation combination it is
13324
13325 boolean[] traindataObservedValues_ncurrindex = traindataObservedValues[ncurrindex];
13326 boolean[] traindataNotMissing_ncurrindex = traindataNotMissing[ncurrindex];
13327
13328 //if the mapping string is less than the number of data sets then
13329 //there are leading 0's will set for leading 0's not missing and absent
13330 int numch = szmapping.length();
13331 int numleading0 = numdatasets - numch;
13332 for (int nj = 0; nj < numleading0; nj++)
13333 {
13334 traindataObservedValues_ncurrindex[nj] = false;
13335 traindataNotMissing_ncurrindex[nj] = true;
13336 }
13337
13338 int nmappedindex = numleading0; //starting from the leading 0 position
13339 for (int nj = 0; nj < numch; nj++)
13340 {
13341 char ch = szmapping.charAt(nj);
13342
13343 if (ch == '0')
13344 {
13345 traindataObservedValues_ncurrindex[nmappedindex] = false;
13346 traindataNotMissing_ncurrindex[nmappedindex] = true;
13347 }
13348 else if (ch=='1')
13349 {
13350 traindataObservedValues_ncurrindex[nmappedindex] = true;
13351 traindataNotMissing_ncurrindex[nmappedindex] = true;
13352 }
13353 else
13354 {
13355 //missing data
13356 traindataObservedValues_ncurrindex[nmappedindex] = false;
13357 traindataNotMissing_ncurrindex[nmappedindex] = false;
13358 }
13359 nmappedindex++;
13360 }
13361
13362 boolean[] currFlags = theObservedRec.flagA;
13363 for (int nj = 0; nj < chromfiles.length; nj++)
13364 {
13365 //storing at this observation whether it is found for each chromosome
13366 traindataObservedSeqFlags[nj][ncurrindex] = currFlags[nj];
13367 }
13368 }
13369 }
13370
13371
13372 //////////////////////////////////////////////////////////////////////////////////////////////
13373
13374 public static void main(String[] args) throws IOException
13375 {
13376
13377 boolean bok = true;
13378 String szcommand = "";
13379 if (args.length >= 1)
13380 {
13381 szcommand = args[0];
13382 }
13383 else
13384 {
13385 bok = false;
13386 }
13387
13388 if (szcommand.equalsIgnoreCase("Version"))
13389 {
13390 System.out.println("This is Version 1.27 of ChromHMM (c) Copyright 2008-2012 Massachusetts Institute of Technology");
13391 }
13392 else if ((szcommand.equals("BinarizeBam"))||(szcommand.equalsIgnoreCase("BinarizeBed")))
13393 {
13394 boolean bstacked = false;
13395 boolean bgzip = false;
13396 boolean bpairend = false;
13397 boolean bmixed = false;
13398 boolean bsplit = false;
13399 String szcontroldir=null;
13400 int nflankwidthcontrol = 5;
13401 int nshift = 100;
13402 boolean bcenterinterval = false;
13403 int noffsetleft = 0;
13404 int noffsetright = 1;
13405 double dpoissonthresh = 0.0001;
13406 double dfoldthresh = 0;
13407 double dcountthresh = 0;
13408 boolean bcontainsthresh = true;
13409 int npseudocount = 1;
13410 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
13411 String szcolfields=null;
13412 String szoutputcontroldir=null;
13413 String szoutputsignaldir = null;
13414 int npseudocountcontrol = 1;
13415 boolean bpeaks = false;
13416 int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
13417 int nsplitindex = -1;
13418 boolean bshift = false;
13419 boolean bflagsplitbins = false;
13420
13421 boolean bflagsplitcols = false;
13422
13423 boolean bsplitcols = false;
13424 int nnummarksplit = 10;
13425 int nmarksplitindex = -1;
13426
13427 int nargindex = 1;
13428 if (args.length <= 4)
13429 {
13430 bok = false;
13431 }
13432 else
13433 {
13434 try
13435 {
13436 while (nargindex < args.length-4)
13437 {
13438 if (args[nargindex].equals("-b"))
13439 {
13440 nbinsize = Integer.parseInt(args[++nargindex]);
13441 }
13442 else if (args[nargindex].equals("-c"))
13443 {
13444 szcontroldir = args[++nargindex];
13445 }
13446 else if ((args[nargindex].equals("-colfields"))&&(szcommand.equalsIgnoreCase("BinarizeBed")))
13447 {
13448 szcolfields = args[++nargindex];
13449 }
13450 else if (args[nargindex].equals("-e"))
13451 {
13452 noffsetright= Integer.parseInt(args[++nargindex]);
13453 }
13454 else if (args[nargindex].equals("-f"))
13455 {
13456 dfoldthresh = Double.parseDouble(args[++nargindex]);
13457 }
13458 else if (args[nargindex].equals("-g"))
13459 {
13460 dcountthresh = Double.parseDouble(args[++nargindex]);
13461 }
13462 else if (args[nargindex].equals("-gzip"))
13463 {
13464 bgzip = true;
13465 }
13466 else if (args[nargindex].equals("-i"))
13467 {
13468 nsplitindex = Integer.parseInt(args[++nargindex]);
13469 }
13470 else if (args[nargindex].equals("-j"))
13471 {
13472 numsplitbins = Integer.parseInt(args[++nargindex]);
13473 bflagsplitbins = true;
13474 //bsplit = true;
13475 }
13476 else if (args[nargindex].equals("-k"))
13477 {
13478 nmarksplitindex = Integer.parseInt(args[++nargindex]);
13479 bflagsplitcols = true;
13480 }
13481 else if (args[nargindex].equals("-m"))
13482 {
13483 nnummarksplit = Integer.parseInt(args[++nargindex]);
13484 bflagsplitcols = true;
13485 }
13486 else if (args[nargindex].equals("-n"))
13487 {
13488 nshift = Integer.parseInt(args[++nargindex]);
13489 bshift = true;
13490 }
13491 else if (args[nargindex].equals("-o"))
13492 {
13493 szoutputcontroldir = args[++nargindex];
13494 File f = new File(szoutputcontroldir);
13495 if (!f.exists())
13496 {
13497 if (!f.mkdirs())
13498 {
13499 throw new IllegalArgumentException(szoutputcontroldir+" does not exist and could not be created!");
13500 }
13501 }
13502 }
13503 else if (args[nargindex].equals("-p"))
13504 {
13505 dpoissonthresh = Double.parseDouble(args[++nargindex]);
13506 }
13507 else if (args[nargindex].equals("-s"))
13508 {
13509 noffsetleft = Integer.parseInt(args[++nargindex]);
13510 }
13511 else if (args[nargindex].equals("-splitrows"))
13512 {
13513 bsplit = true;
13514 }
13515 else if (args[nargindex].equals("-splitcols"))
13516 {
13517 bsplitcols = true;
13518 }
13519 else if (args[nargindex].equals("-stacked"))
13520 {
13521 bstacked = true;
13522 }
13523 else if (args[nargindex].equals("-strictthresh"))
13524 {
13525 bcontainsthresh = false;
13526 }
13527 else if (args[nargindex].equals("-t"))
13528 {
13529 szoutputsignaldir = args[++nargindex];
13530 File f = new File(szoutputsignaldir);
13531 if (!f.exists())
13532 {
13533 if (!f.mkdirs())
13534 {
13535 throw new IllegalArgumentException(szoutputsignaldir+" does not exist and could not be created!");
13536 }
13537 }
13538 }
13539 else if (args[nargindex].equals("-u"))
13540 {
13541 npseudocountcontrol = Integer.parseInt(args[++nargindex]);
13542 }
13543 else if (args[nargindex].equals("-center"))
13544 {
13545 bcenterinterval = true;
13546 }
13547 else if (args[nargindex].equals("-peaks"))
13548 {
13549 bpeaks = true;
13550 }
13551 else if ((args[nargindex].equals("-paired"))&&(szcommand.equalsIgnoreCase("BinarizeBam")))
13552 {
13553 bpairend = true;
13554 }
13555 else if ((args[nargindex].equals("-mixed"))&&(szcommand.equalsIgnoreCase("BinarizeBam")))
13556 {
13557 bmixed = true;
13558 }
13559 else if (args[nargindex].equals("-w"))
13560 {
13561 nflankwidthcontrol = Integer.parseInt(args[++nargindex]);
13562 }
13563 else
13564 {
13565 bok = false;
13566 break;
13567 }
13568 nargindex++;
13569 }
13570 }
13571 catch (NumberFormatException ex)
13572 {
13573 bok = false;
13574 }
13575 }
13576
13577 if ((bpairend) && (bmixed||bcenterinterval||bshift||bpeaks))
13578 {
13579 bok = false;
13580 }
13581
13582 if ((!bsplit)&& (bflagsplitbins))
13583 {
13584 bok = false;
13585 }
13586
13587 if ((!bsplitcols)&&(bflagsplitcols))
13588 {
13589 bok = false;
13590 }
13591
13592
13593
13594 if ((bok)&&(nargindex == args.length-4))
13595 {
13596 String szchromlengthfile = args[nargindex++];
13597 String szmarkdir = args[nargindex++];
13598 String szcellmarkfiletable = args[nargindex++];
13599 String szoutputbinarydir= args[nargindex];
13600
13601 File f = new File(szoutputbinarydir);
13602 if (!f.exists())
13603 {
13604 if (!f.mkdirs())
13605 {
13606 throw new IllegalArgumentException(szoutputbinarydir+" does not exist and could not be created!");
13607 }
13608 }
13609
13610 if (szcontroldir == null)
13611 {
13612 szcontroldir = szmarkdir;
13613 }
13614
13615
13616
13617 int nmaxsplit = 0;
13618 if (bsplitcols)
13619 {
13620 String szLineCellMark;
13621 int ncellmarkline = 0;
13622
13623 BufferedReader brcellmark = Util.getBufferedReader(szcellmarkfiletable);
13624 HashSet hscombo = new HashSet();
13625
13626 while ((szLineCellMark=brcellmark.readLine()) != null)
13627 {
13628 if (szLineCellMark.trim().equals("")) continue;
13629
13630 StringTokenizer stcellmark = new StringTokenizer(szLineCellMark,"\t");
13631
13632 if (stcellmark.countTokens() < 3)
13633 {
13634 throw new IllegalArgumentException("In "+szcellmarkfiletable+" "+szLineCellMark+" does not have at least three columns");
13635 }
13636 String szcell = stcellmark.nextToken().trim(); //added trim in v1.20 to remove leading and trailing white space
13637 String szmark = stcellmark.nextToken().trim();
13638
13639 if (hscombo.contains(szcell+"\t"+szmark))
13640 {
13641 throw new IllegalArgumentException("In "+szcellmarkfiletable+" "+szcell+"\t"+szmark+" found twice, but -splitcols specified");
13642 }
13643 hscombo.add(szcell+"\t"+szmark);
13644
13645 if (ncellmarkline % nnummarksplit == 0)
13646 {
13647 nmaxsplit++;
13648 }
13649 ncellmarkline++;
13650 }
13651 brcellmark.close();
13652 }
13653
13654 if (nsplitindex >= 0)
13655 {
13656 if (bpeaks)
13657 {
13658 if ((bsplitcols)&&(nmarksplitindex==-1))
13659 {
13660 //need to figure out maxsplit
13661
13662 for (nmarksplitindex = 0; nmarksplitindex < nmaxsplit; nmarksplitindex++)
13663 {
13664 String szoutputbinarydirsub = szoutputbinarydir+"/SET"+(nmarksplitindex+1);
13665 f = new File(szoutputbinarydirsub);
13666 if (!f.exists())
13667 {
13668 if (!f.mkdirs())
13669 {
13670 throw new IllegalArgumentException(szoutputbinarydirsub+" does not exist and could not be created!");
13671 }
13672 }
13673
13674 Preprocessing.makeBinaryDataFromPeaksSplit(szchromlengthfile, szmarkdir, szoutputbinarydir, szcellmarkfiletable,
13675 nbinsize, bgzip, numsplitbins, nsplitindex, noffsetleft,noffsetright,
13676 bsplitcols,nnummarksplit,nmarksplitindex,bstacked);
13677 }
13678 }
13679 else
13680 {
13681 if (bsplitcols)
13682 {
13683 if (nmarksplitindex >= nmaxsplit)
13684 {
13685 throw new IllegalArgumentException("nmarksplitindex"+" value of "+nmarksplitindex+" is greater than the maximum of "+(nmaxsplit-1));
13686 }
13687 szoutputbinarydir = szoutputbinarydir+"/SET"+(nmarksplitindex+1);
13688 f = new File(szoutputbinarydir);
13689 if (!f.exists())
13690 {
13691 if (!f.mkdirs())
13692 {
13693 throw new IllegalArgumentException(szoutputbinarydir+" does not exist and could not be created!");
13694 }
13695 }
13696 }
13697
13698 Preprocessing.makeBinaryDataFromPeaksSplit(szchromlengthfile, szmarkdir, szoutputbinarydir, szcellmarkfiletable,
13699 nbinsize, bgzip, numsplitbins, nsplitindex, noffsetleft,noffsetright,
13700 bsplitcols,nnummarksplit,nmarksplitindex, bstacked);
13701 }
13702 }
13703 else
13704 {
13705 bok = false;
13706 }
13707 }
13708 else
13709 {
13710
13711 if ((bsplitcols)&&(nmarksplitindex==-1))
13712 {
13713 //going through all
13714 //need to figure out maxsplit
13715
13716 for (nmarksplitindex = 0; nmarksplitindex < nmaxsplit; nmarksplitindex++)
13717 {
13718 String szoutputbinarydirsub = szoutputbinarydir+"/SET"+(nmarksplitindex+1);
13719 f = new File(szoutputbinarydirsub);
13720 if (!f.exists())
13721 {
13722 if (!f.mkdirs())
13723 {
13724 throw new IllegalArgumentException(szoutputbinarydirsub+" does not exist and could not be created!");
13725 }
13726 }
13727
13728 String szoutputsignaldirsub = null;
13729 if (szoutputsignaldir != null)
13730 {
13731 szoutputsignaldirsub = szoutputsignaldir+"/SET"+(nmarksplitindex+1);
13732 f = new File(szoutputsignaldirsub);
13733 if (!f.exists())
13734 {
13735 if (!f.mkdirs())
13736 {
13737 throw new IllegalArgumentException(szoutputsignaldirsub+" does not exist and could not be created!");
13738 }
13739 }
13740 }
13741
13742 String szoutputcontroldirsub = null;
13743 if (szoutputcontroldirsub != null)
13744 {
13745 szoutputcontroldirsub = szoutputcontroldir+"/SET"+(nmarksplitindex+1);
13746 f = new File(szoutputcontroldirsub);
13747 if (!f.exists())
13748 {
13749 if (!f.mkdirs())
13750 {
13751 throw new IllegalArgumentException(szoutputcontroldirsub+" does not exist and could not be created!");
13752 }
13753 }
13754 }
13755
13756 Preprocessing.makeBinaryDataFromBed(szchromlengthfile,szmarkdir,szcontroldir,nflankwidthcontrol,szcellmarkfiletable,
13757 nshift,bcenterinterval, noffsetleft,noffsetright,szoutputsignaldir,
13758 szoutputbinarydirsub,szoutputcontroldir,
13759 dpoissonthresh,dfoldthresh,bcontainsthresh,
13760 npseudocountcontrol,nbinsize,szcolfields,bpeaks, dcountthresh,szcommand.equalsIgnoreCase("BinarizeBam"),
13761 bpairend, bgzip, bsplit, numsplitbins, bsplitcols,nnummarksplit,nmarksplitindex, bstacked, bmixed);
13762 }
13763 }
13764 else
13765 {
13766 if (bsplitcols)
13767 {
13768 if (nmarksplitindex >= nmaxsplit)
13769 {
13770 throw new IllegalArgumentException("nmarksplitindex"+" value of "+nmarksplitindex+" is greater than the maximum of "+(nmaxsplit-1));
13771 }
13772 szoutputbinarydir = szoutputbinarydir+"/SET"+(nmarksplitindex+1);
13773 f = new File(szoutputbinarydir);
13774 if (!f.exists())
13775 {
13776 if (!f.mkdirs())
13777 {
13778 throw new IllegalArgumentException(szoutputbinarydir+" does not exist and could not be created!");
13779 }
13780 }
13781
13782 if (szoutputsignaldir != null)
13783 {
13784 szoutputsignaldir = szoutputsignaldir+"/SET"+(nmarksplitindex+1);
13785 f = new File(szoutputsignaldir);
13786 if (!f.exists())
13787 {
13788 if (!f.mkdirs())
13789 {
13790 throw new IllegalArgumentException(szoutputsignaldir+" does not exist and could not be created!");
13791 }
13792 }
13793 }
13794
13795 if (szoutputcontroldir != null)
13796 {
13797 szoutputcontroldir = szoutputcontroldir+"/SET"+(nmarksplitindex+1);
13798 f = new File(szoutputcontroldir);
13799 if (!f.exists())
13800 {
13801 if (!f.mkdirs())
13802 {
13803 throw new IllegalArgumentException(szoutputcontroldir+" does not exist and could not be created!");
13804 }
13805 }
13806 }
13807 }
13808
13809 Preprocessing.makeBinaryDataFromBed(szchromlengthfile,szmarkdir,szcontroldir,nflankwidthcontrol,szcellmarkfiletable,
13810 nshift,bcenterinterval, noffsetleft,noffsetright,szoutputsignaldir,
13811 szoutputbinarydir,szoutputcontroldir,
13812 dpoissonthresh,dfoldthresh,bcontainsthresh,
13813 npseudocountcontrol,nbinsize,szcolfields,bpeaks, dcountthresh,szcommand.equalsIgnoreCase("BinarizeBam"),
13814 bpairend, bgzip, bsplit, numsplitbins, bsplitcols,nnummarksplit,nmarksplitindex,bstacked,bmixed);
13815
13816 }
13817 }
13818 }
13819 else
13820 {
13821 bok = false;
13822 }
13823
13824
13825 if (!bok)
13826 {
13827 if (szcommand.equalsIgnoreCase("BinarizeBed"))
13828 {
13829 //v1.18 update
13830 System.out.println("usage BinarizeBed [-b binsize][-c controldir][-center][-colfields chromosome,start,end[,strand]][-e offsetend][-f foldthresh]"+
13831 "[-g signalthresh][-gzip][-n shift][-o outputcontroldir][-p poissonthresh][-peaks [-i splitrowindex]][-s offsetstart][-splitcols [-k splitcolindex][-m numsplitcols]][-splitrows [-j numsplitbins]][-stacked][-strictthresh][-t outputsignaldir]"+
13832 "[-u pseudocountcontrol][-w flankwidthcontrol] "+
13833 "chromosomelengthfile inputbeddir cellmarkfiletable outputbinarydir");
13834 }
13835 else
13836 {
13837 System.out.println("usage BinarizeBam [-b binsize][-c controldir][-e offsetend][-f foldthresh]"+
13838 "[-g signalthresh][-gzip][[-o outputcontroldir][-p poissonthresh][-paired|[-mixed][-center][-n shift][-peaks [-i splitindex]]"+
13839 "[-s offsetstart][-splitcols [-k splitcolindex][-m numsplitcols]][-splitrows [-j numsplitbins]][-stacked][-strictthresh][-t outputsignaldir]"+
13840 "[-u pseudocountcontrol][-w flankwidthcontrol] "+
13841 "chromosomelengthfile inputbamdir cellmarkfiletable outputbinarydir");
13842 }
13843 }
13844 }
13845 else if (szcommand.equalsIgnoreCase("BinarizeSignal"))
13846 {
13847 boolean bcontainsthresh = true;
13848 boolean bgzip = false;
13849 boolean bsplit = false;
13850 double dfoldthresh = 0;
13851 double dcountthresh = 0;
13852 double dpoissonthresh = 0.0001;
13853 int nflankwidthcontrol = 5;
13854 int npseudocountcontrol = 1;
13855 int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
13856 boolean bflagsplitbins = false;
13857
13858 String szsignaldir = null;
13859 String szoutputdir = null;
13860 String szcontroldir = null;
13861
13862 if (args.length <= 2)
13863 {
13864 bok = false;
13865 }
13866 else
13867 {
13868 int nargindex = 1;
13869 try
13870 {
13871 while (nargindex < args.length-2)
13872 {
13873 if (args[nargindex].equals("-c"))
13874 {
13875 szcontroldir = args[++nargindex];
13876 }
13877 else if (args[nargindex].equals("-f"))
13878 {
13879 dfoldthresh = Double.parseDouble(args[++nargindex]);
13880 }
13881 else if (args[nargindex].equals("-g"))
13882 {
13883 dcountthresh = Double.parseDouble(args[++nargindex]);
13884 }
13885 else if (args[nargindex].equals("-gzip"))
13886 {
13887 bgzip = true;
13888 }
13889 else if (args[nargindex].equals("-j"))
13890 {
13891 numsplitbins = Integer.parseInt(args[++nargindex]);
13892 bflagsplitbins = true;
13893 }
13894 else if (args[nargindex].equals("-p"))
13895 {
13896 dpoissonthresh = Double.parseDouble(args[++nargindex]);
13897 }
13898 else if (args[nargindex].equals("-splitrows"))
13899 {
13900 bsplit = true;
13901 }
13902 else if (args[nargindex].equals("-strictthresh"))
13903 {
13904 bcontainsthresh = false;
13905 }
13906 else if (args[nargindex].equals("-u"))
13907 {
13908 npseudocountcontrol = Integer.parseInt(args[++nargindex]);
13909 }
13910 else if (args[nargindex].equals("-w"))
13911 {
13912 nflankwidthcontrol = Integer.parseInt(args[++nargindex]);
13913 }
13914 else
13915 {
13916 bok = false;
13917 break;
13918 }
13919 nargindex++;
13920 }
13921 }
13922 catch (NumberFormatException ex)
13923 {
13924 bok = false;
13925 }
13926
13927 if ((!bsplit)&& (bflagsplitbins))
13928 {
13929 bok = false;
13930 }
13931
13932 if ((bok)&&(nargindex == args.length-2))
13933 {
13934 szsignaldir = args[nargindex++];
13935 szoutputdir = args[nargindex];
13936
13937 File f = new File(szoutputdir);
13938 if (!f.exists())
13939 {
13940 if (!f.mkdirs())
13941 {
13942 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
13943 }
13944 }
13945
13946 if (szcontroldir!=null)
13947 {
13948 Preprocessing.makeBinaryDataFromSignalAgainstControl(szsignaldir,szcontroldir, szoutputdir,
13949 dpoissonthresh, dfoldthresh,bcontainsthresh,
13950 nflankwidthcontrol,npseudocountcontrol, dcountthresh,bgzip, bsplit, numsplitbins);
13951 }
13952 else
13953 {
13954 Preprocessing.makeBinaryDataFromSignalUniform(szsignaldir, szoutputdir, dpoissonthresh,
13955 dfoldthresh, bcontainsthresh,dcountthresh,bgzip, bsplit, numsplitbins);
13956 }
13957 }
13958 else
13959 {
13960 bok = false;
13961 }
13962 }
13963
13964 if (!bok)
13965 {
13966 System.out.println("usage BinarizeSignal [-c controldir][-f foldthresh][-g signalthresh][-gzip][-p poissonthresh][-splitrows [-j numsplitbins]][-strictthresh][-u pseudocountcontrol][-w flankwidth] signaldir outputdir");
13967 }
13968
13969 }
13970 else if (szcommand.equalsIgnoreCase("MergeBinary"))
13971 {
13972
13973 boolean bgzip = false;
13974 int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
13975 boolean bsplit = false;
13976 String szdirlistfile = null;
13977 String sztype = "binary";
13978 String szinputdir = null;
13979 String szoutputdir = null;
13980 boolean bflagsplitbins = false;
13981
13982 if (args.length <= 2)
13983 {
13984 bok = false;
13985 }
13986 else
13987 {
13988 int nargindex = 1;
13989 try
13990 {
13991 while (nargindex < args.length-2)
13992 {
13993 if (args[nargindex].equals("-f"))
13994 {
13995 szdirlistfile = args[++nargindex];
13996 }
13997 else if (args[nargindex].equals("-t"))
13998 {
13999 sztype = args[++nargindex];
14000 }
14001 else if (args[nargindex].equals("-j"))
14002 {
14003 numsplitbins = Integer.parseInt(args[++nargindex]);
14004 bflagsplitbins = true;
14005 //bsplit = true;
14006 }
14007 else if (args[nargindex].equals("-splitrows"))
14008 {
14009 bsplit = true;
14010 }
14011 else if (args[nargindex].equals("-gzip"))
14012 {
14013 bgzip = true;
14014 }
14015 else
14016 {
14017 bok = false;
14018 break;
14019 }
14020 nargindex++;
14021 }
14022 }
14023 catch (NumberFormatException ex)
14024 {
14025 bok = false;
14026 }
14027
14028 if ((!bsplit)&& (bflagsplitbins))
14029 {
14030 bok = false;
14031 }
14032
14033 if ((bok)&&(nargindex == args.length-2))
14034 {
14035 szinputdir = args[nargindex++];
14036 szoutputdir = args[nargindex];
14037
14038 File f = new File(szoutputdir);
14039 if (!f.exists())
14040 {
14041 if (!f.mkdirs())
14042 {
14043 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
14044 }
14045 }
14046 Preprocessing.mergeBinarizedFiles(szinputdir, szoutputdir, szdirlistfile, bsplit, numsplitbins, bgzip, sztype);
14047 }
14048 else
14049 {
14050 bok = false;
14051 }
14052 }
14053
14054 if (!bok)
14055 {
14056 System.out.println("usage MergeBinary [-f dirlistfile][-gzip][-splitrows [-j numsplitbins]][-t type] inputdir outputdir");
14057 }
14058 }
14059 else if (szcommand.equalsIgnoreCase("CompareModels"))
14060 {
14061 String szmainmodel;
14062 String szinputdir;
14063 String szoutputprefix;
14064
14065 int nr=ChromHMM.DEFAULTCOLOR_R;
14066 int ng=ChromHMM.DEFAULTCOLOR_G;
14067 int nb=ChromHMM.DEFAULTCOLOR_B;
14068 boolean bprintimage = true;
14069
14070 int nargindex = 1;
14071
14072 if (args.length <= 2)
14073 {
14074 bok = false;
14075 }
14076 else
14077 {
14078 try
14079 {
14080 while (nargindex < args.length-3)
14081 {
14082 if (args[nargindex].equals("-color"))
14083 {
14084 String szcolor = args[++nargindex];
14085 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
14086 if (stcolor.countTokens()==3)
14087 {
14088 nr = Integer.parseInt(stcolor.nextToken().trim());
14089 ng = Integer.parseInt(stcolor.nextToken().trim());
14090 nb = Integer.parseInt(stcolor.nextToken().trim());
14091 }
14092 else
14093 {
14094 bok = false;
14095 }
14096 }
14097 else if (args[nargindex].equals("-noimage"))
14098 {
14099 bprintimage = false;
14100 }
14101 else
14102 {
14103 bok = false;
14104 }
14105 nargindex++;
14106 }
14107 }
14108 catch (NumberFormatException ex)
14109 {
14110 bok = false;
14111 }
14112 }
14113
14114 if (nargindex != args.length-3)
14115 {
14116 bok = false;
14117 }
14118
14119 if (bok)
14120 {
14121 szmainmodel = args[nargindex++];
14122 szinputdir = args[nargindex++];
14123 szoutputprefix = args[nargindex];
14124 StateAnalysis.makeModelEmissionCompare(szmainmodel,szinputdir,szoutputprefix,new Color(nr,ng,nb),bprintimage);
14125 }
14126
14127 if (!bok)
14128 {
14129 System.out.println("usage CompareModels [-color r,g,b][-noimage] referencemodelemissions comparedir outputprefix");
14130 }
14131 }
14132 else if (szcommand.equalsIgnoreCase("StatePruning"))
14133 {
14134 boolean beuclidean = true;
14135 int nindex = 1;
14136 String szinputdir;
14137 String szoutputdir;
14138 if (nindex >= args.length)
14139 {
14140 bok = false;
14141 }
14142 else
14143 {
14144 if (args[nindex].equals("-correlation"))
14145 {
14146 beuclidean = false;
14147 nindex++;
14148 }
14149 if (nindex+1 == (args.length-1))
14150 {
14151 szinputdir = args[nindex++];
14152 szoutputdir = args[nindex];
14153 File f = new File(szoutputdir);
14154 if (!f.exists())
14155 {
14156 if (!f.mkdirs())
14157 {
14158 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
14159 }
14160 }
14161
14162 NestedEliminateInitialize.nestedEliminateInitialize(szinputdir, szoutputdir,beuclidean);
14163 }
14164 else
14165 {
14166 bok = false;
14167 }
14168 }
14169
14170 if (!bok)
14171 {
14172 System.out.println("usage: StatePruning [-correlation] inputdir outputdir");
14173 }
14174 }
14175 else if (szcommand.equalsIgnoreCase("EvalSubset"))
14176 {
14177 int nr=ChromHMM.DEFAULTCOLOR_R;
14178 int ng=ChromHMM.DEFAULTCOLOR_G;
14179 int nb=ChromHMM.DEFAULTCOLOR_B;
14180 Color theColor = new Color(nr, ng, nb);
14181
14182 String szinputfilelist = null;
14183 boolean breadposterior = false;
14184 boolean breadstatebyline = false;
14185 boolean breadsegment = false;
14186 boolean bprintimage = true;
14187 boolean bscaleemissions = false;
14188 boolean bscalebeta = false;
14189 String szchromlengthfile = null;
14190 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
14191 String szoutfileID = "";
14192 boolean bappend = false;
14193 int nargindex = 1;
14194 boolean blowmem = false;
14195
14196 try
14197 {
14198 while (nargindex < args.length-5)
14199 {
14200 if (args[nargindex].equals("-color"))
14201 {
14202 String szcolor = args[++nargindex];
14203 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
14204 if (stcolor.countTokens()==3)
14205 {
14206 nr = Integer.parseInt(stcolor.nextToken().trim());
14207 ng = Integer.parseInt(stcolor.nextToken().trim());
14208 nb = Integer.parseInt(stcolor.nextToken().trim());
14209 }
14210 else
14211 {
14212 bok = false;
14213 }
14214 }
14215 else if (args[nargindex].equals("-b"))
14216 {
14217 nbinsize = Integer.parseInt(args[++nargindex]);
14218 }
14219 else if (args[nargindex].equals("-f"))
14220 {
14221 szinputfilelist = args[++nargindex];
14222 }
14223 else if (args[nargindex].equals("-i"))
14224 {
14225 szoutfileID = args[++nargindex];
14226 }
14227 else if (args[nargindex].equals("-lowmem"))
14228 {
14229 blowmem = true;
14230 }
14231 else if (args[nargindex].equals("-append"))
14232 {
14233 bappend = true;
14234 }
14235 else if (args[nargindex].equals("-many"))
14236 {
14237 bscaleemissions = true;
14238 }
14239 else if (args[nargindex].equals("-noimage"))
14240 {
14241 bprintimage = false;
14242 }
14243 else if (args[nargindex].equals("-readposterior"))
14244 {
14245 breadposterior = true;
14246 }
14247 else if ((args[nargindex].equals("-readstatesbyline"))||(args[nargindex].equals("-readstatebyline")))
14248 {
14249 breadstatebyline = true;
14250 }
14251 else if (args[nargindex].equals("-scalebeta"))
14252 {
14253 bscalebeta = true;
14254 }
14255 else
14256 {
14257 bok = false;
14258 break;
14259 }
14260 nargindex++;
14261 }
14262 }
14263 catch (NumberFormatException ex)
14264 {
14265 bok = false;
14266 }
14267
14268 if (bok&&(nargindex==args.length-5))
14269 {
14270 String szmodelfile = args[nargindex++];
14271 String szinputdir = args[nargindex++];
14272 String szsegmentdir = args[nargindex++];
14273 String szconfusionfileprefix = args[nargindex++];
14274 String szinclude = args[nargindex];
14275
14276 boolean breadsegments = !breadstatebyline&&!breadposterior;
14277 if (breadposterior && breadstatebyline)
14278 {
14279 System.out.println("Invalid to specify both -readposterior and -readstatesbyline output");
14280 }
14281 else
14282 {
14283 ChromHMM theHMM = new ChromHMM(szinputdir, szsegmentdir,szinputfilelist,szconfusionfileprefix,
14284 szmodelfile, szoutfileID, nbinsize, breadposterior,
14285 breadsegments,breadstatebyline,szinclude,bappend, theColor,bprintimage,blowmem,
14286 bscaleemissions,bscalebeta);
14287
14288 if (blowmem)
14289 {
14290 theHMM.makeSegmentationConfusionWithLoad();
14291 }
14292 else
14293 {
14294 theHMM.makeSegmentationConfusion();
14295 }
14296 }
14297
14298 }
14299 else
14300 {
14301 bok = false;
14302 }
14303
14304 if (!bok)
14305 {
14306 System.out.println("usage: EvalSubset [-append][-b binsize][-f inputfilelist][-i outfileID]"+
14307 "[-lowmem][-many][-noimage][-readposterior|-readstatesbyline][-scalebeta]"+
14308 " inputmodel inputdir segmentdir outconfusionfileprefix includemarks");
14309 }
14310 }
14311 else if (szcommand.equalsIgnoreCase("MakeSegmentation"))
14312 {
14313 String szinputfilelist = null;
14314 boolean bscaleemissions = false;
14315 boolean bprintposterior = false;
14316 boolean bprintstatebyline = false;
14317 boolean bnoprintsegment = false;
14318 boolean bscalebeta = false;
14319 String szchromlengthfile = null;
14320 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
14321 //int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
14322 String szoutfileID = "";
14323 boolean blowmem = false;
14324 boolean bgzip = false;
14325 int nargindex = 1;
14326 boolean bsplit = false;
14327
14328 try
14329 {
14330 while (nargindex < args.length-3)
14331 {
14332 if (args[nargindex].equals("-b"))
14333 {
14334 nbinsize = Integer.parseInt(args[++nargindex]);
14335 }
14336 else if (args[nargindex].equals("-f"))
14337 {
14338 szinputfilelist = args[++nargindex];
14339 }
14340 else if (args[nargindex].equals("-gzip"))
14341 {
14342 bgzip = true;
14343 }
14344 else if (args[nargindex].equals("-i"))
14345 {
14346 szoutfileID = args[++nargindex];
14347 }
14348 //else if (args[nargindex].equals("-j"))
14349 //{
14350 // numsplitbins = Integer.parseInt(args[++nargindex]);
14351 // bsplit = true;
14352 //}
14353 else if (args[nargindex].equals("-l"))
14354 {
14355 szchromlengthfile = args[++nargindex];
14356 }
14357 else if (args[nargindex].equals("-lowmem"))
14358 {
14359 blowmem = true;
14360 }
14361 else if (args[nargindex].equals("-many"))
14362 {
14363 bscaleemissions = true;
14364 }
14365 else if (args[nargindex].equals("-nobed"))
14366 {
14367 bnoprintsegment = true;
14368 }
14369 else if (args[nargindex].equals("-printposterior"))
14370 {
14371 bprintposterior = true;
14372 }
14373 else if ((args[nargindex].equals("-printstatesbyline"))||(args[nargindex].equals("-printstatebyline")))
14374 {
14375 bprintstatebyline = true;
14376 }
14377 else if (args[nargindex].equals("-scalebeta"))
14378 {
14379 bscalebeta = true;
14380 }
14381 else if (args[nargindex].equals("-splitrows"))
14382 {
14383 bsplit = true;
14384 }
14385 else
14386 {
14387 bok = false;
14388 break;
14389 }
14390 nargindex++;
14391 }
14392 }
14393 catch (NumberFormatException ex)
14394 {
14395 bok = false;
14396 }
14397
14398 if (bok&&(nargindex==args.length-3))
14399 {
14400 String szmodelfile = args[nargindex++];
14401 String szinputdir = args[nargindex++];
14402 String szoutputdir = args[nargindex];
14403 File f = new File(szoutputdir);
14404 if (!f.exists())
14405 {
14406 if (!f.mkdirs())
14407 {
14408 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
14409 }
14410 }
14411
14412 if (bprintposterior)
14413 {
14414 File fposterior = new File(szoutputdir+"/POSTERIOR");
14415 if (!fposterior.exists())
14416 {
14417 if (!fposterior.mkdirs())
14418 {
14419 throw new IllegalArgumentException(szoutputdir+"POSTERIOR does not exist and could not be created!");
14420 }
14421 }
14422 }//update in v1.20 to allow creating STATEBYLINE directory even if print posterior not asked for
14423
14424 if (bprintstatebyline)
14425 {
14426 File fstatebyline = new File(szoutputdir+"/STATEBYLINE");
14427 if (!fstatebyline.exists())
14428 {
14429 if (!fstatebyline.mkdirs())
14430 {
14431 throw new IllegalArgumentException(szoutputdir+" STATEBYLINE does not exist and could not be created!");
14432 }
14433 }
14434 }
14435
14436 boolean bprintsegments = !bnoprintsegment;
14437 if (bprintsegments||bprintposterior||bprintstatebyline)
14438 {
14439
14440 ChromHMM theHMM = new ChromHMM(szinputdir, szinputfilelist,szchromlengthfile, szoutputdir, szmodelfile, szoutfileID, nbinsize, bprintposterior,
14441 bprintsegments,bprintstatebyline, blowmem,bscaleemissions, bgzip, bsplit, bscalebeta);
14442
14443 if (blowmem)
14444 {
14445 theHMM.makeSegmentationWithLoad();
14446 }
14447 else
14448 {
14449 theHMM.makeSegmentation();
14450 }
14451 }
14452 else
14453 {
14454 System.out.println("No output type was requested!");
14455 }
14456 }
14457 else
14458 {
14459 bok = false;
14460 }
14461
14462 if (!bok)
14463 {
14464 System.out.println("usage: MakeSegmentation [-b binsize][-f inputfilelist][-gzip][-i outfileID][-l chromosomelengthfile][-lowmem][-many][-nobed]"+
14465 "[-printposterior][-printstatebyline][-scalebeta][-splitrows]"+
14466 " modelfile inputdir outputdir");
14467 }
14468 }
14469 else if (szcommand.equalsIgnoreCase("MakeBrowserFiles"))
14470 {
14471 String szcolormapping = null;
14472 String szlabelmapping = null;
14473 boolean bgzip = false;
14474 boolean blowmem = false;
14475 boolean bnobrowserheader = false;
14476 int nargindex = 1;
14477 int numstates = -1;
14478
14479 while (nargindex < args.length-3)
14480 {
14481 if (args[nargindex].equals("-c"))
14482 {
14483 szcolormapping = args[++nargindex];
14484 }
14485 else if (args[nargindex].equals("-gzip"))
14486 {
14487 bgzip = true;
14488 }
14489 else if (args[nargindex].equals("-nobrowserheader"))
14490 {
14491 bnobrowserheader = true;
14492 }
14493 else if ((args[nargindex].equals("-l"))||(args[nargindex].equals("-m")))
14494 {
14495 //the -l is for backwards compatibility
14496 szlabelmapping = args[++nargindex];
14497 }
14498 else if (args[nargindex].equals("-lowmem"))
14499 {
14500 blowmem = true;
14501 }
14502 else if (args[nargindex].equals("-n"))
14503 {
14504 numstates = Integer.parseInt(args[++nargindex]);
14505 }
14506 else
14507 {
14508 bok = false;
14509 break;
14510 }
14511 nargindex++;
14512 }
14513
14514 if ((bok)&&(nargindex==args.length-3))
14515 {
14516 String szsegmentfile = args[nargindex++];
14517 String szsegmentationname = args[nargindex++];
14518 String szoutputfileprefix =args[nargindex];
14519 BrowserOutput theBrowserOutput = new BrowserOutput(szsegmentfile,szcolormapping,szlabelmapping,
14520 szsegmentationname, szoutputfileprefix,numstates,bgzip, bnobrowserheader);
14521 theBrowserOutput.makebrowserdense();
14522 if (blowmem)
14523 {
14524 theBrowserOutput.makebrowserexpandedLowMem();
14525 }
14526 else
14527 {
14528 theBrowserOutput.makebrowserexpanded();
14529 }
14530 }
14531 else
14532 {
14533 bok = false;
14534 }
14535
14536 if (!bok)
14537 {
14538 System.out.println("usage: MakeBrowserFiles [-c colormappingfile][-gzip][-lowmem][-m labelmappingfile][-n numstates][-nobrowserheader] segmentfile segmentationname outputfileprefix");
14539 }
14540 }
14541 else if (szcommand.equalsIgnoreCase("OverlapEnrichment"))
14542 {
14543 String szinput;
14544 String szcell = "";
14545 String szinputcoorddir;
14546 String szinputcoordlist=null;
14547 String szlabelmapping = null;
14548 int noffsetleft = ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETLEFT; //int ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETLEFT = 0;
14549 int noffsetright = ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETRIGHT; //int ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETRIGHT = 1;
14550 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS; //
14551 boolean bcenter = ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCENTER; //boolean ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCENTER = false;
14552 boolean bcountmulti = ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCOUNTMULTI; //boolean ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCOUNTMULTI = false;
14553 boolean busesignal = ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUSESIGNAL; //boolean ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUSESIGNAL = false;
14554 String szcolfields = null;
14555 boolean bbaseres = ChromHMM.DEFAULT_OVERLAPENRICHMENT_BBASERES; //boolean ChromHMM.DEFAULT_OVERLAPENRICHMENT_BBASERES = true;
14556 String szoutfile;
14557 boolean buniformheat = ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUNIFORMHEAT; //boolean ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUNIFORMHEAT = false;
14558 boolean bstringlabels = false;
14559 boolean bbrowser = false;
14560
14561
14562 String sztitle = "Fold Enrichments";
14563
14564 boolean bmax= true;
14565 boolean blowmem = false;
14566 boolean bprintimage = true;
14567
14568 boolean blogpvals = true;
14569
14570 int nr=ChromHMM.DEFAULTCOLOR_R;
14571 int ng=ChromHMM.DEFAULTCOLOR_G;
14572 int nb=ChromHMM.DEFAULTCOLOR_B;
14573
14574 int nargindex = 1;
14575
14576 try
14577 {
14578 while (nargindex < args.length-3)
14579 {
14580 if (args[nargindex].equals("-a"))
14581 {
14582 szcell = args[++nargindex];
14583 }
14584 else if (args[nargindex].equals("-b"))
14585 {
14586 nbinsize = Integer.parseInt(args[++nargindex]);
14587 }
14588 else if (args[nargindex].equals("-color"))
14589 {
14590 String szcolor = args[++nargindex];
14591 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
14592 if (stcolor.countTokens()==3)
14593 {
14594 nr = Integer.parseInt(stcolor.nextToken().trim());
14595 ng = Integer.parseInt(stcolor.nextToken().trim());
14596 nb = Integer.parseInt(stcolor.nextToken().trim());
14597 }
14598 else
14599 {
14600 bok = false;
14601 }
14602 }
14603 else if (args[nargindex].equals("-colfields"))
14604 {
14605 szcolfields = args[++nargindex];
14606 }
14607 else if (args[nargindex].equals("-binres"))
14608 {
14609 bbaseres = false;
14610 }
14611 else if (args[nargindex].equals("-browser"))
14612 {
14613 bbrowser = true;
14614 }
14615 else if (args[nargindex].equals("-f"))
14616 {
14617 szinputcoordlist = args[++nargindex];
14618 }
14619 else if (args[nargindex].equals("-nopvals"))
14620 {
14621 blogpvals = false;
14622 }
14623 else if (args[nargindex].equals("-signal"))
14624 {
14625 busesignal = true;
14626 }
14627 else if (args[nargindex].equals("-uniformscale"))
14628 {
14629 buniformheat = true; //scales heatmap columns individually
14630 }
14631 else if (args[nargindex].equals("-s"))
14632 {
14633 noffsetleft = Integer.parseInt(args[++nargindex]);
14634 }
14635 else if (args[nargindex].equals("-center"))
14636 {
14637 bcenter = true;
14638 }
14639 else if (args[nargindex].equals("-labels"))
14640 {
14641 bstringlabels = true;
14642 }
14643 else if (args[nargindex].equals("-m"))
14644 {
14645 szlabelmapping = args[++nargindex];
14646 }
14647 else if (args[nargindex].equals("-multicount"))
14648 {
14649 bcountmulti = true;
14650 }
14651 else if (args[nargindex].equals("-noimage"))
14652 {
14653 bprintimage = false;
14654 }
14655 else if (args[nargindex].equals("-posterior"))
14656 {
14657 bmax = false;
14658 }
14659 else if (args[nargindex].equals("-e"))
14660 {
14661 noffsetright = Integer.parseInt(args[++nargindex]);
14662 }
14663 else if (args[nargindex].equals("-t"))
14664 {
14665 sztitle = args[++nargindex];
14666 }
14667 else if (args[nargindex].equals("-lowmem"))
14668 {
14669 blowmem = true;
14670 }
14671 else
14672 {
14673 bok = false;
14674 break;
14675 }
14676 nargindex++;
14677 }
14678 }
14679 catch (NumberFormatException ex)
14680 {
14681 bok = false;
14682 }
14683
14684 if ((nargindex == args.length-3)&&(bok))
14685 {
14686 szinput = args[nargindex++];
14687 szinputcoorddir = args[nargindex++];
14688 szoutfile = args[nargindex];
14689 boolean bunique = !bcountmulti;
14690 boolean bcolscaleheat = !buniformheat;
14691 Color theColor = new Color(nr, ng, nb);
14692 System.out.println("Computing Enrichments...");
14693 if (bmax)
14694 {
14695 if (blowmem)
14696 {
14697 StateAnalysis.enrichmentMaxLowMem(szinput, szinputcoorddir,szinputcoordlist,noffsetleft,noffsetright,nbinsize,
14698 bcenter, bunique, busesignal,szcolfields,bbaseres, szoutfile,bcolscaleheat,theColor,sztitle, szlabelmapping, bprintimage,bstringlabels,bbrowser,blogpvals);
14699 }
14700 else
14701 {
14702 StateAnalysis.enrichmentMax(szinput, szinputcoorddir,szinputcoordlist,noffsetleft,noffsetright,nbinsize,
14703 bcenter, bunique, busesignal,szcolfields,bbaseres, szoutfile,bcolscaleheat,theColor,sztitle, szlabelmapping,bprintimage,bstringlabels,bbrowser,blogpvals);
14704 }
14705 }
14706 else
14707 {
14708 StateAnalysis.enrichmentPosterior(szinput, szcell,szinputcoorddir,szinputcoordlist,noffsetleft,noffsetright,nbinsize,
14709 bcenter, bunique, busesignal,szcolfields,bbaseres,szoutfile,bcolscaleheat,theColor,sztitle, szlabelmapping,bprintimage,blogpvals);
14710 }
14711 }
14712 else
14713 {
14714 bok = false;
14715 }
14716
14717 if (!bok)
14718 {
14719 System.out.println("usage OverlapEnrichment [-a cell][-b binsize][-binres][-browser][-color r,g,b][-center][-colfields chromosome,start,end[,signal]]"+
14720 "[-e offsetend][-f coordlistfile][-labels][-lowmem][-m labelmappingfile]"+
14721 "[-multicount][-noimage][-nopvals][-posterior][-s offsetstart][-signal][-t title][-uniformscale]"+
14722 " inputsegment inputcoorddir outfileprefix");
14723 }
14724 }
14725 else if ((szcommand.equalsIgnoreCase("NeighborhoodEnrichment"))||(szcommand.equalsIgnoreCase("NeighborhoodSignal")))
14726 {
14727 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
14728 String szinput;
14729
14730 int numleft = ChromHMM.DEFAULT_NEIGHBORHOOD_NUMLEFT;
14731 int numright = ChromHMM.DEFAULT_NEIGHBORHOOD_NUMRIGHT;
14732 int nspacing = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
14733 String szlabelmapping = null;
14734 boolean busestrand =ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESTRAND;
14735 boolean busesignal = ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESIGNAL;
14736 boolean bstringlabels = false;
14737 boolean bbrowser = false;
14738 String szcolfields = null;
14739 int noffsetanchor = ChromHMM.DEFAULT_NEIGHBORHOOD_NOFFSETANCHOR;
14740 String szoutfile;
14741 String sztitle = "Fold Enrichments";
14742 String szcell = "";
14743 String szanchorpositions;
14744
14745 int nr=ChromHMM.DEFAULTCOLOR_R;
14746 int ng=ChromHMM.DEFAULTCOLOR_G;
14747 int nb=ChromHMM.DEFAULTCOLOR_B;
14748
14749 boolean bmax = true;
14750 boolean blowmem = false;
14751 boolean bprintimage = true;
14752
14753 int nargindex = 1;
14754
14755 boolean bspacing = false;
14756
14757 try
14758 {
14759 while (nargindex < args.length-3)
14760 {
14761 if (args[nargindex].equals("-a"))
14762 {
14763 szcell = args[++nargindex];
14764 }
14765 else if (args[nargindex].equals("-b"))
14766 {
14767 nbinsize = Integer.parseInt(args[++nargindex]);
14768 }
14769 else if (args[nargindex].equals("-browser"))
14770 {
14771 bbrowser = true;
14772 }
14773 else if (args[nargindex].equals("-color"))
14774 {
14775 String szcolor = args[++nargindex];
14776 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
14777 if (stcolor.countTokens()==3)
14778 {
14779 nr = Integer.parseInt(stcolor.nextToken().trim());
14780 ng = Integer.parseInt(stcolor.nextToken().trim());
14781 nb = Integer.parseInt(stcolor.nextToken().trim());
14782 }
14783 else
14784 {
14785 bok = false;
14786 }
14787 }
14788 else if (args[nargindex].equals("-colfields"))
14789 {
14790 szcolfields = args[++nargindex];
14791 }
14792 else if (args[nargindex].equals("-signal"))
14793 {
14794 busesignal = true;
14795 }
14796 else if (args[nargindex].equals("-l"))
14797 {
14798 numleft = Integer.parseInt(args[++nargindex]);
14799 }
14800 else if (args[nargindex].equals("-labels"))
14801 {
14802 bstringlabels = true;
14803 }
14804 else if (args[nargindex].equals("-lowmem"))
14805 {
14806 blowmem = true;
14807 }
14808 else if (args[nargindex].equals("-m"))
14809 {
14810 szlabelmapping = args[++nargindex];
14811 }
14812 else if (args[nargindex].equals("-noimage"))
14813 {
14814 bprintimage = false;
14815 }
14816 else if (args[nargindex].equals("-o"))
14817 {
14818 noffsetanchor = Integer.parseInt(args[++nargindex]);
14819 }
14820 else if (args[nargindex].equals("-posterior"))
14821 {
14822 bmax = false;
14823 }
14824 else if (args[nargindex].equals("-r"))
14825 {
14826 numright = Integer.parseInt(args[++nargindex]);
14827 }
14828 else if (args[nargindex].equals("-s"))
14829 {
14830 nspacing = Integer.parseInt(args[++nargindex]);
14831 bspacing = true;
14832 }
14833 else if (args[nargindex].equals("-nostrand"))
14834 {
14835 busestrand = false;
14836 }
14837 else if (args[nargindex].equals("-t"))
14838 {
14839 sztitle = args[++nargindex];
14840 }
14841 else
14842 {
14843 bok =false;
14844 break;
14845 }
14846 nargindex++;
14847 }
14848 }
14849 catch (NumberFormatException ex)
14850 {
14851 bok = false;
14852 }
14853
14854
14855 if (!bspacing)
14856 {
14857 nspacing = nbinsize;
14858 }
14859
14860 if ((nargindex == args.length-3)&&(bok))
14861 {
14862 Color theColor = new Color(nr, ng, nb);
14863 szinput = args[nargindex++];
14864 szanchorpositions = args[nargindex++];
14865 szoutfile = args[nargindex];
14866 System.out.println("Computing Enrichments...");
14867 if (szcommand.equalsIgnoreCase("NeighborhoodSignal"))
14868 {
14869 //this is an undocumented feature to compute signal enrichment for marks around a position
14870 StateAnalysis.neighborhoodSignal(szinput,szcell,szanchorpositions,nbinsize,numleft,numright,
14871 nspacing,busestrand,busesignal,szcolfields,noffsetanchor,szoutfile,theColor,
14872 sztitle,szlabelmapping, bprintimage);
14873 }
14874 else if (bmax)
14875 {
14876 if (blowmem)
14877 {
14878 StateAnalysis.neighborhoodMaxLowMem(szinput,szanchorpositions,nbinsize,numleft,numright,
14879 nspacing,busestrand,busesignal,szcolfields,noffsetanchor,szoutfile,theColor,
14880 sztitle,szlabelmapping, bprintimage, bstringlabels, bbrowser);
14881 }
14882 else
14883 {
14884 StateAnalysis.neighborhoodMax(szinput,szanchorpositions,nbinsize,numleft,numright,
14885 nspacing,busestrand,busesignal,szcolfields,noffsetanchor,szoutfile,theColor,sztitle,szlabelmapping,
14886 bprintimage, bstringlabels,bbrowser);
14887 }
14888 }
14889 else
14890 {
14891 StateAnalysis.neighborhoodPosterior(szinput,szcell,szanchorpositions,nbinsize,numleft,numright,
14892 nspacing,busestrand,busesignal,szcolfields,noffsetanchor,szoutfile,theColor,sztitle,szlabelmapping,bprintimage);
14893 }
14894 }
14895 else
14896 {
14897 bok = false;
14898 }
14899
14900 if (!bok)
14901 {
14902 System.out.println("usage NeighborhoodEnrichment [-a cell][-b binsize][-browser][-color r,g,b][-colfields chromosome,position[,optionalcol1|,optionalcol1,optionalcol2]"+
14903 "[-l numleftintervals][-labels][-lowmem][-m labelmappingfile][-noimage][-nostrand]"+
14904 "[-o anchoroffset][-posterior][-r numrightintervals]"+
14905 "[-s spacing][-signal][-t title] inputsegment anchorpositions outfileprefix");
14906 }
14907 }
14908 else if (szcommand.equalsIgnoreCase("LearnModel"))
14909 {
14910 String path = ChromHMM.class.getProtectionDomain().getCodeSource().getLocation().getPath();
14911 String decodedPath = URLDecoder.decode(path, "UTF-8");
14912 String szprefixpath = decodedPath.substring(0, decodedPath.lastIndexOf("/") + 1);
14913 //String szfullprefixpathchromsizedir = szprefixpath+"/"+CHROMSIZESDIR;
14914 String szfullprefixpathcoorddir = szprefixpath+"/"+COORDDIR;
14915 String szfullprefixpathanchorfiledir = szprefixpath+"/"+ANCHORFILEDIR;
14916
14917 //System.out.println("prefix path is "+szprefixpath);
14918
14919
14920 int nseed = 999;
14921 int nmaxiterations= 200;//number of passes through all the data
14922 int nzerotransitionpower =8; //Sets the transition probability to 0 if below this constant value
14923 String szInitFile =null;
14924 int ninitmethod = ChromHMM.INITMETHOD_INFORMATION;
14925 double dconvergediff = 0.001;//-1;
14926 double dinformationsmooth= 0.02;
14927 double dloadsmoothemission = 0.02;
14928 double dloadsmoothtransition = 0.5;
14929 boolean bautoopen = true;
14930 boolean bprintposterior = false;
14931 boolean bprintstatebyline = false;
14932 boolean bnoprintsegment = false;
14933 boolean bprintbrowser = true;
14934 boolean bprintenrich = true;
14935 boolean bnobrowserheader = false;
14936 boolean bprintimage = true;
14937 boolean blowmem = false;
14938 boolean bscaleemissions = false;
14939 boolean bpseudo = false;
14940 boolean bnopseudolast = false;
14941 boolean bgzip = false;
14942 boolean bsplit = false;
14943 int numsplitbins = ChromHMM.DEFAULT_NUMSPLITBINS;
14944
14945 String szinputfilelist = null;
14946 String szchromlengthfile = null;
14947 int nbinsize = ChromHMM.DEFAULT_BINSIZEBASEPAIRS;
14948 String szoutfileID = "";
14949 int nstateorder =ChromHMM.STATEORDER_EMISSION;
14950 boolean bnoordercols = false;
14951 boolean bnoorderrows = false;
14952 int nargindex = 1;
14953 int nmaxseconds = -1;
14954 int nmaxprocessors = 0;
14955 int numincludeseq = 0;
14956 boolean bnormalEM = false;
14957 boolean bscalebeta = false;
14958
14959 int nr=ChromHMM.DEFAULTCOLOR_R;
14960 int ng=ChromHMM.DEFAULTCOLOR_G;
14961 int nb=ChromHMM.DEFAULTCOLOR_B;
14962
14963 try
14964 {
14965 while (nargindex < args.length-4)
14966 {
14967 if (args[nargindex].equals("-b"))
14968 {
14969 nbinsize = Integer.parseInt(args[++nargindex]);
14970 }
14971 else if (args[nargindex].equals("-color"))
14972 {
14973 String szcolor = args[++nargindex];
14974 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
14975 if (stcolor.countTokens()==3)
14976 {
14977 nr = Integer.parseInt(stcolor.nextToken().trim());
14978 ng = Integer.parseInt(stcolor.nextToken().trim());
14979 nb = Integer.parseInt(stcolor.nextToken().trim());
14980 }
14981 else
14982 {
14983 bok = false;
14984 }
14985 }
14986 else if (args[nargindex].equals("-d"))
14987 {
14988 dconvergediff = Double.parseDouble(args[++nargindex]);
14989 }
14990 else if (args[nargindex].equals("-e"))
14991 {
14992 dloadsmoothemission = Double.parseDouble(args[++nargindex]);
14993 }
14994 else if (args[nargindex].equals("-f"))
14995 {
14996 szinputfilelist = args[++nargindex];
14997 }
14998 else if (args[nargindex].equals("-gzip"))
14999 {
15000 bgzip = true;
15001 }
15002 else if (args[nargindex].equals("-h"))
15003 {
15004 dinformationsmooth = Double.parseDouble(args[++nargindex]);
15005 }
15006 else if (args[nargindex].equals("-i"))
15007 {
15008 szoutfileID = args[++nargindex];
15009 }
15010 else if (args[nargindex].equals("-init"))
15011 {
15012 String sztoken = args[++nargindex];
15013
15014 if ((sztoken.equals("information"))||(sztoken.equals("0")))
15015 {
15016 ninitmethod = ChromHMM.INITMETHOD_INFORMATION;
15017 }
15018 else if ((sztoken.equals("random"))||(sztoken.equals("1")))
15019 {
15020 ninitmethod = ChromHMM.INITMETHOD_RANDOM;
15021 }
15022 else if ((sztoken.equals("load"))||(sztoken.equals("2")))
15023 {
15024 ninitmethod = ChromHMM.INITMETHOD_LOAD;
15025 }
15026 else
15027 {
15028 bok = false;
15029 break;
15030 }
15031 }
15032 //else if (args[nargindex].equals("-j"))
15033 //{
15034 // numsplitbins = Integer.parseInt(args[++nargindex]);
15035 // bsplit = true;
15036 // }
15037 else if (args[nargindex].equals("-l"))
15038 {
15039 szchromlengthfile = args[++nargindex];
15040 }
15041 else if (args[nargindex].equals("-m"))
15042 {
15043 szInitFile = args[++nargindex];
15044 }
15045 else if (args[nargindex].equals("-many"))
15046 {
15047 bscaleemissions = true;
15048 }
15049 else if (args[nargindex].equals("-n"))
15050 {
15051 numincludeseq = Integer.parseInt(args[++nargindex]);
15052 }
15053 else if (args[nargindex].equals("-noautoopen"))
15054 {
15055 bautoopen = false;
15056 }
15057 else if (args[nargindex].equals("-nobed"))
15058 {
15059 bnoprintsegment = true;
15060 }
15061 else if (args[nargindex].equals("-nobrowser"))
15062 {
15063 bprintbrowser = false;
15064 }
15065 else if (args[nargindex].equals("-nobrowserheader"))
15066 {
15067 bnobrowserheader = true;
15068 }
15069 else if (args[nargindex].equals("-noenrich"))
15070 {
15071 bprintenrich = false;
15072 }
15073 else if (args[nargindex].equals("-noimage"))
15074 {
15075 bprintimage = false;
15076 }
15077 else if (args[nargindex].equals("-p"))
15078 {
15079 bnormalEM = true;
15080 nmaxprocessors = Integer.parseInt(args[++nargindex]);
15081 }
15082 else if (args[nargindex].equals("-pseudo"))
15083 {
15084 bpseudo = true;
15085 }
15086 else if (args[nargindex].equals("-nopseudolast"))
15087 {
15088 bnopseudolast = true;
15089 }
15090 else if (args[nargindex].equals("-stateordering"))
15091 {
15092 String sztoken = args[++nargindex];
15093 if (sztoken.equals("emission"))
15094 {
15095 nstateorder = ChromHMM.STATEORDER_EMISSION;
15096 }
15097 else if (sztoken.equals("transition"))
15098 {
15099 nstateorder = ChromHMM.STATEORDER_TRANSITION;
15100 }
15101 else
15102 {
15103 bok = false;
15104 break;
15105 }
15106 }
15107 else if (args[nargindex].equals("-printposterior"))
15108 {
15109 bprintposterior = true;
15110 }
15111 else if (args[nargindex].equals("-lowmem"))
15112 {
15113 blowmem = true;
15114 }
15115 else if (args[nargindex].equals("-r"))
15116 {
15117 nmaxiterations = Integer.parseInt(args[++nargindex]);
15118 }
15119 else if (args[nargindex].equals("-s"))
15120 {
15121 nseed = Integer.parseInt(args[++nargindex]);
15122 }
15123 else if (args[nargindex].equals("-scalebeta"))
15124 {
15125 bscalebeta = true;
15126 }
15127 else if (args[nargindex].equals("-t"))
15128 {
15129 dloadsmoothtransition = Double.parseDouble(args[++nargindex]);
15130 }
15131 else if (args[nargindex].equals("-holdcolumnorder"))
15132 {
15133 bnoordercols = true;
15134 }
15135 else if (args[nargindex].equals("-holdroworder"))
15136 {
15137 bnoorderrows = true;
15138 nstateorder = ChromHMM.STATEORDER_FIXED;
15139 }
15140 else if ((args[nargindex].equals("-printstatebyline"))||(args[nargindex].equals("-printstatesbyline")))
15141 {
15142 bprintstatebyline = true;
15143 }
15144 else if (args[nargindex].equals("-splitrows"))
15145 {
15146 bsplit = true;
15147 }
15148 //else if (args[nargindex].equals("-u"))
15149 //{
15150 // szfullprefixpathchromsizedir = args[++nargindex];
15151 //}
15152 else if (args[nargindex].equals("-u"))
15153 {
15154 szfullprefixpathcoorddir = args[++nargindex];
15155 }
15156 else if (args[nargindex].equals("-v"))
15157 {
15158 szfullprefixpathanchorfiledir = args[++nargindex];
15159 }
15160 else if (args[nargindex].equals("-x"))
15161 {
15162 nmaxseconds = Integer.parseInt(args[++nargindex]);
15163 }
15164 else if (args[nargindex].equals("-z"))
15165 {
15166 nzerotransitionpower = Integer.parseInt(args[++nargindex]);
15167 }
15168 else
15169 {
15170 bok = false;
15171 }
15172 nargindex++;
15173 }
15174 }
15175 catch (NumberFormatException ex)
15176 {
15177 bok = false;
15178 }
15179
15180
15181 if (bok&&(nargindex==args.length-4))
15182 {
15183 Color theColor = new Color(nr, ng, nb);
15184 String szinputdir = args[nargindex++];
15185 String szoutputdir = args[nargindex++];
15186 File f = new File(szoutputdir);
15187 if (!f.exists())
15188 {
15189 if (!f.mkdirs())
15190 {
15191 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
15192 }
15193 }
15194
15195 if (bprintposterior)
15196 {
15197 File fposterior = new File(szoutputdir+"/POSTERIOR");
15198 if (!fposterior.exists())
15199 {
15200 if (!fposterior.mkdirs())
15201 {
15202 throw new IllegalArgumentException(szoutputdir+"/POSTERIOR does not exist and could not be created!");
15203 }
15204 }
15205 }
15206
15207 if (bprintstatebyline)
15208 {
15209 File fstatebyline = new File(szoutputdir+"/STATEBYLINE");
15210 if (!fstatebyline.exists())
15211 {
15212 if (!fstatebyline.mkdirs())
15213 {
15214 throw new IllegalArgumentException(szoutputdir+"/STATEBYLINE does not exist and could not be created!");
15215 }
15216 }
15217 }
15218
15219 int numstates = 0;
15220 try
15221 {
15222 numstates = Integer.parseInt(args[nargindex++]);
15223 }
15224 catch (NumberFormatException ex)
15225 {
15226 bok = false;
15227 }
15228
15229 if (bok)
15230 {
15231 String szassembly= args[nargindex++];
15232
15233 boolean bprintsegments = !bnoprintsegment;
15234 boolean bordercols = !bnoordercols;
15235 boolean borderrows = !bnoorderrows;
15236 if ((szoutfileID.equals(""))&&(ninitmethod == ChromHMM.INITMETHOD_RANDOM))
15237 {
15238 szoutfileID = ""+nseed;
15239 }
15240
15241 if (szchromlengthfile == null)
15242 {
15243 //updated v.1.16
15244 File flength = new File(szprefixpath+"/"+CHROMSIZESDIR+"/"+szassembly+".txt");
15245 //File flength = new File(szfullprefixpathchromsizedir+"/"+szassembly+".txt");
15246 if (flength.exists())
15247 {
15248 //szchromlengthfile = szfullprefixpathchromsizedir+"/"+szassembly+".txt";
15249 szchromlengthfile = szprefixpath+"/"+CHROMSIZESDIR+"/"+szassembly+".txt";
15250 }
15251 }
15252 ChromHMM theHMM = new ChromHMM(szinputdir, szoutputdir, szinputfilelist,szchromlengthfile,numstates, nseed,ninitmethod,
15253 szInitFile,dloadsmoothemission,dloadsmoothtransition,dinformationsmooth,
15254 nmaxiterations,dconvergediff,nmaxseconds, bprintposterior,bprintsegments,bprintstatebyline,
15255 nbinsize,szoutfileID,nstateorder,bordercols,nzerotransitionpower,theColor,bnormalEM, nmaxprocessors,
15256 blowmem,numincludeseq,bprintimage,bscaleemissions, bpseudo,bnopseudolast, bgzip, bsplit, borderrows, bscalebeta);
15257 theHMM.buildModel();
15258
15259
15260 String szunderscoreoutfileID;
15261 if (szoutfileID.equals(""))
15262 {
15263 szunderscoreoutfileID = "";
15264 }
15265 else
15266 {
15267 szunderscoreoutfileID = "_"+szoutfileID;
15268 }
15269
15270 String szwebpage = szoutputdir+"/webpage_"+numstates+szunderscoreoutfileID+".html";
15271 PrintWriter pwweb = new PrintWriter(new FileWriter(szwebpage));
15272
15273
15274 pwweb.println("<center><h1>ChromHMM Report</h1></center>");
15275 pwweb.println("Input Directory: "+szinputdir+"<br>");
15276 pwweb.println("Output Directory: "+szoutputdir+"<br>");
15277 pwweb.println("Number of States: "+numstates+"<br>");
15278 pwweb.println("Assembly: "+szassembly+"<br>");
15279 pwweb.print("Full ChromHMM command: ");
15280 for (int na = 0; na < args.length-1; na++)
15281 {
15282 pwweb.print(args[na]+" ");
15283 }
15284 pwweb.println(args[args.length-1]+"");
15285
15286
15287
15288 pwweb.println("<h1>Model Parameters</h1>");
15289 if (bprintimage)
15290 {
15291 pwweb.println("<img src=\"emissions_"+numstates+szunderscoreoutfileID+".png\"><br>");
15292 pwweb.println("<li><a href=\"emissions_"+numstates+szunderscoreoutfileID+".svg\">Emission Parameter SVG File</a><br>");
15293 }
15294 pwweb.println("<li><a href=\"emissions_"+numstates+szunderscoreoutfileID+".txt\">Emission Parameter Tab-Delimited Text File</a><br>");
15295 if (bprintimage)
15296 {
15297 pwweb.println("<img src=\"transitions_"+numstates+szunderscoreoutfileID+".png\"><br>");
15298 pwweb.println("<li><a href=\"transitions_"+numstates+szunderscoreoutfileID+".svg\">Transition Parameter SVG File</a><br>");
15299 }
15300 pwweb.println("<li><a href=\"transitions_"+numstates+szunderscoreoutfileID+".txt\">Transition Parameter Tab-Delimited Text File</a><br><br>");
15301 pwweb.println("<li><a href=\"model_"+numstates+szunderscoreoutfileID+".txt\">All Model Parameters Tab-Delimited Text File</a> <br>");
15302 pwweb.println("<h1>Genome Segmentation Files</h1>");
15303
15304 if (bprintsegments||bprintposterior||bprintstatebyline)
15305 {
15306 if (blowmem)
15307 {
15308 theHMM.makeSegmentationWithLoad();
15309 }
15310 else
15311 {
15312 theHMM.makeSegmentation();
15313 }
15314
15315 if (bprintsegments)
15316 {
15317 Iterator hsiterator = theHMM.hsprefix.iterator();
15318 String[] prefixes = new String[theHMM.hsprefix.size()];
15319 int nhsindex = 0;
15320 while (hsiterator.hasNext())
15321 {
15322 prefixes[nhsindex] = (String) hsiterator.next();
15323 nhsindex++;
15324 }
15325 Arrays.sort(prefixes);
15326
15327 for (int nfile = 0; nfile < prefixes.length; nfile++)
15328 {
15329 String szsegmentfile;
15330 if (bgzip)
15331 {
15332 szsegmentfile = prefixes[nfile]+ChromHMM.SZSEGMENTEXTENSION+".gz";
15333 }
15334 else
15335 {
15336 szsegmentfile = prefixes[nfile]+ChromHMM.SZSEGMENTEXTENSION;
15337 }
15338 pwweb.println("<li><a href=\""+szsegmentfile+"\">"+prefixes[nfile]+" Segmentation File (Four Column Bed File)</a><br>");
15339 }
15340
15341 if (bprintstatebyline)
15342 {
15343 pwweb.println("<li><a href=\"STATEBYLINE\"> Directory of Maximum States Assignments Line By Line</a><br>");
15344 }
15345
15346 if (bprintposterior)
15347 {
15348 pwweb.println("<li><a href=\"POSTERIOR\"> Directory of Posterior Files</a><br>");
15349 }
15350
15351
15352 if (bprintbrowser)
15353 {
15354 pwweb.println("<br>");
15355 pwweb.println("Custom Tracks for loading into the <a href=\"http://genome.ucsc.edu\">UCSC Genome Browser</a>:<br>");
15356
15357 for (int nprefixindex = 0; nprefixindex < prefixes.length; nprefixindex++)
15358 {
15359 String szprefix = prefixes[nprefixindex];
15360
15361 String szsegmentfile;
15362 if (bgzip)
15363 {
15364 szsegmentfile = szoutputdir+"/"+szprefix+ChromHMM.SZSEGMENTEXTENSION+".gz";
15365 }
15366 else
15367 {
15368 szsegmentfile = szoutputdir+"/"+szprefix+ChromHMM.SZSEGMENTEXTENSION;
15369 }
15370
15371
15372 BrowserOutput theBrowserOutput = new BrowserOutput(szsegmentfile,null,null,
15373 szprefix,szoutputdir+"/"+szprefix,numstates,bgzip,bnobrowserheader);
15374
15375 theBrowserOutput.makebrowserdense();
15376 if (blowmem)
15377 {
15378 theBrowserOutput.makebrowserexpandedLowMem();
15379 }
15380 else
15381 {
15382 theBrowserOutput.makebrowserexpanded();
15383 }
15384
15385 if (bgzip)
15386 {
15387 pwweb.println("<li><a href="+szprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed.gz>"+szprefix+" Browser Custom Track Dense File</a> <br>");
15388 pwweb.println("<li><a href="+szprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed.gz>"+szprefix+" Browser Custom Track Expanded File</a><br>");
15389 }
15390 else
15391 {
15392 pwweb.println("<li><a href="+szprefix+ChromHMM.SZBROWSERDENSEEXTENSION+".bed>"+szprefix+" Browser Custom Track Dense File</a> <br>");
15393 pwweb.println("<li><a href="+szprefix+ChromHMM.SZBROWSEREXPANDEDEXTENSION+".bed>"+szprefix+" Browser Custom Track Expanded File</a><br>");
15394 }
15395 }
15396 }
15397
15398
15399 if (bprintenrich)
15400 {
15401 pwweb.println("<h1>State Enrichments</h1>");
15402
15403 for (int nprefixindex = 0; nprefixindex < prefixes.length; nprefixindex++)
15404 {
15405 String szprefix = prefixes[nprefixindex];
15406 pwweb.println("<h2>"+szprefix+" Enrichments</h2>");
15407 String szsegmentfile;
15408 if (bgzip)
15409 {
15410 szsegmentfile = szoutputdir+"/"+szprefix+ChromHMM.SZSEGMENTEXTENSION+".gz";
15411 }
15412 else
15413 {
15414 szsegmentfile = szoutputdir+"/"+szprefix+ChromHMM.SZSEGMENTEXTENSION;
15415 }
15416 //File fcoordassembly = new File(szprefixpath+"/"+COORDDIR+"/"+szassembly);
15417 File fcoordassembly = new File(szfullprefixpathcoorddir+"/"+szassembly);
15418 if (fcoordassembly.exists())
15419 {
15420 if (blowmem)
15421 {
15422 StateAnalysis.enrichmentMaxLowMem(szsegmentfile,szfullprefixpathcoorddir+"/"+szassembly,null,//szinputcoordlist,
15423 ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETLEFT,
15424 ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETRIGHT,nbinsize,
15425 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCENTER, !ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCOUNTMULTI,
15426 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUSESIGNAL,null,//szcolfields,
15427 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BBASERES, szoutputdir+"/"+szprefix+ChromHMM.SZOVERLAPEXTENSION,
15428 !ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUNIFORMHEAT,theColor,"Fold Enrichment "+szprefix,null,bprintimage, false,false,false);
15429 }
15430 else
15431 {
15432 //update v.1.16
15433 //StateAnalysis.enrichmentMax(szsegmentfile,szprefixpath+"/"+COORDDIR+"/"+szassembly,null,//szinputcoordlist,
15434 StateAnalysis.enrichmentMax(szsegmentfile,szfullprefixpathcoorddir+"/"+szassembly,null,//szinputcoordlist,
15435 ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETLEFT,
15436 ChromHMM.DEFAULT_OVERLAPENRICHMENT_NOFFSETRIGHT,nbinsize,
15437 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCENTER, !ChromHMM.DEFAULT_OVERLAPENRICHMENT_BCOUNTMULTI,
15438 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUSESIGNAL,null,//szcolfields,
15439 ChromHMM.DEFAULT_OVERLAPENRICHMENT_BBASERES, szoutputdir+"/"+szprefix+ChromHMM.SZOVERLAPEXTENSION,
15440 !ChromHMM.DEFAULT_OVERLAPENRICHMENT_BUNIFORMHEAT,theColor,"Fold Enrichment "+szprefix,null,bprintimage, false,false,false);
15441 }
15442 String szoverlapoutfile = szprefix+ChromHMM.SZOVERLAPEXTENSION+".txt";
15443 if (bprintimage)
15444 {
15445 pwweb.println("<img src=\""+szprefix+ChromHMM.SZOVERLAPEXTENSION+".png\"> <br>");
15446 pwweb.println("<li><a href=\""+szprefix+ChromHMM.SZOVERLAPEXTENSION+".svg"+"\">"+szprefix+" Overlap Enrichment SVG File"+"</a><br>");
15447 }
15448 pwweb.println("<li><a href=\""+szoverlapoutfile+"\">"+szprefix+" Overlap Enrichment Tab-Delimited Text File"+"</a><br>");
15449
15450 }
15451 else
15452 {
15453 System.out.println("Warning: No coordinate directory found for assembly "+szassembly+" in "+szfullprefixpathcoorddir);//szprefixpath+"/"+COORDDIR);
15454 }
15455
15456 //szfullprefixpathanchorfiledir
15457 //File fanchorassembly = new File(szprefixpath+"/"+ANCHORFILEDIR+"/"+szassembly);
15458 File fanchorassembly = new File(szfullprefixpathanchorfiledir+"/"+szassembly);
15459 if (fanchorassembly.exists())
15460 {
15461 String[] dir = fanchorassembly.list();
15462 for (int nfile = 0; nfile < dir.length; nfile++)
15463 {
15464 File fhidden = new File(dir[nfile]);
15465 if (fhidden.isHidden())
15466 {
15467 //added in v1.11
15468 continue;
15469 }
15470
15471 int nperiodindex = dir[nfile].indexOf(".");
15472 String szanchorname;
15473 if (nperiodindex == -1)
15474 {
15475 szanchorname = dir[nfile];
15476 }
15477 else
15478 {
15479 szanchorname = dir[nfile].substring(0,nperiodindex);
15480 }
15481
15482 if (blowmem)
15483 {
15484 StateAnalysis.neighborhoodMaxLowMem(szsegmentfile,
15485 szfullprefixpathanchorfiledir+"/"+szassembly+"/"+dir[nfile],nbinsize,ChromHMM.DEFAULT_NEIGHBORHOOD_NUMLEFT,
15486 ChromHMM.DEFAULT_NEIGHBORHOOD_NUMRIGHT, nbinsize,//nspacing
15487 ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESTRAND,ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESIGNAL,null,//szcolfields,
15488 ChromHMM.DEFAULT_NEIGHBORHOOD_NOFFSETANCHOR,szoutputdir+"/"+szprefix+"_"+szanchorname+"_neighborhood",
15489 theColor,"Fold Enrichment "+szprefix+" "+szanchorname,null,bprintimage,false,false);
15490 }
15491 else
15492 {
15493 StateAnalysis.neighborhoodMax(szsegmentfile,
15494 szfullprefixpathanchorfiledir+"/"+szassembly+"/"+dir[nfile],nbinsize,ChromHMM.DEFAULT_NEIGHBORHOOD_NUMLEFT,
15495 ChromHMM.DEFAULT_NEIGHBORHOOD_NUMRIGHT, nbinsize,//nspacing
15496 ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESTRAND,ChromHMM.DEFAULT_NEIGHBORHOOD_BUSESIGNAL,null,//szcolfields,
15497 ChromHMM.DEFAULT_NEIGHBORHOOD_NOFFSETANCHOR,szoutputdir+"/"+szprefix+"_"+szanchorname+"_neighborhood",
15498 theColor,"Fold Enrichment "+szprefix+" "+szanchorname,null,bprintimage,false,false);
15499 }
15500 String szneighborhoodoutfileprefix = szprefix+"_"+szanchorname+ChromHMM.SZNEIGHBORHOODEXTENSION;
15501
15502 if (bprintimage)
15503 {
15504 pwweb.println("<img src=\""+szneighborhoodoutfileprefix+".png\"> <br>");
15505 pwweb.println("<li><a href=\""+szneighborhoodoutfileprefix+".svg"+"\">"+szneighborhoodoutfileprefix+" Enrichment SVG File</a><br>");
15506 }
15507 pwweb.println("<li><a href=\""+szneighborhoodoutfileprefix+".txt"+"\">"+szneighborhoodoutfileprefix+" Enrichment Tab-Delimited Text File</a><br>");
15508 }
15509 }
15510 else
15511 {
15512 System.out.println("Warning: No coordinate directory found for assembly "+szassembly+" in "+szfullprefixpathanchorfiledir);
15513 }
15514 }
15515 }
15516 }
15517 }
15518 pwweb.close();
15519
15520 if (bautoopen)
15521 {
15522 try
15523 {
15524 java.awt.Desktop.getDesktop().browse((new File(szwebpage)).toURI());
15525 }
15526 catch (Exception ex)
15527 {
15528 System.out.println("Warning could not automatically open in a browser "+szwebpage);
15529 }
15530 }
15531 }
15532 }
15533 else
15534 {
15535 bok = false;
15536 }
15537
15538 if (!bok)
15539 {
15540 System.out.println("usage: LearnModel [-b binsize][-color r,g,b][-d convergedelta][-e loadsmoothemission][-f inputfilelist][-gzip][-h informationsmooth]"+
15541 "[-holdcolumnorder][-holdroworder][-i outfileID][-init information|random|load][-l chromosomelengthfile][-lowmem][-m modelinitialfile][-many]"+
15542 "[-n numseq][-noautoopen][-nobed][-nobrowser][-nobrowserheader][-noenrich][-noimage][-nopseudolast][-p maxprocessors][-pseudo][-printposterior][-printstatebyline][-r maxiterations][-s seed][-scalebeta]"+
15543 "[-splitrows][-stateordering emission|transition]"+
15544 "[-t loadsmoothtransition][-u coorddir][-v anchorfiledir][-x maxseconds][-z zerotransitionpower] inputdir outputdir numstates assembly");
15545 }
15546 }
15547 else if (szcommand.equalsIgnoreCase("Reorder"))
15548 {
15549 int ninitmethod = ChromHMM.INITMETHOD_INFORMATION;
15550 String szoutfileID = "";
15551 String szlabelmapping = null;
15552 String szstateorderingfile = null;
15553 String szcolumnorderingfile = null;
15554 int nstateorder = ChromHMM.STATEORDER_FIXED;
15555 boolean bnoordercols = false;
15556 boolean bnoprintsegment = false;
15557 boolean bprintimage = true;
15558 int nargindex = 1;
15559 String szreorderinbedfile = null;
15560 String szreorderoutbedfile = null;
15561 boolean breordercolsmodel = false;
15562
15563 int nr=ChromHMM.DEFAULTCOLOR_R;
15564 int ng=ChromHMM.DEFAULTCOLOR_G;
15565 int nb=ChromHMM.DEFAULTCOLOR_B;
15566
15567 try
15568 {
15569 while (nargindex < args.length-2)
15570 {
15571 if (args[nargindex].equals("-color"))
15572 {
15573 String szcolor = args[++nargindex];
15574 StringTokenizer stcolor = new StringTokenizer(szcolor,",");
15575 if (stcolor.countTokens()==3)
15576 {
15577 nr = Integer.parseInt(stcolor.nextToken().trim());
15578 ng = Integer.parseInt(stcolor.nextToken().trim());
15579 nb = Integer.parseInt(stcolor.nextToken().trim());
15580 }
15581 else
15582 {
15583 bok = false;
15584 }
15585 }
15586 else if (args[nargindex].equals("-f"))
15587 {
15588 szcolumnorderingfile = args[++nargindex];
15589 }
15590 else if (args[nargindex].equals("-i"))
15591 {
15592 szoutfileID = args[++nargindex];
15593 }
15594 else if (args[nargindex].equals("-m"))
15595 {
15596 szlabelmapping = args[++nargindex];
15597 }
15598 else if (args[nargindex].equals("-noimage"))
15599 {
15600 bprintimage = false;
15601 }
15602 else if (args[nargindex].equals("-reordercolsmodelfile"))
15603 {
15604 breordercolsmodel = true;
15605 }
15606 else if (args[nargindex].equals("-o"))
15607 {
15608 szstateorderingfile = args[++nargindex];
15609 nstateorder = ChromHMM.STATEORDER_USER;
15610 }
15611 else if (args[nargindex].equals("-r"))
15612 {
15613 szreorderinbedfile = args[++nargindex];
15614 if (nargindex + 1 == args.length)
15615 {
15616 bok = false;
15617 break;
15618 }
15619 else
15620 {
15621 szreorderoutbedfile = args[++nargindex];
15622 }
15623
15624 if (szreorderinbedfile.equals(szreorderoutbedfile))
15625 {
15626 System.out.println("bedfilein cannot be the same as bedfileout");
15627 bok = false;
15628 }
15629 }
15630 else if (args[nargindex].equals("-stateordering"))
15631 {
15632 String sztoken = args[++nargindex];
15633 if (sztoken.equals("emission"))
15634 {
15635 nstateorder = ChromHMM.STATEORDER_EMISSION;
15636 }
15637 else if (sztoken.equals("transition"))
15638 {
15639 nstateorder = ChromHMM.STATEORDER_TRANSITION;
15640 }
15641 else
15642 {
15643 bok = false;
15644 break;
15645 }
15646 }
15647 else if (args[nargindex].equals("-holdcolumnorder"))
15648 {
15649 bnoordercols = true;
15650 }
15651 else
15652 {
15653 bok = false;
15654 }
15655 nargindex++;
15656 }
15657 }
15658 catch (NumberFormatException ex)
15659 {
15660 bok = false;
15661 }
15662
15663 if ((szstateorderingfile == null) && (szreorderinbedfile != null))
15664 {
15665 bok = false;
15666 }
15667
15668 if (bok&&(nargindex==args.length-2))
15669 {
15670 Color theColor = new Color(nr, ng, nb);
15671 String szInitFile = args[nargindex++];
15672 String szoutputdir = args[nargindex++];
15673 File f = new File(szoutputdir);
15674 if (!f.exists())
15675 {
15676 if (!f.mkdirs())
15677 {
15678 throw new IllegalArgumentException(szoutputdir+" does not exist and could not be created!");
15679 }
15680 }
15681
15682 if (bok)
15683 {
15684 boolean bprintsegments = !bnoprintsegment;
15685 boolean bordercols = !bnoordercols;
15686 ChromHMM theHMM = new ChromHMM(szInitFile, szoutputdir, szstateorderingfile, szcolumnorderingfile, szoutfileID,nstateorder,
15687 bordercols,theColor,szlabelmapping,bprintimage, szreorderinbedfile,
15688 szreorderoutbedfile, breordercolsmodel);
15689 theHMM.reorderModel();
15690 }
15691 }
15692 else
15693 {
15694 bok = false;
15695 }
15696
15697 if (!bok)
15698 {
15699
15700 System.out.println("usage: Reorder [-color r,g,b][-f columnorderingfile][-holdcolumnorder][-i outfileID]"+
15701 "[-m labelmappingfile][-noimage][-o stateorderingfile [-r bedfilein bedfileout]][-reordercolsmodelfile][-stateordering emission|transition] inputmodel outputdir");
15702
15703 }
15704 }
15705 else if (szcommand.equalsIgnoreCase("ConvertGeneTable"))
15706 {
15707 String path = ChromHMM.class.getProtectionDomain().getCodeSource().getLocation().getPath();
15708 String decodedPath = URLDecoder.decode(path, "UTF-8");
15709 String szprefixpath = decodedPath.substring(0, decodedPath.lastIndexOf("/") + 1);
15710 //String szfullprefixpathchromsizedir = szprefixpath+"/"+CHROMSIZESDIR;
15711 String szfullprefixpathcoorddir = szprefixpath+"/"+COORDDIR;
15712 String szfullprefixpathanchorfiledir = szprefixpath+"/"+ANCHORFILEDIR;
15713 String szchromlengthfile = null;
15714 int nargindex = 1;
15715 int npromoterwindow = 2000;
15716 boolean bgzip = false;
15717 boolean bnobin = false;
15718 boolean bnoheader = false;
15719 boolean bbiggenepred = false;
15720 String szcoorddir;
15721 String szanchordir;
15722
15723 try
15724 {
15725 while (nargindex < args.length-3)
15726 {
15727 //else if (args[nargindex].equals("-u"))
15728 // {
15729 // szfullprefixpathchromsizedir = args[++nargindex];
15730 // }
15731 if (args[nargindex].equals("-biggenepred"))
15732 {
15733 bbiggenepred = true;
15734 }
15735 else if (args[nargindex].equals("-gzip"))
15736 {
15737 bgzip = true;
15738 }
15739 else if (args[nargindex].equals("-l"))
15740 {
15741 szchromlengthfile = args[++nargindex];
15742 }
15743 else if (args[nargindex].equals("-nobin"))
15744 {
15745 bnobin = true;
15746 }
15747 else if (args[nargindex].equals("-noheader"))
15748 {
15749 bnoheader = true;
15750 }
15751 else if (args[nargindex].equals("-u"))
15752 {
15753 szfullprefixpathcoorddir = args[++nargindex];
15754 }
15755 else if (args[nargindex].equals("-v"))
15756 {
15757 szfullprefixpathanchorfiledir = args[++nargindex];
15758 }
15759 else if (args[nargindex].equals("-w"))
15760 {
15761 npromoterwindow = Integer.parseInt(args[++nargindex]);
15762 }
15763 else
15764 {
15765 bok = false;
15766 }
15767 nargindex++;
15768 }
15769 }
15770 catch (NumberFormatException ex)
15771 {
15772 bok = false;
15773 }
15774
15775 if ((bbiggenepred)&&(bnobin))
15776 {
15777 bok = false;
15778 }
15779
15780 if (bok && (nargindex==args.length-3))
15781 {
15782 String sztable = args[nargindex++];
15783 //String szchromlengths = args[nargindex++];
15784 String szprefix = args[nargindex++];
15785 String szassembly = args[nargindex++];
15786
15787 szcoorddir = szfullprefixpathcoorddir + "/" + szassembly;
15788 szanchordir = szfullprefixpathanchorfiledir + "/" + szassembly;
15789
15790 File f = new File(szcoorddir);
15791 if (!f.exists())
15792 {
15793 if (!f.mkdirs())
15794 {
15795 throw new IllegalArgumentException(szcoorddir+" does not exist and could not be created!");
15796 }
15797 }
15798
15799 f = new File(szanchordir);
15800 if (!f.exists())
15801 {
15802 if (!f.mkdirs())
15803 {
15804 throw new IllegalArgumentException(szanchordir+" does not exist and could not be created!");
15805 }
15806 }
15807
15808 if (szchromlengthfile == null)
15809 {
15810 //updated v.1.16
15811 String szdefaultlengthfile = szprefixpath+"/"+CHROMSIZESDIR+"/"+szassembly+".txt";
15812 File flength = new File(szdefaultlengthfile);
15813 //File flength = new File(szfullprefixpathchromsizedir+"/"+szassembly+".txt");
15814 if (flength.exists())
15815 {
15816 //szchromlengthfile = szfullprefixpathchromsizedir+"/"+szassembly+".txt";
15817 szchromlengthfile = szdefaultlengthfile;
15818 }
15819 else
15820 {
15821 throw new IllegalArgumentException("chromosome length file not specified and default "+szdefaultlengthfile+" not found");
15822 }
15823 }
15824
15825
15826 ConvertGeneTable.convertGeneTableToAnnotations(sztable, szprefix, szassembly, szcoorddir, szanchordir, szchromlengthfile,
15827 npromoterwindow, bgzip, bnobin, bnoheader,bbiggenepred);
15828 }
15829 else
15830 {
15831 bok = false;
15832 }
15833
15834 if (!bok)
15835 {
15836 System.out.println("usage: ConvertGeneTable [-biggenepred|-nobin][-gzip][-l chromosomelengthfile][-noheader][-u coorddir][-v anchordir][-w promoterwindow] inputgenetable prefix assembly");
15837 }
15838
15839 }
15840 else
15841 {
15842 System.out.println("Need to specify the mode BinarizeBam|BinarizeBed|BinarizeSignal|CompareModels|ConvertGeneTable|EvalSubset|LearnModel|MakeBrowserFiles"+
15843 "|MakeSegmentation|MergeBinary|NeighborhoodEnrichment|StatePruning|OverlapEnrichment|Reorder|Version");
15844
15845 }
15846 }
15847 }
15848