Mercurial > cortex
view thesis/cortex.org @ 468:258078f78b33
insert argument about senses.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 28 Mar 2014 16:25:31 -0400 |
parents | ade64947d2bf |
children | ae10f35022ba |
line wrap: on
line source
1 #+title: =CORTEX=2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Using embodied AI to facilitate Artificial Imagination.5 #+keywords: AI, clojure, embodiment6 #+LaTeX_CLASS_OPTIONS: [nofloat]8 * COMMENT templates9 #+caption:10 #+caption:11 #+caption:12 #+caption:13 #+name: name14 #+begin_listing clojure15 #+begin_src clojure16 #+end_src17 #+end_listing19 #+caption:20 #+caption:21 #+caption:22 #+name: name23 #+ATTR_LaTeX: :width 10cm24 [[./images/aurellem-gray.png]]28 * COMMENT Empathy and Embodiment as problem solving strategies30 By the end of this thesis, you will have seen a novel approach to31 interpreting video using embodiment and empathy. You will have also32 seen one way to efficiently implement empathy for embodied33 creatures. Finally, you will become familiar with =CORTEX=, a system34 for designing and simulating creatures with rich senses, which you35 may choose to use in your own research.37 This is the core vision of my thesis: That one of the important ways38 in which we understand others is by imagining ourselves in their39 position and emphatically feeling experiences relative to our own40 bodies. By understanding events in terms of our own previous41 corporeal experience, we greatly constrain the possibilities of what42 would otherwise be an unwieldy exponential search. This extra43 constraint can be the difference between easily understanding what44 is happening in a video and being completely lost in a sea of45 incomprehensible color and movement.47 ** Recognizing actions in video is extremely difficult49 Consider for example the problem of determining what is happening50 in a video of which this is one frame:52 #+caption: A cat drinking some water. Identifying this action is53 #+caption: beyond the state of the art for computers.54 #+ATTR_LaTeX: :width 7cm55 [[./images/cat-drinking.jpg]]57 It is currently impossible for any computer program to reliably58 label such a video as ``drinking''. And rightly so -- it is a very59 hard problem! What features can you describe in terms of low level60 functions of pixels that can even begin to describe at a high level61 what is happening here?63 Or suppose that you are building a program that recognizes chairs.64 How could you ``see'' the chair in figure \ref{hidden-chair}?66 #+caption: The chair in this image is quite obvious to humans, but I67 #+caption: doubt that any modern computer vision program can find it.68 #+name: hidden-chair69 #+ATTR_LaTeX: :width 10cm70 [[./images/fat-person-sitting-at-desk.jpg]]72 Finally, how is it that you can easily tell the difference between73 how the girls /muscles/ are working in figure \ref{girl}?75 #+caption: The mysterious ``common sense'' appears here as you are able76 #+caption: to discern the difference in how the girl's arm muscles77 #+caption: are activated between the two images.78 #+name: girl79 #+ATTR_LaTeX: :width 7cm80 [[./images/wall-push.png]]82 Each of these examples tells us something about what might be going83 on in our minds as we easily solve these recognition problems.85 The hidden chairs show us that we are strongly triggered by cues86 relating to the position of human bodies, and that we can determine87 the overall physical configuration of a human body even if much of88 that body is occluded.90 The picture of the girl pushing against the wall tells us that we91 have common sense knowledge about the kinetics of our own bodies.92 We know well how our muscles would have to work to maintain us in93 most positions, and we can easily project this self-knowledge to94 imagined positions triggered by images of the human body.96 ** =EMPATH= neatly solves recognition problems98 I propose a system that can express the types of recognition99 problems above in a form amenable to computation. It is split into100 four parts:102 - Free/Guided Play :: The creature moves around and experiences the103 world through its unique perspective. Many otherwise104 complicated actions are easily described in the language of a105 full suite of body-centered, rich senses. For example,106 drinking is the feeling of water sliding down your throat, and107 cooling your insides. It's often accompanied by bringing your108 hand close to your face, or bringing your face close to water.109 Sitting down is the feeling of bending your knees, activating110 your quadriceps, then feeling a surface with your bottom and111 relaxing your legs. These body-centered action descriptions112 can be either learned or hard coded.113 - Posture Imitation :: When trying to interpret a video or image,114 the creature takes a model of itself and aligns it with115 whatever it sees. This alignment can even cross species, as116 when humans try to align themselves with things like ponies,117 dogs, or other humans with a different body type.118 - Empathy :: The alignment triggers associations with119 sensory data from prior experiences. For example, the120 alignment itself easily maps to proprioceptive data. Any121 sounds or obvious skin contact in the video can to a lesser122 extent trigger previous experience. Segments of previous123 experiences are stitched together to form a coherent and124 complete sensory portrait of the scene.125 - Recognition :: With the scene described in terms of first126 person sensory events, the creature can now run its127 action-identification programs on this synthesized sensory128 data, just as it would if it were actually experiencing the129 scene first-hand. If previous experience has been accurately130 retrieved, and if it is analogous enough to the scene, then131 the creature will correctly identify the action in the scene.133 For example, I think humans are able to label the cat video as134 ``drinking'' because they imagine /themselves/ as the cat, and135 imagine putting their face up against a stream of water and136 sticking out their tongue. In that imagined world, they can feel137 the cool water hitting their tongue, and feel the water entering138 their body, and are able to recognize that /feeling/ as drinking.139 So, the label of the action is not really in the pixels of the140 image, but is found clearly in a simulation inspired by those141 pixels. An imaginative system, having been trained on drinking and142 non-drinking examples and learning that the most important143 component of drinking is the feeling of water sliding down one's144 throat, would analyze a video of a cat drinking in the following145 manner:147 1. Create a physical model of the video by putting a ``fuzzy''148 model of its own body in place of the cat. Possibly also create149 a simulation of the stream of water.151 2. Play out this simulated scene and generate imagined sensory152 experience. This will include relevant muscle contractions, a153 close up view of the stream from the cat's perspective, and most154 importantly, the imagined feeling of water entering the155 mouth. The imagined sensory experience can come from a156 simulation of the event, but can also be pattern-matched from157 previous, similar embodied experience.159 3. The action is now easily identified as drinking by the sense of160 taste alone. The other senses (such as the tongue moving in and161 out) help to give plausibility to the simulated action. Note that162 the sense of vision, while critical in creating the simulation,163 is not critical for identifying the action from the simulation.165 For the chair examples, the process is even easier:167 1. Align a model of your body to the person in the image.169 2. Generate proprioceptive sensory data from this alignment.171 3. Use the imagined proprioceptive data as a key to lookup related172 sensory experience associated with that particular proproceptive173 feeling.175 4. Retrieve the feeling of your bottom resting on a surface, your176 knees bent, and your leg muscles relaxed.178 5. This sensory information is consistent with the =sitting?=179 sensory predicate, so you (and the entity in the image) must be180 sitting.182 6. There must be a chair-like object since you are sitting.184 Empathy offers yet another alternative to the age-old AI185 representation question: ``What is a chair?'' --- A chair is the186 feeling of sitting.188 My program, =EMPATH= uses this empathic problem solving technique189 to interpret the actions of a simple, worm-like creature.191 #+caption: The worm performs many actions during free play such as192 #+caption: curling, wiggling, and resting.193 #+name: worm-intro194 #+ATTR_LaTeX: :width 15cm195 [[./images/worm-intro-white.png]]197 #+caption: =EMPATH= recognized and classified each of these198 #+caption: poses by inferring the complete sensory experience199 #+caption: from proprioceptive data.200 #+name: worm-recognition-intro201 #+ATTR_LaTeX: :width 15cm202 [[./images/worm-poses.png]]204 One powerful advantage of empathic problem solving is that it205 factors the action recognition problem into two easier problems. To206 use empathy, you need an /aligner/, which takes the video and a207 model of your body, and aligns the model with the video. Then, you208 need a /recognizer/, which uses the aligned model to interpret the209 action. The power in this method lies in the fact that you describe210 all actions form a body-centered viewpoint. You are less tied to211 the particulars of any visual representation of the actions. If you212 teach the system what ``running'' is, and you have a good enough213 aligner, the system will from then on be able to recognize running214 from any point of view, even strange points of view like above or215 underneath the runner. This is in contrast to action recognition216 schemes that try to identify actions using a non-embodied approach.217 If these systems learn about running as viewed from the side, they218 will not automatically be able to recognize running from any other219 viewpoint.221 Another powerful advantage is that using the language of multiple222 body-centered rich senses to describe body-centerd actions offers a223 massive boost in descriptive capability. Consider how difficult it224 would be to compose a set of HOG filters to describe the action of225 a simple worm-creature ``curling'' so that its head touches its226 tail, and then behold the simplicity of describing thus action in a227 language designed for the task (listing \ref{grand-circle-intro}):229 #+caption: Body-centerd actions are best expressed in a body-centered230 #+caption: language. This code detects when the worm has curled into a231 #+caption: full circle. Imagine how you would replicate this functionality232 #+caption: using low-level pixel features such as HOG filters!233 #+name: grand-circle-intro234 #+attr_latex: [htpb]235 #+begin_listing clojure236 #+begin_src clojure237 (defn grand-circle?238 "Does the worm form a majestic circle (one end touching the other)?"239 [experiences]240 (and (curled? experiences)241 (let [worm-touch (:touch (peek experiences))242 tail-touch (worm-touch 0)243 head-touch (worm-touch 4)]244 (and (< 0.2 (contact worm-segment-bottom-tip tail-touch))245 (< 0.2 (contact worm-segment-top-tip head-touch))))))246 #+end_src247 #+end_listing250 ** =CORTEX= is a toolkit for building sensate creatures252 I built =CORTEX= to be a general AI research platform for doing253 experiments involving multiple rich senses and a wide variety and254 number of creatures. I intend it to be useful as a library for many255 more projects than just this thesis. =CORTEX= was necessary to meet256 a need among AI researchers at CSAIL and beyond, which is that257 people often will invent neat ideas that are best expressed in the258 language of creatures and senses, but in order to explore those259 ideas they must first build a platform in which they can create260 simulated creatures with rich senses! There are many ideas that261 would be simple to execute (such as =EMPATH=), but attached to them262 is the multi-month effort to make a good creature simulator. Often,263 that initial investment of time proves to be too much, and the264 project must make do with a lesser environment.266 =CORTEX= is well suited as an environment for embodied AI research267 for three reasons:269 - You can create new creatures using Blender, a popular 3D modeling270 program. Each sense can be specified using special blender nodes271 with biologically inspired paramaters. You need not write any272 code to create a creature, and can use a wide library of273 pre-existing blender models as a base for your own creatures.275 - =CORTEX= implements a wide variety of senses, including touch,276 proprioception, vision, hearing, and muscle tension. Complicated277 senses like touch, and vision involve multiple sensory elements278 embedded in a 2D surface. You have complete control over the279 distribution of these sensor elements through the use of simple280 png image files. In particular, =CORTEX= implements more281 comprehensive hearing than any other creature simulation system282 available.284 - =CORTEX= supports any number of creatures and any number of285 senses. Time in =CORTEX= dialates so that the simulated creatures286 always precieve a perfectly smooth flow of time, regardless of287 the actual computational load.289 =CORTEX= is built on top of =jMonkeyEngine3=, which is a video game290 engine designed to create cross-platform 3D desktop games. =CORTEX=291 is mainly written in clojure, a dialect of =LISP= that runs on the292 java virtual machine (JVM). The API for creating and simulating293 creatures and senses is entirely expressed in clojure, though many294 senses are implemented at the layer of jMonkeyEngine or below. For295 example, for the sense of hearing I use a layer of clojure code on296 top of a layer of java JNI bindings that drive a layer of =C++=297 code which implements a modified version of =OpenAL= to support298 multiple listeners. =CORTEX= is the only simulation environment299 that I know of that can support multiple entities that can each300 hear the world from their own perspective. Other senses also301 require a small layer of Java code. =CORTEX= also uses =bullet=, a302 physics simulator written in =C=.304 #+caption: Here is the worm from above modeled in Blender, a free305 #+caption: 3D-modeling program. Senses and joints are described306 #+caption: using special nodes in Blender.307 #+name: worm-recognition-intro308 #+ATTR_LaTeX: :width 12cm309 [[./images/blender-worm.png]]311 Here are some thing I anticipate that =CORTEX= might be used for:313 - exploring new ideas about sensory integration314 - distributed communication among swarm creatures315 - self-learning using free exploration,316 - evolutionary algorithms involving creature construction317 - exploration of exoitic senses and effectors that are not possible318 in the real world (such as telekenisis or a semantic sense)319 - imagination using subworlds321 During one test with =CORTEX=, I created 3,000 creatures each with322 their own independent senses and ran them all at only 1/80 real323 time. In another test, I created a detailed model of my own hand,324 equipped with a realistic distribution of touch (more sensitive at325 the fingertips), as well as eyes and ears, and it ran at around 1/4326 real time.328 #+BEGIN_LaTeX329 \begin{sidewaysfigure}330 \includegraphics[width=9.5in]{images/full-hand.png}331 \caption{332 I modeled my own right hand in Blender and rigged it with all the333 senses that {\tt CORTEX} supports. My simulated hand has a334 biologically inspired distribution of touch sensors. The senses are335 displayed on the right, and the simulation is displayed on the336 left. Notice that my hand is curling its fingers, that it can see337 its own finger from the eye in its palm, and that it can feel its338 own thumb touching its palm.}339 \end{sidewaysfigure}340 #+END_LaTeX342 ** Contributions344 - I built =CORTEX=, a comprehensive platform for embodied AI345 experiments. =CORTEX= supports many features lacking in other346 systems, such proper simulation of hearing. It is easy to create347 new =CORTEX= creatures using Blender, a free 3D modeling program.349 - I built =EMPATH=, which uses =CORTEX= to identify the actions of350 a worm-like creature using a computational model of empathy.352 * Building =CORTEX=354 I intend for =CORTEX= to be used as a general purpose library for355 building creatures and outfitting them with senses, so that it will356 be useful for other researchers who want to test out ideas of their357 own. To this end, wherver I have had to make archetictural choices358 about =CORTEX=, I have chosen to give as much freedom to the user as359 possible, so that =CORTEX= may be used for things I have not360 forseen.362 ** COMMENT Simulation or Reality?364 The most important archetictural decision of all is the choice to365 use a computer-simulated environemnt in the first place! The world366 is a vast and rich place, and for now simulations are a very poor367 reflection of its complexity. It may be that there is a significant368 qualatative difference between dealing with senses in the real369 world and dealing with pale facilimilies of them in a simulation.370 What are the advantages and disadvantages of a simulation vs.371 reality?373 *** Simulation375 The advantages of virtual reality are that when everything is a376 simulation, experiments in that simulation are absolutely377 reproducible. It's also easier to change the character and world378 to explore new situations and different sensory combinations.380 If the world is to be simulated on a computer, then not only do381 you have to worry about whether the character's senses are rich382 enough to learn from the world, but whether the world itself is383 rendered with enough detail and realism to give enough working384 material to the character's senses. To name just a few385 difficulties facing modern physics simulators: destructibility of386 the environment, simulation of water/other fluids, large areas,387 nonrigid bodies, lots of objects, smoke. I don't know of any388 computer simulation that would allow a character to take a rock389 and grind it into fine dust, then use that dust to make a clay390 sculpture, at least not without spending years calculating the391 interactions of every single small grain of dust. Maybe a392 simulated world with today's limitations doesn't provide enough393 richness for real intelligence to evolve.395 *** Reality397 The other approach for playing with senses is to hook your398 software up to real cameras, microphones, robots, etc., and let it399 loose in the real world. This has the advantage of eliminating400 concerns about simulating the world at the expense of increasing401 the complexity of implementing the senses. Instead of just402 grabbing the current rendered frame for processing, you have to403 use an actual camera with real lenses and interact with photons to404 get an image. It is much harder to change the character, which is405 now partly a physical robot of some sort, since doing so involves406 changing things around in the real world instead of modifying407 lines of code. While the real world is very rich and definitely408 provides enough stimulation for intelligence to develop as409 evidenced by our own existence, it is also uncontrollable in the410 sense that a particular situation cannot be recreated perfectly or411 saved for later use. It is harder to conduct science because it is412 harder to repeat an experiment. The worst thing about using the413 real world instead of a simulation is the matter of time. Instead414 of simulated time you get the constant and unstoppable flow of415 real time. This severely limits the sorts of software you can use416 to program the AI because all sense inputs must be handled in real417 time. Complicated ideas may have to be implemented in hardware or418 may simply be impossible given the current speed of our419 processors. Contrast this with a simulation, in which the flow of420 time in the simulated world can be slowed down to accommodate the421 limitations of the character's programming. In terms of cost,422 doing everything in software is far cheaper than building custom423 real-time hardware. All you need is a laptop and some patience.425 ** COMMENT Because of Time, simulation is perferable to reality427 I envision =CORTEX= being used to support rapid prototyping and428 iteration of ideas. Even if I could put together a well constructed429 kit for creating robots, it would still not be enough because of430 the scourge of real-time processing. Anyone who wants to test their431 ideas in the real world must always worry about getting their432 algorithms to run fast enough to process information in real time.433 The need for real time processing only increases if multiple senses434 are involved. In the extreme case, even simple algorithms will have435 to be accelerated by ASIC chips or FPGAs, turning what would436 otherwise be a few lines of code and a 10x speed penality into a437 multi-month ordeal. For this reason, =CORTEX= supports438 /time-dialiation/, which scales back the framerate of the439 simulation in proportion to the amount of processing each frame.440 From the perspective of the creatures inside the simulation, time441 always appears to flow at a constant rate, regardless of how442 complicated the envorimnent becomes or how many creatures are in443 the simulation. The cost is that =CORTEX= can sometimes run slower444 than real time. This can also be an advantage, however ---445 simulations of very simple creatures in =CORTEX= generally run at446 40x on my machine!448 ** What is a sense?450 If =CORTEX= is to support a wide variety of senses, it would help451 to have a better understanding of what a ``sense'' actually is!452 While vision, touch, and hearing all seem like they are quite453 different things, I was supprised to learn during the course of454 this thesis that they (and all physical senses) can be expressed as455 exactly the same mathematical object due to a dimensional argument!457 Human beings are three-dimensional objects, and the nerves that458 transmit data from our various sense organs to our brain are459 essentially one-dimensional. This leaves up to two dimensions in460 which our sensory information may flow. For example, imagine your461 skin: it is a two-dimensional surface around a three-dimensional462 object (your body). It has discrete touch sensors embedded at463 various points, and the density of these sensors corresponds to the464 sensitivity of that region of skin. Each touch sensor connects to a465 nerve, all of which eventually are bundled together as they travel466 up the spinal cord to the brain. Intersect the spinal nerves with a467 guillotining plane and you will see all of the sensory data of the468 skin revealed in a roughly circular two-dimensional image which is469 the cross section of the spinal cord. Points on this image that are470 close together in this circle represent touch sensors that are471 /probably/ close together on the skin, although there is of course472 some cutting and rearrangement that has to be done to transfer the473 complicated surface of the skin onto a two dimensional image.475 Most human senses consist of many discrete sensors of various476 properties distributed along a surface at various densities. For477 skin, it is Pacinian corpuscles, Meissner's corpuscles, Merkel's478 disks, and Ruffini's endings, which detect pressure and vibration479 of various intensities. For ears, it is the stereocilia distributed480 along the basilar membrane inside the cochlea; each one is481 sensitive to a slightly different frequency of sound. For eyes, it482 is rods and cones distributed along the surface of the retina. In483 each case, we can describe the sense with a surface and a484 distribution of sensors along that surface.486 The neat idea is that every human sense can be effectively487 described in terms of a surface containing embedded sensors. If the488 sense had any more dimensions, then there wouldn't be enough room489 in the spinal chord to transmit the information!491 Therefore, =CORTEX= must support the ability to create objects and492 then be able to ``paint'' points along their surfaces to describe493 each sense.495 Fortunately this idea is already a well known computer graphics496 technique called called /UV-mapping/. The three-dimensional surface497 of a model is cut and smooshed until it fits on a two-dimensional498 image. You paint whatever you want on that image, and when the499 three-dimensional shape is rendered in a game the smooshing and500 cutting is reversed and the image appears on the three-dimensional501 object.503 To make a sense, interpret the UV-image as describing the504 distribution of that senses sensors. To get different types of505 sensors, you can either use a different color for each type of506 sensor, or use multiple UV-maps, each labeled with that sensor507 type. I generally use a white pixel to mean the presence of a508 sensor and a black pixel to mean the absence of a sensor, and use509 one UV-map for each sensor-type within a given sense.511 #+CAPTION: The UV-map for an elongated icososphere. The white512 #+caption: dots each represent a touch sensor. They are dense513 #+caption: in the regions that describe the tip of the finger,514 #+caption: and less dense along the dorsal side of the finger515 #+caption: opposite the tip.516 #+name: finger-UV517 #+ATTR_latex: :width 10cm518 [[./images/finger-UV.png]]520 #+caption: Ventral side of the UV-mapped finger. Notice the521 #+caption: density of touch sensors at the tip.522 #+name: finger-side-view523 #+ATTR_LaTeX: :width 10cm524 [[./images/finger-1.png]]527 ** COMMENT Video game engines are a great starting point529 I did not need to write my own physics simulation code or shader to530 build =CORTEX=. Doing so would lead to a system that is impossible531 for anyone but myself to use anyway. Instead, I use a video game532 engine as a base and modify it to accomodate the additional needs533 of =CORTEX=. Video game engines are an ideal starting point to534 build =CORTEX=, because they are not far from being creature535 building systems themselves.537 First off, general purpose video game engines come with a physics538 engine and lighting / sound system. The physics system provides539 tools that can be co-opted to serve as touch, proprioception, and540 muscles. Since some games support split screen views, a good video541 game engine will allow you to efficiently create multiple cameras542 in the simulated world that can be used as eyes. Video game systems543 offer integrated asset management for things like textures and544 creatures models, providing an avenue for defining creatures. They545 also understand UV-mapping, since this technique is used to apply a546 texture to a model. Finally, because video game engines support a547 large number of users, as long as =CORTEX= doesn't stray too far548 from the base system, other researchers can turn to this community549 for help when doing their research.551 ** COMMENT =CORTEX= is based on jMonkeyEngine3553 While preparing to build =CORTEX= I studied several video game554 engines to see which would best serve as a base. The top contenders555 were:557 - [[http://www.idsoftware.com][Quake II]]/[[http://www.bytonic.de/html/jake2.html][Jake2]] :: The Quake II engine was designed by ID558 software in 1997. All the source code was released by ID559 software into the Public Domain several years ago, and as a560 result it has been ported to many different languages. This561 engine was famous for its advanced use of realistic shading562 and had decent and fast physics simulation. The main advantage563 of the Quake II engine is its simplicity, but I ultimately564 rejected it because the engine is too tied to the concept of a565 first-person shooter game. One of the problems I had was that566 there does not seem to be any easy way to attach multiple567 cameras to a single character. There are also several physics568 clipping issues that are corrected in a way that only applies569 to the main character and do not apply to arbitrary objects.571 - [[http://source.valvesoftware.com/][Source Engine]] :: The Source Engine evolved from the Quake II572 and Quake I engines and is used by Valve in the Half-Life573 series of games. The physics simulation in the Source Engine574 is quite accurate and probably the best out of all the engines575 I investigated. There is also an extensive community actively576 working with the engine. However, applications that use the577 Source Engine must be written in C++, the code is not open, it578 only runs on Windows, and the tools that come with the SDK to579 handle models and textures are complicated and awkward to use.581 - [[http://jmonkeyengine.com/][jMonkeyEngine3]] :: jMonkeyEngine3 is a new library for creating582 games in Java. It uses OpenGL to render to the screen and uses583 screengraphs to avoid drawing things that do not appear on the584 screen. It has an active community and several games in the585 pipeline. The engine was not built to serve any particular586 game but is instead meant to be used for any 3D game.588 I chose jMonkeyEngine3 because it because it had the most features589 out of all the free projects I looked at, and because I could then590 write my code in clojure, an implementation of =LISP= that runs on591 the JVM.593 ** =CORTEX= uses Blender to create creature models595 For the simple worm-like creatures I will use later on in this596 thesis, I could define a simple API in =CORTEX= that would allow597 one to create boxes, spheres, etc., and leave that API as the sole598 way to create creatures. However, for =CORTEX= to truly be useful599 for other projects, it needs a way to construct complicated600 creatures. If possible, it would be nice to leverage work that has601 already been done by the community of 3D modelers, or at least602 enable people who are talented at moedling but not programming to603 design =CORTEX= creatures.605 Therefore, I use Blender, a free 3D modeling program, as the main606 way to create creatures in =CORTEX=. However, the creatures modeled607 in Blender must also be simple to simulate in jMonkeyEngine3's game608 engine, and must also be easy to rig with =CORTEX='s senses. I609 accomplish this with extensive use of Blender's ``empty nodes.''611 Empty nodes have no mass, physical presence, or appearance, but612 they can hold metadata and have names. I use a tree structure of613 empty nodes to specify senses in the following manner:615 - Create a single top-level empty node whose name is the name of616 the sense.617 - Add empty nodes which each contain meta-data relevant to the618 sense, including a UV-map describing the number/distribution of619 sensors if applicable.620 - Make each empty-node the child of the top-level node.622 #+caption: An example of annoting a creature model with empty623 #+caption: nodes to describe the layout of senses. There are624 #+caption: multiple empty nodes which each describe the position625 #+caption: of muscles, ears, eyes, or joints.626 #+name: sense-nodes627 #+ATTR_LaTeX: :width 10cm628 [[./images/empty-sense-nodes.png]]631 ** Bodies are composed of segments connected by joints633 Blender is a general purpose animation tool, which has been used in634 the past to create high quality movies such as Sintel635 \cite{sintel}. Though Blender can model and render even complicated636 things like water, it is crucual to keep models that are meant to637 be simulated as creatures simple. =Bullet=, which =CORTEX= uses638 though jMonkeyEngine3, is a rigid-body physics system. This offers639 a compromise between the expressiveness of a game level and the640 speed at which it can be simulated, and it means that creatures641 should be naturally expressed as rigid components held together by642 joint constraints.644 But humans are more like a squishy bag with wrapped around some645 hard bones which define the overall shape. When we move, our skin646 bends and stretches to accomodate the new positions of our bones.648 One way to make bodies composed of rigid pieces connected by joints649 /seem/ more human-like is to use an /armature/, (or /rigging/)650 system, which defines a overall ``body mesh'' and defines how the651 mesh deforms as a function of the position of each ``bone'' which652 is a standard rigid body. This technique is used extensively to653 model humans and create realistic animations. It is not a good654 technique for physical simulation, however because it creates a lie655 -- the skin is not a physical part of the simulation and does not656 interact with any objects in the world or itself. Objects will pass657 right though the skin until they come in contact with the658 underlying bone, which is a physical object. Whithout simulating659 the skin, the sense of touch has little meaning, and the creature's660 own vision will lie to it about the true extent of its body.661 Simulating the skin as a physical object requires some way to662 continuously update the physical model of the skin along with the663 movement of the bones, which is unacceptably slow compared to rigid664 body simulation.666 Therefore, instead of using the human-like ``deformable bag of667 bones'' approach, I decided to base my body plans on multiple solid668 objects that are connected by joints, inspired by the robot =EVE=669 from the movie WALL-E.671 #+caption: =EVE= from the movie WALL-E. This body plan turns672 #+caption: out to be much better suited to my purposes than a more673 #+caption: human-like one.674 #+ATTR_LaTeX: :width 10cm675 [[./images/Eve.jpg]]677 =EVE='s body is composed of several rigid components that are held678 together by invisible joint constraints. This is what I mean by679 ``eve-like''. The main reason that I use eve-style bodies is for680 efficiency, and so that there will be correspondence between the681 AI's semses and the physical presence of its body. Each individual682 section is simulated by a separate rigid body that corresponds683 exactly with its visual representation and does not change.684 Sections are connected by invisible joints that are well supported685 in jMonkeyEngine3. Bullet, the physics backend for jMonkeyEngine3,686 can efficiently simulate hundreds of rigid bodies connected by687 joints. Just because sections are rigid does not mean they have to688 stay as one piece forever; they can be dynamically replaced with689 multiple sections to simulate splitting in two. This could be used690 to simulate retractable claws or =EVE='s hands, which are able to691 coalesce into one object in the movie.693 *** Solidifying/Connecting the body695 #+caption: View of the hand model in Blender showing the main ``joints''696 #+caption: node (highlighted in yellow) and its children which each697 #+caption: represent a joint in the hand. Each joint node has metadata698 #+caption: specifying what sort of joint it is.699 #+name: blender-hand700 #+ATTR_LaTeX: :width 10cm701 [[./images/hand-screenshot1.png]]703 =CORTEX= creates a creature in two steps: first, it traverses the704 nodes in the blender file and creates physical representations for705 any of them that have mass defined.707 #+caption: Program for iterating through the nodes in a blender file708 #+caption: and generating physical jMonkeyEngine3 objects with mass709 #+caption: and a matching physics shape.710 #+name: name711 #+begin_listing clojure712 #+begin_src clojure713 (defn physical!714 "Iterate through the nodes in creature and make them real physical715 objects in the simulation."716 [#^Node creature]717 (dorun718 (map719 (fn [geom]720 (let [physics-control721 (RigidBodyControl.722 (HullCollisionShape.723 (.getMesh geom))724 (if-let [mass (meta-data geom "mass")]725 (float mass) (float 1)))]726 (.addControl geom physics-control)))727 (filter #(isa? (class %) Geometry )728 (node-seq creature)))))729 #+end_src730 #+end_listing732 The next step to making a proper body is to connect those pieces733 together with joints. jMonkeyEngine has a large array of joints734 available via =bullet=, such as Point2Point, Cone, Hinge, and a735 generic Six Degree of Freedom joint, with or without spring736 restitution. =CORTEX='s procedure for binding the creature together737 with joints is as follows:739 - Find the children of the "joints" node.740 - Determine the two spatials the joint is meant to connect.741 - Create the joint based on the meta-data of the empty node.743 The higher order function =sense-nodes= from =cortex.sense=744 simplifies finding the joints based on their parent ``joints''745 node.747 #+caption: Retrieving the children empty nodes from a single748 #+caption: named empty node is a common pattern in =CORTEX=749 #+caption: further instances of this technique for the senses750 #+caption: will be omitted751 #+name: get-empty-nodes752 #+begin_listing clojure753 #+begin_src clojure754 (defn sense-nodes755 "For some senses there is a special empty blender node whose756 children are considered markers for an instance of that sense. This757 function generates functions to find those children, given the name758 of the special parent node."759 [parent-name]760 (fn [#^Node creature]761 (if-let [sense-node (.getChild creature parent-name)]762 (seq (.getChildren sense-node)) [])))764 (def765 ^{:doc "Return the children of the creature's \"joints\" node."766 :arglists '([creature])}767 joints768 (sense-nodes "joints"))769 #+end_src770 #+end_listing772 To find a joint's targets targets, =CORTEX= creates a small cube,773 centered around the empty-node, and grows the cube exponentially774 until it intersects two /physical/ objects. The objects are ordered775 according to the joint's rotation, with the first one being the776 object that has more negative coordinates in the joint's reference777 frame. Since the objects must be physical, the empty-node itself778 escapes detection. Because the objects must be physical,779 =joint-targets= must be called /after/ =physical!= is called.781 #+caption: Program to find the targets of a joint node by782 #+caption: exponentiallly growth of a search cube.783 #+name: joint-targets784 #+begin_listing clojure785 #+begin_src clojure786 (defn joint-targets787 "Return the two closest two objects to the joint object, ordered788 from bottom to top according to the joint's rotation."789 [#^Node parts #^Node joint]790 (loop [radius (float 0.01)]791 (let [results (CollisionResults.)]792 (.collideWith793 parts794 (BoundingBox. (.getWorldTranslation joint)795 radius radius radius) results)796 (let [targets797 (distinct798 (map #(.getGeometry %) results))]799 (if (>= (count targets) 2)800 (sort-by801 #(let [joint-ref-frame-position802 (jme-to-blender803 (.mult804 (.inverse (.getWorldRotation joint))805 (.subtract (.getWorldTranslation %)806 (.getWorldTranslation joint))))]807 (.dot (Vector3f. 1 1 1) joint-ref-frame-position))808 (take 2 targets))809 (recur (float (* radius 2))))))))810 #+end_src811 #+end_listing813 Once =CORTEX= finds all joints and targets, it creates them using a814 simple dispatch on the metadata of the joint node.816 #+caption: Program to dispatch on blender metadata and create joints817 #+caption: sutiable for physical simulation.818 #+name: joint-dispatch819 #+begin_listing clojure820 #+begin_src clojure821 (defmulti joint-dispatch822 "Translate blender pseudo-joints into real JME joints."823 (fn [constraints & _]824 (:type constraints)))826 (defmethod joint-dispatch :point827 [constraints control-a control-b pivot-a pivot-b rotation]828 (doto (SixDofJoint. control-a control-b pivot-a pivot-b false)829 (.setLinearLowerLimit Vector3f/ZERO)830 (.setLinearUpperLimit Vector3f/ZERO)))832 (defmethod joint-dispatch :hinge833 [constraints control-a control-b pivot-a pivot-b rotation]834 (let [axis (if-let [axis (:axis constraints)] axis Vector3f/UNIT_X)835 [limit-1 limit-2] (:limit constraints)836 hinge-axis (.mult rotation (blender-to-jme axis))]837 (doto (HingeJoint. control-a control-b pivot-a pivot-b838 hinge-axis hinge-axis)839 (.setLimit limit-1 limit-2))))841 (defmethod joint-dispatch :cone842 [constraints control-a control-b pivot-a pivot-b rotation]843 (let [limit-xz (:limit-xz constraints)844 limit-xy (:limit-xy constraints)845 twist (:twist constraints)]846 (doto (ConeJoint. control-a control-b pivot-a pivot-b847 rotation rotation)848 (.setLimit (float limit-xz) (float limit-xy)849 (float twist)))))850 #+end_src851 #+end_listing853 All that is left for joints it to combine the above pieces into a854 something that can operate on the collection of nodes that a855 blender file represents.857 #+caption: Program to completely create a joint given information858 #+caption: from a blender file.859 #+name: connect860 #+begin_listing clojure861 #+begin_src clojure862 (defn connect863 "Create a joint between 'obj-a and 'obj-b at the location of864 'joint. The type of joint is determined by the metadata on 'joint.866 Here are some examples:867 {:type :point}868 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}869 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)871 {:type :cone :limit-xz 0]872 :limit-xy 0]873 :twist 0]} (use XZY rotation mode in blender!)"874 [#^Node obj-a #^Node obj-b #^Node joint]875 (let [control-a (.getControl obj-a RigidBodyControl)876 control-b (.getControl obj-b RigidBodyControl)877 joint-center (.getWorldTranslation joint)878 joint-rotation (.toRotationMatrix (.getWorldRotation joint))879 pivot-a (world-to-local obj-a joint-center)880 pivot-b (world-to-local obj-b joint-center)]881 (if-let882 [constraints (map-vals eval (read-string (meta-data joint "joint")))]883 ;; A side-effect of creating a joint registers884 ;; it with both physics objects which in turn885 ;; will register the joint with the physics system886 ;; when the simulation is started.887 (joint-dispatch constraints888 control-a control-b889 pivot-a pivot-b890 joint-rotation))))891 #+end_src892 #+end_listing894 In general, whenever =CORTEX= exposes a sense (or in this case895 physicality), it provides a function of the type =sense!=, which896 takes in a collection of nodes and augments it to support that897 sense. The function returns any controlls necessary to use that898 sense. In this case =body!= cerates a physical body and returns no899 control functions.901 #+caption: Program to give joints to a creature.902 #+name: name903 #+begin_listing clojure904 #+begin_src clojure905 (defn joints!906 "Connect the solid parts of the creature with physical joints. The907 joints are taken from the \"joints\" node in the creature."908 [#^Node creature]909 (dorun910 (map911 (fn [joint]912 (let [[obj-a obj-b] (joint-targets creature joint)]913 (connect obj-a obj-b joint)))914 (joints creature))))915 (defn body!916 "Endow the creature with a physical body connected with joints. The917 particulars of the joints and the masses of each body part are918 determined in blender."919 [#^Node creature]920 (physical! creature)921 (joints! creature))922 #+end_src923 #+end_listing925 All of the code you have just seen amounts to only 130 lines, yet926 because it builds on top of Blender and jMonkeyEngine3, those few927 lines pack quite a punch!929 The hand from figure \ref{blender-hand}, which was modeled after my930 own right hand, can now be given joints and simulated as a931 creature.933 #+caption: With the ability to create physical creatures from blender,934 #+caption: =CORTEX= gets one step closer to a full creature simulation935 #+caption: environment.936 #+name: name937 #+ATTR_LaTeX: :width 15cm938 [[./images/physical-hand.png]]942 ** Eyes reuse standard video game components944 ** Hearing is hard; =CORTEX= does it right946 ** Touch uses hundreds of hair-like elements948 ** Proprioception is the sense that makes everything ``real''950 ** Muscles are both effectors and sensors952 ** =CORTEX= brings complex creatures to life!954 ** =CORTEX= enables many possiblities for further research956 * COMMENT Empathy in a simulated worm958 Here I develop a computational model of empathy, using =CORTEX= as a959 base. Empathy in this context is the ability to observe another960 creature and infer what sorts of sensations that creature is961 feeling. My empathy algorithm involves multiple phases. First is962 free-play, where the creature moves around and gains sensory963 experience. From this experience I construct a representation of the964 creature's sensory state space, which I call \Phi-space. Using965 \Phi-space, I construct an efficient function which takes the966 limited data that comes from observing another creature and enriches967 it full compliment of imagined sensory data. I can then use the968 imagined sensory data to recognize what the observed creature is969 doing and feeling, using straightforward embodied action predicates.970 This is all demonstrated with using a simple worm-like creature, and971 recognizing worm-actions based on limited data.973 #+caption: Here is the worm with which we will be working.974 #+caption: It is composed of 5 segments. Each segment has a975 #+caption: pair of extensor and flexor muscles. Each of the976 #+caption: worm's four joints is a hinge joint which allows977 #+caption: about 30 degrees of rotation to either side. Each segment978 #+caption: of the worm is touch-capable and has a uniform979 #+caption: distribution of touch sensors on each of its faces.980 #+caption: Each joint has a proprioceptive sense to detect981 #+caption: relative positions. The worm segments are all the982 #+caption: same except for the first one, which has a much983 #+caption: higher weight than the others to allow for easy984 #+caption: manual motor control.985 #+name: basic-worm-view986 #+ATTR_LaTeX: :width 10cm987 [[./images/basic-worm-view.png]]989 #+caption: Program for reading a worm from a blender file and990 #+caption: outfitting it with the senses of proprioception,991 #+caption: touch, and the ability to move, as specified in the992 #+caption: blender file.993 #+name: get-worm994 #+begin_listing clojure995 #+begin_src clojure996 (defn worm []997 (let [model (load-blender-model "Models/worm/worm.blend")]998 {:body (doto model (body!))999 :touch (touch! model)1000 :proprioception (proprioception! model)1001 :muscles (movement! model)}))1002 #+end_src1003 #+end_listing1005 ** Embodiment factors action recognition into managable parts1007 Using empathy, I divide the problem of action recognition into a1008 recognition process expressed in the language of a full compliment1009 of senses, and an imaganitive process that generates full sensory1010 data from partial sensory data. Splitting the action recognition1011 problem in this manner greatly reduces the total amount of work to1012 recognize actions: The imaganitive process is mostly just matching1013 previous experience, and the recognition process gets to use all1014 the senses to directly describe any action.1016 ** Action recognition is easy with a full gamut of senses1018 Embodied representations using multiple senses such as touch,1019 proprioception, and muscle tension turns out be be exceedingly1020 efficient at describing body-centered actions. It is the ``right1021 language for the job''. For example, it takes only around 5 lines1022 of LISP code to describe the action of ``curling'' using embodied1023 primitives. It takes about 10 lines to describe the seemingly1024 complicated action of wiggling.1026 The following action predicates each take a stream of sensory1027 experience, observe however much of it they desire, and decide1028 whether the worm is doing the action they describe. =curled?=1029 relies on proprioception, =resting?= relies on touch, =wiggling?=1030 relies on a fourier analysis of muscle contraction, and1031 =grand-circle?= relies on touch and reuses =curled?= as a gaurd.1033 #+caption: Program for detecting whether the worm is curled. This is the1034 #+caption: simplest action predicate, because it only uses the last frame1035 #+caption: of sensory experience, and only uses proprioceptive data. Even1036 #+caption: this simple predicate, however, is automatically frame1037 #+caption: independent and ignores vermopomorphic differences such as1038 #+caption: worm textures and colors.1039 #+name: curled1040 #+attr_latex: [htpb]1041 #+begin_listing clojure1042 #+begin_src clojure1043 (defn curled?1044 "Is the worm curled up?"1045 [experiences]1046 (every?1047 (fn [[_ _ bend]]1048 (> (Math/sin bend) 0.64))1049 (:proprioception (peek experiences))))1050 #+end_src1051 #+end_listing1053 #+caption: Program for summarizing the touch information in a patch1054 #+caption: of skin.1055 #+name: touch-summary1056 #+attr_latex: [htpb]1058 #+begin_listing clojure1059 #+begin_src clojure1060 (defn contact1061 "Determine how much contact a particular worm segment has with1062 other objects. Returns a value between 0 and 1, where 1 is full1063 contact and 0 is no contact."1064 [touch-region [coords contact :as touch]]1065 (-> (zipmap coords contact)1066 (select-keys touch-region)1067 (vals)1068 (#(map first %))1069 (average)1070 (* 10)1071 (- 1)1072 (Math/abs)))1073 #+end_src1074 #+end_listing1077 #+caption: Program for detecting whether the worm is at rest. This program1078 #+caption: uses a summary of the tactile information from the underbelly1079 #+caption: of the worm, and is only true if every segment is touching the1080 #+caption: floor. Note that this function contains no references to1081 #+caption: proprioction at all.1082 #+name: resting1083 #+attr_latex: [htpb]1084 #+begin_listing clojure1085 #+begin_src clojure1086 (def worm-segment-bottom (rect-region [8 15] [14 22]))1088 (defn resting?1089 "Is the worm resting on the ground?"1090 [experiences]1091 (every?1092 (fn [touch-data]1093 (< 0.9 (contact worm-segment-bottom touch-data)))1094 (:touch (peek experiences))))1095 #+end_src1096 #+end_listing1098 #+caption: Program for detecting whether the worm is curled up into a1099 #+caption: full circle. Here the embodied approach begins to shine, as1100 #+caption: I am able to both use a previous action predicate (=curled?=)1101 #+caption: as well as the direct tactile experience of the head and tail.1102 #+name: grand-circle1103 #+attr_latex: [htpb]1104 #+begin_listing clojure1105 #+begin_src clojure1106 (def worm-segment-bottom-tip (rect-region [15 15] [22 22]))1108 (def worm-segment-top-tip (rect-region [0 15] [7 22]))1110 (defn grand-circle?1111 "Does the worm form a majestic circle (one end touching the other)?"1112 [experiences]1113 (and (curled? experiences)1114 (let [worm-touch (:touch (peek experiences))1115 tail-touch (worm-touch 0)1116 head-touch (worm-touch 4)]1117 (and (< 0.55 (contact worm-segment-bottom-tip tail-touch))1118 (< 0.55 (contact worm-segment-top-tip head-touch))))))1119 #+end_src1120 #+end_listing1123 #+caption: Program for detecting whether the worm has been wiggling for1124 #+caption: the last few frames. It uses a fourier analysis of the muscle1125 #+caption: contractions of the worm's tail to determine wiggling. This is1126 #+caption: signigicant because there is no particular frame that clearly1127 #+caption: indicates that the worm is wiggling --- only when multiple frames1128 #+caption: are analyzed together is the wiggling revealed. Defining1129 #+caption: wiggling this way also gives the worm an opportunity to learn1130 #+caption: and recognize ``frustrated wiggling'', where the worm tries to1131 #+caption: wiggle but can't. Frustrated wiggling is very visually different1132 #+caption: from actual wiggling, but this definition gives it to us for free.1133 #+name: wiggling1134 #+attr_latex: [htpb]1135 #+begin_listing clojure1136 #+begin_src clojure1137 (defn fft [nums]1138 (map1139 #(.getReal %)1140 (.transform1141 (FastFourierTransformer. DftNormalization/STANDARD)1142 (double-array nums) TransformType/FORWARD)))1144 (def indexed (partial map-indexed vector))1146 (defn max-indexed [s]1147 (first (sort-by (comp - second) (indexed s))))1149 (defn wiggling?1150 "Is the worm wiggling?"1151 [experiences]1152 (let [analysis-interval 0x40]1153 (when (> (count experiences) analysis-interval)1154 (let [a-flex 31155 a-ex 21156 muscle-activity1157 (map :muscle (vector:last-n experiences analysis-interval))1158 base-activity1159 (map #(- (% a-flex) (% a-ex)) muscle-activity)]1160 (= 21161 (first1162 (max-indexed1163 (map #(Math/abs %)1164 (take 20 (fft base-activity))))))))))1165 #+end_src1166 #+end_listing1168 With these action predicates, I can now recognize the actions of1169 the worm while it is moving under my control and I have access to1170 all the worm's senses.1172 #+caption: Use the action predicates defined earlier to report on1173 #+caption: what the worm is doing while in simulation.1174 #+name: report-worm-activity1175 #+attr_latex: [htpb]1176 #+begin_listing clojure1177 #+begin_src clojure1178 (defn debug-experience1179 [experiences text]1180 (cond1181 (grand-circle? experiences) (.setText text "Grand Circle")1182 (curled? experiences) (.setText text "Curled")1183 (wiggling? experiences) (.setText text "Wiggling")1184 (resting? experiences) (.setText text "Resting")))1185 #+end_src1186 #+end_listing1188 #+caption: Using =debug-experience=, the body-centered predicates1189 #+caption: work together to classify the behaviour of the worm.1190 #+caption: the predicates are operating with access to the worm's1191 #+caption: full sensory data.1192 #+name: basic-worm-view1193 #+ATTR_LaTeX: :width 10cm1194 [[./images/worm-identify-init.png]]1196 These action predicates satisfy the recognition requirement of an1197 empathic recognition system. There is power in the simplicity of1198 the action predicates. They describe their actions without getting1199 confused in visual details of the worm. Each one is frame1200 independent, but more than that, they are each indepent of1201 irrelevant visual details of the worm and the environment. They1202 will work regardless of whether the worm is a different color or1203 hevaily textured, or if the environment has strange lighting.1205 The trick now is to make the action predicates work even when the1206 sensory data on which they depend is absent. If I can do that, then1207 I will have gained much,1209 ** \Phi-space describes the worm's experiences1211 As a first step towards building empathy, I need to gather all of1212 the worm's experiences during free play. I use a simple vector to1213 store all the experiences.1215 Each element of the experience vector exists in the vast space of1216 all possible worm-experiences. Most of this vast space is actually1217 unreachable due to physical constraints of the worm's body. For1218 example, the worm's segments are connected by hinge joints that put1219 a practical limit on the worm's range of motions without limiting1220 its degrees of freedom. Some groupings of senses are impossible;1221 the worm can not be bent into a circle so that its ends are1222 touching and at the same time not also experience the sensation of1223 touching itself.1225 As the worm moves around during free play and its experience vector1226 grows larger, the vector begins to define a subspace which is all1227 the sensations the worm can practicaly experience during normal1228 operation. I call this subspace \Phi-space, short for1229 physical-space. The experience vector defines a path through1230 \Phi-space. This path has interesting properties that all derive1231 from physical embodiment. The proprioceptive components are1232 completely smooth, because in order for the worm to move from one1233 position to another, it must pass through the intermediate1234 positions. The path invariably forms loops as actions are repeated.1235 Finally and most importantly, proprioception actually gives very1236 strong inference about the other senses. For example, when the worm1237 is flat, you can infer that it is touching the ground and that its1238 muscles are not active, because if the muscles were active, the1239 worm would be moving and would not be perfectly flat. In order to1240 stay flat, the worm has to be touching the ground, or it would1241 again be moving out of the flat position due to gravity. If the1242 worm is positioned in such a way that it interacts with itself,1243 then it is very likely to be feeling the same tactile feelings as1244 the last time it was in that position, because it has the same body1245 as then. If you observe multiple frames of proprioceptive data,1246 then you can become increasingly confident about the exact1247 activations of the worm's muscles, because it generally takes a1248 unique combination of muscle contractions to transform the worm's1249 body along a specific path through \Phi-space.1251 There is a simple way of taking \Phi-space and the total ordering1252 provided by an experience vector and reliably infering the rest of1253 the senses.1255 ** Empathy is the process of tracing though \Phi-space1257 Here is the core of a basic empathy algorithm, starting with an1258 experience vector:1260 First, group the experiences into tiered proprioceptive bins. I use1261 powers of 10 and 3 bins, and the smallest bin has an approximate1262 size of 0.001 radians in all proprioceptive dimensions.1264 Then, given a sequence of proprioceptive input, generate a set of1265 matching experience records for each input, using the tiered1266 proprioceptive bins.1268 Finally, to infer sensory data, select the longest consective chain1269 of experiences. Conecutive experience means that the experiences1270 appear next to each other in the experience vector.1272 This algorithm has three advantages:1274 1. It's simple1276 3. It's very fast -- retrieving possible interpretations takes1277 constant time. Tracing through chains of interpretations takes1278 time proportional to the average number of experiences in a1279 proprioceptive bin. Redundant experiences in \Phi-space can be1280 merged to save computation.1282 2. It protects from wrong interpretations of transient ambiguous1283 proprioceptive data. For example, if the worm is flat for just1284 an instant, this flattness will not be interpreted as implying1285 that the worm has its muscles relaxed, since the flattness is1286 part of a longer chain which includes a distinct pattern of1287 muscle activation. Markov chains or other memoryless statistical1288 models that operate on individual frames may very well make this1289 mistake.1291 #+caption: Program to convert an experience vector into a1292 #+caption: proprioceptively binned lookup function.1293 #+name: bin1294 #+attr_latex: [htpb]1295 #+begin_listing clojure1296 #+begin_src clojure1297 (defn bin [digits]1298 (fn [angles]1299 (->> angles1300 (flatten)1301 (map (juxt #(Math/sin %) #(Math/cos %)))1302 (flatten)1303 (mapv #(Math/round (* % (Math/pow 10 (dec digits))))))))1305 (defn gen-phi-scan1306 "Nearest-neighbors with binning. Only returns a result if1307 the propriceptive data is within 10% of a previously recorded1308 result in all dimensions."1309 [phi-space]1310 (let [bin-keys (map bin [3 2 1])1311 bin-maps1312 (map (fn [bin-key]1313 (group-by1314 (comp bin-key :proprioception phi-space)1315 (range (count phi-space)))) bin-keys)1316 lookups (map (fn [bin-key bin-map]1317 (fn [proprio] (bin-map (bin-key proprio))))1318 bin-keys bin-maps)]1319 (fn lookup [proprio-data]1320 (set (some #(% proprio-data) lookups)))))1321 #+end_src1322 #+end_listing1324 #+caption: =longest-thread= finds the longest path of consecutive1325 #+caption: experiences to explain proprioceptive worm data.1326 #+name: phi-space-history-scan1327 #+ATTR_LaTeX: :width 10cm1328 [[./images/aurellem-gray.png]]1330 =longest-thread= infers sensory data by stitching together pieces1331 from previous experience. It prefers longer chains of previous1332 experience to shorter ones. For example, during training the worm1333 might rest on the ground for one second before it performs its1334 excercises. If during recognition the worm rests on the ground for1335 five seconds, =longest-thread= will accomodate this five second1336 rest period by looping the one second rest chain five times.1338 =longest-thread= takes time proportinal to the average number of1339 entries in a proprioceptive bin, because for each element in the1340 starting bin it performes a series of set lookups in the preceeding1341 bins. If the total history is limited, then this is only a constant1342 multiple times the number of entries in the starting bin. This1343 analysis also applies even if the action requires multiple longest1344 chains -- it's still the average number of entries in a1345 proprioceptive bin times the desired chain length. Because1346 =longest-thread= is so efficient and simple, I can interpret1347 worm-actions in real time.1349 #+caption: Program to calculate empathy by tracing though \Phi-space1350 #+caption: and finding the longest (ie. most coherent) interpretation1351 #+caption: of the data.1352 #+name: longest-thread1353 #+attr_latex: [htpb]1354 #+begin_listing clojure1355 #+begin_src clojure1356 (defn longest-thread1357 "Find the longest thread from phi-index-sets. The index sets should1358 be ordered from most recent to least recent."1359 [phi-index-sets]1360 (loop [result '()1361 [thread-bases & remaining :as phi-index-sets] phi-index-sets]1362 (if (empty? phi-index-sets)1363 (vec result)1364 (let [threads1365 (for [thread-base thread-bases]1366 (loop [thread (list thread-base)1367 remaining remaining]1368 (let [next-index (dec (first thread))]1369 (cond (empty? remaining) thread1370 (contains? (first remaining) next-index)1371 (recur1372 (cons next-index thread) (rest remaining))1373 :else thread))))1374 longest-thread1375 (reduce (fn [thread-a thread-b]1376 (if (> (count thread-a) (count thread-b))1377 thread-a thread-b))1378 '(nil)1379 threads)]1380 (recur (concat longest-thread result)1381 (drop (count longest-thread) phi-index-sets))))))1382 #+end_src1383 #+end_listing1385 There is one final piece, which is to replace missing sensory data1386 with a best-guess estimate. While I could fill in missing data by1387 using a gradient over the closest known sensory data points,1388 averages can be misleading. It is certainly possible to create an1389 impossible sensory state by averaging two possible sensory states.1390 Therefore, I simply replicate the most recent sensory experience to1391 fill in the gaps.1393 #+caption: Fill in blanks in sensory experience by replicating the most1394 #+caption: recent experience.1395 #+name: infer-nils1396 #+attr_latex: [htpb]1397 #+begin_listing clojure1398 #+begin_src clojure1399 (defn infer-nils1400 "Replace nils with the next available non-nil element in the1401 sequence, or barring that, 0."1402 [s]1403 (loop [i (dec (count s))1404 v (transient s)]1405 (if (zero? i) (persistent! v)1406 (if-let [cur (v i)]1407 (if (get v (dec i) 0)1408 (recur (dec i) v)1409 (recur (dec i) (assoc! v (dec i) cur)))1410 (recur i (assoc! v i 0))))))1411 #+end_src1412 #+end_listing1414 ** Efficient action recognition with =EMPATH=1416 To use =EMPATH= with the worm, I first need to gather a set of1417 experiences from the worm that includes the actions I want to1418 recognize. The =generate-phi-space= program (listing1419 \ref{generate-phi-space} runs the worm through a series of1420 exercices and gatheres those experiences into a vector. The1421 =do-all-the-things= program is a routine expressed in a simple1422 muscle contraction script language for automated worm control. It1423 causes the worm to rest, curl, and wiggle over about 700 frames1424 (approx. 11 seconds).1426 #+caption: Program to gather the worm's experiences into a vector for1427 #+caption: further processing. The =motor-control-program= line uses1428 #+caption: a motor control script that causes the worm to execute a series1429 #+caption: of ``exercices'' that include all the action predicates.1430 #+name: generate-phi-space1431 #+attr_latex: [htpb]1432 #+begin_listing clojure1433 #+begin_src clojure1434 (def do-all-the-things1435 (concat1436 curl-script1437 [[300 :d-ex 40]1438 [320 :d-ex 0]]1439 (shift-script 280 (take 16 wiggle-script))))1441 (defn generate-phi-space []1442 (let [experiences (atom [])]1443 (run-world1444 (apply-map1445 worm-world1446 (merge1447 (worm-world-defaults)1448 {:end-frame 7001449 :motor-control1450 (motor-control-program worm-muscle-labels do-all-the-things)1451 :experiences experiences})))1452 @experiences))1453 #+end_src1454 #+end_listing1456 #+caption: Use longest thread and a phi-space generated from a short1457 #+caption: exercise routine to interpret actions during free play.1458 #+name: empathy-debug1459 #+attr_latex: [htpb]1460 #+begin_listing clojure1461 #+begin_src clojure1462 (defn init []1463 (def phi-space (generate-phi-space))1464 (def phi-scan (gen-phi-scan phi-space)))1466 (defn empathy-demonstration []1467 (let [proprio (atom ())]1468 (fn1469 [experiences text]1470 (let [phi-indices (phi-scan (:proprioception (peek experiences)))]1471 (swap! proprio (partial cons phi-indices))1472 (let [exp-thread (longest-thread (take 300 @proprio))1473 empathy (mapv phi-space (infer-nils exp-thread))]1474 (println-repl (vector:last-n exp-thread 22))1475 (cond1476 (grand-circle? empathy) (.setText text "Grand Circle")1477 (curled? empathy) (.setText text "Curled")1478 (wiggling? empathy) (.setText text "Wiggling")1479 (resting? empathy) (.setText text "Resting")1480 :else (.setText text "Unknown")))))))1482 (defn empathy-experiment [record]1483 (.start (worm-world :experience-watch (debug-experience-phi)1484 :record record :worm worm*)))1485 #+end_src1486 #+end_listing1488 The result of running =empathy-experiment= is that the system is1489 generally able to interpret worm actions using the action-predicates1490 on simulated sensory data just as well as with actual data. Figure1491 \ref{empathy-debug-image} was generated using =empathy-experiment=:1493 #+caption: From only proprioceptive data, =EMPATH= was able to infer1494 #+caption: the complete sensory experience and classify four poses1495 #+caption: (The last panel shows a composite image of \emph{wriggling},1496 #+caption: a dynamic pose.)1497 #+name: empathy-debug-image1498 #+ATTR_LaTeX: :width 10cm :placement [H]1499 [[./images/empathy-1.png]]1501 One way to measure the performance of =EMPATH= is to compare the1502 sutiability of the imagined sense experience to trigger the same1503 action predicates as the real sensory experience.1505 #+caption: Determine how closely empathy approximates actual1506 #+caption: sensory data.1507 #+name: test-empathy-accuracy1508 #+attr_latex: [htpb]1509 #+begin_listing clojure1510 #+begin_src clojure1511 (def worm-action-label1512 (juxt grand-circle? curled? wiggling?))1514 (defn compare-empathy-with-baseline [matches]1515 (let [proprio (atom ())]1516 (fn1517 [experiences text]1518 (let [phi-indices (phi-scan (:proprioception (peek experiences)))]1519 (swap! proprio (partial cons phi-indices))1520 (let [exp-thread (longest-thread (take 300 @proprio))1521 empathy (mapv phi-space (infer-nils exp-thread))1522 experience-matches-empathy1523 (= (worm-action-label experiences)1524 (worm-action-label empathy))]1525 (println-repl experience-matches-empathy)1526 (swap! matches #(conj % experience-matches-empathy)))))))1528 (defn accuracy [v]1529 (float (/ (count (filter true? v)) (count v))))1531 (defn test-empathy-accuracy []1532 (let [res (atom [])]1533 (run-world1534 (worm-world :experience-watch1535 (compare-empathy-with-baseline res)1536 :worm worm*))1537 (accuracy @res)))1538 #+end_src1539 #+end_listing1541 Running =test-empathy-accuracy= using the very short exercise1542 program defined in listing \ref{generate-phi-space}, and then doing1543 a similar pattern of activity manually yeilds an accuracy of around1544 73%. This is based on very limited worm experience. By training the1545 worm for longer, the accuracy dramatically improves.1547 #+caption: Program to generate \Phi-space using manual training.1548 #+name: manual-phi-space1549 #+attr_latex: [htpb]1550 #+begin_listing clojure1551 #+begin_src clojure1552 (defn init-interactive []1553 (def phi-space1554 (let [experiences (atom [])]1555 (run-world1556 (apply-map1557 worm-world1558 (merge1559 (worm-world-defaults)1560 {:experiences experiences})))1561 @experiences))1562 (def phi-scan (gen-phi-scan phi-space)))1563 #+end_src1564 #+end_listing1566 After about 1 minute of manual training, I was able to achieve 95%1567 accuracy on manual testing of the worm using =init-interactive= and1568 =test-empathy-accuracy=. The majority of errors are near the1569 boundaries of transitioning from one type of action to another.1570 During these transitions the exact label for the action is more open1571 to interpretation, and dissaggrement between empathy and experience1572 is more excusable.1574 ** Digression: bootstrapping touch using free exploration1576 In the previous section I showed how to compute actions in terms of1577 body-centered predicates which relied averate touch activation of1578 pre-defined regions of the worm's skin. What if, instead of recieving1579 touch pre-grouped into the six faces of each worm segment, the true1580 topology of the worm's skin was unknown? This is more similiar to how1581 a nerve fiber bundle might be arranged. While two fibers that are1582 close in a nerve bundle /might/ correspond to two touch sensors that1583 are close together on the skin, the process of taking a complicated1584 surface and forcing it into essentially a circle requires some cuts1585 and rerragenments.1587 In this section I show how to automatically learn the skin-topology of1588 a worm segment by free exploration. As the worm rolls around on the1589 floor, large sections of its surface get activated. If the worm has1590 stopped moving, then whatever region of skin that is touching the1591 floor is probably an important region, and should be recorded.1593 #+caption: Program to detect whether the worm is in a resting state1594 #+caption: with one face touching the floor.1595 #+name: pure-touch1596 #+begin_listing clojure1597 #+begin_src clojure1598 (def full-contact [(float 0.0) (float 0.1)])1600 (defn pure-touch?1601 "This is worm specific code to determine if a large region of touch1602 sensors is either all on or all off."1603 [[coords touch :as touch-data]]1604 (= (set (map first touch)) (set full-contact)))1605 #+end_src1606 #+end_listing1608 After collecting these important regions, there will many nearly1609 similiar touch regions. While for some purposes the subtle1610 differences between these regions will be important, for my1611 purposes I colapse them into mostly non-overlapping sets using1612 =remove-similiar= in listing \ref{remove-similiar}1614 #+caption: Program to take a lits of set of points and ``collapse them''1615 #+caption: so that the remaining sets in the list are siginificantly1616 #+caption: different from each other. Prefer smaller sets to larger ones.1617 #+name: remove-similiar1618 #+begin_listing clojure1619 #+begin_src clojure1620 (defn remove-similar1621 [coll]1622 (loop [result () coll (sort-by (comp - count) coll)]1623 (if (empty? coll) result1624 (let [[x & xs] coll1625 c (count x)]1626 (if (some1627 (fn [other-set]1628 (let [oc (count other-set)]1629 (< (- (count (union other-set x)) c) (* oc 0.1))))1630 xs)1631 (recur result xs)1632 (recur (cons x result) xs))))))1633 #+end_src1634 #+end_listing1636 Actually running this simulation is easy given =CORTEX='s facilities.1638 #+caption: Collect experiences while the worm moves around. Filter the touch1639 #+caption: sensations by stable ones, collapse similiar ones together,1640 #+caption: and report the regions learned.1641 #+name: learn-touch1642 #+begin_listing clojure1643 #+begin_src clojure1644 (defn learn-touch-regions []1645 (let [experiences (atom [])1646 world (apply-map1647 worm-world1648 (assoc (worm-segment-defaults)1649 :experiences experiences))]1650 (run-world world)1651 (->>1652 @experiences1653 (drop 175)1654 ;; access the single segment's touch data1655 (map (comp first :touch))1656 ;; only deal with "pure" touch data to determine surfaces1657 (filter pure-touch?)1658 ;; associate coordinates with touch values1659 (map (partial apply zipmap))1660 ;; select those regions where contact is being made1661 (map (partial group-by second))1662 (map #(get % full-contact))1663 (map (partial map first))1664 ;; remove redundant/subset regions1665 (map set)1666 remove-similar)))1668 (defn learn-and-view-touch-regions []1669 (map view-touch-region1670 (learn-touch-regions)))1671 #+end_src1672 #+end_listing1674 The only thing remining to define is the particular motion the worm1675 must take. I accomplish this with a simple motor control program.1677 #+caption: Motor control program for making the worm roll on the ground.1678 #+caption: This could also be replaced with random motion.1679 #+name: worm-roll1680 #+begin_listing clojure1681 #+begin_src clojure1682 (defn touch-kinesthetics []1683 [[170 :lift-1 40]1684 [190 :lift-1 19]1685 [206 :lift-1 0]1687 [400 :lift-2 40]1688 [410 :lift-2 0]1690 [570 :lift-2 40]1691 [590 :lift-2 21]1692 [606 :lift-2 0]1694 [800 :lift-1 30]1695 [809 :lift-1 0]1697 [900 :roll-2 40]1698 [905 :roll-2 20]1699 [910 :roll-2 0]1701 [1000 :roll-2 40]1702 [1005 :roll-2 20]1703 [1010 :roll-2 0]1705 [1100 :roll-2 40]1706 [1105 :roll-2 20]1707 [1110 :roll-2 0]1708 ])1709 #+end_src1710 #+end_listing1713 #+caption: The small worm rolls around on the floor, driven1714 #+caption: by the motor control program in listing \ref{worm-roll}.1715 #+name: worm-roll1716 #+ATTR_LaTeX: :width 12cm1717 [[./images/worm-roll.png]]1720 #+caption: After completing its adventures, the worm now knows1721 #+caption: how its touch sensors are arranged along its skin. These1722 #+caption: are the regions that were deemed important by1723 #+caption: =learn-touch-regions=. Note that the worm has discovered1724 #+caption: that it has six sides.1725 #+name: worm-touch-map1726 #+ATTR_LaTeX: :width 12cm1727 [[./images/touch-learn.png]]1729 While simple, =learn-touch-regions= exploits regularities in both1730 the worm's physiology and the worm's environment to correctly1731 deduce that the worm has six sides. Note that =learn-touch-regions=1732 would work just as well even if the worm's touch sense data were1733 completely scrambled. The cross shape is just for convienence. This1734 example justifies the use of pre-defined touch regions in =EMPATH=.1736 * COMMENT Contributions1738 In this thesis you have seen the =CORTEX= system, a complete1739 environment for creating simulated creatures. You have seen how to1740 implement five senses including touch, proprioception, hearing,1741 vision, and muscle tension. You have seen how to create new creatues1742 using blender, a 3D modeling tool. I hope that =CORTEX= will be1743 useful in further research projects. To this end I have included the1744 full source to =CORTEX= along with a large suite of tests and1745 examples. I have also created a user guide for =CORTEX= which is1746 inculded in an appendix to this thesis.1748 You have also seen how I used =CORTEX= as a platform to attach the1749 /action recognition/ problem, which is the problem of recognizing1750 actions in video. You saw a simple system called =EMPATH= which1751 ientifies actions by first describing actions in a body-centerd,1752 rich sense language, then infering a full range of sensory1753 experience from limited data using previous experience gained from1754 free play.1756 As a minor digression, you also saw how I used =CORTEX= to enable a1757 tiny worm to discover the topology of its skin simply by rolling on1758 the ground.1760 In conclusion, the main contributions of this thesis are:1762 - =CORTEX=, a system for creating simulated creatures with rich1763 senses.1764 - =EMPATH=, a program for recognizing actions by imagining sensory1765 experience.1767 # An anatomical joke:1768 # - Training1769 # - Skeletal imitation1770 # - Sensory fleshing-out1771 # - Classification