source: cpp/frams/genetics/f4/f4_general.cpp @ 760

Last change on this file since 760 was 760, checked in by Maciej Komosinski, 6 years ago
  • added support for new API for neuron types and their properties
  • added support for checkpoints
  • Property svn:eol-style set to native
File size: 32.8 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// Copyright (C) 1999,2000  Adam Rotaru-Varga (adam_rotaru@yahoo.com), GNU LGPL
6// 2018, Grzegorz Latosinski, added support for new API for neuron types and their properties
7
8#include "f4_general.h"
9#include "../oper_fx.h" //for GENOPER_ constants
10#include <common/nonstd_stl.h>
11#include <common/log.h>
12#include <frams/model/model.h> // for min and max attributes
13#include <common/nonstd_math.h>
14
15#ifdef DMALLOC
16#include <dmalloc.h>
17#endif
18
19void rolling_dec(double * v)
20{
21        *v -= 0.7853;  // 0.7853981  45 degrees
22}
23
24void rolling_inc(double * v)
25{
26        *v += 0.7853;  // 0.7853981  45 degrees
27}
28
29int scanrec(const char * s, unsigned int slen, char stopchar)
30{
31        unsigned int i = 0;
32        //DB( printf("    scan('%s', '%c')\n", s, stopchar); )
33        while (1)
34        {
35                if (i >= slen)  // ran out the string, should never happen with correct string
36                        return 1;
37                if (stopchar == s[i])  // bumped into stopchar
38                        return i;
39                if (i < slen - 1) // s[i] is not the last char
40                {
41                        if (s[i] == '(')
42                        {
43                                i += 2 + scanrec(s + i + 1, slen - i - 1, ')');
44                                continue;
45                        }
46                        if (s[i] == '<')
47                        {
48                                i += 2 + scanrec(s + i + 1, slen - i - 1, '>');
49                                continue;
50                        }
51                        if (s[i] == '#')
52                        {
53                                i += 2 + scanrec(s + i + 1, slen - i - 1, '>');
54                                continue;
55                        }
56                }
57                // s[i] a non-special character
58                i++;
59        }
60        return i;
61}
62
63
64f4_Cell::f4_Cell(int nname,
65        f4_Cell * ndad, int nangle, GeneProps newP)
66{
67        name = nname;
68        type = T_UNDIFF4;
69        dadlink = ndad;
70        org = NULL;
71        genot = NULL;
72        gcur = NULL;
73        active = 1;
74        repeat.clear();
75        //genoRange.clear(); -- implicit
76
77        anglepos = nangle;
78        commacount = 0;
79        childcount = 0;
80        P = newP;
81        rolling = 0;
82        xrot = 0;
83        zrot = 0;
84        //OM = Orient_1;
85        ctrl = 0;
86        state = 0;
87        inertia = 0.8;
88        force = 0.04;
89        sigmo = 2;
90        nolink = 0;
91
92        // adjust firstend and OM if there is a stick dad
93        if (ndad != NULL)
94        {
95                // make sure it is a stick (and not a stick f4_Cell!)
96                if (T_STICK4 == ndad->type)
97                {
98                        //firstend = ndad->lastend;
99                        //OM = ndad->OM;
100                        ndad->childcount++;
101                }
102                if (T_NEURON4 == ndad->type)
103                {
104                        state = ndad->state;
105                        inertia = ndad->inertia;
106                        force = ndad->force;
107                        sigmo = ndad->sigmo;
108                }
109        }
110        // adjust lastend
111        //lastend = firstend + ((Orient)OM * (Pt3D(1,0,0) * P.len));
112        mz = 1;
113}
114
115
116f4_Cell::f4_Cell(f4_Cells * nO, int nname, f4_node * ngeno, f4_node * ngcur, f4_Cell * ndad, int nangle, GeneProps newP)
117{
118        name = nname;
119        type = T_UNDIFF4;
120        dadlink = ndad;
121        org = nO;
122        genot = ngeno;
123        gcur = ngcur;
124        active = 1;
125        repeat.clear();
126        //genoRange.clear(); -- implicit
127        // preserve geno range of parent cell
128        if (NULL != ndad)
129                genoRange.add(ndad->genoRange);
130
131        anglepos = nangle;
132        commacount = 0;
133        childcount = 0;
134        P = newP;
135        rolling = 0;
136        xrot = 0;
137        zrot = 0;
138        //OM = Orient_1;
139        ctrl = 0;
140        state = 0;
141        inertia = 0.8;
142        force = 0.04;
143        sigmo = 2;
144        nolink = 0;
145
146        // adjust firstend and OM if there is a stick dad
147        if (ndad != NULL)
148        {
149                // make sure it is a stick (and not a stick f4_Cell!)
150                if (T_STICK4 == ndad->type)
151                {
152                        //firstend = ndad->lastend;
153                        //OM = ndad->OM;
154                        ndad->childcount++;
155                }
156                if (T_NEURON4 == ndad->type)
157                {
158                        state = ndad->state;
159                        inertia = ndad->inertia;
160                        force = ndad->force;
161                        sigmo = ndad->sigmo;
162                }
163        }
164        // adjust lastend
165        //lastend = firstend + ((Orient)OM * (Pt3D(1,0,0) * P.len));
166        mz = 1;
167}
168
169
170f4_Cell::~f4_Cell()
171{
172        // remove links
173        if (nolink)
174        {
175                int i;
176                for (i = nolink - 1; i >= 0; i--)
177                        delete links[i];
178                nolink = 0;
179        }
180}
181
182
183/* return codes:
184        >1 error at pos
185        0  halt development for a cycle
186        -1  development finished OK
187        */
188int f4_Cell::onestep()
189{
190        if (gcur == NULL)
191        {
192                active = 0;
193                return 0;  // stop
194        }
195        while (NULL != gcur)
196        {
197                //DB( printf("  %d (%d) executing '%c' %d\n", name, type, gcur->name, gcur->pos); )
198                // currently this is the last one processed
199                // the current genotype code is processed
200                //genoRange.add(gcur->pos,gcur->pos+gcur->name.length()-1);
201                bool neuclasshandler = false; // if set to true, then there is a set of characters that can be assigned to a neuron class type
202                // old semantics, one-character
203                if (gcur->name.length() == 1)
204                {
205                        genoRange.add(gcur->pos, gcur->pos);
206                        char name = gcur->name[0];
207                        switch (name)
208                        {
209                        case '<':
210                        {
211                                // cell division!
212                                //DB( printf("  div! %d\n", name); )
213
214                                // error: sticks cannot divide
215                                if (T_STICK4 == type)
216                                {
217                                        // cannot fix
218                                        org->setError(gcur->pos);
219                                        return 1;  // stop
220                                }
221
222                                // undiff divides
223                                if (T_UNDIFF4 == type)
224                                {
225                                        // commacount is set only when daughter turns into X
226                                        // daughter cell
227                                        // adjust new len
228                                        GeneProps newP = P;
229                                        newP.propagateAlong(false);
230                                        f4_Cell * tmp = new f4_Cell(org, org->nc, genot, gcur->child2, this, commacount, newP);
231                                        tmp->repeat = repeat;
232                                        repeat.clear();
233                                        org->addCell(tmp);
234                                }
235                                // a neuron divides: create a new, duplicate links
236                                if (T_NEURON4 == type) {
237                                        // daughter cell
238                                        f4_Cell *tmp = new f4_Cell(org, org->nc, genot, gcur->child2,
239                                                // has the same dadlink
240                                                this->dadlink, commacount, P);
241                                        tmp->repeat = repeat;
242                                        repeat.clear();
243                                        // it is a neuron from start
244                                        tmp->type = T_NEURON4;
245                                        // it has the same type as the parent neuron
246                                        tmp->neuclass = neuclass;
247                                        // duplicate links
248                                        f4_CellLink * ll;
249                                        for (int i = 0; i < nolink; i++)
250                                        {
251                                                ll = links[i];
252                                                tmp->addlink(ll->from, ll->w, ll->t);
253                                        }
254                                        org->addCell(tmp);
255                                }
256                                // adjustments for this cell
257                                gcur = gcur->child;
258                                // halt development
259                                return 0;
260                        }
261                        case '>':
262                        {
263                                // finish
264                                // see if there is a repet count
265                                if (repeat.top > 0)
266                                { // there is a repeat counter
267                                        if (!repeat.first()->isNull())
268                                        { // repeat counter is not null
269                                                repeat.first()->dec();
270                                                if (repeat.first()->count > 0)
271                                                {
272                                                        // return to repeat
273                                                        gcur = repeat.first()->node->child;
274                                                }
275                                                else
276                                                {
277                                                        // continue
278                                                        gcur = repeat.first()->node->child2;
279                                                        repeat.pop();
280                                                }
281                                                break;
282                                        }
283                                        else
284                                        {
285                                                repeat.pop();
286                                        }
287                                }
288                                else
289                                {
290                                        // error: still undiff
291                                        if (T_UNDIFF4 == type)
292                                        {
293                                                // fix it: insert an 'X'
294                                                f4_node *insertnode = new f4_node("X", NULL, gcur->pos);
295                                                if (org->setRepairInsert(gcur->pos, gcur, insertnode)) // not in repair mode, release
296                                                        delete insertnode;
297                                                return 1;
298                                        }
299                                        repeat.clear();
300                                        active = 0;  // stop
301                                        // eat up rest
302                                        gcur = NULL;
303                                        return 0;
304                                }
305                        }
306                                /* no break */
307                        case '#':
308                        {
309                                // repetition marker
310                                if (repeat.top >= repeat_stack::stackSize)
311                                {
312                                        // repeat pointer stack is full, cannot remember this one.
313                                        // fix: delete it
314                                        org->setRepairRemove(gcur->pos, gcur);
315                                        return 1;  // stop
316                                }
317                                repeat.push(repeat_ptr(gcur, gcur->i1));
318                                gcur = gcur->child;
319                                break;
320                        }
321                        case ',':
322                        {
323                                commacount++;
324                                gcur = gcur->child;
325                                break;
326                        }
327                        case 'r':  case 'R':
328                        {
329                                // error: if neuron
330                                if (T_NEURON4 == type)
331                                {
332                                        // fix: delete it
333                                        org->setRepairRemove(gcur->pos, gcur);
334                                        return 1;  // stop
335                                }
336                                switch (name)
337                                {
338                                case 'r':   rolling_dec(&rolling); break;
339                                case 'R':   rolling_inc(&rolling); break;
340                                }
341                                gcur = gcur->child;
342                                break;
343                        }
344                        case 'l':  case 'L':
345                        case 'c':  case 'C':
346                        case 'q':  case 'Q':
347                        case 'a':  case 'A':
348                        case 'i':  case 'I':
349                        case 's':  case 'S':
350                        case 'm':  case 'M':
351                        case 'f':  case 'F':
352                        case 'w':  case 'W':
353                        case 'e':  case 'E':
354                        case 'd':  case 'D':
355                        case 'g':  case 'G':
356                        case 'b':  case 'B':
357                        case 'h':  case 'H':
358                        {
359                                // error: if neuron
360                                if (T_NEURON4 == type)
361                                {
362                                        // fix: delete it
363                                        org->setRepairRemove(gcur->pos, gcur);
364                                        return 1;  // stop
365                                }
366                                P.executeModifier(name);
367                                gcur = gcur->child;
368                                break;
369                        }
370                        case 'X':
371                        {
372                                // turn undiff. cell into a stick
373                                // error: already differentiated
374                                if (T_UNDIFF4 != type)
375                                {
376                                        // fix: delete this node
377                                        org->setRepairRemove(gcur->pos, gcur);
378                                        return 1;  // stop
379                                }
380                                type = T_STICK4;
381                                // fix dad commacount and own anglepos
382                                if (NULL != dadlink)
383                                {
384                                        dadlink->commacount++;
385                                        anglepos = dadlink->commacount;
386                                }
387                                // change of type halts developments, see comment at 'N'
388                                gcur = gcur->child;
389                                return 0;
390                        }
391                        case 'N':
392                        {
393                                // turn undiff. cell into a neuron
394                                // error: already differentiated
395                                if (T_UNDIFF4 != type)
396                                {
397                                        // fix: delete this node
398                                        org->setRepairRemove(gcur->pos, gcur);
399                                        return 1;  // stop
400                                }
401                                // error: if no previous
402                                if (NULL == dadlink)
403                                {
404                                        // fix: delete it
405                                        org->setRepairRemove(gcur->pos, gcur);
406                                        return 1;  // stop
407                                }
408                                string temp1 = "N";
409                                char *temp = (char*)temp1.c_str();
410                                neuclass = GenoOperators::parseNeuroClass(temp);
411                                type = T_NEURON4;
412                                // change of type also halts development, to give other
413                                // cells a chance for adjustment.  Namely, it is important
414                                // to wait for other cells to turn N before adding links
415                                gcur = gcur->child;
416                                return 0;
417                        }
418                        case '@':
419                        case '|':
420                        {
421                                // neuron rotating / bending
422                                int j = 1;
423                                if ('@' == name) j = 1; // rot
424                                else
425                                        if ('|' == name) j = 2; // bend
426
427                                // if undiff, then this is a new muscle. Thanks to f4_processrec @ and | case we can skip repairing
428                                if (T_UNDIFF4 == type)
429                                {
430                                        neuclasshandler = true;
431                                        break;
432                                }
433
434                                // error: not a neuron (stick)
435                                if (T_NEURON4 != type)
436                                {
437                                        // fix: delete it
438                                        org->setRepairRemove(gcur->pos, gcur);
439                                        return 1;  // stop
440                                }
441                                // error: already has control
442                                if (ctrl != 0)
443                                {
444                                        // fix: delete it
445                                        org->setRepairRemove(gcur->pos, gcur);
446                                        return 1;  // stop
447                                }
448                                // make neuron ctrl = 1 or 2
449                                ctrl = j;
450                                gcur = gcur->child;
451                                break;
452                        }
453                        case '[':
454                        {
455                                // link to neuron
456                                // error: not a neuron
457                                if (T_NEURON4 != type)
458                                {
459                                        // fix: delete it
460                                        org->setRepairRemove(gcur->pos, gcur);
461                                        return 1;  // stop
462                                }
463                                // input (sensor or %d)
464                                int t = gcur->i1;
465                                int relfrom = gcur->l1;
466                                float w = gcur->f1;
467                                f4_Cell *tneu = NULL;
468                                if (t > 0) // sensors
469                                {
470                                        char *temp = (char*)gcur->s1.c_str();
471                                        NeuroClass *sensortest = GenoOperators::parseNeuroClass(temp);
472                                        if (sensortest == NULL || sensortest->getPreferredInputs() != 0)
473                                        {
474                                                // error: unknown code
475                                                string buf = "wrong sensor in link '";
476                                                buf.append(gcur->s1);
477                                                buf.append("'");
478                                                logMessage("f4_Cell", "onestep", LOG_WARN, buf.c_str()); //TODO ask
479                                                org->setRepairRemove(gcur->pos, gcur);
480                                                return 1;
481                                        }
482                                }
483                                else {
484                                        // input from other neuron
485                                        // find neuron at relative i
486                                        // find own index
487                                        int j = 0, k = 0;
488                                        for (int i = 0; i < org->nc; i++)
489                                        {
490                                                if (org->C[i]->type == T_NEURON4) k++;
491                                                if (org->C[i] == this) { j = k - 1; break; }
492                                        }
493                                        // find index of incoming
494                                        j = j + relfrom;
495                                        if (j < 0) goto wait_link;
496                                        if (j >= org->nc) goto wait_link;
497                                        // find that neuron
498                                        k = 0;
499                                        int i;
500                                        for (i = 0; i < org->nc; i++)
501                                        {
502                                                if (org->C[i]->type == T_NEURON4) k++;
503                                                if (j == (k - 1)) break;
504                                        }
505                                        if (i >= org->nc) goto wait_link;
506                                        tneu = org->C[i];
507                                }
508                                // add link
509                                // error: could not add link (too many?)
510                                if (addlink(tneu, w, gcur->s1))
511                                {
512                                        // cannot fix
513                                        org->setError(gcur->pos);
514                                        return 1;  // stop
515                                }
516                                gcur = gcur->child;
517                                break;
518                        }
519                        wait_link:
520                        {
521                                // wait for other neurons to develop
522                                // if there are others still active
523                                active = 0;
524                                int j = 0;
525                                for (int i = 0; i < org->nc; i++)
526                                {
527                                        if (org->C[i]->active) j++;
528                                }
529                                if (j > 0)
530                                        return 0;  // there is other active, halt, try again
531                                // no more actives, cannot add link, ignore, but treat not as an error
532                                gcur = gcur->child;
533                        }
534                                break;
535                        case ':':
536                        {
537                                // neuron parameter
538                                // error: not a neuron
539                                if (T_NEURON4 != type)
540                                {
541                                        // fix: delete it
542                                        org->setRepairRemove(gcur->pos, gcur);
543                                        return 1;  // stop
544                                }
545                                int j = (int)gcur->l1;
546                                switch ((char)gcur->i1)
547                                {
548                                case '!':
549                                        if (j)
550                                                force += (1.0 - force) * 0.2;
551                                        else
552                                                force -= force * 0.2;
553                                        break;
554                                case '=':
555                                        if (j)
556                                                inertia += (1.0 - inertia) * 0.2;
557                                        else
558                                                inertia -= inertia * 0.2;
559                                        break;
560                                case '/':
561                                        if (j)
562                                                sigmo *= 1.4;
563                                        else
564                                                sigmo /= 1.4;
565                                        break;
566                                default:
567                                        org->setRepairRemove(gcur->pos, gcur);
568                                        return 1;  // stop
569                                }
570                                gcur = gcur->child;
571                                break;
572                        }
573                        case ' ':
574                        {
575                                // space has no effect, should not occur
576                                // fix: delete it
577                                org->setRepairRemove(gcur->pos, gcur);
578                                gcur = gcur->child;
579                                break;
580                        }
581                        default:
582                        {
583                                // because there are one-character neuron classes, default move control to neuclasshandler
584                                neuclasshandler = true;
585                        }
586                        }
587                }
588                else
589                {
590                        // if many characters, then it needs to be parsed below
591                        neuclasshandler = true;
592                }
593
594                if (neuclasshandler)
595                {
596                        genoRange.add(gcur->pos, gcur->pos + gcur->name.length() + 2 - 1); // +2 for N:
597                        if (T_UNDIFF4 != type)
598                        {
599                                // fix: delete this node
600                                org->setRepairRemove(gcur->pos, gcur);
601                                return 1;  // stop
602                        }
603                        // error: if no previous
604                        if (NULL == dadlink)
605                        {
606                                // fix: delete it
607                                org->setRepairRemove(gcur->pos, gcur);
608                                return 1;  // stop
609                        }
610                        // multiple characters are neuron types. Need to check if exists
611                        char *temp = (char*)gcur->name.c_str();
612                        neuclass = GenoOperators::parseNeuroClass(temp);
613                        if (neuclass == NULL)
614                        {
615                                // error: unknown code
616                                string buf = "unknown code '";
617                                buf.append(gcur->name);
618                                buf.append("'");
619                                logMessage("f4_Cell", "onestep", 2, buf.c_str());
620                                org->setRepairRemove(gcur->pos, gcur);
621                                return 1;
622                        }
623                        type = T_NEURON4; //they belong to neurons
624                        gcur = gcur->child;
625                        return 0; //stop
626                }
627        }
628        active = 0;  // done
629        return 0;
630}
631
632
633int f4_Cell::addlink(f4_Cell * nfrom, double nw, string nt)
634{
635        // if incoming neuron does not produce output, return error
636        if (nfrom != NULL && nfrom->neuclass->getPreferredOutput() == 0) return -1;
637        if (neuclass->getPreferredInputs() != -1 && nolink >= neuclass->getPreferredInputs()) return -1;
638        if (nolink >= MAXINPUTS - 1) return -1; // full!
639        links[nolink] = new f4_CellLink(nfrom, nw, nt);
640        nolink++;
641        return 0;
642}
643
644
645void f4_Cell::adjustRec()
646{
647        //f4_OrientMat rot;
648        int i;
649
650        if (recProcessedFlag)
651                // already processed
652                return;
653
654        // mark it processed
655        recProcessedFlag = 1;
656
657        // make sure its parent is processed first
658        if (NULL != dadlink)
659                dadlink->adjustRec();
660
661        // count children
662        childcount = 0;
663        for (i = 0; i < org->nc; i++)
664        {
665                if (org->C[i]->dadlink == this)
666                        if (org->C[i]->type == T_STICK4)
667                                childcount++;
668        }
669
670        if (type == T_STICK4)
671        {
672                if (NULL == dadlink)
673                {
674                        //firstend = Pt3D_0;
675                        // rotation due to rolling
676                        xrot = rolling;
677                        mz = 1;
678                }
679                else
680                {
681                        //firstend = dadlink->lastend;
682                        GeneProps Pdad = dadlink->P;
683                        GeneProps Padj = Pdad;
684                        Padj.propagateAlong(false);
685
686                        //rot = Orient_1;
687
688                        // rotation due to rolling
689                        xrot = rolling +
690                                // rotation due to twist
691                                Pdad.twist;
692                        if (dadlink->commacount <= 1)
693                        {
694                                // rotation due to curvedness
695                                zrot = Padj.curvedness;
696                        }
697                        else
698                        {
699                                zrot = Padj.curvedness + (anglepos * 1.0 / (dadlink->commacount + 1) - 0.5) * M_PI * 2.0;
700                        }
701
702                        //rot = rot * f4_OrientMat(yOz, xrot);
703                        //rot = rot * f4_OrientMat(xOy, zrot);
704                        // rotation relative to parent stick
705                        //OM = rot * OM;
706
707                        // rotation in world coordinates
708                        //OM =  ((f4_OrientMat)dadlink->OM) * OM;
709                        mz = dadlink->mz / dadlink->childcount;
710                }
711                //Pt3D lastoffset = (Orient)OM * (Pt3D(1,0,0)*P.len);
712                //lastend = firstend + lastoffset;
713        }
714}
715
716
717
718f4_CellLink::f4_CellLink(f4_Cell * nfrom, double nw, string nt)
719{
720        from = nfrom;
721        w = nw;
722        t = nt;
723}
724
725
726
727f4_Cells::f4_Cells(f4_node * genome, int nrepair)
728{
729        // create ancestor cell
730        repair = nrepair;
731        error = 0;
732        errorpos = -1;
733        repair_remove = NULL;
734        repair_parent = NULL;
735        repair_insert = NULL;
736        tmpcel = NULL;
737        f4rootnode = NULL;
738        C[0] = new f4_Cell(this, 0, genome, genome, NULL, 0, GeneProps::standard_values);
739        nc = 1;
740}
741
742
743f4_Cells::f4_Cells(SString & genome, int nrepair)
744{
745        int res;
746        repair = nrepair;
747        error = 0;
748        errorpos = -1;
749        repair_remove = NULL;
750        repair_parent = NULL;
751        repair_insert = NULL;
752        tmpcel = NULL;
753        f4rootnode = NULL;
754
755        // transform geno from string to nodes
756        f4rootnode = new f4_node();
757        res = f4_processrec(genome.c_str(), (unsigned)0, f4rootnode);
758        if ((res < 0) || (1 != f4rootnode->childCount()))
759        {
760                error = GENOPER_OPFAIL;
761                errorpos = -1;
762        }
763
764        // create ancestor cell
765        C[0] = new f4_Cell(this, 0, f4rootnode->child, f4rootnode->child, NULL, 0, GeneProps::standard_values);
766        nc = 1;
767}
768
769f4_Cells::~f4_Cells()
770{
771        // release cells
772        int i;
773        if (nc)
774        {
775                for (i = nc - 1; i >= 0; i--)
776                        delete C[i];
777                nc = 0;
778        }
779        if (f4rootnode)
780                delete f4rootnode;
781}
782
783
784int f4_Cells::onestep()
785{
786        int i, ret, oldnc, ret2;
787        oldnc = nc;
788        ret = 0;
789        for (i = 0; i < oldnc; i++)
790        {
791                ret2 = C[i]->onestep();
792                if (ret2 > 0)
793                {
794                        // error
795                        C[i]->active = 0;  // stop
796                        return 0;
797                }
798                // if still active
799                if (C[i]->active)
800                        ret = 1;
801        }
802        return ret;
803}
804
805
806int f4_Cells::simulate()
807{
808        int i;
809        error = GENOPER_OK;
810
811        for (i = 0; i < nc; i++)  C[i]->active = 1;
812
813        // execute onestep() in a cycle
814        while (onestep());
815
816        if (GENOPER_OK != error) return error;
817
818        // fix neuron attachements
819        for (i = 0; i < nc; i++)
820        {
821                if (C[i]->type == T_NEURON4)
822                {
823                        while (T_NEURON4 == C[i]->dadlink->type)
824                        {
825                                C[i]->dadlink = C[i]->dadlink->dadlink;
826                        }
827                }
828        }
829
830        // there should be no undiff. cells
831        // make undifferentiated cells sticks
832        for (i = 0; i < nc; i++)
833        {
834                if (C[i]->type == T_UNDIFF4)
835                {
836                        C[i]->type = T_STICK4;
837                        //seterror();
838                }
839        }
840
841        // recursive adjust
842        // reset recursive traverse flags
843        for (i = 0; i < nc; i++)
844                C[i]->recProcessedFlag = 0;
845        // process every cell
846        for (i = 0; i < nc; i++)
847                C[i]->adjustRec();
848
849        //DB( printf("Cell simulation done, %d cells. \n", nc); )
850
851        return error;
852}
853
854
855void f4_Cells::addCell(f4_Cell * newcell)
856{
857        if (nc >= MAX4CELLS - 1)
858        {
859                delete newcell;
860                return;
861        }
862        C[nc] = newcell;
863        nc++;
864}
865
866
867void f4_Cells::setError(int nerrpos)
868{
869        error = GENOPER_OPFAIL;
870        errorpos = nerrpos;
871}
872
873void f4_Cells::setRepairRemove(int nerrpos, f4_node * rem)
874{
875        if (!repair)
876        {
877                // not in repair mode, treat as repairable error
878                error = GENOPER_REPAIR;
879                errorpos = nerrpos;
880        }
881        else
882        {
883                error = GENOPER_REPAIR;
884                errorpos = nerrpos;
885                repair_remove = rem;
886        }
887}
888
889int f4_Cells::setRepairInsert(int nerrpos, f4_node * parent, f4_node * insert)
890{
891        if (!repair)
892        {
893                // not in repair mode, treat as repairable error
894                error = GENOPER_REPAIR;
895                errorpos = nerrpos;
896                return -1;
897        }
898        else
899        {
900                error = GENOPER_REPAIR;
901                errorpos = nerrpos;
902                repair_parent = parent;
903                repair_insert = insert;
904                return 0;
905        }
906}
907
908void f4_Cells::repairGeno(f4_node * geno, int whichchild)
909{
910        // assemble repaired geno, if the case
911        if (!repair) return;
912        if ((NULL == repair_remove) && (NULL == repair_insert)) return;
913        // traverse genotype tree, remove / insert node
914        f4_node * g2;
915        if (1 == whichchild) g2 = geno->child;
916        else             g2 = geno->child2;
917        if (NULL == g2)
918                return;
919        if (g2 == repair_remove)
920        {
921                f4_node * oldgeno;
922                geno->removeChild(g2);
923                if (g2->child)
924                {
925                        // add g2->child as child to geno
926                        if (1 == whichchild) geno->child = g2->child;
927                        else             geno->child2 = g2->child;
928                        g2->child->parent = geno;
929                }
930                oldgeno = g2;
931                oldgeno->child = NULL;
932                delete oldgeno;
933                if (NULL == geno->child) return;
934                // check this new
935                repairGeno(geno, whichchild);
936                return;
937        }
938        if (g2 == repair_parent)
939        {
940                geno->removeChild(g2);
941                geno->addChild(repair_insert);
942                repair_insert->parent = geno;
943                repair_insert->child = g2;
944                repair_insert->child2 = NULL;
945                g2->parent = repair_insert;
946        }
947        // recurse
948        if (g2->child)  repairGeno(g2, 1);
949        if (g2->child2) repairGeno(g2, 2);
950}
951
952
953void f4_Cells::toF1Geno(SString &out)
954{
955        if (tmpcel) delete tmpcel;
956        tmpcel = new f4_Cell(-1, NULL, 0, GeneProps::standard_values);
957        out = "";
958        toF1GenoRec(0, out);
959        delete tmpcel;
960}
961
962
963void f4_Cells::toF1GenoRec(int curc, SString &out)
964{
965        int i, j, ccount;
966        f4_Cell * thisti;
967        f4_Cell * thneu;
968        char buf[200];
969
970        if (curc >= nc) return;
971
972        if (T_STICK4 != C[curc]->type) return;
973
974        thisti = C[curc];
975        if (NULL != thisti->dadlink)
976                *tmpcel = *(thisti->dadlink);
977
978        // adjust length, curvedness, etc.
979        tmpcel->P.propagateAlong(false);
980        while (tmpcel->P.length > thisti->P.length)
981        {
982                tmpcel->P.executeModifier('l');
983                out += "l";
984        }
985        while (tmpcel->P.length < thisti->P.length)
986        {
987                tmpcel->P.executeModifier('L');
988                out += "L";
989        }
990        while (tmpcel->P.curvedness > thisti->P.curvedness)
991        {
992                tmpcel->P.executeModifier('c');
993                out += "c";
994        }
995        while (tmpcel->P.curvedness < thisti->P.curvedness)
996        {
997                tmpcel->P.executeModifier('C');
998                out += "C";
999        }
1000        while (thisti->rolling > 0.0f)
1001        {
1002                rolling_dec(&(thisti->rolling));
1003                out += "R";
1004        }
1005        while (thisti->rolling < 0.0f)
1006        {
1007                rolling_inc(&(thisti->rolling));
1008                out += "r";
1009        }
1010
1011        // output X for this stick
1012        out += "X";
1013
1014        // neurons attached to it
1015        for (i = 0; i < nc; i++)
1016        {
1017                if (C[i]->type == T_NEURON4)
1018                {
1019                        if (C[i]->dadlink == thisti)
1020                        {
1021                                thneu = C[i];
1022                                out += "[";
1023                                // ctrl
1024                                if (1 == thneu->ctrl) out += "@";
1025                                if (2 == thneu->ctrl) out += "|";
1026                                // links
1027                                for (j = 0; j < thneu->nolink; j++)
1028                                {
1029                                        if (j) out += ",";
1030                                        if (NULL == thneu->links[j]->from)
1031                                        {
1032                                                // sensors
1033                                                out += thneu->links[j]->t.c_str();
1034                                        }
1035                                        else
1036                                        {
1037                                                sprintf(buf, "%d", thneu->links[j]->from->name - thneu->name);
1038                                                out += buf;
1039                                        }
1040                                        out += ":";
1041                                        // connection weight
1042                                        sprintf(buf, "%g", thneu->links[j]->w);
1043                                        out += buf;
1044                                }
1045                                out += "]";
1046                        }
1047                }
1048        }
1049
1050        // sticks connected to it
1051        if (thisti->commacount >= 2)
1052                out += "(";
1053
1054        ccount = 1;
1055        for (i = 0; i < nc; i++)
1056        {
1057                if (C[i]->type == T_STICK4)
1058                {
1059                        if (C[i]->dadlink == thisti)
1060                        {
1061                                while (ccount < (C[i])->anglepos)
1062                                {
1063                                        ccount++;
1064                                        out += ",";
1065                                }
1066                                toF1GenoRec(i, out);
1067                        }
1068                }
1069        }
1070
1071        while (ccount < thisti->commacount)
1072        {
1073                ccount++;
1074                out += ",";
1075        }
1076
1077        if (thisti->commacount >= 2)
1078                out += ")";
1079}
1080
1081
1082
1083// to organize an f4 genotype in a tree structure
1084
1085f4_node::f4_node()
1086{
1087        name = "?";
1088        parent = NULL;
1089        child = NULL;
1090        child2 = NULL;
1091        pos = -1;
1092        l1 = 0;
1093        i1 = 0;
1094        f1 = 0.0f;
1095}
1096
1097f4_node::f4_node(string nname, f4_node *nparent, int npos)
1098{
1099        name = nname;
1100        parent = nparent;
1101        child = NULL;
1102        child2 = NULL;
1103        pos = npos;
1104        if (parent) parent->addChild(this);
1105        l1 = 0;
1106        i1 = 0;
1107        f1 = 0.0f;
1108}
1109
1110f4_node::f4_node(char nname, f4_node * nparent, int npos)
1111{
1112        name = nname;
1113        parent = nparent;
1114        child = NULL;
1115        child2 = NULL;
1116        pos = npos;
1117        if (parent) parent->addChild(this);
1118        l1 = 0;
1119        i1 = 0;
1120        f1 = 0.0f;
1121}
1122
1123f4_node::~f4_node()
1124{
1125        // (destroy() copied here for efficiency)
1126        // children are destroyed (recursively) through the destructor
1127        if (NULL != child2)  delete child2;
1128        if (NULL != child)   delete child;
1129}
1130
1131int f4_node::addChild(f4_node * nchi)
1132{
1133        if (NULL == child)
1134        {
1135                child = nchi;
1136                return 0;
1137        }
1138        if (NULL == child2)
1139        {
1140                child2 = nchi;
1141                return 0;
1142        }
1143        return -1;
1144}
1145
1146int f4_node::removeChild(f4_node * nchi)
1147{
1148        if (nchi == child2)
1149        {
1150                child2 = NULL;
1151                return 0;
1152        }
1153        if (nchi == child)
1154        {
1155                child = NULL;
1156                return 0;
1157        }
1158        return -1;
1159}
1160
1161int f4_node::childCount()
1162{
1163        if (NULL != child)
1164        {
1165                if (NULL != child2) return 2;
1166                else return 1;
1167        }
1168        else
1169        {
1170                if (NULL != child2) return 1;
1171                else return 0;
1172        }
1173}
1174
1175int f4_node::count()
1176{
1177        int c = 1;
1178        if (NULL != child)  c += child->count();
1179        if (NULL != child2) c += child2->count();
1180        return c;
1181}
1182
1183f4_node * f4_node::ordNode(int n)
1184{
1185        int n1;
1186        if (0 == n) return this;
1187        n--;
1188        if (NULL != child)
1189        {
1190                n1 = child->count();
1191                if (n < n1) return child->ordNode(n);
1192                n -= n1;
1193        }
1194        if (NULL != child2)
1195        {
1196                n1 = child2->count();
1197                if (n < n1) return child2->ordNode(n);
1198                n -= n1;
1199        }
1200        return NULL;
1201}
1202
1203f4_node * f4_node::randomNode()
1204{
1205        int n = count();
1206        // pick a random node, between 0 and n-1
1207        return ordNode(randomN(n));
1208}
1209
1210f4_node * f4_node::randomNodeWithSize(int min, int max)
1211{
1212        // try random nodes, and accept if size in range
1213        // limit to maxlim tries
1214        int i, n, maxlim;
1215        f4_node * nod = NULL;
1216        maxlim = count();
1217        for (i = 0; i < maxlim; i++)
1218        {
1219                nod = randomNode();
1220                n = nod->count();
1221                if ((n >= min) && (n <= max)) return nod;
1222        }
1223        // failed, doesn't matter
1224        return nod;
1225}
1226
1227void f4_node::sprint(SString& out)
1228{
1229        string buf2 = "";
1230        // special case: repetition code
1231        if (name == "#")
1232        {
1233                out += "#";
1234                if (i1 != 1)
1235                {
1236                        sprintf((char*)buf2.c_str(), "%d", i1);
1237                        out += buf2.c_str();
1238                }
1239        }
1240        else {
1241                // special case: neuron link
1242                if (name == "[")
1243                {
1244                        out += "[";
1245                        if (i1 > 0)
1246                        {
1247                                // sensor input
1248                                out += s1.c_str();
1249                        }
1250                        else
1251                        {
1252                                sprintf((char*)buf2.c_str(), "%ld", l1);
1253                                out += buf2.c_str();
1254                        }
1255                        sprintf((char*)buf2.c_str(), ":%g]", f1);
1256                        out += buf2.c_str();
1257                }
1258                else if (name == ":")
1259                {
1260                        sprintf((char*)buf2.c_str(), ":%c%c:", l1 ? '+' : '-', (char)i1);
1261                        out += buf2.c_str();
1262                }
1263                else if (name == "@" || name == "|")
1264                {
1265                        if (parent->name == "N")
1266                        {
1267                                buf2 = name;
1268                                out += buf2.c_str();
1269                        }
1270                        else
1271                        {
1272                                out += "N:";
1273                                buf2 = name;
1274                                out += buf2.c_str();
1275                        }
1276                }
1277                else
1278                {
1279                        char *temp = (char*)name.c_str();
1280                        NeuroClass * nc = GenoOperators::parseNeuroClass(temp);
1281                        if (nc != NULL)
1282                        {
1283                                out += "N:";
1284                        }
1285                        buf2 = name;
1286                        out += buf2.c_str();
1287                }
1288        }
1289        if (NULL != child)     child->sprint(out);
1290        // if two children, make sure last char is a '>'
1291        if (2 == childCount())
1292                if (0 == out[0]) out += ">"; else
1293                        if ('>' != out[out.len() - 1]) out += ">";
1294        if (NULL != child2)    child2->sprint(out);
1295        // make sure last char is a '>'
1296        if (0 == out[0]) out += ">"; else
1297                if ('>' != out[out.len() - 1]) out += ">";
1298}
1299
1300void f4_node::sprintAdj(char *& buf)
1301{
1302        unsigned int len;
1303        // build in a SString, with initial size
1304        SString out(strlen(buf) + 2000);
1305        out = "";
1306
1307        sprint(out);
1308
1309        // very last '>' can be omitted
1310        len = out.len();
1311        if (len > 1)
1312                if ('>' == out[len - 1]) { (out.directWrite())[len - 1] = 0; out.endWrite(); };
1313        // copy back to string
1314        // if new is longer, reallocate buf
1315        if (len + 1 > strlen(buf))
1316        {
1317                buf = (char*)realloc(buf, len + 1);
1318        }
1319        strcpy(buf, out.c_str());
1320}
1321
1322f4_node * f4_node::duplicate()
1323{
1324        f4_node * copy;
1325        copy = new f4_node(*this);
1326        copy->parent = NULL;  // set later
1327        copy->child = NULL;
1328        copy->child2 = NULL;
1329        if (NULL != child)
1330        {
1331                copy->child = child->duplicate();
1332                copy->child->parent = copy;
1333        }
1334        if (NULL != child2)
1335        {
1336                copy->child2 = child2->duplicate();
1337                copy->child2->parent = copy;
1338        }
1339        return copy;
1340}
1341
1342
1343void f4_node::destroy()
1344{
1345        // children are destroyed (recursively) through the destructor
1346        if (NULL != child2)  delete child2;
1347        if (NULL != child)   delete child;
1348}
1349
1350// scan genotype string and build tree
1351// return >1 for error (errorpos)
1352int f4_processrec(const char * genot, unsigned pos0, f4_node * parent)
1353{
1354        int i, j, res, t;
1355        char tc1, tc2, tc3; // tc3 is only to ensure that in the end  of neuron parameter definition
1356        int relfrom;
1357        double w;
1358        unsigned gpos, oldpos;
1359        f4_node * node1, *par;
1360        unsigned beginindex;
1361        string neutype = "";
1362
1363        gpos = pos0;
1364        par = parent;
1365        if (gpos >= strlen(genot)) return 1;
1366        while (gpos < strlen(genot))
1367        {
1368                neutype = "";
1369                // first switch across cell dividers and old semantics
1370                switch (genot[gpos])
1371                {
1372                case '<':
1373                {
1374                        // find out genotype start for child
1375                        j = scanrec(genot + gpos + 1, strlen(genot + gpos + 1), '>');
1376
1377                        node1 = new f4_node("<", par, gpos);
1378                        par = node1;
1379                        res = f4_processrec(genot, gpos + 1, par);
1380                        if (res) return res;
1381                        if (gpos + j + 2 < strlen(genot))
1382                        {
1383                                res = f4_processrec(genot, gpos + j + 2, par);
1384                                if (res) return res;
1385                        }
1386                        else // ran out
1387                        {
1388                                node1 = new f4_node(">", par, strlen(genot) - 1);
1389                                par = node1;
1390                        }
1391                        gpos++;
1392                        return 0;  // OK
1393                }
1394                case '>':
1395                {
1396                        node1 = new f4_node(">", par, gpos);
1397                        par = node1;
1398                        gpos = strlen(genot);
1399                        return 0;  // OK
1400                }
1401                case '#':
1402                {
1403                        // repetition marker, 1 by default
1404                        if (sscanf(genot + gpos, "#%d", &i) != 1) i = 1;
1405                        // find out genotype start for continuation
1406                        j = scanrec(genot + gpos + 1, strlen(genot + gpos + 1), '>');
1407                        // skip number
1408                        oldpos = gpos;
1409                        gpos++;
1410                        while ((genot[gpos] >= '0') && (genot[gpos] <= '9')) gpos++;
1411                        node1 = new f4_node("#", par, oldpos);
1412                        node1->i1 = i;
1413                        par = node1;
1414                        res = f4_processrec(genot, gpos, node1);
1415                        if (res) return res;
1416                        if (oldpos + j + 2 < strlen(genot))
1417                        {
1418                                res = f4_processrec(genot, oldpos + j + 2, node1);
1419                                if (res) return res;
1420                        }
1421                        else // ran out
1422                        {
1423                                node1 = new f4_node(">", par, strlen(genot) - 1);
1424                        }
1425                        return 0;  // OK
1426                }
1427                case ' ':
1428                case '\n':
1429                case '\r':
1430                case '\t':
1431                {
1432                        // whitespace: ignore
1433                        gpos++;
1434                        break;
1435                }
1436                case 'l':  case 'L':
1437                case 'c':  case 'C':
1438                case 'q':  case 'Q':
1439                case 'r':  case 'R':
1440                case 'X':  case ',':
1441                case 'a':  case 'A':
1442                case 's':  case 'S':
1443                case 'm':  case 'M':
1444                case 'i':  case 'I':
1445                case 'f':  case 'F':
1446                case 'w':  case 'W':
1447                case 'e':  case 'E':
1448                {
1449                        node1 = new f4_node(genot[gpos], par, gpos);
1450                        par = node1;
1451                        gpos++;
1452                        break;
1453                }
1454                case '@':  case '|':
1455                {
1456                        // in order to prevent the presence of "free muscles", we need to ensure that a muscle is written as N@/N| or N:@/N:|
1457                        if (par != NULL && par->name == "N")
1458                        {
1459                                node1 = new f4_node(genot[gpos], par, gpos);
1460                                par = node1;
1461                                gpos++;
1462                        }
1463                        else
1464                        {
1465                                return gpos + 1;
1466                        }
1467                        break;
1468                }
1469
1470                case 'N':
1471                {
1472                        // if there is no colon after N, then there is no class definition
1473                        if (gpos + 1 >= strlen(genot) || genot[gpos + 1] != ':')
1474                        {
1475                                node1 = new f4_node(genot[gpos], par, gpos);
1476                                par = node1;
1477                                gpos++;
1478                                break;
1479                        }
1480                        // if there is a colon determining neuron parameter, then let the switch case colon handle this
1481                        else if (sscanf(genot + gpos + 1, ":%c%c%[:]", &tc1, &tc2, &tc3) == 3)
1482                        {
1483                                node1 = new f4_node(genot[gpos], par, gpos);
1484                                par = node1;
1485                                gpos++;
1486                                break;
1487                        }
1488                        int forgenorange = gpos;
1489                        gpos += 2; //skipping "N:"
1490                        beginindex = gpos;
1491                        char * end = (char*)genot + beginindex;
1492                        GenoOperators::parseNeuroClass(end);
1493                        gpos += end - genot - beginindex;
1494                        neutype = string(genot + beginindex, genot + gpos);
1495                        node1 = new f4_node(neutype, par, forgenorange);
1496                        par = node1;
1497                        break;
1498                }
1499                case ':':
1500                {
1501                        // neuron parameter  +! -! += -= +/ or -/
1502                        if (sscanf(genot + gpos, ":%c%c%[:]", &tc1, &tc2, &tc3) != 3)
1503                                // error: incorrect format
1504                                return gpos + 1 + 1;
1505                        if ('+' == tc1) j = 1;
1506                        else if ('-' == tc1) j = 0;
1507                        else return gpos + 1 + 1;
1508                        switch (tc2)
1509                        {
1510                        case '!':  case '=':  case '/':  break;
1511                        default:
1512                                return gpos + 1 + 1;
1513                        }
1514                        node1 = new f4_node(":", par, gpos);
1515                        node1->l1 = j;
1516                        node1->i1 = (int)tc2;
1517                        par = node1;
1518                        j = scanrec(genot + gpos + 1, strlen(genot + gpos + 1), ':');
1519                        gpos += j + 2;
1520                        break;
1521                }
1522                case '[':
1523                {
1524                        const char *end = parseConnection(genot + gpos, relfrom, w);
1525                        if (end == NULL)
1526                        {
1527                                end = parseConnectionWithNeuron(genot + gpos, neutype, w);
1528                                if (end == NULL) t = -1;
1529                                t = 1;
1530                        }
1531                        else
1532                        {
1533                                t = 0;
1534                        }
1535                        node1 = new f4_node("[", par, gpos);
1536                        node1->s1 = neutype;
1537                        node1->i1 = t;
1538                        node1->l1 = relfrom;
1539                        node1->f1 = w;
1540                        par = node1;
1541                        j = scanrec(genot + gpos + 1, strlen(genot + gpos + 1), ']');
1542                        gpos += j + 2;
1543                        break;
1544                }
1545                default:
1546                {
1547                        //DB( printf("unknown character '%c' ! \n", genot[gpos]); )
1548                        //add it, build will give the error or repair
1549                        node1 = new f4_node(genot[gpos], par, gpos);
1550                        par = node1;
1551                        gpos++;
1552                        break;
1553                }
1554                }
1555        }
1556
1557        // should end with a '>'
1558        if (par)
1559        {
1560                if (par->name != ">")
1561                {
1562                        node1 = new f4_node('>', par, strlen(genot) - 1);
1563                        par = node1;
1564                }
1565        }
1566
1567        return 0;
1568}
1569
1570const char* parseConnection(const char *fragm, int& relfrom, double &weight)
1571{
1572        const char *parser = fragm;
1573        if (*parser != '[') return NULL;
1574        parser++;
1575        ExtValue val;
1576        parser = val.parseNumber(parser, ExtPType::TInt);
1577        if (parser == NULL) return NULL;
1578        relfrom = val.getInt();
1579        if (*parser != ':') return NULL;
1580        parser++;
1581        parser = val.parseNumber(parser, ExtPType::TDouble);
1582        if (parser == NULL) return NULL;
1583        weight = val.getDouble();
1584        if (*parser != ']') return NULL;
1585        parser++;
1586        return parser;
1587}
1588
1589const char* parseConnectionWithNeuron(const char *fragm, string &neutype, double &weight)
1590{
1591        const char *parser = fragm;
1592        if (*parser != '[') return NULL;
1593        parser++;
1594        char * p = (char*)parser;
1595        if (GenoOperators::parseNeuroClass(p) == NULL) return NULL;
1596        neutype = string(parser, (const char *)p);
1597        parser = p;
1598        if (*parser != ':') return NULL;
1599        parser++;
1600        ExtValue val;
1601        parser = val.parseNumber(parser, ExtPType::TDouble);
1602        if (parser == NULL) return NULL;
1603        weight = val.getDouble();
1604        if (*parser != ']') return NULL;
1605        parser++;
1606        return parser;
1607}
1608
1609f4_node * f4_processtree(const char * geno)
1610{
1611        f4_node * root;
1612        int res;
1613        root = new f4_node();
1614        res = f4_processrec(geno, 0, root);
1615        if (res) return NULL;
1616        //DB( printf("test f4  "); )
1617        DB(
1618                if (root->child)
1619                {
1620                char * buf = (char*)malloc(300);
1621                DB(printf("(%d) ", root->child->count());)
1622                        buf[0] = 0;
1623                root->child->sprintAdj(buf);
1624                DB(printf("%s\n", buf);)
1625                        free(buf);
1626                }
1627        )
1628                return root->child;
1629}
Note: See TracBrowser for help on using the repository browser.