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

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

Added a helper function that counts active neuron classes

  • Property svn:eol-style set to native
File size: 12.7 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 <ctype.h>  //isupper()
6#include "genooperators.h"
7#include <common/log.h>
8#include <common/nonstd_math.h>
9#include <frams/util/rndutil.h>
10
11static double distrib_force[] =   // for '!'
12{
13        3,             // distribution 0 -__/ +1
14        0.001, 0.2,    // "slow" neurons
15        0.001, 1,
16        1, 1,          // "fast" neurons
17};
18static double distrib_inertia[] =  // for '='
19{
20        2,             // distribution 0 |..- +1
21        0, 0,          // "fast" neurons
22        0.7, 0.98,
23};
24static double distrib_sigmo[] =  // for '/'
25{
26        5,             // distribution -999 -..-^-..- +999
27        -999, -999,    //"perceptron"
28        999, 999,
29        -5, -1,        // nonlinear
30        1, 5,
31        -1, 1,         // ~linear
32};
33
34
35int GenoOperators::roulette(const double *probtab, const int count)
36{
37        double sum = 0;
38        int i;
39        for (i = 0; i < count; i++) sum += probtab[i];
40        double sel = rnd01*sum;
41        for (sum = 0, i = 0; i < count; i++) { sum += probtab[i]; if (sel < sum) return i; }
42        return -1;
43}
44
45bool GenoOperators::getMinMaxDef(ParamInterface *p, int i, double &mn, double &mx, double &def)
46{
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;
52                defined = p->getMinMaxDouble(i, _mn, _mx, _def);
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                }
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        {
64                paInt _mn = 0, _mx = 1, _def = 0;
65                defined = p->getMinMaxInt(i, _mn, _mx, _def);
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                }
72                if (defined < 3) _def = (_mn + _mx) / 2;
73                mn = _mn; mx = _mx; def = _def;
74        }
75        return defined == 3;
76}
77
78int GenoOperators::selectRandomProperty(Neuro* n)
79{
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
83        int index = randomN(neuext + neucls);
84        if (index >= neuext) index = index - neuext + 100;
85        return index;
86}
87
88double GenoOperators::mutateNeuProperty(double current, Neuro *n, int i)
89{
90        if (i == -1) return mutateCreepNoLimit('f', current, 2, true); //i==-1: mutating weight of neural connection
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;
97}
98
99bool GenoOperators::mutatePropertyNaive(ParamInterface &p, int i)
100{
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);
104
105        ExtValue ev;
106        p.get(i, ev);
107        ev.setDouble(mutateCreep(p.type(i)[0], ev.getDouble(), mn, mx, true));
108        p.set(i, ev);
109        return true;
110}
111
112bool GenoOperators::mutateProperty(ParamInterface &p, int i)
113{
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;
120}
121
122bool GenoOperators::getMutatedProperty(ParamInterface &p, int i, double oldval, double &newval)
123{
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                        {
131                double mn, mx, df;
132                getMinMaxDef(&p, i, mn, mx, df);
133                newval = mutateCreep(p.type(i)[0], oldval, mn, mx, true);
134                        }
135        return true;
136}
137
138double GenoOperators::mutateCreepNoLimit(char type, double current, double stddev, bool limit_precision_3digits)
139{
140        double result = RndGen.Gauss(current, stddev);
141        if (type == 'd')
142        {
143                result = int(result + 0.5);
144                if (result == current) result += randomN(2) * 2 - 1; //force some change
145        }
146        else
147        {
148                if (limit_precision_3digits)
149                        result = floor(result * 1000 + 0.5) / 1000.0; //round
150        }
151        return result;
152}
153
154double GenoOperators::mutateCreep(char type, double current, double mn, double mx, double stddev, bool limit_precision_3digits)
155{
156        double result = mutateCreepNoLimit(type, current, stddev, limit_precision_3digits);
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        }
172        return result;
173}
174
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
181void GenoOperators::setIntFromDoubleWithProbabilisticDithering(ParamInterface &p, int index, double value) //TODO
182{
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!)
184}
185
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];
197                p1[i] = v1*proportion + v2*(1 - proportion);
198                p2[i] = v2*proportion + v1*(1 - proportion);
199        }
200}
201
202void GenoOperators::linearMix(ParamInterface &p1, int i1, ParamInterface &p2, int i2, double proportion)
203{
204        char type1 = p1.type(i1)[0];
205        char type2 = p2.type(i2)[0];
206        if (type1 == 'f' && type2 == 'f')
207        {
208                double v1 = p1.getDouble(i1);
209                double v2 = p2.getDouble(i2);
210                p1.setDouble(i1, v1*proportion + v2*(1 - proportion));
211                p2.setDouble(i2, v2*proportion + v1*(1 - proportion));
212        }
213        else
214                if (type1 == 'd' && type2 == 'd')
215                {
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));
220                }
221                else
222                        logPrintf("GenoOperators", "linearMix", LOG_WARN, "Cannot mix values of types '%c' and '%c'", type1, type2);
223}
224
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
234NeuroClass* GenoOperators::getRandomNeuroClass()
235{
236        vector<NeuroClass*> active;
237        for (int i = 0; i < Neuro::getClassCount(); i++)
238                if (Neuro::getClass(i)->genactive)
239                        active.push_back(Neuro::getClass(i));
240        if (active.size() == 0) return NULL; else return active[randomN(active.size())];
241}
242
243NeuroClass* GenoOperators::getRandomNeuroClassWithOutput()
244{
245        vector<NeuroClass*> active;
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));
249        if (active.size() == 0) return NULL; else return active[randomN(active.size())];
250}
251
252NeuroClass* GenoOperators::getRandomNeuroClassWithInput()
253{
254        vector<NeuroClass*> active;
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));
258        if (active.size() == 0) return NULL; else return active[randomN(active.size())];
259}
260
261NeuroClass* GenoOperators::getRandomNeuroClassWithOutputAndNoInputs()
262{
263        vector<NeuroClass*> active;
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));
267        if (active.size() == 0) return NULL; else return active[randomN(active.size())];
268}
269
270int GenoOperators::getRandomNeuroClassWithOutput(const vector<NeuroClass*>& NClist)
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);
276        if (allowed.size() == 0) return -1; else return allowed[randomN(allowed.size())];
277}
278
279int GenoOperators::getRandomNeuroClassWithInput(const vector<NeuroClass*>& NClist)
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);
285        if (allowed.size() == 0) return -1; else return allowed[randomN(allowed.size())];
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
293        int rnd_index = randomN(allowed_count) + 1;
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
303NeuroClass* GenoOperators::parseNeuroClass(char*& s)
304{
305        int maxlen = (int)strlen(s);
306        int NClen = 0;
307        NeuroClass *NC = NULL;
308        for (int i = 0; i<Neuro::getClassCount(); i++)
309        {
310                const char *ncname = Neuro::getClass(i)->name.c_str();
311                int ncnamelen = (int)strlen(ncname);
312                if (maxlen >= ncnamelen && ncnamelen>NClen && (strncmp(s, ncname, ncnamelen) == 0))
313                {
314                        NC = Neuro::getClass(i);
315                        NClen = ncnamelen;
316                }
317        }
318        s += NClen;
319        return NC;
320}
321
322Neuro* GenoOperators::findNeuro(const Model *m, const NeuroClass *nc)
323{
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
328}
329
330int GenoOperators::neuroClassProp(char*& s, NeuroClass *nc, bool also_v1_N_props)
331{
332        int len = (int)strlen(s);
333        int Len = 0, I = -1;
334        if (nc)
335        {
336                Param p = nc->getProperties();
337                for (int i = 0; i<p.getPropCount(); i++)
338                {
339                        const char *n = p.id(i);
340                        int l = (int)strlen(n);
341                        if (len >= l && l>Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
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 = "!";
347                                l = (int)strlen(n);
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();
354        for (int i = 0; i<p.getPropCount(); i++)
355        {
356                const char *n = p.id(i);
357                int l = (int)strlen(n);
358                if (len >= l && l>Len && (strncmp(s, n, l) == 0)) { I = i; Len = l; }
359        }
360        s += Len;
361        return I;
362}
363
364bool GenoOperators::isWS(const char c)
365{
366        return c == ' ' || c == '\n' || c == '\t' || c == '\r';
367}
368
369void GenoOperators::skipWS(char *&s)
370{
371        if (s == NULL)
372                logMessage("GenoOperators", "skipWS", LOG_WARN, "NULL reference!");
373        else
374                while (isWS(*s)) s++;
375}
376
377bool GenoOperators::areAlike(char *g1, char *g2)
378{
379        while (*g1 || *g2)
380        {
381                skipWS(g1);
382                skipWS(g2);
383                if (*g1 != *g2) return false; //when difference
384                if (!*g1 && !*g2) break; //both end
385                g1++;
386                g2++;
387        }
388        return true; //equal
389}
390
391char* GenoOperators::strchrn0(const char *str, char ch)
392{
393        return ch == 0 ? NULL : strchr((char*)str, ch);
394}
395
396bool GenoOperators::canStartNeuroClassName(const char firstchar)
397{
398        return isupper(firstchar) || firstchar == '|' || firstchar == '@' || firstchar == '*';
399}
400
Note: See TracBrowser for help on using the repository browser.