source: cpp/frams/genetics/genooperators.cpp @ 906

Last change on this file since 906 was 899, checked in by Maciej Komosinski, 5 years ago

Code formatting

  • Property svn:eol-style set to native
File size: 12.8 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[749]2// Copyright (C) 1999-2018  Maciej Komosinski and Szymon Ulatowski.
[286]3// See LICENSE.txt for details.
[109]4
5#include <ctype.h>  //isupper()
[779]6#include "genooperators.h"
[375]7#include <common/log.h>
[109]8#include <common/nonstd_math.h>
9#include <frams/util/rndutil.h>
10
[168]11static double distrib_force[] =   // for '!'
[109]12{
[168]13        3,             // distribution 0 -__/ +1
14        0.001, 0.2,    // "slow" neurons
15        0.001, 1,
16        1, 1,          // "fast" neurons
[109]17};
[168]18static double distrib_inertia[] =  // for '='
[109]19{
[168]20        2,             // distribution 0 |..- +1
21        0, 0,          // "fast" neurons
22        0.7, 0.98,
[109]23};
[168]24static double distrib_sigmo[] =  // for '/'
[109]25{
[168]26        5,             // distribution -999 -..-^-..- +999
27        -999, -999,    //"perceptron"
28        999, 999,
29        -5, -1,        // nonlinear
30        1, 5,
31        -1, 1,         // ~linear
[109]32};
33
34
[168]35int GenoOperators::roulette(const double *probtab, const int count)
[109]36{
[168]37        double sum = 0;
38        int i;
39        for (i = 0; i < count; i++) sum += probtab[i];
[896]40        double sel = rndDouble(sum);
[168]41        for (sum = 0, i = 0; i < count; i++) { sum += probtab[i]; if (sel < sum) return i; }
42        return -1;
[109]43}
44
[168]45bool GenoOperators::getMinMaxDef(ParamInterface *p, int i, double &mn, double &mx, double &def)
[109]46{
[168]47        mn = mx = def = 0;
48        int defined = 0;
49        if (p->type(i)[0] == 'f')
50        {
51                double _mn = 0, _mx = 1, _def = 0.5;
[743]52                defined = p->getMinMaxDouble(i, _mn, _mx, _def);
[765]53                if (defined == 1) _mx = _mn + 1000.0; //only min was defined, so let's set some arbitrary range, just to have some freedom. Assumes _mn is not close to maxdouble...
54                if (_mx < _mn && defined == 3) //only default was defined, so let's assume some arbitrary range. Again, no check for min/maxdouble...
55                {
56                        _mn = _def - 500.0;
57                        _mx = _def + 500.0;
58                }
[168]59                if (defined < 3) _def = (_mn + _mx) / 2.0;
60                mn = _mn; mx = _mx; def = _def;
61        }
62        if (p->type(i)[0] == 'd')
63        {
[247]64                paInt _mn = 0, _mx = 1, _def = 0;
[743]65                defined = p->getMinMaxInt(i, _mn, _mx, _def);
[765]66                if (defined == 1) _mx = _mn + 1000; //only min was defined, so let's set some arbitrary range, just to have some freedom. Assumes _mn is not close to maxint...
67                if (_mx < _mn && defined == 3) //only default was defined, so let's assume some arbitrary range. Again, no check for min/maxint...
68                {
69                        _mn = _def - 500;
70                        _mx = _def + 500;
71                }
[168]72                if (defined < 3) _def = (_mn + _mx) / 2;
73                mn = _mn; mx = _mx; def = _def;
74        }
75        return defined == 3;
[109]76}
77
[899]78int GenoOperators::selectRandomProperty(Neuro *n)
[109]79{
[168]80        int neuext = n->extraProperties().getPropCount(),
81                neucls = n->getClass() == NULL ? 0 : n->getClass()->getProperties().getPropCount();
82        if (neuext + neucls == 0) return -1; //no properties in this neuron
[896]83        int index = rndUint(neuext + neucls);
[168]84        if (index >= neuext) index = index - neuext + 100;
85        return index;
[109]86}
87
[168]88double GenoOperators::mutateNeuProperty(double current, Neuro *n, int i)
[109]89{
[751]90        if (i == -1) return mutateCreepNoLimit('f', current, 2, true); //i==-1: mutating weight of neural connection
[168]91        Param p;
92        if (i >= 100) { i -= 100; p = n->getClass()->getProperties(); }
93        else p = n->extraProperties();
94        double newval = current;
95        /*bool ok=*/getMutatedProperty(p, i, current, newval);
96        return newval;
[109]97}
98
[168]99bool GenoOperators::mutatePropertyNaive(ParamInterface &p, int i)
[109]100{
[168]101        double mn, mx, df;
102        if (p.type(i)[0] != 'f' && p.type(i)[0] != 'd') return false; //don't know how to mutate
103        getMinMaxDef(&p, i, mn, mx, df);
[109]104
[168]105        ExtValue ev;
106        p.get(i, ev);
[751]107        ev.setDouble(mutateCreep(p.type(i)[0], ev.getDouble(), mn, mx, true));
[168]108        p.set(i, ev);
109        return true;
[109]110}
111
[168]112bool GenoOperators::mutateProperty(ParamInterface &p, int i)
[109]113{
[168]114        double newval;
115        ExtValue ev;
116        p.get(i, ev);
117        bool ok = getMutatedProperty(p, i, ev.getDouble(), newval);
118        if (ok) { ev.setDouble(newval); p.set(i, ev); }
119        return ok;
[109]120}
121
[168]122bool GenoOperators::getMutatedProperty(ParamInterface &p, int i, double oldval, double &newval)
[109]123{
[168]124        newval = 0;
125        if (p.type(i)[0] != 'f' && p.type(i)[0] != 'd') return false; //don't know how to mutate
126        const char *n = p.id(i), *na = p.name(i);
127        if (strcmp(n, "si") == 0 && strcmp(na, "Sigmoid") == 0) newval = CustomRnd(distrib_sigmo); else
128                if (strcmp(n, "in") == 0 && strcmp(na, "Inertia") == 0) newval = CustomRnd(distrib_inertia); else
129                        if (strcmp(n, "fo") == 0 && strcmp(na, "Force") == 0) newval = CustomRnd(distrib_force); else
130                        {
[899]131                                double mn, mx, df;
132                                getMinMaxDef(&p, i, mn, mx, df);
133                                newval = mutateCreep(p.type(i)[0], oldval, mn, mx, true);
[168]134                        }
135        return true;
[109]136}
137
[751]138double GenoOperators::mutateCreepNoLimit(char type, double current, double stddev, bool limit_precision_3digits)
[109]139{
[751]140        double result = RndGen.Gauss(current, stddev);
141        if (type == 'd')
142        {
143                result = int(result + 0.5);
[896]144                if (result == current) result += rndUint(2) * 2 - 1; //force some change
[751]145        }
146        else
147        {
148                if (limit_precision_3digits)
149                        result = floor(result * 1000 + 0.5) / 1000.0; //round
150        }
[168]151        return result;
[109]152}
153
[751]154double GenoOperators::mutateCreep(char type, double current, double mn, double mx, double stddev, bool limit_precision_3digits)
[109]155{
[751]156        double result = mutateCreepNoLimit(type, current, stddev, limit_precision_3digits);
[764]157        if (result<mn || result>mx) //exceeds boundary, so bring to the allowed range
158        {
159                //reflect:
160                if (result > mx) result = mx - (result - mx); else
161                        if (result < mn) result = mn + (mn - result);
162                //wrap (just in case 'result' exceeded the allowed range so much that after reflection above it exceeded the other boundary):
163                if (result > mx) result = mn + fmod(result - mx, mx - mn); else
164                        if (result < mn) result = mn + fmod(mn - result, mx - mn);
165                if (limit_precision_3digits)
166                {
167                        //reflect and wrap above may have changed the (limited) precision, so try to round again (maybe unnecessarily, because we don't know if reflect+wrap above were triggered)
168                        double result_try = floor(result * 1000 + 0.5) / 1000.0; //round
169                        if (mn <= result_try && result_try <= mx) result = result_try; //after rounding still witin allowed range, so keep rounded value
170                }
171        }
[146]172        return result;
[109]173}
174
[751]175double GenoOperators::mutateCreep(char type, double current, double mn, double mx, bool limit_precision_3digits)
176{
177        double stddev = (mx - mn) / 2 / 5; // magic arbitrary formula for stddev, which becomes /halfinterval, 5 times narrower
178        return mutateCreep(type, current, mn, mx, stddev, limit_precision_3digits);
179}
180
[146]181void GenoOperators::setIntFromDoubleWithProbabilisticDithering(ParamInterface &p, int index, double value) //TODO
182{
[749]183        p.setInt(index, (paInt)(value + 0.5)); //TODO value=2.499 will result in 2 and 2.5 will result in 3, but we want these cases to be 2 or 3 with almost equal probability. value=2.1 should be mostly 2, rarely 3. Careful with negative values (test it!)
[146]184}
185
[749]186void GenoOperators::linearMix(vector<double> &p1, vector<double> &p2, double proportion)
187{
188        if (p1.size() != p2.size())
189        {
190                logPrintf("GenoOperators", "linearMix", LOG_ERROR, "Cannot mix vectors of different length (%d and %d)", p1.size(), p2.size());
191                return;
192        }
193        for (unsigned int i = 0; i < p1.size(); i++)
194        {
195                double v1 = p1[i];
196                double v2 = p2[i];
[899]197                p1[i] = v1 * proportion + v2 * (1 - proportion);
198                p2[i] = v2 * proportion + v1 * (1 - proportion);
[749]199        }
200}
201
[146]202void GenoOperators::linearMix(ParamInterface &p1, int i1, ParamInterface &p2, int i2, double proportion)
203{
[158]204        char type1 = p1.type(i1)[0];
205        char type2 = p2.type(i2)[0];
206        if (type1 == 'f' && type2 == 'f')
[146]207        {
208                double v1 = p1.getDouble(i1);
209                double v2 = p2.getDouble(i2);
[899]210                p1.setDouble(i1, v1 * proportion + v2 * (1 - proportion));
211                p2.setDouble(i2, v2 * proportion + v1 * (1 - proportion));
[146]212        }
[158]213        else
214                if (type1 == 'd' && type2 == 'd')
215                {
[899]216                        int v1 = p1.getInt(i1);
217                        int v2 = p2.getInt(i2);
218                        setIntFromDoubleWithProbabilisticDithering(p1, i1, v1 * proportion + v2 * (1 - proportion));
219                        setIntFromDoubleWithProbabilisticDithering(p2, i2, v2 * proportion + v1 * (1 - proportion));
[158]220                }
221                else
[375]222                        logPrintf("GenoOperators", "linearMix", LOG_WARN, "Cannot mix values of types '%c' and '%c'", type1, type2);
[146]223}
224
[801]225int GenoOperators::getActiveNeuroClassCount()
226{
227        int count = 0;
228        for (int i = 0; i < Neuro::getClassCount(); i++)
229                if (Neuro::getClass(i)->genactive)
230                        count++;
231        return count;
232}
233
[899]234NeuroClass *GenoOperators::getRandomNeuroClass()
[109]235{
[899]236        vector<NeuroClass *> active;
[168]237        for (int i = 0; i < Neuro::getClassCount(); i++)
[673]238                if (Neuro::getClass(i)->genactive)
239                        active.push_back(Neuro::getClass(i));
[896]240        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[109]241}
242
[899]243NeuroClass *GenoOperators::getRandomNeuroClassWithOutput()
[758]244{
[899]245        vector<NeuroClass *> active;
[758]246        for (int i = 0; i < Neuro::getClassCount(); i++)
247                if (Neuro::getClass(i)->genactive && Neuro::getClass(i)->getPreferredOutput() != 0)
248                        active.push_back(Neuro::getClass(i));
[896]249        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]250}
251
[899]252NeuroClass *GenoOperators::getRandomNeuroClassWithInput()
[758]253{
[899]254        vector<NeuroClass *> active;
[758]255        for (int i = 0; i < Neuro::getClassCount(); i++)
256                if (Neuro::getClass(i)->genactive && Neuro::getClass(i)->getPreferredInputs() != 0)
257                        active.push_back(Neuro::getClass(i));
[896]258        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]259}
260
[899]261NeuroClass *GenoOperators::getRandomNeuroClassWithOutputAndNoInputs()
[758]262{
[899]263        vector<NeuroClass *> active;
[758]264        for (int i = 0; i < Neuro::getClassCount(); i++)
265                if (Neuro::getClass(i)->genactive && Neuro::getClass(i)->getPreferredOutput() != 0 && Neuro::getClass(i)->getPreferredInputs() == 0)
266                        active.push_back(Neuro::getClass(i));
[896]267        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]268}
269
[899]270int GenoOperators::getRandomNeuroClassWithOutput(const vector<NeuroClass *> &NClist)
[673]271{
272        vector<int> allowed;
273        for (size_t i = 0; i < NClist.size(); i++)
274                if (NClist[i]->getPreferredOutput() != 0) //this NeuroClass provides output
275                        allowed.push_back(i);
[896]276        if (allowed.size() == 0) return -1; else return allowed[rndUint(allowed.size())];
[673]277}
278
[899]279int GenoOperators::getRandomNeuroClassWithInput(const vector<NeuroClass *> &NClist)
[673]280{
281        vector<int> allowed;
282        for (size_t i = 0; i < NClist.size(); i++)
283                if (NClist[i]->getPreferredInputs() != 0) //this NeuroClass wants one input connection or more                 
284                        allowed.push_back(i);
[896]285        if (allowed.size() == 0) return -1; else return allowed[rndUint(allowed.size())];
[673]286}
287
288int GenoOperators::getRandomChar(const char *choices, const char *excluded)
289{
290        int allowed_count = 0;
291        for (size_t i = 0; i < strlen(choices); i++) if (!strchrn0(excluded, choices[i])) allowed_count++;
292        if (allowed_count == 0) return -1; //no char is allowed
[896]293        int rnd_index = rndUint(allowed_count) + 1;
[673]294        allowed_count = 0;
295        for (size_t i = 0; i < strlen(choices); i++)
296        {
297                if (!strchrn0(excluded, choices[i])) allowed_count++;
298                if (allowed_count == rnd_index) return i;
299        }
300        return -1; //never happens
301}
302
[899]303NeuroClass *GenoOperators::parseNeuroClass(char *&s)
[109]304{
[670]305        int maxlen = (int)strlen(s);
306        int NClen = 0;
307        NeuroClass *NC = NULL;
[899]308        for (int i = 0; i < Neuro::getClassCount(); i++)
[168]309        {
[670]310                const char *ncname = Neuro::getClass(i)->name.c_str();
311                int ncnamelen = (int)strlen(ncname);
[899]312                if (maxlen >= ncnamelen && ncnamelen > NClen && (strncmp(s, ncname, ncnamelen) == 0))
[670]313                {
314                        NC = Neuro::getClass(i);
315                        NClen = ncnamelen;
316                }
[168]317        }
[670]318        s += NClen;
319        return NC;
[109]320}
321
[899]322Neuro *GenoOperators::findNeuro(const Model *m, const NeuroClass *nc)
[109]323{
[168]324        if (!m) return NULL;
325        for (int i = 0; i < m->getNeuroCount(); i++)
326                if (m->getNeuro(i)->getClass() == nc) return m->getNeuro(i);
327        return NULL; //neuron of class 'nc' was not found
[109]328}
329
[899]330int GenoOperators::neuroClassProp(char *&s, NeuroClass *nc, bool also_v1_N_props)
[109]331{
[247]332        int len = (int)strlen(s);
[168]333        int Len = 0, I = -1;
334        if (nc)
335        {
336                Param p = nc->getProperties();
[899]337                for (int i = 0; i < p.getPropCount(); i++)
[168]338                {
339                        const char *n = p.id(i);
[247]340                        int l = (int)strlen(n);
[899]341                        if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
[168]342                        if (also_v1_N_props) //recognize old properties symbols /=!
343                        {
344                                if (strcmp(n, "si") == 0) n = "/"; else
345                                        if (strcmp(n, "in") == 0) n = "="; else
346                                                if (strcmp(n, "fo") == 0) n = "!";
[247]347                                l = (int)strlen(n);
[168]348                                if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
349                        }
350                }
351        }
352        Neuro n;
353        Param p = n.extraProperties();
[899]354        for (int i = 0; i < p.getPropCount(); i++)
[168]355        {
356                const char *n = p.id(i);
[247]357                int l = (int)strlen(n);
[899]358                if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = i; Len = l; }
[168]359        }
360        s += Len;
361        return I;
[109]362}
363
[121]364bool GenoOperators::isWS(const char c)
[168]365{
366        return c == ' ' || c == '\n' || c == '\t' || c == '\r';
367}
[109]368
[121]369void GenoOperators::skipWS(char *&s)
[158]370{
[168]371        if (s == NULL)
[375]372                logMessage("GenoOperators", "skipWS", LOG_WARN, "NULL reference!");
[158]373        else
[670]374                while (isWS(*s)) s++;
[109]375}
376
[168]377bool GenoOperators::areAlike(char *g1, char *g2)
[109]378{
379        while (*g1 || *g2)
380        {
381                skipWS(g1);
382                skipWS(g2);
383                if (*g1 != *g2) return false; //when difference
[168]384                if (!*g1 && !*g2) break; //both end
385                g1++;
386                g2++;
[109]387        }
388        return true; //equal
389}
390
[899]391char *GenoOperators::strchrn0(const char *str, char ch)
[168]392{
[899]393        return ch == 0 ? NULL : strchr((char *)str, ch);
[168]394}
[109]395
[758]396bool GenoOperators::canStartNeuroClassName(const char firstchar)
[109]397{
[168]398        return isupper(firstchar) || firstchar == '|' || firstchar == '@' || firstchar == '*';
[109]399}
Note: See TracBrowser for help on using the repository browser.