source: cpp/frams/genetics/f1/conv_f1.cpp @ 672

Last change on this file since 672 was 672, checked in by Maciej Komosinski, 7 years ago

More appropriate name for the "model_energy_max" variable

  • Property svn:eol-style set to native
File size: 16.4 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2017  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#include "conv_f1.h"
6#include <common/nonstd_stl.h>
7#include <common/log.h>
8#include <frams/util/multirange.h>
9#include <frams/util/multimap.h>
10#include <ctype.h>
11
12//#define v1f1COMPATIBLE //as in ancient Framsticks 1.x
13
14F1Props stdprops = { 1, 0, 1, 0.4, 0.25, 0.25, 0.25, 0.25, 0.0, 1.0, 1.0, 1,
15        0.2, 0.5, 0.5, 0.5 };
16
17class Builder
18{
19public:
20        Builder(const char*g, int mapping = 0) :invalid(0), genbegin(g), usemapping(mapping), first_part_mapping(NULL), model_energy(0), model_energy_count(0) {}
21        ~Builder() { SAFEDELETE(first_part_mapping); }
22        char tmp[222];
23        bool invalid;
24        Model model;
25        const char *genbegin;
26        SList neuro_f1_to_f0; // neuro_f1_to_f0(f1_refno) = actual neuro pointer
27        Neuro *last_f1_neuro;
28        SyntParam *neuro_cls_param;
29
30        struct Connection
31        {
32                int n1, n2; double w;
33                Connection(int _n1, int _n2, double _w) :n1(_n1), n2(_n2), w(_w) {}
34        };
35
36        SListTempl<Connection> connections;
37        int usemapping;
38        MultiRange range;
39        MultiRange *first_part_mapping;
40        double lastjoint_muscle_power;
41        double model_energy;
42        int model_energy_count;
43        void grow(int part1, const char*g, Pt3D k, F1Props c);
44        void setPartMapping(int p, const char* g);
45        int growJoint(int part1, int part2, Pt3D &angle, F1Props &c, const char *g);
46        int growPart(F1Props &c, const char *g);
47        const char *skipNeuro(const char *z);
48        const char* growNeuro(const char* t, F1Props &c, int&);
49        void growConnection(const char* begin, const char* colon, const char* end, F1Props& props);
50        int countBranches(const char*g, SList &out);
51        SyntParam* lastNeuroClassParam();
52        void addClassParam(const char* name, double value);
53        void addClassParam(const char* name, const char* value);
54
55        const MultiRange* makeRange(const char*g) { return makeRange(g, g); }
56        const MultiRange* makeRange(const char*g, const char*g2);
57        Part *getLastPart() { return getLastJoint()->part2; }
58        Neuro *getLastNeuro() { return model.getNeuro(model.getNeuroCount() - 1); }
59        Joint *getLastJoint() { return model.getJoint(model.getJointCount() - 1); }
60        void addOrRememberInput(int n1, int n2, double w)
61        {
62                //if (!addInput(n1,n2,w,false))
63                connections += Connection(n1, n2, w);
64        }
65        bool addInput(int n1, int n2, double w, bool final)
66        {
67                if ((n1 < 0) || (n2 < 0) || (n1 >= neuro_f1_to_f0.size()) || (n2 >= neuro_f1_to_f0.size()))
68                {
69                        if (final) logPrintf("GenoConvF1", "addInput", LOG_WARN,
70                                "illegal neuron connection %d <- %d (ignored)", n1, n2);
71                        return 0;
72                }
73                Neuro *neuro = (Neuro*)neuro_f1_to_f0(n1);
74                Neuro *input = (Neuro*)neuro_f1_to_f0(n2);
75                neuro->addInput(input, w);
76                return 1;
77        }
78        void addPendingInputs()
79        {
80                for (int i = 0; i < connections.size(); i++)
81                {
82                        Connection *c = &connections(i);
83                        addInput(c->n1, c->n2, c->w, true);
84                }
85        }
86};
87
88const MultiRange* Builder::makeRange(const char*g, const char*g2)
89{
90        if (!usemapping) return 0;
91        range.clear();
92        range.add(g - genbegin, g2 - genbegin);
93        return &range;
94}
95
96void F1Props::normalizeBiol4()
97{
98        double sum = muscle_power + assimilation + stamina + ingestion;
99        muscle_power /= sum;
100        assimilation /= sum;
101        stamina /= sum;
102        ingestion /= sum;
103}
104
105/** main conversion function - with conversion map support */
106SString GenoConv_f1::convert(SString &i, MultiMap *map)
107{
108        const char* g = i.c_str();
109        Builder builder(g, map ? 1 : 0);
110        builder.model.open();
111        builder.grow(-1, g, Pt3D_0, stdprops); // uses Model::singleStepBuild to create model elements
112        if (builder.invalid) return SString();
113        builder.addPendingInputs();
114        builder.model.startenergy = (builder.model_energy_count > 0) ? (builder.model_energy / builder.model_energy_count) : 1.0;
115        builder.model.close(); // model is ready to use now
116        if (map) builder.model.getCurrentToF0Map(*map); // generate f1-to-f0 conversion map
117        return builder.model.getF0Geno().getGenes();
118}
119
120void Builder::setPartMapping(int p, const char* g)
121{
122        if (!usemapping) return;
123        const MultiRange *r = makeRange(g);
124        if (p < 0)
125        { //special case: mapping the part which is not yet created
126                if (first_part_mapping) first_part_mapping->add(*r);
127                else first_part_mapping = new MultiRange(*r);
128        }
129        else
130                model.getPart(p)->addMapping(*r);
131}
132
133void Builder::grow(int part1, const char*g, Pt3D k, F1Props c)
134{
135        int hasmuscles = 0;
136        k += Pt3D(c.twist, 0, c.curvedness);
137        while (1)
138        {
139                switch (*g)
140                {
141                case 0: case ',': case ')': return;
142                case 'R': k.x += 0.7853; setPartMapping(part1, g); break;
143                case 'r': k.x -= 0.7853;        setPartMapping(part1, g); break;
144                case 'Q': c.twist += (1.58 - c.twist)*0.3; setPartMapping(part1, g); break;
145                case 'q': c.twist += (-1.58 - c.twist)*0.3; setPartMapping(part1, g); break;
146#ifdef v1f1COMPATIBLE
147                case 'L': c.length += (3.0 - c.length)*0.3; setPartMapping(part1, g); break;
148#else
149                case 'L': c.length += (2.0 - c.length)*0.3; setPartMapping(part1, g); break;
150#endif                                       
151                case 'l': c.length += (0.33 - c.length)*0.3; setPartMapping(part1, g); break;
152                case 'A': c.assimilation += (1 - c.assimilation)*0.8;   c.normalizeBiol4(); setPartMapping(part1, g);  break;
153                case 'a': c.assimilation -= c.assimilation*0.4; c.normalizeBiol4(); setPartMapping(part1, g); break;
154                case 'I': c.ingestion += (1 - c.ingestion)*0.8; c.normalizeBiol4(); setPartMapping(part1, g); break;
155                case 'i': c.ingestion -= c.ingestion*0.4;       c.normalizeBiol4(); setPartMapping(part1, g); break;
156                case 'S': c.stamina += (1 - c.stamina)*0.8; c.normalizeBiol4(); setPartMapping(part1, g); break;
157                case 's': c.stamina -= c.stamina*0.4; c.normalizeBiol4(); setPartMapping(part1, g); break;
158                case 'M': c.muscle_power += (1 - c.muscle_power)*0.8;   c.normalizeBiol4(); setPartMapping(part1, g); break;
159                case 'm': c.muscle_power -= c.muscle_power*0.4; c.normalizeBiol4(); setPartMapping(part1, g); break;
160                case 'C': c.curvedness += (2.0 - c.curvedness)*0.25;    setPartMapping(part1, g); break;
161                case 'c': c.curvedness += (-2.0 - c.curvedness)*0.25; setPartMapping(part1, g); break;
162                case 'F': c.friction += (4 - c.friction)*0.2; setPartMapping(part1, g); break;
163                case 'f': c.friction -= c.friction*0.2; setPartMapping(part1, g); break;
164                case 'W': c.weight += (2.0 - c.weight)*0.3; setPartMapping(part1, g); break;
165                case 'w': c.weight += (0.5 - c.weight)*0.3; setPartMapping(part1, g); break;
166                case 'E': c.energy += (10.0 - c.energy)*0.1; setPartMapping(part1, g); break;
167                case 'e': c.energy -= c.energy*0.1;     setPartMapping(part1, g); break;
168
169                case 'D': c.cred += (1.0 - c.cred)*0.25; setPartMapping(part1, g); break;
170                case 'd': c.cred += (0.0 - c.cred)*0.25; setPartMapping(part1, g); break;
171                case 'G': c.cgreen += (1.0 - c.cgreen)*0.25; setPartMapping(part1, g); break;
172                case 'g': c.cgreen += (0.0 - c.cgreen)*0.25; setPartMapping(part1, g); break;
173                case 'B': c.cblue += (1.0 - c.cblue)*0.25; setPartMapping(part1, g); break;
174                case 'b': c.cblue += (0.0 - c.cblue)*0.25; setPartMapping(part1, g); break;
175                case 'H': c.visual_size += (0.7 - c.visual_size)*0.25; setPartMapping(part1, g); break;
176                case 'h': c.visual_size += (0.05 - c.visual_size)*0.25; setPartMapping(part1, g); break;
177
178                case '[': //neuron
179                        //              setdebug(g-(char*)geny,DEBUGNEURO | !l_neu);
180                        if (model.getJointCount())
181                                g = growNeuro(g + 1, c, hasmuscles);
182                        else
183                        {
184                                logMessage("GenoConv_F1", "grow", 1, "Illegal neuron position (ignored)");
185                                g = skipNeuro(g + 1);
186                        }
187                        break;
188                case 'X':
189                {
190                        int freshpart = 0;
191                        //setdebug(g-(char*)geny,DEBUGEST | !l_est);
192                        if (part1 < 0) //initial grow
193                        {
194                                if (model.getPartCount() > 0)
195                                        part1 = 0;
196                                else
197                                {
198                                        part1 = growPart(c, g);
199                                        freshpart = 1;
200                                        if (first_part_mapping)
201                                                model.getPart(part1)->setMapping(*first_part_mapping);
202                                }
203                        }
204                        if (!freshpart)
205                        {
206                                Part *part = model.getPart(part1);
207                                part->density = ((part->mass*part->density) + 1.0 / c.weight) / (part->mass + 1.0); // v=m*d
208                                //                      part->volume+=1.0/c.weight;
209                                part->mass += 1.0;
210                        }
211                        model_energy += 0.9*c.energy + 0.1;
212                        model_energy_count++;
213
214                        int part2 = growPart(c, g);
215                        growJoint(part1, part2, k, c, g);
216                        //              est* e = new est(*s,*s2,k,c,zz,this);
217
218                        // attenuate properties as they are propagated along the structure
219                        c.length = 0.5*c.length + 0.5*stdprops.length;
220                        c.visual_size = 0.5*c.visual_size + 0.5*stdprops.visual_size;
221                        c.curvedness = 0.66*c.curvedness;
222                        c.twist = 0.66*c.twist;
223                        c.friction = 0.8*c.friction + 0.2*stdprops.friction;
224
225                        c.assimilation = 0.8*c.assimilation + 0.2*stdprops.assimilation;
226                        c.stamina = 0.8*c.stamina + 0.2*stdprops.stamina;
227                        c.muscle_power = 0.8*c.muscle_power + 0.2*stdprops.muscle_power;
228                        c.ingestion = 0.8*c.ingestion + 0.2*stdprops.ingestion;
229                        c.weight += (stdprops.weight - c.weight)*0.5;
230                        c.normalizeBiol4();
231
232                        if (c.muscle_reset_range) c.muscle_bend_range = 1.0; else c.muscle_reset_range = true;
233                        grow(part2, g + 1, Pt3D_0, c);
234                        return;
235                }
236                case '(':
237                {
238                        setPartMapping(part1, g);
239                        SList ga;
240                        int i, count;
241                        count = countBranches(g + 1, ga);
242                        c.muscle_reset_range = false;
243                        c.muscle_bend_range = 1.0 / count;
244                        for (i = 0; i < count; i++)
245                                grow(part1, (char*)ga(i), k + Pt3D(0, 0, -M_PI + (i + 1)*(2*M_PI / (count + 1))), c);
246                        return;
247                }
248                case ' ': case '\t': case '\n': case '\r': break;
249                default: invalid = 1; return;
250                }
251                g++;
252        }
253}
254
255SyntParam* Builder::lastNeuroClassParam()
256{
257        if (!neuro_cls_param)
258        {
259                NeuroClass *cls = last_f1_neuro->getClass();
260                if (cls)
261                {
262                        neuro_cls_param = new SyntParam(last_f1_neuro->classProperties());
263                        // this is equivalent to:
264                        //              SyntParam tmp=last_f1_neuro->classProperties();
265                        //              neuro_cls_param=new SyntParam(tmp);
266                        // interestingly, some compilers eliminate the call to new SyntParam,
267                        // realizing that a copy constructor is redundant when the original object is
268                        // temporary. there are no side effect of such optimization, as long as the
269                        // copy-constructed object is exact equivalent of the original.
270                }
271        }
272        return neuro_cls_param;
273}
274
275void Builder::addClassParam(const char* name, double value)
276{
277        lastNeuroClassParam();
278        if (neuro_cls_param)
279                neuro_cls_param->setDoubleById(name, value);
280}
281
282void Builder::addClassParam(const char* name, const char* value)
283{
284        lastNeuroClassParam();
285        if (neuro_cls_param)
286        {
287                ExtValue e(value);
288                const ExtValue &re(e);
289                neuro_cls_param->setById(name, re);
290        }
291}
292
293int Builder::countBranches(const char*g, SList &out)
294{
295        int gl = 0;
296        out += (void*)g;
297        while (gl >= 0)
298        {
299                switch (*g)
300                {
301                case 0: gl = -1; break;
302                case '(': case '[': ++gl; break;
303                case ')': case ']': --gl; break;
304                case ',': if (!gl) out += (void*)(g + 1);
305                }
306                g++;
307        }
308        return out.size();
309}
310
311int Builder::growJoint(int part1, int part2, Pt3D &angle, F1Props &c, const char *g)
312{
313        double len = min(2.0, c.length);
314        sprintf(tmp, "j:p1=%ld,p2=%ld,dx=%lg,rx=%lg,ry=%lg,rz=%lg,stam=%lg,vr=%g,vg=%g,vb=%g",
315                part1, part2, len, angle.x, angle.y, angle.z, c.stamina, c.cred, c.cgreen, c.cblue);
316        lastjoint_muscle_power = c.muscle_power;
317        return model.singleStepBuild(tmp, makeRange(g));
318}
319
320int Builder::growPart(F1Props &c, const char *g)
321{
322        sprintf(tmp, "p:dn=%lg,fr=%lg,ing=%lg,as=%lg,vs=%g,vr=%g,vg=%g,vb=%g",
323                1.0 / c.weight, c.friction, c.ingestion, c.assimilation, c.visual_size, c.cred, c.cgreen, c.cblue);
324        return model.singleStepBuild(tmp, makeRange(g));
325}
326
327const char *Builder::skipNeuro(const char *z)
328{
329        for (; *z; z++) if ((*z == ']') || (*z == ')')) break;
330        return z - 1;
331}
332
333const char* Builder::growNeuro(const char* t, F1Props& props, int &hasmuscles)
334{
335        const char*neuroend = skipNeuro(t);
336        last_f1_neuro = model.addNewNeuro();
337        neuro_cls_param = NULL;
338        last_f1_neuro->attachToPart(getLastPart());
339        const MultiRange *mr = makeRange(t - 1, neuroend + 1);
340        if (mr) last_f1_neuro->addMapping(*mr);
341        neuro_f1_to_f0 += last_f1_neuro;
342
343        SString clsname;
344        bool haveclass = 0;
345        while (*t && *t <= ' ') t++;
346        const char* next = (*t) ? (t + 1) : t;
347        while (*next && *next <= ' ') next++;
348        if (*t && *next != ',' && *next != ']') // old style muscles [|rest] or [@rest]
349                switch (*t)
350        {
351                case '@': if (t[1] == ':') break;
352                        haveclass = 1;
353                        //              if (!(hasmuscles&1))
354                        {
355                                hasmuscles |= 1;
356                                Neuro *muscle = model.addNewNeuro();
357                                sprintf(tmp, "@:p=%lg", lastjoint_muscle_power);
358                                muscle->addInput(last_f1_neuro);
359                                muscle->setDetails(tmp);
360                                muscle->attachToJoint(getLastJoint());
361                                if (usemapping) muscle->addMapping(*makeRange(t));
362                        }
363                        t++;
364                        break;
365                case '|': if (t[1] == ':') break;
366                        haveclass = 1;
367                        //              if (!(hasmuscles&2))
368                        {
369                                hasmuscles |= 2;
370                                Neuro *muscle = model.addNewNeuro();
371                                sprintf(tmp, "|:p=%lg,r=%lg", lastjoint_muscle_power, props.muscle_bend_range);
372                                muscle->addInput(last_f1_neuro);
373                                muscle->setDetails(tmp);
374                                muscle->attachToJoint(getLastJoint());
375                                if (usemapping) muscle->addMapping(*makeRange(t));
376                        }
377                        t++;
378                        break;
379        }
380        while (*t && *t <= ' ') t++;
381        bool finished = 0;
382        const char *begin = t;
383        const char* colon = 0;
384        SString classparams;
385        while (!finished)
386        {
387                switch (*t)
388                {
389                case ':': colon = t; break;
390                case 0: case ']': case ')': finished = 1;
391                        // NO break!
392                case ',':
393                        if (!haveclass && !colon && t > begin)
394                        {
395                                haveclass = 1;
396                                SString clsname(begin, t - begin);
397                                clsname = trim(clsname);
398                                last_f1_neuro->setClassName(clsname);
399                                NeuroClass *cls = last_f1_neuro->getClass();
400                                if (cls)
401                                {
402                                        if (cls->getPreferredLocation() == 2)
403                                                last_f1_neuro->attachToJoint(getLastJoint());
404                                        else if (cls->getPreferredLocation() == 1)
405                                                last_f1_neuro->attachToPart(getLastPart());
406
407                                        lastNeuroClassParam();
408                                        //special handling: muscle properties (can be overwritten by subsequent property assignments)
409                                        if (!strcmp(cls->getName().c_str(), "|"))
410                                        {
411                                                neuro_cls_param->setDoubleById("p", lastjoint_muscle_power);
412                                                neuro_cls_param->setDoubleById("r", props.muscle_bend_range);
413                                        }
414                                        else if (!strcmp(cls->getName().c_str(), "@"))
415                                        {
416                                                neuro_cls_param->setDoubleById("p", lastjoint_muscle_power);
417                                        }
418                                }
419                        }
420                        else if (colon && (colon > begin) && (t > colon))
421                                growConnection(begin, colon, t, props);
422                        if (t[0] != ',') t--;
423                        begin = t + 1; colon = 0;
424                        break;
425                }
426                t++;
427        }
428        SAFEDELETE(neuro_cls_param);
429        return t;
430}
431void Builder::growConnection(const char* begin, const char* colon, const char* end, F1Props& props)
432{
433        while (*begin && *begin <= ' ') begin++;
434        int i;
435        if (isdigit(begin[0]) || (begin[0] == '-'))
436        {
437                double conn_weight = ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str());
438                paInt relative = ExtValue::getInt(trim(SString(begin, colon - begin)).c_str(), false);
439                int this_refno = neuro_f1_to_f0.size() - 1;
440                addOrRememberInput(this_refno, this_refno + relative, conn_weight);
441        }
442        else if ((i = last_f1_neuro->extraProperties().findIdn(begin, colon - begin)) >= 0)
443        {
444                last_f1_neuro->extraProperties().set(i, colon + 1);
445        }
446        else if (isupper(begin[0]) || strchr("*|@", begin[0]))
447        {
448                SString clsname(begin, colon - begin);
449                trim(clsname);
450                Neuro *receptor = model.addNewNeuro();
451                receptor->setClassName(clsname);
452                NeuroClass *cls = receptor->getClass();
453                if (cls)
454                {
455                        if (cls->getPreferredLocation() == 2) receptor->attachToJoint(getLastJoint());
456                        else if (cls->getPreferredLocation() == 1) receptor->attachToPart(getLastPart());
457                }
458                last_f1_neuro->addInput(receptor, ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str()));
459                if (usemapping) receptor->addMapping(*makeRange(begin, end - 1));
460        }
461        else if ((begin[0] == '>') && (begin[1]))
462        {
463                Neuro *out = model.addNewNeuro();
464                out->addInput(last_f1_neuro, ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str()));
465                out->setClassName(SString(begin + 1, end - colon - 1));
466                if (begin[1] == '@')
467                {
468                        sprintf(tmp, "p=%lg", lastjoint_muscle_power);
469                        out->setClassParams(tmp);
470                }
471                else if (begin[1] == '|')
472                {
473                        sprintf(tmp, "p=%lg,r=%lg", lastjoint_muscle_power, props.muscle_bend_range);
474                        out->setClassParams(tmp);
475                }
476                NeuroClass *cls = out->getClass();
477                if (cls)
478                {
479                        if (cls->getPreferredLocation() == 2) out->attachToJoint(getLastJoint());
480                        else if (cls->getPreferredLocation() == 1) out->attachToPart(getLastPart());
481                }
482                if (usemapping) out->addMapping(*makeRange(begin, end - 1));
483        }
484        else if (*begin == '!') addClassParam("fo", ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str()));
485        else if (*begin == '=') addClassParam("in", ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str()));
486        else if (*begin == '/') addClassParam("si", ExtValue::getDouble(trim(SString(colon + 1, end - (colon + 1))).c_str()));
487        else if (islower(begin[0]))
488        {
489                SString name(begin, colon - begin);
490                SString value(colon + 1, end - (colon + 1));
491                addClassParam(name.c_str(), value.c_str());
492        }
493}
Note: See TracBrowser for help on using the repository browser.