source: cpp/gdk/gdktest.cpp @ 73

Last change on this file since 73 was 73, checked in by Maciej Komosinski, 12 years ago

a genotype can be passed as a parameter

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