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

Last change on this file since 955 was 955, checked in by Maciej Komosinski, 4 years ago

Genetic format ID becomes a string (no longer limited to a single character)

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