source: cpp/frams/genetics/genman.cpp @ 792

Last change on this file since 792 was 780, checked in by Maciej Komosinski, 7 years ago

Added sources for genetic encodings fB, fH, fL

  • Property svn:eol-style set to native
File size: 22.5 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[761]2// Copyright (C) 1999-2018  Maciej Komosinski and Szymon Ulatowski.
[286]3// See LICENSE.txt for details.
[138]4
5#include "genman.h"
6#include <frams/vm/classes/genoobj.h>
7#include GEN_CONFIG_FILE //configuration of active genetic operators
[375]8#include "common/log.h"
[138]9#include "common/nonstd_math.h"
[200]10#include "common/stl-util.h"
[391]11#include <common/loggers/loggers.h>
[138]12
13
[768]14#define GENMAN_REPEAT_FAILED 100 //how many times GenMan tries to repeat a mutation or crossover when the operator does not return acceptable genotype
[761]15#define STRINGIFY_1(x) #x
16#define STRINGIFY(x) STRINGIFY_1(x) //this second-level macro allows the parameter to be a macro itself and to stringify its value, not its name
17#define GENMAN_REPEAT_FAILED_STR STRINGIFY(GENMAN_REPEAT_FAILED)
18
19
[139]20#ifdef USE_GENMAN_f0
[779]21#include "f0/f0_oper.h"
[138]22#endif
[139]23#ifdef USE_GENMAN_f0FUZZY
[779]24#include "f0/f0Fuzzy_oper.h"
[138]25#endif
[139]26#ifdef USE_GENMAN_f1
[779]27#include "f1/f1_oper.h"
[138]28#endif
[139]29#ifdef USE_GENMAN_f2
[779]30#include "f2/f2_oper.h"
[138]31#endif
[139]32#ifdef USE_GENMAN_f2
[779]33#include "f3/f3_oper.h"
[138]34#endif
[139]35#ifdef USE_GENMAN_f4
[779]36#include "f4/f4_oper.h"
[138]37#endif
[139]38#ifdef USE_GENMAN_f5
[779]39#include "f5/f5_oper.h"
[138]40#endif
[139]41#ifdef USE_GENMAN_f6
[779]42#include "f6/f6_oper.h"
[138]43#endif
[139]44#ifdef USE_GENMAN_f7
[779]45#include "f7/f7_oper.h"
[138]46#endif
[139]47#ifdef USE_GENMAN_f8
[779]48#include "f8/f8_oper.h"
[138]49#endif
[139]50#ifdef USE_GENMAN_f9
[779]51#include "f9/f9_oper.h"
[138]52#endif
[139]53#ifdef USE_GENMAN_fF
[779]54#include "fF/fF_oper.h"
[139]55#endif
[748]56#ifdef USE_GENMAN_fn
[779]57#include "fn/fn_oper.h"
[748]58#endif
[194]59#ifdef USE_GENMAN_fT
[779]60#include "fT/fTest_oper.h"
[194]61#endif
[780]62#ifdef USE_GENMAN_fB
63#include "fB/fB_oper.h"
64#endif
65#ifdef USE_GENMAN_fH
66#include "fH/fH_oper.h"
67#endif
68#ifdef USE_GENMAN_fL
69#include "fL/fL_oper.h"
70#endif
[138]71
72using namespace std; //string, vector
73
74//old code needs update:
75//#include "gengroups.h"
76//extern GenGroup *listaGen;
77//   GENGROUP(0)->l_del.add(sim->GM.onDelGen,&sim->GM); //before delete
78//   GENGROUP(0)->l_del.remove(sim->GM.onDelGen,&sim->GM); //before delete
79
80
81#define FIELDSTRUCT GenMan
82
83static ParamEntry GMparam_tab[] =
84{
85        { "Genetics", 1, 10, "GenMan", },
86        { "gen_hist", 0, PARAM_DONTSAVE, "Remember history of genetic operations", "d 0 1 0", FIELD(history), "Required for phylogenetic analysis", },
87        { "gen_hilite", 0, 0, "Use syntax highlighting", "d 0 1 1", FIELD(hilite), "Use colors for genes?\n(slows down viewing/editing of huge genotypes)", },
88        { "gen_extmutinfo", 0, 0, "Extended mutation info", "d 0 2 0 ~Off~Method ID~Method description", FIELD(extmutinfo), "If active, information about employed mutation method will be stored in the 'info' field of each mutated genotype.", },
89        { "operReport", 0, PARAM_DONTSAVE, "Operators report", "p()", PROCEDURE(p_report), "Show available genetic operators", },
90        { "toHTML", 0, PARAM_DONTSAVE, "HTMLize a genotype", "p s(s)", PROCEDURE(p_htmlize), "returns genotype expressed as colored HTML", },
91        { "toHTMLshort", 0, PARAM_DONTSAVE, "HTMLize a genotype, shorten if needed", "p s(s)", PROCEDURE(p_htmlizeshort), "returns genotype (abbreviated if needed) expressed as colored HTML", },
[240]92        { "validate", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Validate", "p oGeno(oGeno)", PROCEDURE(p_validate), "returns validated (if possible) Geno object from supplied Geno", },
93        { "mutate", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Mutate", "p oGeno(oGeno)", PROCEDURE(p_mutate), "returns mutated Geno object from supplied Geno", },
94        { "crossOver", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Crossover", "p oGeno(oGeno,oGeno)", PROCEDURE(p_crossover), "returns crossed over genotype", },
[668]95        { "getSimplest", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Get simplest genotype", "p oGeno(s format)", PROCEDURE(p_getsimplest), "returns the simplest genotype for a given encoding (format). \"0\" means f0, \"4\" means f4, etc.", },
[138]96        { 0, },
97};
98
99static ParamEntry GMstats_tab[] =
100{
101        { "Genetics", 1, 12, "GenManStats", "Statistics for genetic operations." },
102        { "gen_count", 0, PARAM_READONLY, "Number of genetic operations so far", "d", FIELD(count), "", },
103        { "gen_mvalid", 0, PARAM_READONLY, "Mutations valid", "d", FIELD(valid_m), "", },
104        { "gen_mvalidated", 0, PARAM_READONLY, "Mutations validated", "d", FIELD(validated_m), "", },
105        { "gen_minvalid", 0, PARAM_READONLY, "Mutations invalid", "d", FIELD(invalid_m), "couldn't be repaired", },
106        { "gen_mfailed", 0, PARAM_READONLY, "Mutations failed", "d", FIELD(failed_m), "couldn't be performed", },
107        { "gen_xovalid", 0, PARAM_READONLY, "Crossovers valid", "d", FIELD(valid_xo), "", },
108        { "gen_xovalidated", 0, PARAM_READONLY, "Crossovers validated", "d", FIELD(validated_xo), "", },
109        { "gen_xoinvalid", 0, PARAM_READONLY, "Crossovers invalid", "d", FIELD(invalid_xo), "couldn't be repaired", },
110        { "gen_xofailed", 0, PARAM_READONLY, "Crossovers failed", "d", FIELD(failed_xo), "couldn't be performed", },
111        { "gen_mutimpr", 0, PARAM_READONLY, "Mutations total effect", "f", FIELD(mutchg), "total cumulative mutation change", },
112        { "gen_xoimpr", 0, PARAM_READONLY, "Crossovers total effect", "f", FIELD(xochg), "total cumulative crossover change", },
113        { "clrstats", 0, PARAM_DONTSAVE, "Clear stats and history", "p()", PROCEDURE(p_clearStats), "", },
114        { 0, },
115};
116
117#undef FIELDSTRUCT
118
119GenMan::GenMan() : localpar(GMparam_tab, this), localstats(GMstats_tab, this),
120seloperpar("GenOperators", "Genetics: Active operators"),
[319]121neuronsparam("Genetics: Neurons to add", "neuronsAdd", "neuadd_"),
122par("GenMan", "Manages various genetic operations, using appropriate operators for the argument genotype format.")
[138]123{
124        history = 0;
125        hilite = 1;
126        clearStats();
127
[139]128#ifdef USE_GENMAN_f0
[145]129        oper_fx_list.push_back(new Geno_f0);
[138]130#endif
[139]131#ifdef USE_GENMAN_f0FUZZY
[145]132        oper_fx_list.push_back(new Geno_f0Fuzzy);
[138]133#endif
[139]134#ifdef USE_GENMAN_f1
[145]135        oper_fx_list.push_back(new Geno_f1);
[138]136#endif
[139]137#ifdef USE_GENMAN_f2
[145]138        oper_fx_list.push_back(new Geno_f2);
[138]139#endif
[139]140#ifdef USE_GENMAN_f3
[145]141        oper_fx_list.push_back(new Geno_f3);
[138]142#endif
[139]143#ifdef USE_GENMAN_f4
[145]144        oper_fx_list.push_back(new Geno_f4);
[138]145#endif
[139]146#ifdef USE_GENMAN_f5
[145]147        oper_fx_list.push_back(new Geno_f5);
[138]148#endif
[139]149#ifdef USE_GENMAN_f6
[145]150        oper_fx_list.push_back(new Geno_f6);
[138]151#endif
[139]152#ifdef USE_GENMAN_f7
[145]153        oper_fx_list.push_back(new Geno_f7);
[138]154#endif
[139]155#ifdef USE_GENMAN_f8
[145]156        oper_fx_list.push_back(new Geno_f8);
[138]157#endif
[139]158#ifdef USE_GENMAN_f9
[145]159        oper_fx_list.push_back(new GenoOper_f9);
[138]160#endif
[139]161#ifdef USE_GENMAN_fF
[145]162        oper_fx_list.push_back(new GenoOper_fF);
[139]163#endif
[748]164#ifdef USE_GENMAN_fn
165        oper_fx_list.push_back(new GenoOper_fn);
166#endif
[194]167#ifdef USE_GENMAN_fT
168        oper_fx_list.push_back(new GenoOper_fTest);
169#endif
[780]170#ifdef USE_GENMAN_fB
171        oper_fx_list.push_back(new Geno_fB);
172#endif
173#ifdef USE_GENMAN_fH
174        oper_fx_list.push_back(new Geno_fH);
175#endif
176#ifdef USE_GENMAN_fL
177        oper_fx_list.push_back(new Geno_fL);
178#endif
[138]179
[145]180        seloper = new int[oper_fx_list.size()]; //may result in a little overhead if some of the operators on the oper_fx_list concern the same genetic format
[138]181        int selopercount = 0;
[145]182        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
[138]183        {
[145]184                if (operformats.find(oper_fx_list[i]->supported_format) != -1) continue;
[200]185                string type = string("~") + oper_fx_list[i]->name;
[138]186                int dup = 0;
[145]187                for (unsigned int j = i + 1; j < oper_fx_list.size(); j++)
188                        if (oper_fx_list[i]->supported_format == oper_fx_list[j]->supported_format)
[138]189                        {
[761]190                        type += "~";
191                        type += oper_fx_list[j]->name;
192                        dup++;
[138]193                        }
[200]194                type = ssprintf("d 0 %d ", dup) + type;
195                string id = ssprintf("genoper_f%c", oper_fx_list[i]->supported_format);
196                string name = ssprintf("Operators for f%c", oper_fx_list[i]->supported_format);
[138]197                seloper[selopercount] = 0;
[145]198                operformats += oper_fx_list[i]->supported_format;
[138]199                //printf("%x %s %s %s\n",&seloper[selopercount],(const char*)id,(const char*)type,(const char*)name);
[200]200                seloperpar.addProperty(&seloper[selopercount++], id.c_str(), type.c_str(), name.c_str(), "", PARAM_READONLY*(dup == 0));
[138]201        }
202
203        par += &localpar;
204        par += &seloperpar;
205        par += &neuronsparam;
[145]206        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
207                if (oper_fx_list[i]->par.getParamTab()) par += &oper_fx_list[i]->par;
[715]208
209        setDefaults(); //use Param to initialize all values of fields in the paramtab of this object and genetic operators on oper_fx_list
[138]210}
211
212GenMan::~GenMan()
213{
[145]214        for (unsigned int i = 0; i < oper_fx_list.size(); i++) delete oper_fx_list[i];
[138]215        delete[] seloper;
216}
217
218void GenMan::setDefaults()
219{
[145]220        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
[138]221        {
[145]222                oper_fx_list[i]->par.setDefault();
223                oper_fx_list[i]->setDefaults();
[138]224        }
225        localpar.setDefault();
226        //...and we do not reset others that are linked to 'par',
227        //because there quite a few of them, and not every of them defines defaults for each of its parameters.
228}
229
230int GenMan::testValidity(Geno &g, bool &canvalidate)
231{
[761]232        SString ggs = g.getGenes();
[348]233        const char *gg = ggs.c_str();
[145]234        GenoOperators *gf = getOper_f(g.getFormat());
[138]235        int check1;
236        if (!gf) { canvalidate = false; return GENOPER_NOOPER; }
[761]237        else check1 = gf->checkValidity(gg, g.getName().c_str());
[138]238        if (!canvalidate) return check1; //just checking
239        if (check1 == GENOPER_OK) { canvalidate = false; return check1; }
240        char *g2 = strdup(gg);
[761]241        if (gf->validate(g2, g.getName().c_str()) == GENOPER_NOOPER) { free(g2); canvalidate = false; return check1; }
[138]242        if (check1 == GENOPER_NOOPER) //disaster: cannot check because there is no check operator
243        {
[534]244                g.setGenesAssumingSameFormat(g2); free(g2); canvalidate = false; return GENOPER_NOOPER;
[138]245        }
[513]246        int check2 = gf->checkValidity(g2, "validated");
[534]247        if (check2 == GENOPER_OK) g.setGenesAssumingSameFormat(g2);
[138]248        free(g2);
249        if (check2 == GENOPER_OK) return check1;
250        canvalidate = false;
251        return check1; //could not validate.
252}
253
254int GenMan::testGenoValidity(Geno& g)
255{
256        bool fix = false;
257        switch (testValidity(g, fix))
258        {
259        case GENOPER_OK: return 1;
260        case GENOPER_NOOPER: return -1;
261        default: return 0;
262        }
263}
264
[532]265Geno GenMan::validate(const Geno& geny)
[138]266{
[168]267        char format = geny.getFormat();
268        GenoOperators *gf = getOper_f(format);
269        if (gf == NULL)
270                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: Validate(): don't know how to handle genetic format %c", format));
[534]271        char *g2 = strdup(geny.getGenes().c_str()); //copy for validation
[513]272        int res = gf->validate(g2, geny.getName().c_str());
[168]273        SString sg2 = g2;
[138]274        free(g2);
[168]275        if (res == GENOPER_OK)
276                return Geno(sg2, format, geny.getName(), geny.getComment());
[138]277        else
[168]278                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: validate() for format %c returned invalid value", format));
[138]279}
280
[532]281Geno GenMan::mutate(const Geno& g)
[138]282{
283        float chg; //how many changes
284        int method; //mutation method
[168]285        char format = g.getFormat();
286        GenoOperators *gf = getOper_f(format);
287        if (gf == NULL)
288                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: Mutate(): don't know how to handle genetic format %c", format));
289        Geno gv = g;
290        bool canvalidate = true;
291        if (testValidity(gv, canvalidate) > 0 && canvalidate == false)
292                return Geno("", -1, "", "GENOPER_OPFAIL: Mutate(): cannot validate invalid source genotype");
293        bool ok = false;
294        int pcount = count;
[138]295        while (!ok)
296        {
[534]297                char *gn = strdup(gv.getGenes().c_str()); //copy for mutation
[168]298                chg = 0;
299                if (gf->mutate(gn, chg, method) == GENOPER_OK)
[138]300                {
[375]301                        LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
[168]302                        Geno G(gn, gv.getFormat(), "", "");
303                        canvalidate = true;
304                        int res = testValidity(G, canvalidate);
305                        if (res == GENOPER_OK && canvalidate == false) { valid_m++; ok = true; }
306                        else
307                                if (res > 0 && canvalidate == false) invalid_m++; else
308                                {
[761]309                                validated_m++; ok = true;
[168]310                                }
311                        if (ok) gv = G;
312                }
313                else failed_m++;
[138]314                free(gn);
315                count++;
[761]316                if (!ok && (count - pcount > GENMAN_REPEAT_FAILED))
[138]317                {
[761]318                        logPrintf("GenMan", "Mutate", 2, "Tried " GENMAN_REPEAT_FAILED_STR "x and failed: %s", g.getGenes().c_str());
319                        return Geno("", -1, "", "GENOPER_OPFAIL: Mutate() tried " GENMAN_REPEAT_FAILED_STR "x and failed");
[138]320                }
321        }
[168]322        mutchg += chg;
[534]323        if (history) saveLink(g.getGenes().c_str(), "", gv.getGenes().c_str(), chg);
[138]324        SString mutinfo;
[348]325        if (extmutinfo == 0) mutinfo = SString::sprintf("%.2f%% mutation of '%s'", 100 * chg, g.getName().c_str()); else
326                if (extmutinfo == 1) mutinfo = SString::sprintf("%.2f%% mutation(%d) of '%s'", 100 * chg, method, g.getName().c_str()); else
327                        mutinfo = SString::sprintf("%.2f%% mutation(%s) of '%s'", 100 * chg, gf->mutation_method_names ? gf->mutation_method_names[method] : "unspecified method name", g.getName().c_str());
[138]328        gv.setComment(mutinfo);
329        return gv;
330}
331
[532]332Geno GenMan::crossOver(const Geno& g1, const Geno& g2)
[138]333{
334        char format = g1.getFormat();
[257]335        if (format != g2.getFormat()) return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: CrossOver(): does not work for parents with differing genetic formats (%c and %c)", format, g2.getFormat()));
[145]336        GenoOperators *gf = getOper_f(format);
[138]337        if (gf == NULL)
[257]338                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: CrossOver(): no operators found for genetic format %c", format));
[138]339        Geno g1v = g1, g2v = g2;
340
341        {
[375]342                LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
[138]343                bool canvalidate = true;
344                if (testValidity(g1v, canvalidate) > 0 && canvalidate == false)
345                        return Geno("", -1, "", "GENOPER_OPFAIL: CrossOver(): cannot validate invalid source genotype #1");
346                canvalidate = true;
347                if (testValidity(g2v, canvalidate) > 0 && canvalidate == false)
348                        return Geno("", -1, "", "GENOPER_OPFAIL: CrossOver(): cannot validate invalid source genotype #2");
349        }
350
351        float chg;
352        bool ok = false;
353        int pcount = count;
354
355        while (!ok)
356        {
357                float chg1, chg2;
[534]358                char *g1n = strdup(g1.getGenes().c_str()); //copy for crossover
359                char *g2n = strdup(g2.getGenes().c_str()); //copy for crossover
[138]360                chg1 = chg2 = 0;
361                if (gf->crossOver(g1n, g2n, chg1, chg2) == GENOPER_OK)
362                {
363                        char *gn;
[168]364                        if (g1n[0] && g2n[0]) if (randomN(2) == 0) g1n[0] = 0; else g2n[0] = 0; //both provided? we want only one
[138]365                        if (g1n[0]) { gn = g1n; chg = chg1; }
366                        else { gn = g2n; chg = chg2; }
[375]367                        LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
[138]368                        Geno G(gn, g1v.getFormat(), "", "");
369                        bool canvalidate = true;
370                        int res = testValidity(G, canvalidate);
371                        if (res == GENOPER_OK && canvalidate == false) { valid_xo++; ok = true; }
372                        else
373                                if (res > 0 && canvalidate == false) invalid_xo++; else
374                                {
[761]375                                validated_xo++; ok = true;
[138]376                                }
377                        if (ok) g1v = G;
378                }
379                else failed_xo++;
380                free(g1n);
381                free(g2n);
382                count++;
[761]383                if (!ok && (count - pcount > GENMAN_REPEAT_FAILED))
[138]384                {
[761]385                        logPrintf("GenMan", "CrossOver", 2, "Tried " GENMAN_REPEAT_FAILED_STR "x and failed: %s and %s", g1.getGenes().c_str(), g2.getGenes().c_str());
386                        return Geno("", -1, "", "GENOPER_OPFAIL: CrossOver() tried " GENMAN_REPEAT_FAILED_STR "x and failed");
[138]387                }
388        }
389        // result in g1v
390        xochg += chg;
[534]391        if (history) saveLink(g1.getGenes().c_str(), g2.getGenes().c_str(), g1v.getGenes().c_str(), chg);
[138]392        SString xoinfo = SString::sprintf("Crossing over of '%s' (%.2f%%) and '%s' (%.2f%%)",
[348]393                g1.getName().c_str(), 100 * chg, g2.getName().c_str(), 100 * (1 - chg));
[138]394        g1v.setComment(xoinfo);
395        return g1v;
396}
397
[532]398float GenMan::similarity(const Geno& g1, const Geno& g2)
[138]399{
400        char format = g1.getFormat();
401        if (format != g2.getFormat()) return GENOPER_NOOPER;
[145]402        GenoOperators *gf = getOper_f(format);
[534]403        if (!gf) return GENOPER_NOOPER; else return gf->similarity(g1.getGenes().c_str(), g2.getGenes().c_str());
[138]404}
405
[532]406uint32_t GenMan::getStyle(const char *g, const Geno *G, int pos)
[138]407{
[532]408        char format = G->getFormat();
409        if (format == Geno::INVALID_FORMAT)
410                return GENSTYLE_RGBS(64, 64, 64, 0); // gray & "valid" (unknown format so we don't know what is valid and what is not)
411        if ((pos = G->mapStringToGen(pos)) == -1) return GENSTYLE_COMMENT;
412        GenoOperators *gf = getOper_f(format);
[138]413        if (!gf) return GENSTYLE_CS(0, 0); //black & valid
[534]414        else return gf->style(G->getGenes().c_str(), pos);
[138]415}
416
[532]417uint32_t GenMan::getStyle(const char *g, int pos)
[138]418{
419        Geno G(g);
[532]420        return getStyle(g, &G, pos);
421}
422
423void GenMan::getFullStyle(const char *g, const Geno *G, uint32_t *styletab)
424{
425        char format = G->getFormat();
426        if (format == Geno::INVALID_FORMAT)
427        {
428                for (unsigned int pos = 0; pos < strlen(g); pos++)
429                        styletab[pos] = GENSTYLE_RGBS(64, 64, 64, 0); // gray & "valid" (unknown format so we don't know what is valid and what is not)
430                return;
431        }
432        GenoOperators *gf = getOper_f(format);
[761]433        SString geny = G->getGenes();
[138]434        for (unsigned int pos = 0; pos < strlen(g); pos++)
435        {
[532]436                int posmapped = G->mapStringToGen(pos);
[138]437                if (posmapped == -1) styletab[pos] = GENSTYLE_COMMENT;
438                else if (!gf) styletab[pos] = GENSTYLE_CS(0, 0); //black & valid
[348]439                else styletab[pos] = gf->style(geny.c_str(), posmapped);
[532]440                //logPrintf("GenMan", "getFullStyle", 0, "%d  char='%c' (%d)  format=0x%08x", pos, g[pos], g[pos], styletab[pos]);
[138]441        }
442}
443
[532]444void GenMan::getFullStyle(const char *g, uint32_t *styletab)
445{
446        Geno G(g);
447        getFullStyle(g, &G, styletab);
448}
449
[467]450string GenMan::HTMLize(const char *g) { return HTMLize(g, false); }
[138]451
[467]452string GenMan::HTMLizeShort(const char *g) { return HTMLize(g, true); }
[138]453
[467]454string GenMan::HTMLize(const char *g, bool shorten)
[138]455{
456        char buf[50];
457        int len = strlen(g);
458        int chars = 0, lines = 0;
459        bool shortened = false;
[247]460        uint32_t *styletab = new uint32_t[len];
[532]461        getFullStyle(g, styletab);
[467]462        string html = "\n<div style=\"background:white;padding:0.2em;font-family:arial,helvetica,sans-serif;font-size:90%\">";
[247]463        uint32_t prevstyle, prevcolor, style = 0, color = 0;
[761]464        for (int i = 0; i < len; i++)
[138]465        {
[761]466                if (shorten && ((lines == 0 && chars > 160) || (lines > 5 || chars > 300))) { shortened = true; break; }
[138]467                if (g[i] == '\r') continue;
468                if (g[i] == '\n') { html += "<br>\n"; lines++; continue; }
469                chars++;
470                prevstyle = style;
471                prevcolor = color;
472                style = GENGETSTYLE(styletab[i]);
473                color = GENGETCOLOR(styletab[i]);
474                if ((i != 0 && (color != prevcolor))) html += "</font>";
475                if ((style&GENSTYLE_INVALID) != (prevstyle&GENSTYLE_INVALID))
476                {
477                        html += "<"; if (!(style&GENSTYLE_INVALID)) html += "/"; html += "u>";
478                }
479                if ((style&GENSTYLE_BOLD) != (prevstyle&GENSTYLE_BOLD))
480                {
481                        html += "<"; if (!(style&GENSTYLE_BOLD)) html += "/"; html += "b>";
482                }
483                if ((style&GENSTYLE_ITALIC) != (prevstyle&GENSTYLE_ITALIC))
484                {
485                        html += "<"; if (!(style&GENSTYLE_ITALIC)) html += "/"; html += "i>";
486                }
487                if ((i == 0 || (color != prevcolor)))
488                {
489                        sprintf(buf, "<font color=#%02x%02x%02x>", GENGET_R(color), GENGET_G(color), GENGET_B(color)); html += buf;
490                }
491                if (g[i] == '<') html += "&lt;"; else if (g[i] == '>') html += "&gt;"; else html += g[i];
492                if ((i % 3) == 0 && g[i] == ' ') html += "\n"; //for readability, insert some newlines into html...
493        }
494        delete[] styletab;
495        html += "</u></b></i></font>";
496        if (shortened) html += " [etc...]";
497        html += "</div>\n";
498        return html;
499}
500
501void GenMan::p_htmlize(ExtValue *args, ExtValue *ret)
502{
[467]503        ret->setString(HTMLize(args->getString().c_str()).c_str());
[138]504}
505
506void GenMan::p_htmlizeshort(ExtValue *args, ExtValue *ret)
507{
[467]508        ret->setString(HTMLizeShort(args->getString().c_str()).c_str());
[138]509}
510
[532]511Geno GenMan::getSimplest(char format)
[138]512{
[145]513        GenoOperators *gf = getOper_f(format);
[138]514        if (!gf) return Geno();
[200]515        string info = "The simplest genotype of format f"; info += format;
[138]516        info += " for operators '"; info += gf->name; info += "'.";
[200]517        return Geno(gf->getSimplest(), format, "Root", info.c_str());
[138]518}
519
520void GenMan::p_getsimplest(ExtValue *args, ExtValue *ret)
521{
[516]522        int format = GenoObj::formatFromExtValue(args[0]);
[145]523        if (!getOper_f(format))
[138]524                ret->setEmpty();
525        else
[532]526                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(getSimplest(format)));
[138]527}
528
[532]529const char *GenMan::getOpName(char format)
[138]530{
[145]531        GenoOperators *gf = getOper_f(format);
[200]532        if (!gf) return "n/a"; else return gf->name.c_str();
[138]533}
534
[145]535GenoOperators* GenMan::getOper_f(char format)
[138]536{
537        int ind = operformats.find(format);
538        if (ind == -1) return NULL;
[168]539        int which_oper_of_format = seloper[ind];
[145]540        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
541                if (oper_fx_list[i]->supported_format == format)
[168]542                        if (which_oper_of_format == 0) return oper_fx_list[i]; else which_oper_of_format--;
[138]543        return NULL; //should never happen
544}
545
[275]546void GenMan::saveLink(const string parent1, const string parent2, const string child, const float chg)
[138]547{
548        GenoLink l;
549        l.count = count;
[275]550        l.parent1 = parent1;
551        l.parent2 = parent2;
552        l.child = child;
[138]553        l.chg = chg;
554        l.fit = 0; //temporarily. Will be set when the genotype dies
[375]555        //logPrintf("GenMan","saveLink",0,"#%d: [%d] '%s' + '%s' -> '%s'",GenoLinkList.size(),count,parent1.c_str(),parent2.c_str(),child.c_str());
[138]556        GenoLinkList.push_back(l);
557}
558
[247]559void GenMan::onDelGen(void *obj, intptr_t n)
[138]560{
561        //old code needs update:
562        //   ((SpeciesList*)obj)->przyDodaniu(i);
563        /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
564           GenMan *gm=(GenMan*)obj;
565           Genotype *gt=(Genotype*)(*listaGen)(n); //there is no more "listaGen"
566           string g=(const char*)gt->genotype.getGene();
567           float fit=gt->getFinalFitness();
568           for(int i=0;i<gm->GenoLinkList.size();i++) //find genotype
569           if (gm->GenoLinkList[i].g1==g) {gm->GenoLinkList[i].fit=fit; break;}
570           */
571}
572
573void GenMan::clearStats()
574{
575        count = 0;
576        valid_m = valid_xo = validated_m = validated_xo = invalid_m = invalid_xo = failed_m = failed_xo = 0;
577        mutchg = xochg = 0;
578        GenoLinkList.clear();
579}
580
581void GenMan::p_clearStats(ExtValue *args, ExtValue *ret) { clearStats(); }
582
583void GenMan::p_report(ExtValue *args, ExtValue *ret)
584{                      //should be updated to handle multiple operators for a single format
585        char *g, *g2;
[145]586        float f1, f2;
587        int m;
[375]588        logMessage("GenMan", "Report", 0, "The following genetic operators are available:");
[145]589        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
[138]590        {
[200]591                string l;
[761]592                if (oper_fx_list[i]->checkValidity("", "") != GENOPER_NOOPER) l += " checkValidity";
[145]593                if (oper_fx_list[i]->getSimplest())
[138]594                {
[145]595                        g = strdup(oper_fx_list[i]->getSimplest());
[138]596                        g2 = strdup(g);
[761]597                        if (oper_fx_list[i]->validate(g, "") != GENOPER_NOOPER) l += " validate";
[145]598                        if (oper_fx_list[i]->mutate(g, f1, m) != GENOPER_NOOPER) l += " mutate";
599                        if (oper_fx_list[i]->crossOver(g, g2, f1, f2) != GENOPER_NOOPER) l += " crossover";
[138]600                        l += " getSimplest";
601                        free(g); free(g2);
602                }
[145]603                //      if (oper_fx_list[i]->similarity("","")!=GENOPER_NOOPER) l+=" similarity";
[375]604                logPrintf("GenMan", "Report", 0, "format f%c (%s):%s",
[200]605                        oper_fx_list[i]->supported_format, oper_fx_list[i]->name.c_str(), l.c_str());
[138]606        }
607}
608
609void GenMan::p_validate(ExtValue *args, ExtValue *ret)
610{
611        Geno *g = GenoObj::fromObject(args[0]);
612        if (g == NULL)
613                ret->setEmpty();
614        else
[532]615                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(validate(*g)));
[138]616}
617
618void GenMan::p_mutate(ExtValue *args, ExtValue *ret)
619{
620        Geno *g = GenoObj::fromObject(args[0]);
621        if (g == NULL)
622                ret->setEmpty();
623        else
[532]624                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(mutate(*g)));
[138]625}
626
627void GenMan::p_crossover(ExtValue *args, ExtValue *ret)
628{
629        Geno *g1 = GenoObj::fromObject(args[1]);
630        Geno *g2 = GenoObj::fromObject(args[0]);
631        if (g1 == NULL || g2 == NULL)
632                ret->setEmpty();
633        else
[532]634                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(crossOver(*g1, *g2)));
[138]635}
[532]636
Note: See TracBrowser for help on using the repository browser.