aboutsummaryrefslogtreecommitdiffstats
path: root/src/gentech/gentech.cpp
blob: 1c3421cf1d48ddc53b932809fb3c7f039aae1a31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
/*
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 1994-2022 Gothel Software e.K.
 * Copyright (c) 1994 Christian Mueller
 *
 * Proprietary licenses are available
 * via Gothel Software e.K. <sgothel@jausoft.com>.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA  02111-1307, USA.
 *
 * You can also check the GNU General Public License
 * in the internet at http://www.gnu.org/copyleft/gpl.html !
 */

#include <gentech/gentech.hpp>
#include <gentech/random.hpp>

#include <jau/basic_algos.hpp>

#include <climits>
#include <limits>
#include <iostream>

#include <cassert>

using namespace jau::gentech;

#define THIS (*this)

std::ostream& std::operator<< (std::ostream& os, const jau::gentech::nucleotide_array_t& list)
{
    const nucleotide_array_t::size_type Zeilenlaenge = 10;

    os << "( " << list.size() << " ) < ";
    for (nucleotide_array_t::size_type i=0; i<list.size(); i++) {
        if (i % Zeilenlaenge == 0 &&  i)   os << "\n\t";

        os << list[i];
        if (i % Zeilenlaenge != Zeilenlaenge-1 && i != list.size()-1) {
            os << ", ";
        }
    }
    os << " >";
	return os;
}

// *******************************************************************
// *******************************************************************
//  C H R O M O S O M
// *******************************************************************
// *******************************************************************

// STATISCHE-KLASSEN-GLOBALE VARIABLEN !!!

Chromosom::Chromosom ( Chromosomen & env, size_type initial_length )
: nucleotide_array_t(initial_length), m_env(env), m_fitness(0)
// Zufaellig erzeugte Chromosomen
{
    for ( Chromosom::size_type i=initial_length; i > 0; --i) {
        push_back( Random<size_type>(env.m_min_nucleotide_value,env.m_max_nucleotide_value) );
    }
    assert (size() == initial_length);
}

Chromosom::Chromosom ( Chromosomen & env, const std::string& FileName )
: nucleotide_array_t(), m_env(env), m_fitness(0)
{
    Load(FileName);
}

void Chromosom::Copy (const Chromosom &a)
{
    m_fitness = a.m_fitness;
    assert (size() == a.size());
}

Chromosom& Chromosom::operator=(const Chromosom& m)
{
    if (this == &m) { return *this; }

    // Neue Liste der Nukleotide anlegen.
    // In Liste<NukleoTyp> wird der *this-Zeiger auf Gleichheit ueberprueft
    // Das Environment env (Chromosomen) bleibt !
    nucleotide_array_t::operator=(m);
    Copy(m);
    return *this;
}

bool Chromosom::operator==(const Chromosom& ch) const noexcept
{
    if (this == &ch) { return true; };     // gleiches Chromosom
    if (size() != ch.size()) {    // garantiert Ungleich
        return false;
    }
    size_type i;
    for(i=0; i < size() && THIS[i] == ch[i]; ++i ) ; // Ueberprufung
    return i == size();
}

void Chromosom::Save(const std::string& FileName) const
{
    FILE *file;
    if( ( file=fopen(FileName.c_str(),"wb") ) == nullptr ) {
        ABORT("Couldn't open file '%s'", FileName.c_str());
    }

    {
        // 4-7-94, 2:51 PM
        // Speichert die Groesse des NukleoDatenTyps als erstes in der Datei
        const uint16_t NukleoLen = sizeof(nucleotide_t);
        if( fwrite (&NukleoLen, sizeof (NukleoLen), 1, file) != 1 ) {
            ABORT("Couldn't write to file '%s'", FileName.c_str());
        }
        // 4-7-94, 2:51 PM
    }
    const size_type len=size();
    if( fwrite (&len, sizeof(len), 1, file) != 1 ) {
        ABORT("Couldn't write to file '%s'", FileName.c_str());
    }
    for(size_type i=0; i<len; ++i) {
        if( fwrite (&(THIS[i]), sizeof (nucleotide_t), 1, file) != 1 ) {
            ABORT("Couldn't write to file '%s'", FileName.c_str());
        }
    }
    fclose(file);
}

void Chromosom::Load(const std::string& FileName) {
    FILE *file;
    if ((file=fopen(FileName.c_str(), "rb")) == nullptr) {
        ABORT("Couldn't open file '%s'", FileName.c_str());
    }

    {
        // 4-7-94, 3:3 PM
        // Liest als erstes die Groesse des abgespeicherten NukleoTyps
        // aus dem File
        uint16_t NukleoLen;
        if( fread (&NukleoLen, sizeof (NukleoLen), 1, file) != 1 ) {
            ABORT("Couldn't read file '%s'", FileName.c_str());
        }
        if( NukleoLen != sizeof(nucleotide_t) ) {
            std::cerr << "!! ERROR !!\n"
                    << "   Laenge des Datentyps der gespeicherten Nuklotide\n"
                    << "   ist kleiner als das abgespeicherte Format\n";
            exit (0);
        }
        // 4-7-94, 3:3 PM
    }
    // Puffer der richtigen Laenge bereit stellen
    nucleotide_t value;
    size_type len;
    if (fread (&len, sizeof (len), 1, file) == 0) {
        ABORT("Couldn't read file '%s'", FileName.c_str());
    }
    reserve(len);
    for(size_type i=0; i<len; ++i) {
        if( fread (&value, sizeof(value), 1, file) == 0 ) {
            ABORT("Couldn't read file '%s'", FileName.c_str());
        }
        insert(i, value);
    }
    fclose(file);
}

Chromosom::size_type Chromosom::GetNukleotidNumber(size_type nuckleotide_idx) const noexcept
{
    nucleotide_t nuckleotide_value=THIS[nuckleotide_idx];

    if( m_env.m_nucleotide_value_scale * (m_env.m_nucleotide_count-1) <= nuckleotide_value &&
        nuckleotide_value <= m_env.m_max_nucleotide_value )
    {
        // Trifft auch fuer Nukleotide gleich nullptr zu !!!
        return m_env.m_nucleotide_count;
    }

    for (size_type n=m_env.m_nucleotide_count-1; n > 0; --n) { // FIXME: Double '-1' here and on 'n'?
        if( m_env.m_nucleotide_value_scale * (n-1) <= nuckleotide_value &&
            nuckleotide_value < m_env.m_nucleotide_value_scale * n ) {
            return n;
        }
    }

    ABORT("Failed to determine nucleotide number of nucleotide[%zu]=%zu", (size_t)nuckleotide_idx, (size_t)nuckleotide_value);
    return 0;
}

nucleotide_t Chromosom::GetUserNukleotidValue(size_type i) const noexcept
{
    return m_env.m_nucleotide_value_scale*(i-1);
}

bool Chromosom::FindIntron(size_type &von, size_type &bis) const noexcept
{
    bool done = false;
    size_type i, i2, i3;

    if (bis-von+1 >= m_env.m_splice_code_ptr->Length)
    {
        // Spleissen..Anfang suchen
        i=von; i2=0;
        while (i <= bis && m_env.m_splice_code_ptr->SpliceCode[i2] != 0) {
            if (GetNukleotidNumber (i) == m_env.m_splice_code_ptr->SpliceCode[i2]) {
                ++i2;
                ++i;
            } else {
                i2=0;
                von=++i;
            }
        }
        if (i < bis) {
            assert (m_env.m_splice_code_ptr->SpliceCode[i2] == 0) ;
            // von gefunden...
            // Spleissen..Ende suchen
            i3=i;
            i=++i2;
            while (i3 <= bis && m_env.m_splice_code_ptr->SpliceCode[i2] != 0) {
                if (GetNukleotidNumber(i3) == m_env.m_splice_code_ptr->SpliceCode[i2]) {
                    i2++;
                } else {
                    i2=i;
                }
                i3++;
            }
            if (m_env.m_splice_code_ptr->SpliceCode[i2] == 0) {
                // bis gefunden...
                bis=i3-1;
                done=true;
            }
        }
    }
    return done;
}

Chromosom::size_type Chromosom::Splicing()
{
  size_type NNukleotide=0, IntronStart=0, IntronEnd=size()-1;
  #ifndef NDEBUG
      size_type len_old;
  #endif

  // Die Bedingung fuer den SpliceCode ist Nukleotide > 1 !
  // Nukleotide wird in Chromosomen::CalcParameter gesetzt !
  if (m_env.m_nucleotide_count <= 1) {
      // Kein Splicing , da kein SpliceCode !!!
      return 0;
  }

  while( FindIntron(IntronStart, IntronEnd) ) {
      #ifndef NDEBUG
          len_old=size();
      #endif
      assert( IntronStart <= IntronEnd );
      erase( IntronStart, IntronEnd+1 );
      assert ( len_old - ( IntronEnd - IntronStart + 1 ) == size() );
      NNukleotide+=IntronEnd-IntronStart+1;
      IntronEnd=size()-1;
  }
  return NNukleotide;
}

void Chromosom::InsertIntrons (size_type von, size_type length)
{
    size_type i, iRumpf;

    if (m_env.m_splice_code_ptr != nullptr &&
            m_env.m_splice_code_ptr->SpliceCode[0] != 0 &&
            von <= size()           &&
            length >= m_env.m_splice_code_ptr->Length)
    {
        // StartSequenz einfuegen.
        for (i=0; m_env.m_splice_code_ptr->SpliceCode[i] != 0; ++i, ++von, --length) {
            insert(von, GetUserNukleotidValue(m_env.m_splice_code_ptr->SpliceCode[i]));
        }
        // Stelle fuer Rumpf merken.
        iRumpf=von;
        // EndSequenz einfuegen.
        for (++i; m_env.m_splice_code_ptr->SpliceCode[i] != 0; ++i, ++von, --length) {
            insert(von, GetUserNukleotidValue (m_env.m_splice_code_ptr->SpliceCode[i]));
        }
        // Rumpf fuellen.
        while (length > 0) {
            insert(iRumpf, Random (m_env.m_min_nucleotide_value, m_env.m_max_nucleotide_value));
            length--;
        }
    }
}

void Chromosom::Inversion()
{
    const size_type start = Random<size_type>(0, size()-2);
    assert (start < size()-1);

    const size_type end = Random(start+1, size()-1) ;
    assert (end < size());
    assert (end > start);

    const size_type length = end-start+1;
    nucleotide_array_t save(length);

    /**
     *   S   E
     * 0123456789     01234
     * abcdefghij  -> cdefg
     *
     *   S   E
     * 0123456789     43210
     * abgfedchij  <- gfedc
     */
    for (size_type i=start; i <= end; ++i) {
        save.push_back( THIS[i] );
    }
    assert( save.size() == length );

    for (size_type i=start; i <= end; ++i)  {
        THIS[i]=save[end-i];
    }
}

void Chromosom::Translocation()
{
    const size_type start = Random<size_type>(0, size()-2);
    assert (start < size()-1);
    const size_type end = Random (start+1, size()-1) ;
    assert (end < size());
    assert (end > start);

    const size_type length = end-start+1;
    nucleotide_array_t save(length);

    for(size_type i=start; i <= end; ++i) {
        save.push_back(THIS[i]);
    }
    erase(start, end+1);
    assert( save.size() == length );

    const size_type dest = Random<size_type>( 0, size()-1 );
    for(size_type i=0; i<save.size(); ++i) {
        THIS.insert(dest+i, save[i]);
    }
}

// *******************************************************************
// *******************************************************************
//  C H R O M O S O M E N
// *******************************************************************
// *******************************************************************

// STATISCHE-KLASSEN-GLOBALE VARIABLEN !!!

const Chromosomen::size_type Chromosomen::m_mutation_freq_variance=1000;

Chromosomen::Chromosomen (nucleotide_t UserNukleoMinVal, 
                          nucleotide_t UserNukleoMaxVal,
                          size_type max_chromosom_count,
                          const std::string& StartGenFile,
                          size_type Nukleotide,
                          SpliceCodeInfo *PtrSpliceCodeInfo,
                          size_type InversionFreq,
                          size_type TranslocationFreq,
                          size_type AsymXOverFreq,
                          size_type CrossVal,
                          size_type MutationFreq,
                          size_type max_no_improving_gens)
: chromosom_array_t(max_chromosom_count),
  m_all_time_best_gen(1),
  m_all_time_best_avrg_fitness(0),
  m_all_time_best(*this),

  m_avrg_fitness(0),
  m_best_fitness(0),
  m_fitness_sum(0),

  m_max_no_improving_gens(max_no_improving_gens),
  m_no_improving_gens(0),

  m_generation(1),
  m_max_chromosom_count(max_chromosom_count),
  m_intro_code_len_sum(0),
  m_spliced_chromosom_count(0),

  m_file_ptk_ptr(nullptr),

  m_generation_start(0),
  m_generation_end(0),
  m_evolution_start(0),
  m_evolution_end(0),

  m_min_chromosom_len(0),
  m_max_chromosom_len(0),
  m_avrg_chromosom_len(0),
  m_chromosom_above_zero_count(0),

  m_mutations_this_gen(0),
  m_inversions_this_gen(0),
  m_translocations_this_gen(0),
  m_mutation_freq(MutationFreq),

  m_inversion_freq(InversionFreq),
  m_translocation_freq(TranslocationFreq),
  m_asymxover_freq(AsymXOverFreq),
  m_cross_val(CrossVal),
  m_xover_number(0), // FIXME

  m_splice_code_ptr(PtrSpliceCodeInfo),
  m_min_nucleotide_value(UserNukleoMinVal),
  m_max_nucleotide_value(UserNukleoMaxVal),
  m_nucleotide_value_scale(1),
  m_nucleotide_count(Nukleotide)
{
    // StartGene aus dem File holen ! ....
    FILE *file;

    CalcParameter();

    if ((file=fopen(StartGenFile.c_str(),"rb") ) == nullptr ) {
        ABORT("Couldn't open file '%s'", StartGenFile.c_str());
    }
    {
        // 4-7-94, 3:3 PM
        // Liest als erstes die Groesse des abgespeicherten NukleoTyps
        // aus dem File
        uint16_t NukleoLen;
        if (fread (&NukleoLen, sizeof(NukleoLen), 1, file)!=1) {
            ABORT("can't read file %s\n", StartGenFile.c_str());
        }
        if( NukleoLen != sizeof(nucleotide_t) ) {
            std::cerr << "!! ERROR !!\n"
                    << "   Laenge des Datentyps der gespeicherten Nuklotide\n"
                    << "   ist kleiner als das abgespeicherte Format\n";
            exit (0);
        }
        // 4-7-94, 3:3 PM
    }

    // int ChromLen, ChromQuantity, i, j;
    size_type ChromQuantity;
    if (fread(&ChromQuantity, sizeof(ChromQuantity), 1, file)==0) {
        ABORT("can't read file %s\n", StartGenFile.c_str());
    }

    // Puffer der richtigen Laenge bereitstellen
    nucleotide_t value;
    for(size_type j=0; j<ChromQuantity; ++j ) {
        Chromosom Gamma( *this, 0 );
        assert (Gamma.size()==0);

        size_type ChromLen;
        if (fread(&ChromLen, sizeof(ChromLen), 1, file) == 0) {
            ABORT("can't read file %s\n", StartGenFile.c_str());
        } // FIXME: Use fixed width type
        for(size_type i=0; i<ChromLen; ++i) {
            if (fread(&value, sizeof(value), 1, file) == 0) {
                ABORT("can't read file %s\n", StartGenFile.c_str());
            }
            Gamma.push_back(value);
        }
        assert (Gamma.size()==ChromLen);
        push_back(Gamma);
    }
    assert (size()==ChromQuantity);
    fclose (file);
}

Chromosomen::Chromosomen ( nucleotide_t UserNukleoMinVal, nucleotide_t UserNukleoMaxVal,
                           size_type max_chromosom_count,
                           size_type StartChromosomNumber,
                           size_type StartChromosomLength,
                           size_type Nukleotide,
                           SpliceCodeInfo *PtrSpliceCodeInfo,
                           size_type InversionFreq,
                           size_type TranslocationFreq,
                           size_type AsymXOverFreq,
                           size_type CrossVal,
                           size_type MutationFreq,
                           size_type max_no_improving_gens)
: chromosom_array_t(max_chromosom_count),
  m_all_time_best_gen(1),
  m_all_time_best_avrg_fitness(0),
  m_all_time_best(*this),

  m_avrg_fitness(0),
  m_best_fitness(0),
  m_fitness_sum(0),

  m_max_no_improving_gens(max_no_improving_gens),
  m_no_improving_gens(0),

  m_generation(1),
  m_max_chromosom_count(max_chromosom_count),
  m_intro_code_len_sum(0),
  m_spliced_chromosom_count(0),

  m_file_ptk_ptr(nullptr),

  m_generation_start(0),
  m_generation_end(0),
  m_evolution_start(0),
  m_evolution_end(0),

  m_min_chromosom_len(0),
  m_max_chromosom_len(0),
  m_avrg_chromosom_len(0),
  m_chromosom_above_zero_count(0),

  m_mutations_this_gen(0),
  m_inversions_this_gen(0),
  m_translocations_this_gen(0),
  m_mutation_freq(MutationFreq),

  m_inversion_freq(InversionFreq),
  m_translocation_freq(TranslocationFreq),
  m_asymxover_freq(AsymXOverFreq),
  m_cross_val(CrossVal),
  m_xover_number(0), // FIXME

  m_splice_code_ptr(PtrSpliceCodeInfo),
  m_min_nucleotide_value(UserNukleoMinVal),
  m_max_nucleotide_value(UserNukleoMaxVal),
  m_nucleotide_value_scale(1),
  m_nucleotide_count(Nukleotide)
{
    CalcParameter();

    // StartGene zufaellig setzen !
    for (size_type i=0; i<StartChromosomNumber ; ++i) {
        Chromosom Gamma (*this, StartChromosomLength);
        assert (Gamma.size() == StartChromosomLength);
        push_back(Gamma);
    }
    assert (size()==StartChromosomNumber);
}

void Chromosomen::Save (const std::string& FileName) const
{
    FILE *file;

    if((file=fopen(FileName.c_str(), "wb")) == nullptr) {
        ABORT("Couldn't open file '%s'", FileName.c_str());
    }
    {
        // 4-7-94, 2:51 PM
        // Speichert die Groesse des NukleoTyps als erstes im File ab
        const uint16_t NukleoLen=sizeof(nucleotide_t);
        if (fwrite (&NukleoLen, sizeof (NukleoLen), 1, file) != 1) {
            ABORT("can't write to file %s\n", FileName.c_str());
        }
        // 4-7-94, 2:51 PM
    }
    size_type ChromQuantity = size();
    if (fwrite (&ChromQuantity, sizeof (ChromQuantity), 1, file) != 1 ) {
        ABORT("can't write to file %s\n", FileName.c_str());
    }
    for (size_type j=0; j<ChromQuantity; j++ ) {
        const size_type ChromLen = THIS[j].size();
        if (fwrite (&ChromLen, sizeof (ChromLen), 1, file) != 1) {
            ABORT("can't write to file %s\n", FileName.c_str());
        }
        for(size_type i=0; i<ChromLen; ++i) {
            nucleotide_t value = THIS[j][i];
            if (fwrite (&value, sizeof (nucleotide_t), 1, file) != 1) {
                ABORT("can't write to file %s\n", FileName.c_str());
            }
        }
    }
    fclose(file);
}

Chromosomen::size_type Chromosomen::Evolution (double GoalFitness, const std::string& chrptrPtkFile,
			                                   double BirthRate, int Bigamie )
{
    double BestEverAverageFitness = -1,
           Cut = 0; // Der Cut beim Sterben
    bool stop = false;

    InitFitness() ;
    if( !chrptrPtkFile.empty() ) {
        if ((m_file_ptk_ptr=fopen (chrptrPtkFile.c_str(), "wt")) == nullptr) {
            ABORT("Couldn't open file '%s'", chrptrPtkFile.c_str());
        }
    } else {
        m_file_ptk_ptr = nullptr;
    }

    m_evolution_start=time(nullptr);
    m_generation=1;
    m_spliced_chromosom_count=0;
    m_intro_code_len_sum=0;
    m_no_improving_gens = 0;
    Protokoll();
    if( !Echo() ) { stop = true; }

    if( BirthRate <= 0.0 || BirthRate > 1.0 ) { stop = true; }

    while( m_best_fitness < GoalFitness &&
           m_no_improving_gens < m_max_no_improving_gens &&
           !stop )
    {
        m_generation++;
        m_spliced_chromosom_count=0;
        m_intro_code_len_sum=0;
        if( BirthRate < 1.0 ) {
            NewGeneration(BirthRate, Bigamie);
            // Fuer LetDie !!!
            Cut = GetXWorstFitness( size() - m_max_chromosom_count );
        } else {
            NewGeneration(Bigamie);
            Cut = -.5;	// Eltern Fitness auf -1 gesetzt
        }
        // Sterben !!!
        LetDie(Cut);
        // Die Mutation
        Mutation();
        // Fitness berechnen
        CalcWholeFitness();
        // Weitere Mutationen
        InversionsMutation();
        TranslocationsMutation();

        m_generation_end=time(nullptr);

        if( BestEverAverageFitness < m_avrg_fitness ) {
            m_no_improving_gens=0;
            BestEverAverageFitness = m_avrg_fitness ;
        } else {
            m_no_improving_gens++ ;
        }
        Protokoll();
        if(!Echo()) { stop = true; }
    }

    m_evolution_end=time(nullptr);
    Echo();
    Protokoll();

    if (m_file_ptk_ptr != nullptr) { fclose (m_file_ptk_ptr); }

    return m_generation;
}

void Chromosomen::InitFitness()
{
    for (size_type i = 0; i < size(); ++i) {
        Chromosom Neu = THIS[i];
        Neu.Splicing();
        THIS[i].SetFitness(Fitness(Neu));
    }
    CalcWholeFitness();
}

void Chromosomen::NewGeneration(double BirthRate, bool Bigamie)
{
    indexlist_t ElternPaare;

    size_type l = (size_type) ( (double)size() * BirthRate );
    size_type i;

    m_generation_start=time(nullptr);

    // Gerade Anzahl der ElternPaare !!!
    if( l%2 > 0 ) {
        --l;
    }

    // ooops, die letzten beiden Elternpaare sind nicht-bigamistisch SCHLECHT
    // zu finden !!!
    if( 2 <= m_chromosom_above_zero_count && m_chromosom_above_zero_count <= l ) {
        m_chromosom_above_zero_count -= 2;
    }

    // Neue Partner in die ElternPaare-Menge einfuegen
    // "Bigamistische Beziehung" werden, wenn moeglich, nicht erlaubt.
    while(l>0) {
        // Nur NEUE Partner !!!
        if (!Bigamie && ElternPaare.size() < m_chromosom_above_zero_count) {
            do {
                i=RouletteSelect();
            } while( jau::contains(ElternPaare, i) ) ;
            ElternPaare.push_back(i);
            l--;
        } else {
            if (!Bigamie)   {
                // the hard way ...
                do {
                    i = Random<size_type>(0, size()-1);
                } while( jau::contains(ElternPaare, i) ) ;
                ElternPaare.push_back(i);
                l--;
            } else {
                // Bigamistische Beziehung JA, aber sexuell !!!
                size_type w, m;
                ElternPaare.push_back((w = Random<size_type>(0, size()-1))) ;
                while (w == (m=Random<size_type>(0, size()-1))) ;
                ElternPaare.push_back(m) ;
                l-=2;
            }
        }
    };

    l=ElternPaare.size();

    #ifndef NDEBUG
        // alles ok ?? GERADE ELTERNPAARE ????
        assert( l%2==0 );
        assert( l== ( (size_type)( size() * BirthRate ) % 2 ) ?
                    (size_type)( size() * BirthRate ) - 1 :
                    (size_type)( size() * BirthRate )
        );
    #endif

    // Fortpflanzen !!!
    while (l > 1) {
        CrossingOver (ElternPaare[l-1], ElternPaare[l-2]);
        l -= 2 ;
    }
    assert (l == 0);
}


void Chromosomen::NewGeneration(bool Bigamie)
{
    indexlist_t ElternPaare;
    size_type l = m_max_chromosom_count;

    m_generation_start=time(nullptr);

    // Gerade Anzahl der ElternPaare !!!
    if( l%2 > 0 ) {
        --l;
    }

    // ooops, die letzten beiden Elternpaare sind nicht-bigamistisch SCHLECHT
    // zu finden !!!
    if( 2 <= m_chromosom_above_zero_count && m_chromosom_above_zero_count <= l ) {
        m_chromosom_above_zero_count -= 2;
    }

    // Neue Partner in die ElternPaare-Menge einfuegen
    // "Bigamistische Beziehung" werden, wenn moeglich, nicht erlaubt.
    while( l > 0 ) {
        // Nur NEUE Partner !!!
        if( !Bigamie && ElternPaare.size() < m_chromosom_above_zero_count ) {
            size_type i;
            do {
                i = RouletteSelect();
            } while ( jau::contains(ElternPaare, i) ) ;
            ElternPaare.push_back(i);
            l--;
        } else {
            if( !Bigamie ) {
                size_type i;
                do {
                    i = Random<size_type>(0, size()-1);
                } while( jau::contains(ElternPaare, i) ) ;
                ElternPaare.push_back(i);
                l--;
            } else { // Bigamistische Beziehung JA, aber sexuell !!!
                size_type w, m;
                ElternPaare.push_back( ( w = Random<size_type>(0, size()-1) ) );
                while( w == ( m = Random<size_type>(0, size()-1) ) ) ;
                ElternPaare.push_back(m);
                l-=2;
            }
        }
    };

    l=ElternPaare.size();

    // alles ok ?? GERADE ANZAHL DER ELTERN !!!
    assert (l%2==0);
    (void)l;

    // Neue Population...
    l=ElternPaare.size();
    while (l > 1) {
        // Beim Crossing Over werden die Nachkommen am Ende der Populations-Liste
        // eingefuegt.
        // Die Indizes fuer die ElternPaare bleiben somit aktuell !!!
        CrossingOver (ElternPaare[l-1], ElternPaare[l-2]);
        l-=2;
    }

    // Eltern markieren, damit sie "getoetet" werden koennen !!!
    // Das geschied in 'LetDie', Aufruf in Evolution
    l=ElternPaare.size()-1;
    while (l > 0) {
        const size_type w=ElternPaare[l-1];
        // markieren !!!
        THIS[w].SetFitness(-1);
        l--;
    }
}

void Chromosomen::LetDie(double cut)
{
    size_type i=0;

    while (i < size() && size() > m_max_chromosom_count) {
        if (THIS[i].GetFitness() <= cut) {
            Kill (i);
        } else {
            ++i;
        }
    }

    // Sicherheitsabfrage
    if (size() > m_max_chromosom_count) {
        cut = GetXWorstFitness (size()-m_max_chromosom_count);
        i = 0;
        while (i < size() && size() > m_max_chromosom_count) {
            if (THIS[i].GetFitness() <= cut) {
                Kill (i);
            } else {
                ++i;
            }
        }
    }
    assert (size() <= m_max_chromosom_count);
}

Chromosomen::size_type Chromosomen::RouletteSelect() const
// Chris: geaendert
{
    size_type i;

    double Sum       = 0.0;
    const double Threshold = Random (0.0, 1.0) * GetFitnessSum();

    // Aufgrund der Ungenauigkeit der Flieskommaoperatoren
    // muss auch das Ende der Liste abgefragt werden.
    for (i=0; Sum < Threshold && i<size(); ++i) {
        Sum += THIS[i].GetFitness();
    }
    return ( i < size() ) ? i : size()-1;
}

void Chromosomen::CreateNewSymChromosom ( Chromosom &dest, size_type m, size_type w,
                                          crosspoints_t &CrossPoints )
{
    // i          : Indize des Crosspoints
    // von, bis   : Zu Uebertragender Chromosomenabschnitt [von..bis[
    // ch         : Alternierendes Indize zwischen den beiden Chromosomen
    //              mit den Geschlechtern 'm' und 'w'
    // done       : Abbruch Indikator
    bool done = false;
    size_type i, von, bis, ch;

    // Startwerte !!
    i = bis = 0;
    ch = w;

    dest.reserve( THIS[ch].size() );

    do {
        // An dem letzten exklusiven Ende fortfahren
        von = bis;
        if ( i < CrossPoints.size() ) {
            // Chromosomenabschnitt-Ende holen.
            if( CrossPoints[i] < THIS[ch].size() ) bis = CrossPoints[i];
            else                                   bis = THIS[ch].size();
            ++i;
        } else {
            // ...und den Rest uebertragen
            bis = THIS[ch].size();
            done = true;
        }
        assert ( bis <= THIS[ch].size() );
        assert ( von == dest.size() );
        // Chromosomenabschnitt uebertragen [von..bis[
        for (size_type n=von; n<bis; n++) {
            dest.insert(n, THIS[ch][n]);
        }
        // Indize zwischen den Geschlechtern alternieren
        ch = ( ch==m ? w : m ) ;
    } while ( !done );

    // ...sonst Fehler !!!
    assert( dest.size() > 0 );
}

void Chromosomen::CrossingOver (size_type m, size_type w)
{
    if ( m_cross_val == 0 ) { return; }

    size_type shortest=( ( THIS[m].size() < THIS[w].size() ) ? m : w);

    if ( m_xover_number++ < m_asymxover_freq || m_asymxover_freq==0 ) {
        // Symmetrisches XOver !!!
        crosspoints_t CrossPoints;
        assert( CrossPoints.size()==0 );

        // Kreuzungspunkte sortiert eintragen.
        for ( size_type i = 0; i < m_cross_val; ++i ) {
            CrossPoints.insert( Random<size_type>(0 , THIS[shortest].size()) );
        }

        Chromosom NeuA (*this, 0);
        Chromosom NeuB (*this, 0);
        size_type SplicedCode;

        CreateNewSymChromosom ( NeuA, m, w, CrossPoints );
        push_back( NeuA );
        SplicedCode=NeuA.Splicing();
        if(SplicedCode>0) {
            m_spliced_chromosom_count++;
            m_intro_code_len_sum+=SplicedCode;
        }
        // Die Fitness des gespleissten Chromosomes in das ungespleisste
        // eingebundene Chromosom einsetzen !!!
        THIS[size()-1].SetFitness(Fitness(NeuA));

        CreateNewSymChromosom ( NeuB, w, m, CrossPoints );
        push_back( NeuB );
        SplicedCode=NeuB.Splicing();
        if(SplicedCode>0) {
            m_spliced_chromosom_count++;
            m_intro_code_len_sum+=SplicedCode;
        }
        // Die Fitness des gespleissten Chromosomes in das ungespleisste
        // eingebundene Chromosom einsetzen !!!
        THIS[size()-1].SetFitness(Fitness(NeuB));

    } else {

        m_xover_number = 0;
        // Assymetrisches XOver : Nur ein neues Element !
        Chromosom Neu (*this, 0);

        // Kopieren
        Neu=THIS[m];

        // anhaengen
        for (size_type n=0; n<THIS[w].size(); n++) {
            Neu.push_back( THIS[w][n] );
        }
        Neu.SetFitness(Fitness(Neu));
        push_back( Neu );

    }
}

void Chromosomen::Mutation()
{
    static size_type next_nukleotide_idx = m_mutation_freq + Random<size_type>( 0, (size_type)(m_mutation_freq/m_mutation_freq_variance) ) ;
    m_mutations_this_gen=0;

    if ( m_mutation_freq > 0 ) {
        size_type nukleotide_idx = next_nukleotide_idx;
        for(size_type chromosom_idx = 0; chromosom_idx < size(); ++chromosom_idx ) {
            bool mutated = false;
            const size_type chromosom_len = THIS[chromosom_idx].size();
            while( nukleotide_idx < chromosom_len ) {
                // Die Mutation.
                (THIS[chromosom_idx])[nukleotide_idx] = Random<size_type>( m_min_nucleotide_value, m_max_nucleotide_value);
                m_mutations_this_gen++;
                mutated=true;
                nukleotide_idx += m_mutation_freq + Random<size_type>( 0, (size_type)(m_mutation_freq/m_mutation_freq_variance) );
            }
            if( nukleotide_idx >= chromosom_len ) {
                nukleotide_idx -= chromosom_len;
            }
            if(mutated) {
                // Fitness neuberechnen ...
                // ... this is a social event - we are hard folks :-)
                Chromosom Neu (THIS[chromosom_idx]);
                Neu.Splicing();
                THIS[chromosom_idx].SetFitness(Fitness(Neu));
            }
        }
        next_nukleotide_idx = nukleotide_idx;
    }
}


void Chromosomen::InversionsMutation()
{
    static size_type next_chromosomen_idx = m_inversion_freq;
    m_inversions_this_gen=0;
    size_type chromosomen_idx = next_chromosomen_idx;
    while( chromosomen_idx < size() ) {
        m_inversions_this_gen++;
        THIS[chromosomen_idx].Inversion();
        // Fitness neuberechnen ...
        Chromosom Neu (THIS[chromosomen_idx]);
        Neu.Splicing();
        THIS[chromosomen_idx].SetFitness(Fitness(Neu));
        chromosomen_idx += m_inversion_freq;
    }
    if( chromosomen_idx >= size() ) {
        chromosomen_idx -= size();
    }
    next_chromosomen_idx = chromosomen_idx;
}

void Chromosomen::TranslocationsMutation()
{
    static size_type next_chromosomen_idx = m_translocation_freq;
    m_translocations_this_gen=0;
    size_type chromosomen_idx = next_chromosomen_idx;
    while( chromosomen_idx < size() ) {
        m_translocations_this_gen++;
        THIS[chromosomen_idx].Translocation();
        // Fitness neuberechnen ...
        Chromosom Neu (THIS[chromosomen_idx]);
        Neu.Splicing();
        THIS[chromosomen_idx].SetFitness(Fitness(Neu));
        chromosomen_idx += m_translocation_freq;
    }
    if( chromosomen_idx >= size() ) {
        chromosomen_idx -= size();
    }
    next_chromosomen_idx = chromosomen_idx;
}

void Chromosomen::CalcWholeFitness()
{
    double Total=0, TempFitness;
    size_type BestChrom=npos, ChromLen;
    size_type ChromLenSum=0;

    m_min_chromosom_len = std::numeric_limits<size_type>::max();
    m_max_chromosom_len = std::numeric_limits<size_type>::min();
    m_best_fitness = -1;
    m_chromosom_above_zero_count = 0;

    for (size_type i = 0; i < size(); ++i) {
        ChromLen = THIS[i].size();
        ChromLenSum += ChromLen;
        if( m_min_chromosom_len > ChromLen ) { m_min_chromosom_len=ChromLen; }
        if( m_max_chromosom_len < ChromLen ) { m_max_chromosom_len=ChromLen; }
        if( ( TempFitness = THIS[i].GetFitness() ) > 2*std::numeric_limits<double>::epsilon() ) {
            m_chromosom_above_zero_count++ ;
        }
        Total += TempFitness ;
        if( m_best_fitness < TempFitness ) {
            m_best_fitness = TempFitness;
            BestChrom = i;
        }
    }
    m_avrg_fitness = Total / (double)size();
    m_fitness_sum = Total;
    m_avrg_chromosom_len = (double)ChromLenSum/(double)size();
    if( m_all_time_best.GetFitness() < m_best_fitness && npos != BestChrom) {
        m_all_time_best=THIS[BestChrom];
        m_all_time_best.Splicing();
    }
    if (m_all_time_best_avrg_fitness < m_avrg_fitness) {
        m_all_time_best_avrg_fitness = m_avrg_fitness;
        m_all_time_best_gen = m_generation;
    }
}

Chromosomen::size_type Chromosomen::GetWorstChromosom() const
{
    double WorstFitness=2, TempFitness;
    size_type iw = npos;

    for (size_type i=0; i<size(); ++i) {
        TempFitness=THIS[i].GetFitness();
        if (WorstFitness > TempFitness) {
            WorstFitness = TempFitness ;
            iw=i;
        }
    }
    return iw;
}

double Chromosomen::GetXWorstFitness(size_type count) const
{
    doubles_sorted_t Worst;

    if (count == 0) { return -1; } // Falsche Anzahl uebergeben
    for (size_type i=0; i<size(); ++i) {
        if( Worst.size() < count ||
            THIS[i].GetFitness() < Worst[count-1] ) 
        {
            Worst.insert(THIS[i].GetFitness());
        }
    }
    if (Worst.size() >= count) {
        return Worst[count-1];
    } else {
        return Worst[Worst.size()-1];
    }
}

Chromosomen::size_type Chromosomen::GetBestChromosom() const
{
    double BestFitness=-1, TempFitness;
    size_type ib = npos;

    for (size_type i=0; i<size(); ++i) {
        TempFitness=THIS[i].GetFitness();
        if (BestFitness < TempFitness) {
            BestFitness = TempFitness ;
            ib=i;
        }
    }
    return ib;
}

const Chromosom &Chromosomen::GetTheBestEverChromosom()
// Hier kein kein Slicing mehr, da beim abspeichern des besten
// Chromosoms in der Variablen 'TheBestEver' der Code schon
// gesplict abgespeichert wird.
{
  return (const Chromosom&) m_all_time_best;
}

void Chromosomen::CalcParameter()
{
    if (m_splice_code_ptr==nullptr ||
        m_splice_code_ptr->SpliceCode==nullptr ||
        m_splice_code_ptr->SpliceCode[0]==0 )
    {
        // Ohne Splicing ....
        m_nucleotide_count=0;
        m_nucleotide_value_scale=1;
    } else {
        if (m_splice_code_ptr->Length ==0) {
            // Laenge berechnen ...
            int i;

            for (i=0; m_splice_code_ptr->SpliceCode[i]!=0; ++i) {
                m_splice_code_ptr->Length ++;
            }
            for (++i; m_splice_code_ptr->SpliceCode[i]!=0; ++i) {
                m_splice_code_ptr->Length ++;
            }
        }
        if(m_nucleotide_count>0) {
            m_nucleotide_value_scale = ( m_max_nucleotide_value - m_min_nucleotide_value + 1 ) / m_nucleotide_count ;
        } else {
            m_nucleotide_value_scale = 1;
        }
    }
}

void Chromosomen::Protokoll()
{
    double SpliceCodePerChrom ;

    SpliceCodePerChrom = ( m_spliced_chromosom_count > 0 ) ?
                         ( (double)m_intro_code_len_sum / (double)m_spliced_chromosom_count )
                         : 0.0;

    if (m_file_ptk_ptr != nullptr) {
        if (m_evolution_end == 0) {
            fprintf (m_file_ptk_ptr, "=======================================================\n\n\n");
            fprintf (m_file_ptk_ptr, "\nGeneration / Generierungsdauer        : %3zu  /  %zu s\n",
                    (size_t)m_generation, (size_t)(m_generation_end-m_generation_start) );
            fprintf (m_file_ptk_ptr, "Populationsgroesse                    : %3zu\n",
                    (size_t)size());
            fprintf (m_file_ptk_ptr, "Chromosomen Laenge Minimum            : %3zu\n",
                    (size_t)m_min_chromosom_len);
            fprintf (m_file_ptk_ptr, "Chromosomen Laenge Maximum            : %3zu\n",
                    (size_t)m_max_chromosom_len);
            fprintf (m_file_ptk_ptr, "Chromosomen Laenge Durchschnitt       : %10.6lf\n",
                    m_avrg_chromosom_len);
            fprintf (m_file_ptk_ptr, "Gespleisste Chromosomen               : %3zu\n",
                    (size_t)m_spliced_chromosom_count);
            fprintf (m_file_ptk_ptr, "Gespleisstes Code pro Chromosom       : %10.6lf\n",
                    SpliceCodePerChrom);

            fprintf (m_file_ptk_ptr, "\nBestFitness                           : %10.6lf\n",
                    m_best_fitness);
            fprintf (m_file_ptk_ptr, "Average Fitness                       : %10.6lf\n",
                    m_avrg_fitness);

            fprintf (m_file_ptk_ptr, "\nMutationen dieser Generation          : %3zu\n",
                    (size_t)m_mutations_this_gen);
            fprintf (m_file_ptk_ptr, "Inversionen dieser Generation         : %3zu\n",
                    (size_t)m_inversions_this_gen);
            fprintf (m_file_ptk_ptr, "Translokationen dieser Generation     : %3zu\n",
                    (size_t)m_translocations_this_gen);
            fprintf (m_file_ptk_ptr, "\nTheBestEverFitness                    : %10.6lf\n",
                    m_all_time_best.GetFitness());
            fprintf (m_file_ptk_ptr, "TheBestEversAverageFitness            : %10.6lf\n",
                    m_all_time_best_avrg_fitness);
            fprintf (m_file_ptk_ptr, "TheBestEversGeneration                : %3zu\n\n",
                    (size_t)m_all_time_best_gen);
        } else {
            if(m_generation>1) {
                fprintf (m_file_ptk_ptr, "Avrg. Generationsdauer                  : %f s / Generation\n",
                        ((double) (m_evolution_end-m_evolution_start))/((double)(GetGeneration()-1)) );
            }
            fprintf (m_file_ptk_ptr, "\nGenerationen / Evolutionsdauer        : %3zu /  %zu s\n",
                    (size_t)m_generation, (size_t)(m_evolution_end-m_evolution_start));
        }
    }
}

bool Chromosomen::Echo() const
{
    if (m_generation == 1) {
        printf(" Generation: BestGeneration: AverageFitness: BestFitness:"
                " TheBestLength:\n");
    }
    printf("\r%11zu%16zu%16.9lf%13.9lf%15zu",
            (size_t)GetGeneration(), (size_t)m_all_time_best_gen,
            GetAverageFitness(), GetBestFitness(),
            (size_t)m_all_time_best.size() );

    if (m_evolution_end > 0) {
        if (m_generation > 1) {
            printf ("\n\nAvrg. Generationsdauer                : %f s / Generation\n",
                    ((double)(m_evolution_end-m_evolution_start))/((double)(GetGeneration()-1)) );

        }
        printf ("\n\nGenerationen / Evolutionsdauer        : %3zu  /  %3zu s\n",
                (size_t)m_generation, (size_t)(m_evolution_end-m_evolution_start));
    }
    return true;
}

void Chromosom::Ausgabe (std::ostream& OS) const noexcept
{
    const int Zeilenlaenge = 10;

    OS << "( l " << size() << ", f "
       << ( ( GetFitness() < std::numeric_limits<double>::epsilon() ) ? (double)(0) : GetFitness() )
       << " ) < ";
    for (size_type i=0; i<size(); ++i) {
        if (i % Zeilenlaenge == 0 &&  i) {
            OS << "\n\t";
        }
        double wandler = THIS[i];
        OS << wandler;
        if (i % Zeilenlaenge != Zeilenlaenge-1 && i != size()-1) {
            OS << ", ";
        }
    }
    OS << " >";
}

void Chromosomen::Ausgabe (std::ostream& OS) const noexcept
{
    const int Zeilenlaenge = 7;

    OS << "( " << size() << " ) < ";
    for (size_type i=0; i<size(); ++i) {
        if (i % Zeilenlaenge == 0 &&  i) {
            OS << "\n\t";
        }
        OS << ( ( THIS[i].GetFitness() < std::numeric_limits<double>::epsilon() ) ? (double)(0) : THIS[i].GetFitness() );
        if (i % Zeilenlaenge != Zeilenlaenge-1 && i != size()-1) {
            OS << ", ";
        }
    }
    OS << " >";
}

/*
std::ostream& operator << (std::ostream& OS, Liste<NukleoTyp>& Ch)
{
  Ch.Ausgabe (OS);
  return OS;
}
*/
# ifdef TEST
    // Der Testteil
    # include "error.cpp"
    # include "maschine.cpp"

    int main()
    {
      Chromosom test1(0, 4, 5, nullptr, 50), test2(0, 4, 5, nullptr, 60);

      randomize();
      if (test1 == test1)
	cout << "\ntest2\n" << test2;
      else
	cerr << "\nopps: Operator \"==\" arbeitet nicht korekt !!";

      if (test1 != test2)
	cout << "\ntest1\n" << test1;
      else
	cerr << "\nopps: Operator \"!=\" arbeitet nicht korekt !!";

      test2 = test1;
      getch();

      if (test2 == test1)
	cout << "\ntest2 nach Zuweisung\n" << test2;
      else
	cerr << "\nopps: Operator \"==\" arbeitet nicht korekt !!";

      while (!kbhit())  {
	Chromosom test3(0, Random (0, 10), 5, nullptr, Random (30, 50));
	cout << endl << test3;
	getch();
      }
      return 0;
    }
# endif