Codebase list augustus / 984ef698-c606-4157-9207-1d9b10a870de/main src / orthograph.cc
984ef698-c606-4157-9207-1d9b10a870de/main

Tree @984ef698-c606-4157-9207-1d9b10a870de/main (Download .tar.gz)

orthograph.cc @984ef698-c606-4157-9207-1d9b10a870de/mainraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
 * orthograph.cc
 *
 * License: Artistic License, see file LICENSE.TXT or 
 *          https://opensource.org/licenses/artistic-license-1.0
 * 
 * Description: orthologous graphs for comparative gene prediction
 */

#include "orthograph.hh"
#include "contTimeMC.hh"
#include "mea.hh"

using namespace std;

PhyloTree *OrthoGraph::tree = NULL;
StepRule OrthoGraph::step_rule = square_root;

size_t OrthoGraph::numSpecies;


void OrthoGraph::buildGeneList(vector< list<Transcript*>* > &genelist) {
    for (size_t pos = 0; pos < numSpecies; pos++){
	if (graphs[pos]){
	    // delete old genelist
	    if (genelist[pos]){
		delete genelist[pos];
	    }
	    list<Transcript*> *genes = new list<Transcript*>;
	    Node* current = graphs[pos]->tail;
	    Node* head =  graphs[pos]->head;
	    Node* succExon= NULL;
	    Transcript *currentGene = NULL;
	
	    // convert node labeling of graph into a list of genes (backtracking from tail)

	    State *intr = current->pred->getIntron(current);
	    if (intr){
		// this is a bit messy, but the problem is that
		// the type of a non-coding intron is wrong
		// so its hard to figure out if the intron ins between coding or non-coding exons
		if(current->pred->pred->n_type == ncintr || current->pred->pred->n_type == rncintr) // non-coding gene
		    currentGene = new Transcript();
		else
		    currentGene = new Gene();
		addIntronToGene(currentGene, intr);  
	    }
	    while (current != NULL){
		if (current == head && succExon){
		    State *intr = current->getIntron(succExon->pred);
		    if(intr)
			addIntronToGene(currentGene,intr); 
		    setGeneProperties(currentGene);
		    genes->push_front(currentGene);
		    currentGene = NULL;
		}
		if(current->n_type == IR && succExon){
		    setGeneProperties(currentGene);
		    genes->push_front(currentGene);
		    currentGene = NULL;
		    succExon = NULL;
		}
		if(current->n_type >= utrExon){ // add an exon to the current gene
		    State *ex;
		    if(current->n_type == sampled || current->n_type == utrExon){
			ex = new State(*((State*)(current->item)));
		    }
		    else{
			ex = new State(current->begin, current->end, current->castToStateType());
		    }
		    if(!currentGene){
			if(isNcExon(ex->type))
			    currentGene = new Transcript();
			else
			    currentGene = new Gene();
		    }
		    addExonToGene(currentGene, ex);
		    if(succExon){ // if the current exon is not the last, add an intron from the current exon to the succeding exon
			if(current->end+1 < succExon->begin){
			    State *intr = current->edges.begin()->to->getIntron(succExon->pred);
			    if(!intr){ // if no explicit intron exists, convert auxiliary edge to an intron
				intr = new State(current->end+1, succExon->begin-1, getIntronStateType((State*)current->item,(State*)succExon->item));
			    }
			    addIntronToGene(currentGene, intr);   
			}
		    }
		    succExon=current;
		}
		current=current->pred;
	    }
	    genelist[pos] = genes;
	}
    }
}

void OrthoGraph::filterGeneList(vector< list<Transcript*> *> &genelist, vector<int> &geneid){
    
    vector< list<AltGene> *> agls(numSpecies);

    for (size_t pos = 0; pos < numSpecies; pos++){	
	if (genelist[pos]){
	    AnnoSequence *annoseq = graphs[pos]->getAnnoSeq();

	    // filter criteria that apply to coding genes only
	    // delete gene if the combined CDS is too short, unless a CDS exon is truncated
	    for(list<Transcript*>::iterator git = genelist[pos]->begin(); git != genelist[pos]->end();){
		Gene *g = dynamic_cast<Gene *>(*git);
		if (g && ((g->clength < Constant::min_coding_len && g->completeCDS())
			  || (g->clength < 4 && g->clength < Constant::min_coding_len && !g->completeCDS()))){
		    //(*git)->printGFF();
		    //cout << "Gene deleted! (clength " << g->clength << ")" << endl;
		    delete *git;
		    git = genelist[pos]->erase(git);
		}
		else{
		    ++git;
		}
	    }

	    list<AltGene> *agl = groupTranscriptsToGenes(*genelist[pos]);

	    if(sfcs[pos] && sfcs[pos]->collection->hasHintsFile){
		// compile extrinsic evidence
		for (list<AltGene>::iterator git = agl->begin(); git != agl->end(); git++) {
		    for (list<Transcript*>::iterator trit = git->transcripts.begin(); trit != git->transcripts.end(); trit++) {
			Gene *g = dynamic_cast<Gene*> (*trit);
			if (g)
			    g->compileExtrinsicEvidence(sfcs[pos]->groupList);
		    }
		}
	    }

	    agl->sort();

	    int transcriptid;

	    // shift gene coordinates, set sequence name, gene and transcript names
	    for (list<AltGene>::iterator agit = agl->begin(); agit != agl->end(); ++agit){
		agit->seqname =  annoseq->seqname;
		agit->id = "g"+itoa(geneid[pos]);
		agit->sortTranscripts();

		transcriptid = 1;
		for (list<Transcript*>::iterator it = agit->transcripts.begin();it != agit->transcripts.end(); ++it ) {
		    (*it)->seqname = annoseq->seqname;
		    (*it)->id = "t" + itoa(transcriptid);
		    (*it)->geneid = agit->id;
		    transcriptid++;
		}
		geneid[pos]++;
	    }
	    geneLists[pos]=agl;
	}
    }
}
    

void OrthoGraph::printGenelist(vector<ofstream*> &filestreams){

    for (size_t pos = 0; pos < numSpecies; pos++){	
	if (geneLists[pos]){
	    AnnoSequence *annoseq = graphs[pos]->getAnnoSeq();
	    Strand strand = graphs[pos]->getSeqStrand();

	    bool withEvidence = false;
	    if(sfcs[pos] && sfcs[pos]->collection->hasHintsFile)
		withEvidence = true;

	    list<AltGene> *agl = geneLists[pos];
	    
	    if (strand == minusstrand){
 		agl = reverseGeneList(agl, annoseq->length - 1);
		agl->sort();
	    }

	    // shift gene coordinates
	    for (list<AltGene>::iterator agit = agl->begin(); agit != agl->end(); ++agit)
		agit->shiftCoordinates(annoseq->offset);
	    
	    //print the genes
	    streambuf *coutbuf = cout.rdbuf(); //save old buf
	    cout.rdbuf(filestreams[pos]->rdbuf()); //redirect std::cout to species file

	    //print sequence information

	    cout << "#----- prediction on sequence range " << annoseq->seqname << ":" << annoseq->offset + 1  << "-" << annoseq->offset + annoseq->length << " (" << annoseq->length << "bp) -----" << endl << "#" << endl;

	    if(!agl->empty()){
		if(strand == minusstrand){
		    char *DNA = annoseq->sequence;
		    char *reverseDNA = reverseComplement(DNA);
		    annoseq->sequence = reverseDNA;
		    printGeneList(agl, annoseq, Constant::codSeqOutput, Constant::proteinOutput, withEvidence);
		    annoseq->sequence = DNA;
		    delete [] reverseDNA;
		}
		else{
		    printGeneList(agl, annoseq, Constant::codSeqOutput, Constant::proteinOutput, withEvidence);
		}
	    }
	    else{
		cout << "# (none)" << endl;
	    }
	    cout.rdbuf(coutbuf); //reset to standard output again
	}
    }
}



vector<ofstream*> initOutputFiles(string outdir, string extension){

    vector<ofstream*> filestreams;
    filestreams.resize(OrthoGraph::numSpecies);
    vector<string> species;
    OrthoGraph::tree->getSpeciesNames(species);
    for(size_t pos = 0; pos < OrthoGraph::numSpecies; pos++){

    // label "SHIFTED" added to distinguish GFFs using the shrinked data set (hence having shifted coordinates) from standard GFFs
    #ifdef TESTING
    string testMode, filename, label; 
    try {
        testMode = Properties::getProperty("/Testing/testMode");
    } catch (...) {
        testMode = "none"; 
    }
    
    if(testMode=="run")
        label = ".SHIFTED";
    filename = outdir + species[pos] + extension + label + ".gff";
	#else
	string filename = outdir + species[pos] + extension + ".gff";
    #endif
    
    if(Gene::gff3){
	    filename += "3";	    
	}
	ofstream *out = new ofstream(filename.c_str());
	if(out){
	    filestreams[pos] = out;
	    (*out) << PREAMBLE << endl;
	    (*out) << "#\n#----- prediction for species '" << species[pos] << "' -----" << endl << "#" << endl;
	}	
    }
    return filestreams;
}

void closeOutputFiles(vector<ofstream*> filestreams){

    for(size_t pos = 0; pos < OrthoGraph::numSpecies; pos++){
	if(filestreams[pos]){
	    if(filestreams[pos]->is_open()){
		filestreams[pos]->close();
		delete filestreams[pos];
	    }
	}
    }
}
/* old code
  void OrthoGraph::addScoreSelectivePressure(){

    double a;
    double b;
    try {
	a = Properties::getdoubleProperty("/CompPred/ec_addend");
    } catch (...) {
	a = 0;
    }
    try {
	b = Properties::getdoubleProperty("/CompPred/ec_factor");
    } catch (...) {
	b = 0;
    }
    
    // reward/penalty that each EC receives
    for(size_t pos = 0; pos < numSpecies; pos++){
	if(graphs[pos]){
	    for(list<Node*>::iterator node = graphs[pos]->nodelist.begin(); node != graphs[pos]->nodelist.end(); node++){
		if( (*node)->n_type >= sampled ){
		    for(list<Edge>::iterator edge = (*node)->edges.begin(); edge != (*node)->edges.end(); edge++){
			// default EC-filter on:
			edge->score += a + (-1.396*b);
			}
		}
	    }
	}
    }
    // reward/penalty that only EC receives which are part of an OE
    static bool detection = false;
    if(!all_orthoex.empty()){
	for(list<OrthoExon>::const_iterator it = all_orthoex.begin(); it != all_orthoex.end(); it++){
	    for(size_t pos = 0; pos < numSpecies; pos++){
		if(it->orthoex[pos]){
		    Node* node = it->orthonode[pos];
		    int len =  node->end - node->begin + 1;
 		    double x = b*(0.015 * len + 1.277 * it->getConsScore() + 4.37 * it->getDiversity() -0.92);
		    if (string("honeybee1") == Properties::getProperty("species") && !detection){
			cout << "honeybee1 detected" << endl;
			detection = true;
			double Eomega = it->getEomega(),
			    cons = it->getConsScore(),
			    cont = it->getContainment(),
			    s = it->numExons(),
			    len = it->getAliLen();
			x = b*(1.396 - 6.585 -3.80 * Eomega + 0.860 * Eomega * Eomega -5.147 * cons -0.0084 * cont + 1.446 * s + 1.245 * log(len));
		    }
		    for (list<Edge>::iterator iter =  node->edges.begin(); iter != node->edges.end(); iter++){
			// default EC-filter on:  
		       	iter->score += x;
		    }
		}
	    }
	}
    }
    }*/

double OrthoGraph::globalPathSearch(){

    double score=0;

    for(size_t pos = 0; pos < numSpecies; pos++){
	if(graphs[pos]){
	    score += graphs[pos]->relax();
	}
    }
    return score;
}

double OrthoGraph::dualdecomp(list<OrthoExon> &all_orthoex, ExonEvo &evo, vector< list<Transcript*> *> &genelist, int gr_ID, int T, vector<double> &c){

    cout << "dual decomposition on gene Range " << gr_ID << endl;
    cout<<"round\titer\tstep_size\tprimal\tdual\t#inconsistencies"<<endl;

    double best_dual = std::numeric_limits<double>::max();   // best dual value so far
    double best_primal = -std::numeric_limits<double>::max(); // best primal value so far
    double initial_primal = std::numeric_limits<double>::max(); // initial primal value (in 0-the iteration)

    /* 
     * key: orthoexon ID
     * value: list of indices of species, in which the exon is predicted
     */
    map<int, list<int> >pp_init; // stores predicted HECTs in first iteration
    map<int, list<int> >pp_opt;  // ...................... in  best iteration
	
    for(size_t r=0; r < c.size(); r++){ // number of rounds
	
	/*
	 * initialization
	 */
	double old_dual = 0.0; // dual value of the previous iteration
	double delta = 0.0; // step size	
	int v = 0; 	// number of iterations prior to t where the dual value increases

	cout.precision(10);
	for(int t=0; t<T;t++){
	    double path_score = globalPathSearch();
	    int numInconsistent = 0;
	    double hect_score = 0;
	    if(t == 0 && r == 0){
		// initially set labels of hects by a simple majority rule
		// set all labels of a hect to 1, if the majority
		// iff the corresponding labels in the graph are labelled with one/
		// otherwise, set all labels to 0
		hect_score += init(all_orthoex,evo,numInconsistent);
	    }
	    else{
		hect_score += treeMAPInf(all_orthoex,evo,numInconsistent);
	    }
	    double current_dual = path_score + hect_score;       // dual value of the t-th iteration 
	    best_dual = min(best_dual,current_dual);              // update upper bound
	    if( (t >= 1) && (old_dual < current_dual) )  // update v
		v++;
	    double current_primal = path_score + makeConsistent(all_orthoex,evo); // primal value of the t-the iteration
	    if(best_primal < current_primal){
		best_primal = current_primal;
		buildGeneList(genelist); // save new record
		// update pp_opt
		pp_opt.clear();
		for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
		    list<int> pp;
		    for(int pos=0; pos < hects->orthonode.size(); pos++){
			if(hects->orthonode[pos] && hects->orthonode[pos]->label == 1)
			    pp.push_back(pos);
		    }
		    if(!pp.empty())
			pp_opt.insert(pair< int, list<int> > (hects->ID , pp));
		}
	    }
	    if(t == 0 && r == 0){ // first iteration
		initial_primal = current_primal;
		pp_init = pp_opt;
	    }
	    cout<<r<<"\t"<<t<<"\t"<<delta<<"\t"<<current_primal<<"\t"<<current_dual<<"\t"<<numInconsistent<<endl;
	    
	    if(numInconsistent == 0 || best_dual - best_primal < 1e-8) // exact solution is found
		goto END;
	    
	    // determine new step size
	    delta = getStepSize(r,c[r], t, v, numInconsistent, current_dual, best_primal, best_dual);
	    
	    // updated weights
	    for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
		for(size_t pos = 0; pos < numSpecies; pos++){
		    if(hects->orthoex[pos]){
			// get corresponding node in graph
			Node* node = hects->orthonode[pos];
			bool h = node->label;
			bool v = hects->labels[pos];
			if(v != h){  //shared nodes are labelled inconsistently in the two subproblems
			    float weight = delta*(v-h);
			    //update weights
			    node->addWeight(weight);
			    hects->weights[pos] -= weight;     
			}
		    }
		}
	    }
	    old_dual = current_dual;
	}
	// reset weights
	/*for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
	    for(size_t pos = 0; pos < numSpecies; pos++){
		if(hects->orthoex[pos]){
		    Node* node = hects->orthonode[pos];
		    node->addWeight(hects->weights[pos]);
		    hects->weights[pos] = 0;     
		}
	    }
	    }*/
    }

 END:
    // set phyletic pattern (only used as output information in orthoExon files)
    for(list<OrthoExon>::iterator hects=all_orthoex.begin(); hects!=all_orthoex.end(); hects++){
	hects->setPhyleticPattern(pp_init, pp_opt);
    }

    double best_gap = (best_dual - best_primal > 0) ? (best_dual - best_primal) : 0;
    double initial_gap = (best_dual - initial_primal > 0) ? (best_dual - initial_primal) : 0;
    double perc_gap = (initial_gap > 0 )? best_gap/initial_gap : 0;
    perc_gap*=100;
    cout<<"dual decomposition reduced initial duality gap of "<<initial_gap<<" to "<<best_gap<<" (to "<<perc_gap<<"%)"<<endl;
    return best_gap;
}

/*
 * requirement delta -> 0 for t -> infinity and
 * sum(deltas) = infinity
 * v ist the number of iterations prior to t where the dual value increases
 * the purpose of v is to decrease the step size only if we move in the wrong direction
 */
double OrthoGraph::getStepSize(int r, double c, int t, int v, int numInconsistent, double current_dual, double best_primal, double best_dual){
    if(step_rule == harmonic)
	return c/(v+1);
    if(step_rule == square_root || (step_rule == mixed && r > 0))
	return c/sqrt(v+1);
    if(step_rule == base_2)
	return c/pow(2,v);
    if(step_rule == base_e)
	return c/exp(v);
    if(step_rule == polyak || (step_rule == mixed && r == 0))
	return (current_dual - best_primal)/numInconsistent;
    if(step_rule == constant)
	return c;
    return c/sqrt(v+1);
}

double OrthoGraph::init(list<OrthoExon> &all_orthoex, ExonEvo &evo, int &numInconsistent){

    double score = 0;

    for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
	//count number of zeros   
	size_t numOnes = 0;
	size_t numZeros = 0;

	for(int pos=0; pos < hects->orthonode.size(); pos++){
	    if(hects->orthonode[pos])
		(hects->orthonode[pos]->label == 1) ? numOnes++ : numZeros++;
	}
	size_t majority = 0;
	(numOnes >= numZeros) ? majority=1 : majority=0;


	for(int pos=0; pos < hects->orthoex.size(); pos++){
	    if(hects->orthoex[pos])
		(hects->labels[pos] = majority);
	}
	PhyloTree *temp = hects->getTree();
	Evo *evo_base = &evo;
	score += temp->MAP(hects->labels, hects->weights, evo_base, true);
	double maxi =  max(numOnes,numZeros);
	numInconsistent += ((numOnes+numZeros) - maxi);
	
    }
    return score;
    
}

double OrthoGraph::treeMAPInf(list<OrthoExon> &all_orthoex, ExonEvo &evo, int &numInconsistent){

    double score=0;

    for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
	PhyloTree *temp = hects->getTree();
	Evo *evo_base = &evo;
	score += temp->MAP(hects->labels, hects->weights, evo_base);
	for(int pos=0; pos < hects->orthonode.size(); pos++){
            if(hects->orthonode[pos] && hects->orthonode[pos]->label != hects->labels[pos])
                numInconsistent++;
        }

    }
    return score;
}

double OrthoGraph::makeConsistent(list<OrthoExon> &all_orthoex, ExonEvo &evo){

    double score = 0;

    for(list<OrthoExon>::iterator hects = all_orthoex.begin(); hects != all_orthoex.end(); hects++){
	PhyloTree *temp = hects->getTree();
	Evo *evo_base = &evo;
	vector<int> labels = hects->labels;
	for(int pos=0; pos < hects->orthonode.size(); pos++){
	    if(hects->orthonode[pos])
		labels[pos] = hects->orthonode[pos]->label;
	}
	score += temp->MAP(labels, hects->weights, evo_base, true);
    }
    return score;
}	

void OrthoGraph::linkToOEs(list<OrthoExon> &all_orthoex){

    for(list<OrthoExon>::iterator it = all_orthoex.begin(); it != all_orthoex.end(); it++){
	double oe_score = it->getLogRegScore();
	for(size_t pos = 0; pos < OrthoGraph::numSpecies; pos++){ 
	    if(it->exonExists(pos)){
		if(!graphs[pos])
		    throw ProjectError("Internal error OrthoGraph::linkToOEs: graph does not exist.");
		Node* node = graphs[pos]->getNode(it->orthoex[pos]);
		if(!node){
		    throw ProjectError("Internal error OrthoGraph::linkToOEs: EC has no corrpesonding node in OrthoGraph.");
		}
		it->orthonode[pos]=node;
		node->addWeight(oe_score); // add OE score to all outgoing edges
	    }
	}
    }  
}

/* old code: optimize cgp by making small moves
void OrthoGraph::optimize(ExonEvo &evo){

    //create MoveObjects

    //for now, loop over OrthoExons and apply majority rule move if possible

    int shift_size=3;     // number of exons local_head/local_tail is shifted to the left/right on the current path 
    if(!all_orthoex.empty()){
	for(list<OrthoExon>::iterator orthoex = all_orthoex.begin(); orthoex != all_orthoex.end(); orthoex++){
	    vector<Move*> orthomove = majorityRuleMove(*orthoex, shift_size);
	    if(!orthomove.empty()){
		localMove(orthomove,evo,shift_size);
		//delete MoveObjects
		for(size_t pos = 0; pos < numSpecies; pos++){
		    delete orthomove[pos];
		} 
	    }   
	}
    }
}

void OrthoGraph::localMove(vector<Move*> &orthomove, ExonEvo &evo, int shift_size){

    int maxIterations=0;  // max number a move can be repeated                                                                                                                                         
    bool retry = false;  //if true, the move is repeated on a 'larger' subgraph
    int iter = 0;  // number of current repetition
   
    do{

	if(retry){

	    cout << "repetition:\t" << iter <<"\tshift_size:\t"<<shift_size <<endl;

	    //shift local_heads and local_tails for each species
	    for(size_t pos = 0; pos < numSpecies; pos++){
		if(orthomove[pos]){
		    orthomove[pos]->shiftHead(shift_size);
		    orthomove[pos]->shiftTail(shift_size);
		    cout << graphs[pos]->getSpeciesname() << endl;
		    cout << "local_head:\t" << orthomove[pos]->getHead() << endl;
		    cout << "local_tail:\t" << orthomove[pos]->getTail() << endl;
		}
	    }
	}

	retry = false;

	double graph_score = 0; //difference between the new and the old scores of the local paths
	double phylo_score = 0; //diference between the new and the old phylogenetic score

	// determine all OrthoExons in that range	
	list<OrthoExon> local_orthoexons = orthoExInRange(orthomove);
 
	//calculate phylo_score
	phylo_score -= pruningAlgor(local_orthoexons,evo);

	// do local changes for each graph  
	for(size_t pos = 0; pos < numSpecies; pos++){
	    if(orthomove[pos]){
		graph_score += graphs[pos]->localChange(orthomove[pos]);
	    }
	}
	print_change = true;
	//calculate new phylo_score
	phylo_score += pruningAlgor(local_orthoexons, evo);
	print_change = false;
	cout << "-------------------------------------" << endl;
	cout << "graph_score\t" << graph_score << endl;
	cout << "phylo_score\t" << phylo_score << endl;

	if( graph_score == 0 && phylo_score == 0 ){
	    //nothing changed, repeat move on larger subgraph
	    if( iter < maxIterations ){
		cout << "repeat\n" << endl;
		retry = true;
	    }
	}
	else if( (graph_score + phylo_score) > 0 ){
	    //score improved, accept move
	    cout << "accept\n" << endl; 
	}
	else{
	    cout << "undo\n" << endl;
	    // no improvement, undo local changes by relaxing nodes again this time with original weights
	    // TODO: has to be replaced by an undo buffer or something similar in future
	    for(size_t pos = 0; pos < numSpecies; pos++){
		if(orthomove[pos]){
		    graphs[pos]->relax(orthomove[pos]->getHead(), orthomove[pos]->getTail());
		}
	    }
	}
	iter++;
    }
    while( retry );
}

double OrthoGraph::pruningAlgor(list<OrthoExon> &orthoex, ExonEvo &evo){

    double tree_score = 0;
    Evo *evo_base = &evo;

    for(list<OrthoExon>::iterator ortho = orthoex.begin(); ortho != orthoex.end(); ortho++){

	string labelpattern = getLabelpattern(*ortho);
	if(cache::inHash(labelpattern)){
	    tree_score += cache::getScore(labelpattern);
	}
	else{
	    PhyloTree temp(*tree);
	    double score = temp.pruningAlgor(labelpattern, evo_base);
	    score=score * evo.getPhyloFactor();
	    cache::addToHash(labelpattern, score);
	    tree_score += score;
	}
    }
    return tree_score;
}

string OrthoGraph::getLabelpattern(OrthoExon &ex){

    string labelpattern;
    for (size_t i = 0; i < ex.orthoex.size(); i++){

	if (ex.orthoex.at(i) == NULL){
	    labelpattern += "2";
	}
	else {
	    map<string, Node*>::iterator it = graphs.at(i)->existingNodes.find(graphs.at(i)->getKey(ex.orthoex.at(i)));
	    if (it != graphs.at(i)->existingNodes.end()){
		bool label = it->second->label;
		if (label == 1){
		    labelpattern += "1";
		}
		else if (label == 0){
		    labelpattern += "0";
		}
	    }
	    else
		throw ProjectError("Error in OrthoExon::getKey: exon " + graphs.at(i)->getKey(ex.orthoex.at(i)) +" not in graph!");
	}
    }
    if ( ex.labelpattern != labelpattern){
	if(print_change){
	    cout << ex << "\t" << ex.labelpattern << "-->" << labelpattern << endl;
	    //temp: html output for gBrowse
	    printHTMLgBrowse(ex);
	}
    }

    ex.labelpattern = labelpattern;
    return ex.labelpattern;
}


list<OrthoExon> OrthoGraph::orthoExInRange(vector<Move*> &orthomove){

    list<OrthoExon> local_orthoexons;

    for(list<OrthoExon>::const_iterator ortho = all_orthoex.begin(); ortho != all_orthoex.end(); ortho++){
	for(size_t pos = 0; pos < numSpecies; pos++){
	    if(orthomove[pos]){
		if(ortho->orthoex[pos]){
		    if(ortho->orthoex[pos]->begin >= orthomove[pos]->getHead()->begin && ortho->orthoex[pos]->end <= orthomove[pos]->getTail()->end){
			local_orthoexons.push_back(*ortho);
			break;
		    }
		}
	    }
	}
    }
    return local_orthoexons;
}
	
vector<Move*> OrthoGraph::majorityRuleMove(OrthoExon &orthoex, int shift_size){

    vector<Move*> orthomove;
  
    //count number of zeros and ones in labelpattern of an OrthoExon
  
    size_t numOnes = 0;
    size_t numZeros = 0;

    //get current label pattern
    string labelpattern = getLabelpattern(orthoex);

  
    for(string::iterator string_it = labelpattern.begin(); string_it < labelpattern.end(); string_it++){
	if(*string_it == '1'){
	    numOnes++;
	}
	if(*string_it == '0'){
	    numZeros++;
	}
    }
    if ( numOnes > numZeros && numZeros > 0 ){                    // make all zeros to ones	
	cout << "Majority Rule Move " << endl;
	cout << orthoex << "\t" << labelpattern << endl;
	cout << "iteration:\t" << 0  << "\tshift_size:\t" << shift_size << endl;
	orthomove.resize(numSpecies);
	for(size_t pos = 0; pos < numSpecies; pos++){
	    if( (labelpattern[pos] == '0')  ){
		Move *move = new Move(graphs[pos], shift_size + 1);
		move->addNodeBack( graphs[pos]->getNode(orthoex.orthoex[pos]), graphs[pos]->getMaxWeight() );
		move->initLocalHeadandTail();
		orthomove[pos] = move;
		cout << "local_head:\t";
		graphs[pos]->printNode(orthomove[pos]->getHead());
		cout << "local_tail:\t";
		graphs[pos]->printNode(orthomove[pos]->getTail());
	    }
	}
    }
    return orthomove;
}

map<string, Score> cache::labelscore; //stores score of prunning algorithm for each pattern (leaf labeling)

bool cache::inHash(string labelpattern){
    return ( labelscore.find(labelpattern) != labelscore.end() );
}

void cache::addToHash(string labelpattern, double score){
    Score s;
    s.treescore = score;
    labelscore[labelpattern] = s;

}

void cache::resetCounter(){

    for(map<string, Score>::iterator it = labelscore.begin(); it != labelscore.end(); it++){
	it->second.count = 0;
    }

}


void OrthoGraph::printCache(list<OrthoExon> &ortho){

    cache::resetCounter();

    cout << "*************************************************************************" << endl;
    cout << "--- orthologous exons + labelpattern ---" << endl;
    for(list<OrthoExon>::iterator it = ortho.begin(); it != ortho.end(); it++){
	cache::incrementCounter(getLabelpattern(*it));
	cout << *it << "\t" << getLabelpattern(*it)  << endl;
	printHTMLgBrowse(*it);
    }
    cout << "\n--- cache summary ---" << endl;
    cout.width(4); cout << "";
    cout.width(12); cout << "score";
    cout.width(4); cout << "#" << endl;

    for(map<string, Score>::iterator it = cache::labelscore.begin(); it != cache::labelscore.end(); it++){

	cout.width(4); cout << it->first;
	cout.width(12); cout << it->second.treescore;
	cout.width(4); cout << it->second.count << endl;

    }
    cout << "*************************************************************************" << endl;
}

double cache::getScore(string labelpattern){
    return labelscore[labelpattern].treescore;
}
void cache::incrementCounter(string labelpattern){
    labelscore[labelpattern].count++;
}

void OrthoGraph::printHTMLgBrowse(OrthoExon &ex){

    for (int j=0; j<ex.orthoex.size(); j++) {
	if (ex.orthoex.at(j)!=NULL) {

	    int offset = graphs[j]->getSeqOffset();
	    Strand strand = graphs[j]->getSeqStrand();
	    int length = graphs[j]->getSeqLength();
	    char* seqname = graphs[j]->getSeqID();

	    cout << "http://bioinf.uni-greifswald.de/gb2/gbrowse/vergl" << itoa(j+1) <<"/?name=" << seqname  << "%3A";
	    if (strand == plusstrand) {
		cout << ex.orthoex.at(j)->begin + offset + 1 << ".." << ex.orthoex.at(j)->end + offset + 1 << endl;
	    } else {
		cout << length - ex.orthoex.at(j)->end + offset << ".." << length - ex.orthoex.at(j)->begin + offset << endl;
	    }
	}
    }
}
*/

/* 
 * Patrick Balmerths playground
 */
void OrthoGraph::createOrthoGenes(const GeneMSA *geneRange){
    // create all_orthogenes

    // In case the alignment in geneRange is actually not needed and
    // the orthoexons are sufficient, then remove this argument.
}

void OrthoGraph::printOrthoGenes(){
  // ouput all_orthogenes
}

void OrthoGraph::setStepRule(const char* r){
    
    if(strcmp(r, "harmonic") == 0){
	step_rule = harmonic;
    }
    else if(strcmp(r, "square_root") == 0){
	step_rule = square_root;
    }
    else if(strcmp(r, "base_2") == 0){
	step_rule = base_2;
    }
    else if(strcmp(r, "base_e") == 0){
	step_rule = base_e;
    }
    else if(strcmp(r, "polyak") == 0){
	step_rule = polyak;
    }
    else if(strcmp(r, "constant") == 0){
	step_rule = constant;
    }
    else if(strcmp(r, "mixed") == 0){
	step_rule = mixed;
    }
    else{
	std::string s(r);
	throw ProjectError("Warning: " + s + "is not a valid dd_step_rule. Choose one of the step_rules from below\n"
			   "constant\nharmonic\nsquare_root\nbase_2\nbase_e\npolyak\tmixed\n");
    }
}