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

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

Cosmetic

  • Property svn:eol-style set to native
File size: 25.8 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, 11, "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) in colored HTML format", },
95        { "toLaTeX", 0, PARAM_DONTSAVE, "LaTeXize a genotype", "p s(s)", PROCEDURE(p_latexize), "returns genotype in colored LaTeX format", },
96        { "validate", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Validate", "p oGeno(oGeno)", PROCEDURE(p_validate), "returns validated (if possible) Geno object from supplied Geno", },
97        { "mutate", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Mutate", "p oGeno(oGeno)", PROCEDURE(p_mutate), "returns mutated Geno object from supplied Geno", },
98        { "crossOver", 0, PARAM_DONTSAVE | PARAM_USERHIDDEN, "Crossover", "p oGeno(oGeno,oGeno)", PROCEDURE(p_crossover), "returns crossed over genotype", },
99        { "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.", },
100        { 0, },
101};
102
103static ParamEntry GMstats_tab[] =
104{
105        { "Genetics", 1, 12, "GenManStats", "Statistics for genetic operations." },
106        { "gen_count", 0, PARAM_READONLY, "Number of genetic operations so far", "d", FIELD(count), "", },
107        { "gen_mvalid", 0, PARAM_READONLY, "Mutations valid", "d", FIELD(valid_m), "", },
108        { "gen_mvalidated", 0, PARAM_READONLY, "Mutations validated", "d", FIELD(validated_m), "", },
109        { "gen_minvalid", 0, PARAM_READONLY, "Mutations invalid", "d", FIELD(invalid_m), "couldn't be repaired", },
110        { "gen_mfailed", 0, PARAM_READONLY, "Mutations failed", "d", FIELD(failed_m), "couldn't be performed", },
111        { "gen_xovalid", 0, PARAM_READONLY, "Crossovers valid", "d", FIELD(valid_xo), "", },
112        { "gen_xovalidated", 0, PARAM_READONLY, "Crossovers validated", "d", FIELD(validated_xo), "", },
113        { "gen_xoinvalid", 0, PARAM_READONLY, "Crossovers invalid", "d", FIELD(invalid_xo), "couldn't be repaired", },
114        { "gen_xofailed", 0, PARAM_READONLY, "Crossovers failed", "d", FIELD(failed_xo), "couldn't be performed", },
115        { "gen_mutimpr", 0, PARAM_READONLY, "Mutations total effect", "f", FIELD(mutchg), "total cumulative mutation change", },
116        { "gen_xoimpr", 0, PARAM_READONLY, "Crossovers total effect", "f", FIELD(xochg), "total cumulative crossover change", },
117        { "clrstats", 0, PARAM_DONTSAVE, "Clear stats and history", "p()", PROCEDURE(p_clearStats), "", },
118        { 0, },
119};
120
121#undef FIELDSTRUCT
122
123GenMan::GenMan() : localpar(GMparam_tab, this), localstats(GMstats_tab, this),
124seloperpar("GenOperators", "Genetics: Active operators"),
125neuronsparam("Genetics: Neurons to add", "neuronsAdd", "neuadd_"),
126par("GenMan", "Manages various genetic operations, using appropriate operators for the argument genotype format.")
127{
128        history = 0;
129        hilite = 1;
130        clearStats();
131
132#ifdef USE_GENMAN_f0
133        oper_fx_list.push_back(new Geno_f0);
134#endif
135#ifdef USE_GENMAN_f0FUZZY
136        oper_fx_list.push_back(new Geno_f0Fuzzy);
137#endif
138#ifdef USE_GENMAN_f1
139        oper_fx_list.push_back(new Geno_f1);
140#endif
141#ifdef USE_GENMAN_f2
142        oper_fx_list.push_back(new Geno_f2);
143#endif
144#ifdef USE_GENMAN_f3
145        oper_fx_list.push_back(new Geno_f3);
146#endif
147#ifdef USE_GENMAN_f4
148        oper_fx_list.push_back(new Geno_f4);
149#endif
150#ifdef USE_GENMAN_f5
151        oper_fx_list.push_back(new Geno_f5);
152#endif
153#ifdef USE_GENMAN_f6
154        oper_fx_list.push_back(new Geno_f6);
155#endif
156#ifdef USE_GENMAN_f7
157        oper_fx_list.push_back(new Geno_f7);
158#endif
159#ifdef USE_GENMAN_f8
160        oper_fx_list.push_back(new Geno_f8);
161#endif
162#ifdef USE_GENMAN_f9
163        oper_fx_list.push_back(new GenoOper_f9);
164#endif
165#ifdef USE_GENMAN_fF
166        oper_fx_list.push_back(new GenoOper_fF);
167#endif
168#ifdef USE_GENMAN_fn
169        oper_fx_list.push_back(new GenoOper_fn);
170#endif
171#ifdef USE_GENMAN_fT
172        oper_fx_list.push_back(new GenoOper_fTest);
173#endif
174#ifdef USE_GENMAN_fB
175        oper_fx_list.push_back(new Geno_fB);
176#endif
177#ifdef USE_GENMAN_fH
178        oper_fx_list.push_back(new Geno_fH);
179#endif
180#ifdef USE_GENMAN_fL
181        oper_fx_list.push_back(new Geno_fL);
182#endif
183#ifdef USE_GENMAN_fS
184        oper_fx_list.push_back(new GenoOper_fS);
185#endif
186
187        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
188        int selopercount = 0;
189        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
190        {
191                if (findOperFormatIndex(oper_fx_list[i]->supported_format) != -1) continue;
192                string type = string("~") + oper_fx_list[i]->name;
193                int dup = 0;
194                for (unsigned int j = i + 1; j < oper_fx_list.size(); j++)
195                        if (oper_fx_list[i]->supported_format == oper_fx_list[j]->supported_format)
196                        {
197                                type += "~";
198                                type += oper_fx_list[j]->name;
199                                dup++;
200                        }
201                type = ssprintf("d 0 %d ", dup) + type;
202                string id = ssprintf("genoper_f%s", oper_fx_list[i]->supported_format.c_str());
203                string name = ssprintf("Operators for f%s", oper_fx_list[i]->supported_format.c_str());
204                seloper[selopercount] = 0;
205                operformats += &oper_fx_list[i]->supported_format;
206                //printf("%x %s %s %s\n",&seloper[selopercount],(const char*)id,(const char*)type,(const char*)name);
207                seloperpar.addProperty(&seloper[selopercount++], id.c_str(), type.c_str(), name.c_str(), "", PARAM_READONLY * (dup == 0));
208        }
209
210        par += &localpar;
211        par += &seloperpar;
212        par += &neuronsparam;
213        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
214                if (oper_fx_list[i]->par.getParamTab()) par += &oper_fx_list[i]->par;
215
216        setDefaults(); //use Param to initialize all values of fields in the paramtab of this object and genetic operators on oper_fx_list
217}
218
219GenMan::~GenMan()
220{
221        for (unsigned int i = 0; i < oper_fx_list.size(); i++) delete oper_fx_list[i];
222        delete[] seloper;
223}
224
225int GenMan::findOperFormatIndex(const SString& format)
226{
227        for (int i = 0; i < operformats.size(); i++)
228                if (*operformats(i) == format)
229                        return i;
230        return -1;
231}
232
233void GenMan::setDefaults()
234{
235        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
236        {
237                oper_fx_list[i]->par.setDefault();
238                oper_fx_list[i]->setDefaults();
239        }
240        localpar.setDefault();
241        //...and we do not reset others that are linked to 'par',
242        //because there quite a few of them, and not every of them defines defaults for each of its parameters.
243}
244
245int GenMan::testValidity(Geno &g, bool &canvalidate)
246{
247        SString ggs = g.getGenes();
248        const char *gg = ggs.c_str();
249        GenoOperators *gf = getOper_f(g.getFormat());
250        int check1;
251        if (!gf) { canvalidate = false; return GENOPER_NOOPER; }
252        else check1 = gf->checkValidity(gg, g.getName().c_str());
253        if (!canvalidate) return check1; //just checking
254        if (check1 == GENOPER_OK) { canvalidate = false; return check1; }
255        char *g2 = strdup(gg);
256        if (gf->validate(g2, g.getName().c_str()) == GENOPER_NOOPER) { free(g2); canvalidate = false; return check1; }
257        if (check1 == GENOPER_NOOPER) //disaster: cannot check because there is no check operator
258        {
259                g.setGenesAssumingSameFormat(g2); free(g2); canvalidate = false; return GENOPER_NOOPER;
260        }
261        int check2 = gf->checkValidity(g2, "validated");
262        if (check2 == GENOPER_OK) g.setGenesAssumingSameFormat(g2);
263        free(g2);
264        if (check2 == GENOPER_OK) return check1;
265        canvalidate = false;
266        return check1; //could not validate.
267}
268
269int GenMan::testGenoValidity(Geno& g)
270{
271        bool fix = false;
272        switch (testValidity(g, fix))
273        {
274        case GENOPER_OK: return 1;
275        case GENOPER_NOOPER: return -1;
276        default: return 0;
277        }
278}
279
280Geno GenMan::validate(const Geno& geny)
281{
282        SString format = geny.getFormat();
283        GenoOperators *gf = getOper_f(format);
284        if (gf == NULL)
285                return Geno("", Geno::INVALID_FORMAT, "", SString::sprintf("GENOPER_NOOPER: Validate(): don't know how to handle genetic format %s", format.c_str()));
286        char *g2 = strdup(geny.getGenes().c_str()); //copy for validation
287        int res = gf->validate(g2, geny.getName().c_str());
288        SString sg2 = g2;
289        free(g2);
290        if (res == GENOPER_OK)
291                return Geno(sg2, format, geny.getName(), geny.getComment());
292        else
293                return Geno("", Geno::INVALID_FORMAT, "", SString::sprintf("GENOPER_NOOPER: validate() for format %s returned invalid value", format.c_str()));
294}
295
296Geno GenMan::mutate(const Geno& g)
297{
298        float chg; //how many changes
299        int method; //mutation method
300        SString format = g.getFormat();
301        GenoOperators *gf = getOper_f(format);
302        if (gf == NULL)
303                return Geno("", Geno::INVALID_FORMAT, "", SString::sprintf("GENOPER_NOOPER: Mutate(): don't know how to handle genetic format %s", format.c_str()));
304        Geno gv = g;
305        bool canvalidate = true;
306        if (testValidity(gv, canvalidate) > 0 && canvalidate == false)
307                return Geno("", Geno::INVALID_FORMAT, "", "GENOPER_OPFAIL: Mutate(): cannot validate invalid source genotype");
308        bool ok = false;
309        int pcount = count;
310        while (!ok)
311        {
312                char *gn = strdup(gv.getGenes().c_str()); //copy for mutation
313                chg = 0;
314                if (gf->mutate(gn, chg, method) == GENOPER_OK)
315                {
316                        LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
317                        Geno G(gn, gv.getFormat(), "", "");
318                        canvalidate = true;
319                        int res = testValidity(G, canvalidate);
320                        if (res == GENOPER_OK && canvalidate == false) { valid_m++; ok = true; }
321                        else
322                                if (res > 0 && canvalidate == false) invalid_m++; else
323                                {
324                                        validated_m++; ok = true;
325                                }
326                        if (ok) gv = G;
327                }
328                else failed_m++;
329                free(gn);
330                count++;
331                if (!ok && (count - pcount > GENMAN_REPEAT_FAILED))
332                {
333                        logPrintf("GenMan", "Mutate", LOG_WARN, "Tried " GENMAN_REPEAT_FAILED_STR "x and failed: %s", g.getGenes().c_str());
334                        return Geno("", -1, "", "GENOPER_OPFAIL: Mutate() tried " GENMAN_REPEAT_FAILED_STR "x and failed");
335                }
336        }
337        mutchg += chg;
338        if (history) saveLink(g.getGenes().c_str(), "", gv.getGenes().c_str(), chg);
339        SString mutinfo;
340        if (extmutinfo == 0) mutinfo = SString::sprintf("%.2f%% mutation of '%s'", 100 * chg, g.getName().c_str()); else
341                if (extmutinfo == 1) mutinfo = SString::sprintf("%.2f%% mutation(%d) of '%s'", 100 * chg, method, g.getName().c_str()); else
342                        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());
343        gv.setComment(mutinfo);
344        return gv;
345}
346
347Geno GenMan::crossOver(const Geno& g1, const Geno& g2)
348{
349        SString format = g1.getFormat();
350        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()));
351        GenoOperators *gf = getOper_f(format);
352        if (gf == NULL)
353                return Geno("", Geno::INVALID_FORMAT, "", SString::sprintf("GENOPER_NOOPER: CrossOver(): no operators found for genetic format %s", format.c_str()));
354        Geno g1v = g1, g2v = g2;
355
356        {
357                LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
358                bool canvalidate = true;
359                if (testValidity(g1v, canvalidate) > 0 && canvalidate == false)
360                        return Geno("", Geno::INVALID_FORMAT, "", "GENOPER_OPFAIL: CrossOver(): cannot validate invalid source genotype #1");
361                canvalidate = true;
362                if (testValidity(g2v, canvalidate) > 0 && canvalidate == false)
363                        return Geno("", Geno::INVALID_FORMAT, "", "GENOPER_OPFAIL: CrossOver(): cannot validate invalid source genotype #2");
364        }
365
366        float chg;
367        bool ok = false;
368        int pcount = count;
369
370        while (!ok)
371        {
372                float chg1, chg2;
373                char *g1n = strdup(g1.getGenes().c_str()); //copy for crossover
374                char *g2n = strdup(g2.getGenes().c_str()); //copy for crossover
375                chg1 = chg2 = 0;
376                if (gf->crossOver(g1n, g2n, chg1, chg2) == GENOPER_OK)
377                {
378                        char *gn;
379                        if (g1n[0] && g2n[0]) if (rndUint(2) == 0) g1n[0] = 0; else g2n[0] = 0; //both provided? we want only one
380                        if (g1n[0]) { gn = g1n; chg = chg1; }
381                        else { gn = g2n; chg = chg2; }
382                        LoggerToMemory eh(LoggerBase::Enable | LoggerToMemory::StoreFirstMessage); //mute testValidity()
383                        Geno G(gn, g1v.getFormat(), "", "");
384                        bool canvalidate = true;
385                        int res = testValidity(G, canvalidate);
386                        if (res == GENOPER_OK && canvalidate == false) { valid_xo++; ok = true; }
387                        else
388                                if (res > 0 && canvalidate == false) invalid_xo++; else
389                                {
390                                        validated_xo++; ok = true;
391                                }
392                        if (ok) g1v = G;
393                }
394                else failed_xo++;
395                free(g1n);
396                free(g2n);
397                count++;
398                if (!ok && (count - pcount > GENMAN_REPEAT_FAILED))
399                {
400                        logPrintf("GenMan", "CrossOver", LOG_WARN, "Tried " GENMAN_REPEAT_FAILED_STR "x and failed: %s and %s", g1.getGenes().c_str(), g2.getGenes().c_str());
401                        return Geno("", Geno::INVALID_FORMAT, "", "GENOPER_OPFAIL: CrossOver() tried " GENMAN_REPEAT_FAILED_STR "x and failed");
402                }
403        }
404        // result in g1v
405        xochg += chg;
406        if (history) saveLink(g1.getGenes().c_str(), g2.getGenes().c_str(), g1v.getGenes().c_str(), chg);
407        SString xoinfo = SString::sprintf("Crossing over of '%s' (%.2f%%) and '%s' (%.2f%%)",
408                g1.getName().c_str(), 100 * chg, g2.getName().c_str(), 100 * (1 - chg));
409        g1v.setComment(xoinfo);
410        return g1v;
411}
412
413float GenMan::similarity(const Geno& g1, const Geno& g2)
414{
415        SString format = g1.getFormat();
416        if (format != g2.getFormat()) return GENOPER_NOOPER;
417        GenoOperators *gf = getOper_f(format);
418        if (!gf) return GENOPER_NOOPER; else return gf->similarity(g1.getGenes().c_str(), g2.getGenes().c_str());
419}
420
421uint32_t GenMan::getStyle(const char *g, const Geno *G, int pos)
422{
423        SString format = G->getFormat();
424        if (format == Geno::INVALID_FORMAT)
425                return GENSTYLE_RGBS(64, 64, 64, 0); // gray & "valid" (unknown format so we don't know what is valid and what is not)
426        if ((pos = G->mapStringToGen(pos)) == -1) return GENSTYLE_COMMENT;
427        GenoOperators *gf = getOper_f(format);
428        if (!gf) return GENSTYLE_CS(0, 0); //black & valid
429        else return gf->style(G->getGenes().c_str(), pos);
430}
431
432uint32_t GenMan::getStyle(const char *g, int pos)
433{
434        Geno G(g);
435        return getStyle(g, &G, pos);
436}
437
438void GenMan::getFullStyle(const char *g, const Geno *G, uint32_t *styletab)
439{
440        SString format = G->getFormat();
441        if (format == Geno::INVALID_FORMAT)
442        {
443                for (unsigned int pos = 0; pos < strlen(g); pos++)
444                        styletab[pos] = GENSTYLE_RGBS(64, 64, 64, 0); // gray & "valid" (unknown format so we don't know what is valid and what is not)
445                return;
446        }
447        GenoOperators *gf = getOper_f(format);
448        SString geny = G->getGenes();
449        for (unsigned int pos = 0; pos < strlen(g); pos++)
450        {
451                int posmapped = G->mapStringToGen(pos);
452                if (posmapped == -1) styletab[pos] = GENSTYLE_COMMENT;
453                else if (!gf) styletab[pos] = GENSTYLE_CS(0, 0); //black & valid
454                else styletab[pos] = gf->style(geny.c_str(), posmapped);
455                //logPrintf("GenMan", "getFullStyle", LOG_INFO, "%d  char='%c' (%d)  format=0x%08x", pos, g[pos], g[pos], styletab[pos]);
456        }
457}
458
459void GenMan::getFullStyle(const char *g, uint32_t *styletab)
460{
461        Geno G(g);
462        getFullStyle(g, &G, styletab);
463}
464
465string GenMan::HTMLize(const char *g) { return HTMLize(g, false); }
466
467string GenMan::HTMLizeShort(const char *g) { return HTMLize(g, true); }
468
469string GenMan::HTMLize(const char *g, bool shorten)
470{
471        char buf[50];
472        int len = strlen(g);
473        int chars = 0, lines = 0;
474        bool shortened = false;
475        uint32_t *styletab = new uint32_t[len];
476        getFullStyle(g, styletab);
477        string html = "\n<div style=\"background:white;padding:0.2em;font-family:arial,helvetica,sans-serif;font-size:90%\">";
478        uint32_t prevstyle, prevcolor, style = 0, color = 0;
479        for (int i = 0; i < len; i++)
480        {
481                if (shorten && ((lines == 0 && chars > 160) || (lines > 5 || chars > 300))) { shortened = true; break; }
482                if (g[i] == '\r') continue;
483                if (g[i] == '\n') { html += "<br>\n"; lines++; continue; }
484                chars++;
485                prevstyle = style;
486                prevcolor = color;
487                style = GENGETSTYLE(styletab[i]);
488                color = GENGETCOLOR(styletab[i]);
489                if ((i != 0 && (color != prevcolor))) html += "</font>";
490                if ((style & GENSTYLE_INVALID) != (prevstyle & GENSTYLE_INVALID))
491                {
492                        html += "<"; if (!(style & GENSTYLE_INVALID)) html += "/"; html += "u>";
493                }
494                if ((style & GENSTYLE_BOLD) != (prevstyle & GENSTYLE_BOLD))
495                {
496                        html += "<"; if (!(style & GENSTYLE_BOLD)) html += "/"; html += "b>";
497                }
498                if ((style & GENSTYLE_ITALIC) != (prevstyle & GENSTYLE_ITALIC))
499                {
500                        html += "<"; if (!(style & GENSTYLE_ITALIC)) html += "/"; html += "i>";
501                }
502                if ((i == 0 || (color != prevcolor)))
503                {
504                        sprintf(buf, "<font color=#%02x%02x%02x>", GENGET_R(color), GENGET_G(color), GENGET_B(color)); html += buf;
505                }
506                if (g[i] == '<') html += "&lt;"; else if (g[i] == '>') html += "&gt;"; else html += g[i];
507                if ((i % 3) == 0 && g[i] == ' ') html += "\n"; //for readability, insert some newlines into html...
508        }
509        delete[] styletab;
510        html += "</u></b></i></font>";
511        if (shortened) html += " [etc...]";
512        html += "</div>\n";
513        return html;
514}
515
516void GenMan::p_htmlize(ExtValue *args, ExtValue *ret)
517{
518        ret->setString(HTMLize(args->getString().c_str()).c_str());
519}
520
521void GenMan::p_htmlizeshort(ExtValue *args, ExtValue *ret)
522{
523        ret->setString(HTMLizeShort(args->getString().c_str()).c_str());
524}
525
526string GenMan::LaTeXize(const char *g)
527{
528        char buf[50];
529        int len = strlen(g);
530        int chars = 0, lines = 0; //currently not used
531        uint32_t *styletab = new uint32_t[len];
532        getFullStyle(g, styletab);
533        string latex = "\\usepackage{xcolor}\n% Using \\texttt{} may be beneficial for some genetic encodings, but then you may lose bold/italic.\n\\noindent \\sloppy";
534        uint32_t prevstyle, prevcolor, style = 0, color = 0;
535        for (int i = 0; i < len; i++)
536        {
537                if (g[i] == '\r') continue;
538                if (g[i] == '\n') { latex += "\\\\\n"; lines++; continue; }
539                chars++;
540                prevstyle = style;
541                prevcolor = color;
542                style = GENGETSTYLE(styletab[i]);
543                color = GENGETCOLOR(styletab[i]);
544
545                // Unfortunately, LaTeX (as opposed to HTML) uses the same closing tags "}" for color, bold, italic, underline - so they cannot intersect.
546                // Therefore we have to "turn off" everything on every change of style or color, and then "turn on" (to avoid problems with e.g. red-bold-blue-unbold or bold-italic-unbold-unitalic).
547                // This could be optimized by a more complex logic and tracking which color/style section starts and ends within another section.
548
549                if (((style & GENSTYLE_INVALID) != (prevstyle & GENSTYLE_INVALID))
550                        ||
551                        ((style & GENSTYLE_BOLD) != (prevstyle & GENSTYLE_BOLD))
552                        ||
553                        ((style & GENSTYLE_ITALIC) != (prevstyle & GENSTYLE_ITALIC))
554                        ||
555                        ((i == 0 || (color != prevcolor))))
556                {
557                        if (prevstyle & GENSTYLE_INVALID) latex += "}";
558                        if (prevstyle & GENSTYLE_BOLD) latex += "}";
559                        if (prevstyle & GENSTYLE_ITALIC) latex += "}";
560                        if (i != 0) latex += "}"; //for color
561                        if (style & GENSTYLE_INVALID) latex += "\\underline{";
562                        if (style & GENSTYLE_BOLD) latex += "\\textbf{";
563                        if (style & GENSTYLE_ITALIC) latex += "\\textit{";
564                        sprintf(buf, "\\textcolor[rgb]{%.2g,%.2g,%.2g}{", GENGET_R(color) / 255.0, GENGET_G(color) / 255.0, GENGET_B(color) / 255.0); latex += buf;
565                }
566                if (g[i] == '<') latex += "$<$"; else if (g[i] == '>') latex += "$>$"; else
567                        if (g[i] == '-') latex += "$-$"; else if (g[i] == '|') latex += "$|$"; else
568                                if (g[i] == '$') latex += "\\$"; else if (g[i] == '%') latex += "\\%"; else latex += g[i];
569                if ((i % 3) == 0 && g[i] == ' ') latex += "\n"; //for readability, insert some newlines into latex...
570                if (i % 10 == 0) latex += "{\\hskip 0pt}"; // https://tex.stackexchange.com/questions/33526/automatic-line-breaking-of-long-lines-of-text
571        }
572        delete[] styletab;
573        latex += "}"; //for color (it was used at least once)
574        if (style & GENSTYLE_INVALID) latex += "}";
575        if (style & GENSTYLE_BOLD) latex += "}";
576        if (style & GENSTYLE_ITALIC) latex += "}";
577        latex += "\n";
578        return latex;
579}
580
581void GenMan::p_latexize(ExtValue *args, ExtValue *ret)
582{
583        ret->setString(LaTeXize(args->getString().c_str()).c_str());
584}
585
586Geno GenMan::getSimplest(const SString& format)
587{
588        GenoOperators *gf = getOper_f(format);
589        if (!gf) return Geno();
590        string info = "The simplest genotype of format f"; info += format.c_str();
591        info += " for operators '"; info += gf->name; info += "'.";
592        return Geno(gf->getSimplest(), format, "Root", info.c_str());
593}
594
595void GenMan::p_getsimplest(ExtValue *args, ExtValue *ret)
596{
597        SString format = GenoObj::formatFromExtValue(args[0]);
598        if (!getOper_f(format))
599                ret->setEmpty();
600        else
601                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(getSimplest(format)));
602}
603
604const char *GenMan::getOpName(const SString& format)
605{
606        GenoOperators *gf = getOper_f(format);
607        if (!gf) return "n/a"; else return gf->name.c_str();
608}
609
610GenoOperators* GenMan::getOper_f(const SString& format)
611{
612        int ind = findOperFormatIndex(format);
613        if (ind == -1) return NULL;
614        int which_oper_of_format = seloper[ind];
615        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
616                if (oper_fx_list[i]->supported_format == format)
617                        if (which_oper_of_format == 0) return oper_fx_list[i]; else which_oper_of_format--;
618        return NULL; //should never happen
619}
620
621void GenMan::saveLink(const string parent1, const string parent2, const string child, const float chg)
622{
623        GenoLink l;
624        l.count = count;
625        l.parent1 = parent1;
626        l.parent2 = parent2;
627        l.child = child;
628        l.chg = chg;
629        l.fit = 0; //temporarily. Will be set when the genotype dies
630        //logPrintf("GenMan","saveLink",0,"#%d: [%d] '%s' + '%s' -> '%s'",GenoLinkList.size(),count,parent1.c_str(),parent2.c_str(),child.c_str());
631        GenoLinkList.push_back(l);
632}
633
634void GenMan::onDelGen(void *obj, intptr_t n)
635{
636        //old code needs update:
637        //   ((SpeciesList*)obj)->przyDodaniu(i);
638        /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
639           GenMan *gm=(GenMan*)obj;
640           Genotype *gt=(Genotype*)(*listaGen)(n); //there is no more "listaGen"
641           string g=(const char*)gt->genotype.getGene();
642           float fit=gt->getFinalFitness();
643           for(int i=0;i<gm->GenoLinkList.size();i++) //find genotype
644           if (gm->GenoLinkList[i].g1==g) {gm->GenoLinkList[i].fit=fit; break;}
645           */
646}
647
648void GenMan::clearStats()
649{
650        count = 0;
651        valid_m = valid_xo = validated_m = validated_xo = invalid_m = invalid_xo = failed_m = failed_xo = 0;
652        mutchg = xochg = 0;
653        GenoLinkList.clear();
654}
655
656void GenMan::p_clearStats(ExtValue *args, ExtValue *ret) { clearStats(); }
657
658void GenMan::p_report(ExtValue *args, ExtValue *ret)
659{                      //should be updated to handle multiple operators for a single format
660        char *g, *g2;
661        float f1, f2;
662        int m;
663        logMessage("GenMan", "Report", 0, "The following genetic operators are available:");
664        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
665        {
666                string l;
667                if (oper_fx_list[i]->checkValidity("", "") != GENOPER_NOOPER) l += " checkValidity";
668                if (oper_fx_list[i]->getSimplest())
669                {
670                        g = strdup(oper_fx_list[i]->getSimplest());
671                        g2 = strdup(g);
672                        if (oper_fx_list[i]->validate(g, "") != GENOPER_NOOPER) l += " validate";
673                        if (oper_fx_list[i]->mutate(g, f1, m) != GENOPER_NOOPER) l += " mutate";
674                        if (oper_fx_list[i]->crossOver(g, g2, f1, f2) != GENOPER_NOOPER) l += " crossover";
675                        l += " getSimplest";
676                        free(g); free(g2);
677                }
678                //      if (oper_fx_list[i]->similarity("","")!=GENOPER_NOOPER) l+=" similarity";
679                logPrintf("GenMan", "Report", LOG_INFO, "format f%s (%s):%s",
680                        oper_fx_list[i]->supported_format.c_str(), oper_fx_list[i]->name.c_str(), l.c_str());
681        }
682}
683
684void GenMan::p_validate(ExtValue *args, ExtValue *ret)
685{
686        Geno *g = GenoObj::fromObject(args[0]);
687        if (g == NULL)
688                ret->setEmpty();
689        else
690                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(validate(*g)));
691}
692
693void GenMan::p_mutate(ExtValue *args, ExtValue *ret)
694{
695        Geno *g = GenoObj::fromObject(args[0]);
696        if (g == NULL)
697                ret->setEmpty();
698        else
699                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(mutate(*g)));
700}
701
702void GenMan::p_crossover(ExtValue *args, ExtValue *ret)
703{
704        Geno *g1 = GenoObj::fromObject(args[1]);
705        Geno *g2 = GenoObj::fromObject(args[0]);
706        if (g1 == NULL || g2 == NULL)
707                ret->setEmpty();
708        else
709                *ret = GenoObj::makeDynamicObjectAndDecRef(new Geno(crossOver(*g1, *g2)));
710}
711
Note: See TracBrowser for help on using the repository browser.