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

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

Utility functions that provide a set of all neuron classes fulfilling given criteria now also filter neuron classes by the desired Model shape type (BALL_AND_STICK or SOLIDS)

  • Property svn:eol-style set to native
File size: 13.1 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[935]2// Copyright (C) 1999-2020  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
[935]225int GenoOperators::getActiveNeuroClassCount(Model::ShapeType for_shape_type)
[801]226{
227        int count = 0;
228        for (int i = 0; i < Neuro::getClassCount(); i++)
[935]229        {
230                NeuroClass *nc = Neuro::getClass(i);
231                if (nc->isShapeTypeSupported(for_shape_type) && nc->genactive)
[801]232                        count++;
[935]233        }
[801]234        return count;
235}
236
[935]237NeuroClass *GenoOperators::getRandomNeuroClass(Model::ShapeType for_shape_type)
[109]238{
[899]239        vector<NeuroClass *> active;
[168]240        for (int i = 0; i < Neuro::getClassCount(); i++)
[935]241        {
242                NeuroClass *nc = Neuro::getClass(i);
243                if (nc->isShapeTypeSupported(for_shape_type) && nc->genactive)
244                        active.push_back(nc);
245        }
[896]246        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[109]247}
248
[935]249NeuroClass *GenoOperators::getRandomNeuroClassWithOutput(Model::ShapeType for_shape_type)
[758]250{
[899]251        vector<NeuroClass *> active;
[758]252        for (int i = 0; i < Neuro::getClassCount(); i++)
[935]253        {
254                NeuroClass *nc = Neuro::getClass(i);
255                if (nc->isShapeTypeSupported(for_shape_type) && nc->genactive && nc->getPreferredOutput() != 0)
256                        active.push_back(nc);
257        }
[896]258        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]259}
260
[935]261NeuroClass *GenoOperators::getRandomNeuroClassWithInput(Model::ShapeType for_shape_type)
[758]262{
[899]263        vector<NeuroClass *> active;
[758]264        for (int i = 0; i < Neuro::getClassCount(); i++)
[935]265        {
266                NeuroClass *nc = Neuro::getClass(i);
267                if (nc->isShapeTypeSupported(for_shape_type) && nc->genactive && nc->getPreferredInputs() != 0)
268                        active.push_back(nc);
269        }
[896]270        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]271}
272
[935]273NeuroClass *GenoOperators::getRandomNeuroClassWithOutputAndNoInputs(Model::ShapeType for_shape_type)
[758]274{
[899]275        vector<NeuroClass *> active;
[758]276        for (int i = 0; i < Neuro::getClassCount(); i++)
[935]277        {
278                NeuroClass *nc = Neuro::getClass(i);
279                if (nc->isShapeTypeSupported(for_shape_type) && nc->genactive && nc->getPreferredOutput() != 0 && nc->getPreferredInputs() == 0)
280                        active.push_back(nc);
281        }
[896]282        if (active.size() == 0) return NULL; else return active[rndUint(active.size())];
[758]283}
284
[899]285int GenoOperators::getRandomNeuroClassWithOutput(const vector<NeuroClass *> &NClist)
[673]286{
287        vector<int> allowed;
288        for (size_t i = 0; i < NClist.size(); i++)
289                if (NClist[i]->getPreferredOutput() != 0) //this NeuroClass provides output
290                        allowed.push_back(i);
[896]291        if (allowed.size() == 0) return -1; else return allowed[rndUint(allowed.size())];
[673]292}
293
[899]294int GenoOperators::getRandomNeuroClassWithInput(const vector<NeuroClass *> &NClist)
[673]295{
296        vector<int> allowed;
297        for (size_t i = 0; i < NClist.size(); i++)
298                if (NClist[i]->getPreferredInputs() != 0) //this NeuroClass wants one input connection or more                 
299                        allowed.push_back(i);
[896]300        if (allowed.size() == 0) return -1; else return allowed[rndUint(allowed.size())];
[673]301}
302
303int GenoOperators::getRandomChar(const char *choices, const char *excluded)
304{
305        int allowed_count = 0;
306        for (size_t i = 0; i < strlen(choices); i++) if (!strchrn0(excluded, choices[i])) allowed_count++;
307        if (allowed_count == 0) return -1; //no char is allowed
[896]308        int rnd_index = rndUint(allowed_count) + 1;
[673]309        allowed_count = 0;
310        for (size_t i = 0; i < strlen(choices); i++)
311        {
312                if (!strchrn0(excluded, choices[i])) allowed_count++;
313                if (allowed_count == rnd_index) return i;
314        }
315        return -1; //never happens
316}
317
[899]318NeuroClass *GenoOperators::parseNeuroClass(char *&s)
[109]319{
[670]320        int maxlen = (int)strlen(s);
321        int NClen = 0;
322        NeuroClass *NC = NULL;
[899]323        for (int i = 0; i < Neuro::getClassCount(); i++)
[168]324        {
[670]325                const char *ncname = Neuro::getClass(i)->name.c_str();
326                int ncnamelen = (int)strlen(ncname);
[899]327                if (maxlen >= ncnamelen && ncnamelen > NClen && (strncmp(s, ncname, ncnamelen) == 0))
[670]328                {
329                        NC = Neuro::getClass(i);
330                        NClen = ncnamelen;
331                }
[168]332        }
[670]333        s += NClen;
334        return NC;
[109]335}
336
[899]337Neuro *GenoOperators::findNeuro(const Model *m, const NeuroClass *nc)
[109]338{
[168]339        if (!m) return NULL;
340        for (int i = 0; i < m->getNeuroCount(); i++)
341                if (m->getNeuro(i)->getClass() == nc) return m->getNeuro(i);
342        return NULL; //neuron of class 'nc' was not found
[109]343}
344
[899]345int GenoOperators::neuroClassProp(char *&s, NeuroClass *nc, bool also_v1_N_props)
[109]346{
[247]347        int len = (int)strlen(s);
[168]348        int Len = 0, I = -1;
349        if (nc)
350        {
351                Param p = nc->getProperties();
[899]352                for (int i = 0; i < p.getPropCount(); i++)
[168]353                {
354                        const char *n = p.id(i);
[247]355                        int l = (int)strlen(n);
[899]356                        if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
[168]357                        if (also_v1_N_props) //recognize old properties symbols /=!
358                        {
359                                if (strcmp(n, "si") == 0) n = "/"; else
360                                        if (strcmp(n, "in") == 0) n = "="; else
361                                                if (strcmp(n, "fo") == 0) n = "!";
[247]362                                l = (int)strlen(n);
[168]363                                if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
364                        }
365                }
366        }
367        Neuro n;
368        Param p = n.extraProperties();
[899]369        for (int i = 0; i < p.getPropCount(); i++)
[168]370        {
371                const char *n = p.id(i);
[247]372                int l = (int)strlen(n);
[899]373                if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = i; Len = l; }
[168]374        }
375        s += Len;
376        return I;
[109]377}
378
[121]379bool GenoOperators::isWS(const char c)
[168]380{
381        return c == ' ' || c == '\n' || c == '\t' || c == '\r';
382}
[109]383
[121]384void GenoOperators::skipWS(char *&s)
[158]385{
[168]386        if (s == NULL)
[375]387                logMessage("GenoOperators", "skipWS", LOG_WARN, "NULL reference!");
[158]388        else
[670]389                while (isWS(*s)) s++;
[109]390}
391
[168]392bool GenoOperators::areAlike(char *g1, char *g2)
[109]393{
394        while (*g1 || *g2)
395        {
396                skipWS(g1);
397                skipWS(g2);
398                if (*g1 != *g2) return false; //when difference
[168]399                if (!*g1 && !*g2) break; //both end
400                g1++;
401                g2++;
[109]402        }
403        return true; //equal
404}
405
[899]406char *GenoOperators::strchrn0(const char *str, char ch)
[168]407{
[899]408        return ch == 0 ? NULL : strchr((char *)str, ch);
[168]409}
[109]410
[758]411bool GenoOperators::canStartNeuroClassName(const char firstchar)
[109]412{
[168]413        return isupper(firstchar) || firstchar == '|' || firstchar == '@' || firstchar == '*';
[109]414}
Note: See TracBrowser for help on using the repository browser.