1 | """Simple examples of using the "frams" module to communicate directly with the Framsticks library (dll/so).
|
---|
2 |
|
---|
3 | For an introduction to Framsticks, its usage and scripting, see https://www.youtube.com/playlist?list=PLkPlXm7pOPatTl3_Gecx8ZaCVGeH4UV1L
|
---|
4 | For a list of available classes, objects, methods and fields, see http://www.framsticks.com/files/classdoc/
|
---|
5 | For a number of examples of scripting, see the "scripts" directory in the Framsticks distribution.
|
---|
6 | """
|
---|
7 |
|
---|
8 | import sys
|
---|
9 | import json
|
---|
10 | import frams
|
---|
11 |
|
---|
12 | frams.init(*(sys.argv[1:])) # pass whatever args we have, init() is the right place to deal with different scenarios:
|
---|
13 | # frams.init() - should try to figure out everything (and might fail)
|
---|
14 | # frams.init('path/to/lib') - load the library from the specified directory and configure Framsticks path as "data" inside this directory
|
---|
15 | # frams.init('path/to/lib','-d/tmp/workdir/data') - as above, but set the working (writable) directory somewhere else (see also -D)
|
---|
16 | # frams.init('path/to/lib','-Lframs-objects-alt.dll') - use specified library location and non-default file name
|
---|
17 |
|
---|
18 | print('Available objects:', dir(frams))
|
---|
19 | print()
|
---|
20 |
|
---|
21 |
|
---|
22 | def extValueDetails(v):
|
---|
23 | """A helper function to display basic information about a variable of type ExtValue."""
|
---|
24 | return '\t"' + str(v) + '" frams type=' + str(v._type()) + ' frams class=' + str(v._class()) + ' python type=' + str(type(v._value()))
|
---|
25 |
|
---|
26 |
|
---|
27 | dic_as_string = '[100,2.2,"abc",[null,[],{}],XYZ[9,8,7]]'
|
---|
28 | print("We have the following string:\n\t'%s'" % dic_as_string)
|
---|
29 | print("Looks like a serialized dictionary, let's ask Framsticks String.deserialize() to do its job.")
|
---|
30 | v = frams.String.deserialize(dic_as_string)
|
---|
31 | print("Framsticks String.deserialize() returned\n\t", type(v))
|
---|
32 | print("More specifically, it is:")
|
---|
33 | print(extValueDetails(v))
|
---|
34 | print("Even though it is ExtValue (Framsticks' Vector), it supports iteration like a python vector, so let's inspect its elements:")
|
---|
35 | for e in v:
|
---|
36 | print(extValueDetails(e))
|
---|
37 |
|
---|
38 | print("\nNow let's play with the Framsticks simulator. Let's create a Genotype object and set fields in its custom 'data' dictionary.")
|
---|
39 | g = frams.GenePools[0].add('X')
|
---|
40 | g.name = "Snakis Py"
|
---|
41 | g.data['custom'] = 123.456
|
---|
42 | g.data['a'] = 'b' # implicit conversion, looks like python dictionary but still converts '3' and '4' to ExtValue
|
---|
43 | dic = frams.Dictionary.new() # let's create a Dictionary object from Framsticks
|
---|
44 | dic.set('1', '2') # calling set() from Framsticks Dictionary
|
---|
45 | dic['3'] = '4' # implicit conversion, looks like python dictionary but still converts '3' and '4' to ExtValue
|
---|
46 | g.data['d'] = dic
|
---|
47 | print(extValueDetails(g))
|
---|
48 |
|
---|
49 | print("Let's add a few mutants and display their data:")
|
---|
50 | for more in range(5):
|
---|
51 | frams.GenePools[0].add(frams.GenMan.mutate(g.geno))
|
---|
52 |
|
---|
53 | for g in frams.GenePools[0]:
|
---|
54 | print("\t%d. name='%s'\tgenotype='%s'\tdata=%s" % (g.index._value(), str(g.name), str(g.genotype), str(g.data)))
|
---|
55 |
|
---|
56 | print("Let's now change some property of the simulation. Current water level is", frams.World.wrldwat)
|
---|
57 | frams.World.wrldwat = 0.5
|
---|
58 | print("Now water level is", frams.World.wrldwat)
|
---|
59 | frams.World.wrldwat = frams.World.wrldwat._value() + 0.7
|
---|
60 | print("Now water level is", frams.World.wrldwat)
|
---|
61 |
|
---|
62 | initial_genotype = 'X(X,RX(X[T],X[G]))' # simple body with touch and gyroscope sensors
|
---|
63 | print("Let's perform a few simulation steps of the initial genotype:", initial_genotype)
|
---|
64 | frams.ExpProperties.initialgen = initial_genotype
|
---|
65 | frams.ExpProperties.p_mut = 0 # no mutation (the selection procedure will clone our initial genotype)
|
---|
66 | frams.ExpProperties.p_xov = 0 # no crossover (the selection procedure will clone our initial genotype)
|
---|
67 | frams.Populations[0].initial_nn_active = 1 # immediate simulation of neural network - no "waiting for stabilization" period
|
---|
68 | frams.World.wrldg = 5 # gravity=5x default, let it fall quickly
|
---|
69 |
|
---|
70 | frams.Simulator.init() # adds initial_genotype to gene pool (calls onInit() from standard.expdef)
|
---|
71 | frams.Simulator.start() # this does not actually start the simulation, just sets the "Simulator.running" status variable
|
---|
72 | step = frams.Simulator.step # cache reference to avoid repeated lookup in the loop (just for performance)
|
---|
73 | for s in range(15):
|
---|
74 | step() # first step performs selection and revives one genotype according to standard.expdef rules
|
---|
75 | creature = frams.Populations[0][0] # FramScript Creature object
|
---|
76 | mechpart0 = creature.getMechPart(0)
|
---|
77 | print('Step# = %d' % frams.Simulator.stepNumber._value(),
|
---|
78 | '\tSimulated_creatures =', frams.Populations[0].size._value(),
|
---|
79 | "\tpart0_xyz = (% .2f,% .2f,% .2f)" % (mechpart0.x._value(), mechpart0.y._value(), mechpart0.z._value()),
|
---|
80 | "\ttouch = % .3f\tgyro = % .3f" % (creature.getNeuro(0).state._value(), creature.getNeuro(1).state._value()))
|
---|
81 | frams.Simulator.stop()
|
---|
82 |
|
---|
83 | # changing expdef
|
---|
84 | testgenotype = "XrrX[G][-1:80][|,-1:0.9]X[|,-2:-21]"
|
---|
85 | evaluations = 100
|
---|
86 | print("\nLet's change the experiment definition (expdef) and evaluate genotype '%s' %d times." % (testgenotype, evaluations))
|
---|
87 | frams.Simulator.expdef = "standard-eval"
|
---|
88 | frams.ExpProperties.evalcount = evaluations
|
---|
89 | frams.ExpProperties.cr_v = 1
|
---|
90 | frams.ExpProperties.evalplan = ":velocity,vertpos,fit_stdev,time"
|
---|
91 | frams.GenePools[0].add(testgenotype)
|
---|
92 | frams.ExpProperties.evalsavefile = "" # no need to store results in a file - we will get evaluations directly from Genotype's "data" field
|
---|
93 | frams.Simulator.init()
|
---|
94 | frams.Simulator.start()
|
---|
95 | # step = frams.Simulator.step # cache reference to avoid repeated lookup in the loop (just for performance)
|
---|
96 | # while frams.Simulator.running._int(): # standard-eval.expdef sets running to 0 when the evaluation is complete
|
---|
97 | # step()
|
---|
98 | frams.Simulator.eval("while(Simulator.running) Simulator.step();") # loop in FramScript much faster than loop in python
|
---|
99 | for g in frams.GenePools[0]: # loop over all genotypes, even though we know we added only one
|
---|
100 | serialized_dict = frams.String.serialize(g.data[frams.ExpProperties.evalsavedata._value()])
|
---|
101 | print(json.loads(serialized_dict._string()))
|
---|
102 |
|
---|
103 | # sampling a Model in 3D
|
---|
104 | geno = "RXX(X,CXXX)"
|
---|
105 | print("\nNow build a Model from the genotype '%s' and sample it in 3D, then print a 2D projection" % geno)
|
---|
106 | import numpy as np
|
---|
107 |
|
---|
108 | matrix = np.zeros((20, 20, 20), dtype=int) # 3D matrix, "voxels"
|
---|
109 | m = frams.ModelGeometry.forModel(frams.Model.newFromString(geno));
|
---|
110 | m.geom_density = 20;
|
---|
111 | for p in m.voxels():
|
---|
112 | # print('%f %f %f ' % (p.x._value(), p.y._value(), p.z._value()))
|
---|
113 | matrix[int(p.x._value() * 5 + 2), int(p.y._value() * 5 + 5), int(p.z._value() * 5 + 6)] += 1 # scaling and offsets adjusted manually to fit the matrix nicely
|
---|
114 | matrix = np.sum(matrix, axis=1) # sum along axis, make 2D from 3D ("projection")
|
---|
115 | np.set_printoptions(formatter={'int': lambda x: ('.' if x == 0 else str(x // 18))}) # print zeros as dots, x//18 to fit a larger range into a single digit
|
---|
116 | print(matrix)
|
---|
117 | np.set_printoptions() # avoids straange python errors: frams.py, line 48, in __del__ AttributeError: 'NoneType' object has no attribute 'extFree'
|
---|
118 |
|
---|
119 | #
|
---|
120 | #
|
---|
121 | # Note that implementing a complete expdef, especially a complex one, entirely in python may be inconvenient or impractical
|
---|
122 | # because you do not have access to "event handlers" like you have in FramScript - onStep(), onBorn(), onDied(), onCollision() etc.,
|
---|
123 | # so you would have to check various conditions in python in each simulation step to achieve the same effect.
|
---|