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

Last change on this file since 737 was 549, checked in by Maciej Komosinski, 8 years ago

More correct use of PreconfiguredGenetics?: avoid static objects, create after logger is configured (so warnings can be printed)

  • Property svn:eol-style set to native
File size: 12.4 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2015  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#include <stdlib.h>
6#include <stdio.h>
7#include <time.h>
8#include <common/virtfile/stdiofile.h>
9
10#include <frams/model/model.h>
11#include <frams/genetics/preconfigured.h>
12#include <common/loggers/loggertostdout.h>
13
14/**
15 @file
16 Sample code: Accessing model elements
17*/
18
19void printNiceBanner(const char* title)
20{
21printf("    #############################################\n"
22       "   ##                                           ##\n"
23       "  ##    %-37s    ##\n"
24       "   ##                                           ##\n"
25       "    #############################################\n",title);
26}
27void printProperties(Param &pi)
28{
29printf(" #        id                      type  name        group (%d properties)\n",pi.getPropCount());
30for (int i=0;i<pi.getPropCount();i++)
31        {
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)));
35        }
36}
37
38#define PRINT_PROPERTIES(p) {Param tmp_param(p); printProperties(tmp_param);}
39
40void changeOneProperty(Param &pi)
41{
42if (pi.getPropCount()<=0) return;
43int i=rand() % pi.getPropCount();
44double maxprop=1,minprop=0,def;
45pi.getMinMax(i,minprop,maxprop,def);
46printf("      Change property #%d to random value from range [%g..%g]\n",i,minprop,maxprop);
47printf("      Current value of '%s' (%s) is '%s'\n",pi.id(i),pi.name(i),pi.get(i).c_str());
48char t[100];
49sprintf(t,"%g",minprop+(rnd01)*(maxprop-minprop));
50printf("      Setting new value... [ using ParamInterface::set() ]\n");
51pi.set(i,t);
52printf("      The value is now '%s'\n",pi.get(i).c_str());
53}
54
55#define CHANGE_ONE_PROPERTY(p) {Param tmp_param(p); changeOneProperty(tmp_param);}
56
57void moreAboutPart(Part* p)
58{
59printf("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");
64PRINT_PROPERTIES(p->properties());
65printf("\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");
70PRINT_PROPERTIES(p->extraProperties());
71printf("\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");
76p->getModel().open();
77CHANGE_ONE_PROPERTY(p->extraProperties());
78p->getModel().close();
79printf("\nLet's see f0... (check out part #%d !)\n\n%s\n", p->refno, p->getModel().getF0Geno().getGenes().c_str());
80}
81
82void playWithAbsolute(Joint *j)
83{
84printf("\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");
87j->getModel().open();
88j->part1->p.y-=0.1;
89j->getModel().close();
90printf("The Part's position is changed, but everything else stays intact:\n\n%s\n",
91       j->getModel().getF0Geno().getGenes().c_str());
92}
93
94void playWithDelta(Joint *j)
95{
96printf("\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);
99j->getModel().open();
100j->part1->p.y+=0.1;
101j->d.z+=0.1;
102j->getModel().close();
103printf("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());
105printf("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");
108j->getModel().open();
109j->part2->p.z-=0.2;
110j->resetDelta();
111j->getModel().close();
112printf("As you can see, Joint's delta fields have altered:\n\n%s\n", j->getModel().getF0Geno().getGenes().c_str());
113}
114
115void switchDelta(Joint *j)
116{
117int option=! j->isDelta();
118printf("How would this joint look like with delta option %s?\n[ by calling Joint::useDelta(%d) ]\n",option?"enabled":"disabled",option);
119j->getModel().open();
120j->useDelta( ! j->isDelta() );
121j->getModel().close();
122printf("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");
124
125}
126
127void moreAboutJoint(Joint* j)
128{
129printf("Similarly as with Part, the full list of properties comes first:\n\n");
130PRINT_PROPERTIES(j->properties());
131printf("\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");
134if (j->isDelta())
135        {
136        playWithDelta(j);
137        switchDelta(j);
138        playWithAbsolute(j);
139        }
140else
141        {
142        playWithAbsolute(j);
143        switchDelta(j);
144        playWithDelta(j);
145        }
146
147printf("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");
150PRINT_PROPERTIES(j->extraProperties());
151printf("\nThey can be changed just like Part's extra properties:\n");
152j->getModel().open();
153CHANGE_ONE_PROPERTY(j->extraProperties());
154j->getModel().close();
155printf("And after that we have this genotype:\n\n%s\n", j->getModel().getF0Geno().getGenes().c_str());
156}
157
158
159
160void moreAboutNeuro(Neuro* n)
161{
162printf("Basic features of Neuro object are similar to those of Part and Joint.\n"
163       "We can request a property list:\n\n");
164PRINT_PROPERTIES(n->properties());
165printf("\n...and extra properties (which are designed to be always valid and easy to change):\n\n");
166PRINT_PROPERTIES(n->extraProperties());
167printf("\nAs usual, we will change something:\n");
168n->getModel().open();
169CHANGE_ONE_PROPERTY(n->extraProperties());
170n->getModel().close();
171printf("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());
173printf("Standard API is provided for accessing those inputs (getInput(int)),\n"
174       "adding inputs (addInput(Neuro*)) and removing them (removeInput(int)).\n\n");
175
176printf("\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());
179
180{
181NeuroClass* cl=n->getClass();
182if (!cl)
183        printf("It should contain the class name but the meaning of '%s' is unknown\n",n->getDetails().c_str());
184else
185{
186
187printf("'%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());
189printf("Neuro::getClass() gives you information about basic characteristic\n"
190       "of the class, that can be analyzed automatically.\n");
191printf("For the current object we can learn that it supports ");
192if (cl->getPreferredInputs()<0) printf("any number of inputs");
193  else if (cl->getPreferredInputs()==0) printf("no inputs");
194  else printf("%d inputs",cl->getPreferredInputs());
195printf(" (getPreferredInputs()) ");
196printf(cl->getPreferredOutput()?"and provides meaningful output signal (getPreferredOutput()==1).\n":"and doesn't provide useful output signal (getPreferredOutput()==0).\n");
197
198SyntParam p=n->classProperties();
199if (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        }
210else
211        printf("(This class does not have its own properties\n"
212               " - Neuro::classProperties().getPropCount()==0)\n");
213}
214}
215
216printf("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");
219printf(" #  class  description       properties\n");
220for (int i=0;i<n->getClassCount();i++)
221        {
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());
225        }
226int cl=rand() % n->getClassCount();
227printf("\nLet's change the Neuro's class to '%s'...\n",n->getClassName(cl).c_str());
228n->getModel().open();
229n->setClass(n->getClass(cl));
230{
231SyntParam p=n->classProperties();
232if (p.getPropCount()>0)
233        {
234        printProperties(p);
235        changeOneProperty(p);
236        p.update();
237        }
238}
239
240if (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}
247
248n->getModel().close();
249printf("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());
251
252
253}
254
255void findingConverters()
256{
257GenoConverter *gc=Geno::getConverters()->findConverters(0,'1');
258if (gc) printf("found converter accepting f1: \"%s\"\n",gc->name);
259SListTempl<GenoConverter*> found;
260Geno::getConverters()->findConverters(&found,-1,'0');
261printf("found %d converter(s) producing f0\n",found.size());
262}
263
264int main(int argc,char*argv[])
265{
266LoggerToStdout messages_to_stdout(LoggerBase::Enable); //redirect model-related errors to stdout
267PreconfiguredGenetics genetics;
268
269srand(time(0));
270printNiceBanner("Welcome to Genotype Manipulation App!");
271
272findingConverters();
273
274SString gen(argc>1?argv[1]:"X[|G:1.23]");
275if (!strcmp(gen.c_str(),"-"))
276        {
277        gen=0;
278        StdioFILEDontClose in(stdin);
279        loadSString(&in,gen);
280        }
281Geno g(gen);
282printf("\nSource genotype: '%s'\n",g.getGenes().c_str());
283printf("                  ( format %c %s)\n",
284       g.getFormat(), g.getComment().c_str());
285
286Model m(g);//.getConverted('0'));
287
288if (!m.isValid())
289        {
290        printf("Cannot build Model from this genotype!\n");
291        return 2;       
292        }
293printf("Converted to f0:\n%s\n",m.getF0Geno().getGenes().c_str());
294
295printf("Model contains: %d part(s)\n"
296       "                %d joint(s)\n"
297       "                %d neuron(s)\n",m.getPartCount(),m.getJointCount(),m.getNeuroCount());
298
299printf("\nInvestigating details...\n");
300
301if (m.getPartCount()>0)
302        {
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));
307        }
308
309if (m.getJointCount()>0)
310        {
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));
315        }
316
317if (m.getNeuroCount()>0)
318        {
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));
323        }
324
325#ifdef MODEL_V1_COMPATIBLE
326printNiceBanner("Old Neuro/NeuroItem view");
327int nc=m.old_getNeuroCount();
328printf("Model::old_getNeuroCount() = %d\n",nc);
329for (int i=0;i<nc;i++)
330        {
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++)
338                {
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);
342                }
343        }
344printf("end.\n");
345#endif
346
347printf("\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");
355return 0;
356}
Note: See TracBrowser for help on using the repository browser.