source: cpp/frams/_demos/genomanipulation.cpp @ 858

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

Code formatting

  • Property svn:eol-style set to native
File size: 12.6 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[742]2// Copyright (C) 1999-2018  Maciej Komosinski and Szymon Ulatowski.
[286]3// See LICENSE.txt for details.
[109]4
5#include <stdlib.h>
6#include <stdio.h>
7#include <time.h>
[382]8#include <common/virtfile/stdiofile.h>
[109]9
10#include <frams/model/model.h>
[145]11#include <frams/genetics/preconfigured.h>
[391]12#include <common/loggers/loggertostdout.h>
[109]13
14/**
15 @file
16 Sample code: Accessing model elements
[742]17 */
[109]18
19void printNiceBanner(const char* title)
20{
[742]21        printf("    #############################################\n"
22                "   ##                                           ##\n"
23                "  ##    %-37s    ##\n"
24                "   ##                                           ##\n"
25                "    #############################################\n", title);
[109]26}
27void printProperties(Param &pi)
28{
[742]29        printf(" #        id                      type  name        group (%d properties)\n", pi.getPropCount());
30        for (int i = 0; i < pi.getPropCount(); i++)
[109]31        {
[742]32                const char* type = pi.type(i);
33                if (*type == 'p') continue;
34                printf("%2d. %8s = %-20s %-3s %-10s  %-10s\n", i, pi.id(i), pi.get(i).c_str(), pi.type(i), pi.name(i), pi.grname(pi.group(i)));
[109]35        }
36}
37
38#define PRINT_PROPERTIES(p) {Param tmp_param(p); printProperties(tmp_param);}
39
40void changeOneProperty(Param &pi)
41{
[742]42        if (pi.getPropCount() <= 0) return;
43        int i = rand() % pi.getPropCount();
44        double maxprop = 1, minprop = 0, def;
45        pi.getMinMaxDouble(i, minprop, maxprop, def);
46        printf("      Change property #%d to random value from range [%g..%g]\n", i, minprop, maxprop);
47        printf("      Current value of '%s' (%s) is '%s'\n", pi.id(i), pi.name(i), pi.get(i).c_str());
48        char t[100];
49        sprintf(t, "%g", minprop + (rnd01)*(maxprop - minprop));
50        printf("      Setting new value... [ using ParamInterface::set() ]\n");
51        pi.setFromString(i, t);
52        printf("      The value is now '%s'\n", pi.get(i).c_str());
[109]53}
54
55#define CHANGE_ONE_PROPERTY(p) {Param tmp_param(p); changeOneProperty(tmp_param);}
56
57void moreAboutPart(Part* p)
58{
[742]59        printf("Here is the full listing of properties as they are printed in f0\n"
60                " (please compare with f0 genotype).\n"
61                "Some properties have special meaning (eg. geometry and connections groups)\n"
62                "and should be handled with care, because they influence other elements of the model.\n\n"
63                " [this data is provided by Part::properties() ]\n");
64        PRINT_PROPERTIES(p->properties());
65        printf("\nHowever, there is a subset of properties which may be modified more freely.\n"
66                "Properties on this list are related only to this part and can be changed\n"
67                "without much consideration. They are guaranteed to be always valid; any inconsistencies\n"
68                "will be silently repaired.\n"
69                "\n [this data is provided by Part::extraProperties() ]\n");
70        PRINT_PROPERTIES(p->extraProperties());
71        printf("\nThis set of properties can vary from release to release,\n"
72                "but can be safely accessed by using extraProperties() call.\n"
73                "This method accesses the full set of properies (even those\n"
74                "which appear in future releases).\n"
75                "Now we will try to change some of properties:\n\n");
76        p->getModel().open();
77        CHANGE_ONE_PROPERTY(p->extraProperties());
78        p->getModel().close();
79        printf("\nLet's see f0... (check out part #%d !)\n\n%s\n", p->refno, p->getModel().getF0Geno().getGenes().c_str());
[109]80}
81
82void playWithAbsolute(Joint *j)
83{
[742]84        printf("\nAbsolute Joints adapt to its Parts' positions.\n"
85                "We can move a Part, and it does not influence the second part, nor the Joint.\n"
86                "Let's move the first Part along y axis by -0.1...\n");
87        j->getModel().open();
88        j->part1->p.y -= 0.1;
89        j->getModel().close();
90        printf("The Part's position is changed, but everything else stays intact:\n\n%s\n",
91                j->getModel().getF0Geno().getGenes().c_str());
[109]92}
93
94void playWithDelta(Joint *j)
95{
[742]96        printf("\nDelta fields (dx,dy,dz) describe relative location of the second part.\n"
97                "This joint will change the second Part's positions to preserve delta distance.\n"
98                "Let's move the first Part (#%d) along y axis (+0.1) and change delta.z (dz) by 0.1.\n", j->part1->refno);
99        j->getModel().open();
100        j->part1->p.y += 0.1;
101        j->d.z += 0.1;
102        j->getModel().close();
103        printf("Position of the second Part referenced by this joint (part #%d) is now changed:\n\n%s\n",
104                j->part2->refno, j->getModel().getF0Geno().getGenes().c_str());
105        printf("If no delta fields are defined, they will be computed automatically.\n"
106                "You can always delete existing delta values by using Joint::resetDelta().\n"
107                "Now we will change the second Part's z position by -0.2 and call resetDelta()...\n");
108        j->getModel().open();
109        j->part2->p.z -= 0.2;
110        j->resetDelta();
111        j->getModel().close();
112        printf("As you can see, Joint's delta fields have altered:\n\n%s\n", j->getModel().getF0Geno().getGenes().c_str());
[109]113}
114
115void switchDelta(Joint *j)
116{
[742]117        int option = !j->isDelta();
118        printf("How would this joint look like with delta option %s?\n[ by calling Joint::useDelta(%d) ]\n", option ? "enabled" : "disabled", option);
119        j->getModel().open();
120        j->useDelta(!j->isDelta());
121        j->getModel().close();
122        printf("f0 is now:\n\n%s\n...so this is %s joint.\n",
123                j->getModel().getF0Geno().getGenes().c_str(), option ? "a delta" : "an absolute");
[109]124
125}
126
127void moreAboutJoint(Joint* j)
128{
[742]129        printf("Similarly as with Part, the full list of properties comes first:\n\n");
130        PRINT_PROPERTIES(j->properties());
131        printf("\nActually, there are two kinds of Joints: delta and absolute.\n"
132                "For this object, Joint::isDelta() returns %d, so this is the %s Joint.\n",
133                j->isDelta(), j->isDelta() ? "delta" : "absolute");
134        if (j->isDelta())
[109]135        {
[742]136                playWithDelta(j);
137                switchDelta(j);
138                playWithAbsolute(j);
[109]139        }
[742]140        else
[109]141        {
[742]142                playWithAbsolute(j);
143                switchDelta(j);
144                playWithDelta(j);
[109]145        }
146
[742]147        printf("Part references and delta fields are the 'core' properties of the Joint.\n"
148                "The other properties are available from Joint::extraProperties()\n"
149                "and at the moment are defined as follows:\n\n");
150        PRINT_PROPERTIES(j->extraProperties());
151        printf("\nThey can be changed just like Part's extra properties:\n");
152        j->getModel().open();
153        CHANGE_ONE_PROPERTY(j->extraProperties());
154        j->getModel().close();
155        printf("And after that we have this genotype:\n\n%s\n", j->getModel().getF0Geno().getGenes().c_str());
[109]156}
157
158
159
160void moreAboutNeuro(Neuro* n)
161{
[742]162        printf("Basic features of Neuro object are similar to those of Part and Joint.\n"
163                "We can request a property list:\n\n");
164        PRINT_PROPERTIES(n->properties());
165        printf("\n...and extra properties (which are designed to be always valid and easy to change):\n\n");
166        PRINT_PROPERTIES(n->extraProperties());
167        printf("\nAs usual, we will change something:\n");
168        n->getModel().open();
169        CHANGE_ONE_PROPERTY(n->extraProperties());
170        n->getModel().close();
171        printf("Each neuron can have any number of inputs = weighted connections\n with other neurons.\n"
172                "According to Neuro::getInputCount(), this one has %d inputs.\n", n->getInputCount());
173        printf("Standard API is provided for accessing those inputs (getInput(int)),\n"
174                "adding inputs (addInput(Neuro*)) and removing them (removeInput(int)).\n\n");
[109]175
[742]176        printf("\nThe most unusual thing is 'details' field (d).\n"
177                "It is something like separate object with its own set of properties.\n"
178                "Currently the value of 'd' is '%s'.\n", n->getDetails().c_str());
[109]179
[742]180        {
181                NeuroClass* cl = n->getClass();
182                if (!cl)
183                        printf("It should contain the class name but the meaning of '%s' is unknown\n", n->getDetails().c_str());
184                else
185                {
[109]186
[742]187                        printf("'%s' is the class name (Neuro::getClassName() == '%s') and means '%s'.\n",
188                                cl->getName().c_str(), cl->getName().c_str(), cl->getLongName().c_str());
189                        printf("Neuro::getClass() gives you information about basic characteristic\n"
190                                "of the class, that can be analyzed automatically.\n");
191                        printf("For the current object we can learn that it supports ");
192                        if (cl->getPreferredInputs() < 0) printf("any number of inputs");
193                        else if (cl->getPreferredInputs() == 0) printf("no inputs");
194                        else printf("%d inputs", cl->getPreferredInputs());
195                        printf(" (getPreferredInputs()) ");
196                        printf(cl->getPreferredOutput() ? "and provides meaningful output signal (getPreferredOutput()==1).\n" : "and doesn't provide useful output signal (getPreferredOutput()==0).\n");
[109]197
[742]198                        SyntParam p = n->classProperties();
199                        if (p.getPropCount() > 0)
200                        {
201                                printf("The class defines its own properties:\n\n [ data provided by Neuro::classProperties() ]\n");
202                                printProperties(p);
203                                printf("and they can be changed:\n");
204                                n->getModel().open();
205                                changeOneProperty(p);
206                                p.update();
207                                n->getModel().close();
208                                printf("After that, 'details' contains the new object: '%s'.\n", n->getDetails().c_str());
209                        }
210                        else
211                                printf("(This class does not have its own properties\n"
212                                " - Neuro::classProperties().getPropCount()==0)\n");
213                }
[109]214        }
215
[742]216        printf("The class of this object can be changed using Neuro::setClassName()\n"
217                "The following classes are available:\n"
218                " [ data provided by Neuro::getClassInfo()->getProperties() ]\n\n");
219        printf(" #  class  description       properties\n");
220        for (int i = 0; i < n->getClassCount(); i++)
[109]221        {
[742]222                NeuroClass* cl = n->getClass(i);
223                Param p = cl->getProperties();
224                printf("%2d.%6s  %-20s  %2d\n", i, cl->getName().c_str(), cl->getLongName().c_str(), p.getPropCount());
[109]225        }
[742]226        int cl = rand() % n->getClassCount();
227        printf("\nLet's change the Neuro's class to '%s'...\n", n->getClassName(cl).c_str());
228        n->getModel().open();
229        n->setClass(n->getClass(cl));
[109]230        {
[742]231                SyntParam p = n->classProperties();
232                if (p.getPropCount()>0)
233                {
234                        printProperties(p);
235                        changeOneProperty(p);
236                        p.update();
237                }
[109]238        }
239
[742]240        if (n->getInputCount() > 0)
241        {
242                printf("Info for input #0 = \"%s\"\n", n->getInputInfo(0).c_str());
243                printf("Info for input #0, field \"%s\" = \"%s\"\n", "abc", n->getInputInfo(0, "abc").c_str());
244                n->setInputInfo(0, "test", 44);
245                n->setInputInfo(0, "abc", "yeah");
246        }
[109]247
[742]248        n->getModel().close();
249        printf("The final object description will be then: '%s'\nAnd the full f0 genotype:\n\n%s\n",
250                n->getDetails().c_str(), n->getModel().getF0Geno().getGenes().c_str());
[109]251
252
253}
254
255void findingConverters()
256{
[742]257        GenoConverter *gc = Geno::getConverters()->findConverters(0, '1');
258        if (gc) printf("found converter accepting f1: \"%s\"\n", gc->name);
259        SListTempl<GenoConverter*> found;
260        Geno::getConverters()->findConverters(&found, -1, '0');
261        printf("found %d converter(s) producing f0\n", found.size());
[109]262}
263
[742]264int main(int argc, char*argv[])
[109]265{
[742]266        LoggerToStdout messages_to_stdout(LoggerBase::Enable); //redirect model-related errors to stdout
267        PreconfiguredGenetics genetics;
[291]268
[742]269        srand(time(0));
270        printNiceBanner("Welcome to Genotype Manipulation App!");
[109]271
[742]272        findingConverters();
[109]273
[742]274        SString gen(argc > 1 ? argv[1] : "X[|G:1.23]");
275        if (!strcmp(gen.c_str(), "-"))
[109]276        {
[742]277                gen = 0;
278                StdioFILEDontClose in(stdin);
279                loadSString(&in, gen);
[109]280        }
[742]281        Geno g(gen);
282        printf("\nSource genotype: '%s'\n", g.getGenes().c_str());
283        printf("                  ( format %c %s)\n",
284                g.getFormat(), g.getComment().c_str());
[109]285
[742]286        Model m(g);//.getConverted('0'));
[109]287
[742]288        if (!m.isValid())
[109]289        {
[742]290                printf("Cannot build Model from this genotype!\n");
291                return 2;
[109]292        }
[742]293        printf("Converted to f0:\n%s\n", m.getF0Geno().getGenes().c_str());
[109]294
[742]295        printf("Model contains: %d part(s)\n"
296                "                %d joint(s)\n"
297                "                %d neuron(s)\n", m.getPartCount(), m.getJointCount(), m.getNeuroCount());
[109]298
[742]299        printf("\nInvestigating details...\n");
[109]300
[742]301        if (m.getPartCount() > 0)
[109]302        {
[742]303                int p = rand() % m.getPartCount();
304                printNiceBanner("P A R T    O B J E C T");
305                printf("            (part # %d)\n", p);
306                moreAboutPart(m.getPart(p));
[109]307        }
308
[742]309        if (m.getJointCount() > 0)
[109]310        {
[742]311                int j = rand() % m.getJointCount();
312                printNiceBanner("J O I N T    O B J E C T");
313                printf("            (joint # %d)\n", j);
314                moreAboutJoint(m.getJoint(j));
[109]315        }
316
[742]317        if (m.getNeuroCount() > 0)
[109]318        {
[742]319                int n = rand() % m.getNeuroCount();
320                printNiceBanner("N E U R O    O B J E C T");
321                printf("            (neuro # %d)\n", n);
322                moreAboutNeuro(m.getNeuro(n));
[109]323        }
324
325#ifdef MODEL_V1_COMPATIBLE
[742]326        printNiceBanner("Old Neuro/NeuroItem view");
327        int nc = m.old_getNeuroCount();
328        printf("Model::old_getNeuroCount() = %d\n", nc);
329        for (int i = 0; i < nc; i++)
[109]330        {
[742]331                Neuro *n = m.old_getNeuro(i);
332                printf("neuron #%d: p=%d, j=%d, force=%g, inertia=%g, sigmoid=%g\n",
333                        i, n->part_refno, n->joint_refno,
334                        n->force, n->inertia, n->sigmo);
335                int nicount = n->getItemCount();
336                printf("    %d items\n", nicount);
337                for (int j = 0; j < nicount; j++)
[109]338                {
[742]339                        NeuroItem *ni = n->getNeuroItem(j);
340                        printf("        item #%d - '%s', conn=%d, weight=%g\n",
341                                j, ni->getDetails().c_str(), ni->conn_refno, ni->weight);
[109]342                }
343        }
[742]344        printf("end.\n");
[109]345#endif
346
[742]347        printf("\n######### THE END ###########\n\n"
348                "Hints:\n"
349                "  1. You can redirect output: genomanipulation >filename.txt\n"
350                "  2. Each run can yield different results, because some\n"
351                "     values are randomly generated.\n"
352                "  3. This application will use custom genotype passed as\n"
353                "     a commandline parameter: genomanipulation XX\n"
354                "\n");
355        return 0;
[109]356}
Note: See TracBrowser for help on using the repository browser.