source: cpp/gdk/gdktest.cpp @ 81

Last change on this file since 81 was 81, checked in by Maciej Komosinski, 11 years ago

improved parsing of properties (e.g. in f0 genotypes)

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