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

Last change on this file since 761 was 761, checked in by Maciej Komosinski, 6 years ago

Introduced a macro for the number of times GenMan? tries to repeat a mutation or crossover when the operator does not return acceptable genotype; decreased the number of repetitions from 100 to 10

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