Braitenberg Machine Simulator

    I just wanted to write a simulator of Breitenberg cars. The roots of this thing grow from the ideas of building simple robots, but it is also interesting from the point of view of the development of complex systems.


    So what is it?

    (Caution, the article has a lot of pictures and animations!)

    The Breitenberg machine is an automaton based on the simplest logic of the minimum number of elements, which, however, demonstrates complex behavior that an external observer can take as reasonable (simple looks like complex, “show off” robots).
    They are described 6 types, based on a certain design called a neurode . A neurode can receive a braking or accelerating signal, which affects the number of pulses at the output. The neural network of such neurodes (even the simplest: 2-8 elements) can create several basic patterns of behavior. The principle of operation of automatic machines is as follows:

    Sensors (react to light) -> network of neurodes -> actuators (motors)

    The first type of behavior, the simplest - when there are no neurodes and the sensor signal goes directly to the motor. Then the left eye twists the left motor the more, the more lighted, and the same with the right. Such a system will "run away" from the light.

    If we cross the conductors (left eye to the right motor and vice versa), we get a light-loving robot, it will go, accelerating, to the light bulb. Other types are described in more detail as they are modeled.

    It was supposed (by Breitenberg) to put a swarm of these 6 types of cars in a room with bulbs, and then the observer (a hypothetical robotic psychologist) would see complex behavior in their movements. Do you see such complexity? We will see. The article will have a lot of gifs with simulations =)
    Please immediately show such a room with several cars



    White circles are light bulbs. Colored - machines of various types.

    Sometimes a more beautiful demonstration with the trajectory of each automaton is obtained:



    So, let's get started . The first I realized the photophilous type. There is no need to model the entire system. At first, it seemed to me that I could simply divide the power of the light sources by the square of the distance to them, add it in a vector and transfer the received vector “direction to the light” as a motion vector to the machine. But it turns out quite wrong.

    Firstly - in the Braitenberg system, the machine has two photosensitive elements. If they are implemented as directional sensors, then they look forward, and if they are non-directional, they should not distinguish between forward and backward directions. So I took the plane perpendicular to the motion vector, and reflected the "direction to the light" if it pointed back. The result is ears that do not distinguish where the sound came from - front or back, but only to the right or left, and what kind of strength.

    Secondly, the device on wheels cannot move perpendicular to the side, it has a maximum rotation angle (per unit of distance traveled), maximum speed and inertia. I added all this by trimming the angle of the motion vector relative to the direction vector of the automaton to a certain maximum, trimming it modulo, and adding them in a vectorial manner: V_new = Inertia * V_old + (1 - Inertia) * LightDir.

    Something like this (C #):
    ...
     switch (TypeOfAu)
       {
          case1:
            calcangle(); //заранее просчитываются cos и sin всех углов 
            GetLights(); //получаем вектор направления наибольшей освещ'нности
            turn(true); //поворот системы координат на угол автомата
            { 
               lightX = Math.Abs(lightX); // отражение векторов которые смотрели назад
               SetMod(); // расчёт интенсивности света (модуль вектора света)if (light > BackToNormalAfterProtectionClarion) Switch("state");
               CutMod(); // обрезка по модулю к максимальной скорости
               CutAng(ref lightX, ref lightY); // обрезка по допустимому углу поворота
             }    
             turn(false); // возврат в исходную систему координатbreak;
        ...
        }
      vx = (1 - inertia) * lightX * Vv + inertia * vx;
      vy = (1 - inertia) * lightY * Vv + inertia * vy;
      // Vv - константа реакции сенсора, переводит количество света в скорость


    Result:



    As a result, features became noticeable - for example, it can be seen that cars passing exactly in the middle between two bulbs continue to move. All is well, we can create a new type based on this.

    Now there will be a fear of the light. To do this, you need to do everything too, but reflect the motion vector relative to the current orientation of the typewriter (not reflection relative to its coordinate! Otherwise, a physically unrealistic apparatus will turn out again).

    Code Changes
    ...
      case2:
        ...
        turn(true); // внутри блока действий в повёрнутой системе координат
        {                
        ...
        lightY = -lightY; // одна строчка отражения соответсвует перепутыванию проводов левого и правого сенсоров
        }
        turn(false);
        break;
    ...




    The only negative - such machines run away from the screen and leave an empty field. We put them a protective mechanism against running away - in low light they will change their behavior to the first model until they return to the bulbs.

    Now let's configure the cars with a couple of neurodes. The first will repeat the model of the photophilous machine, but with integrated neurodes on the lines. From the sensor, a braking signal will go to the neurode, and from the neurode the signal will go to the motor. Now the more we shine on the sensor, the fewer signals to the motor - the slower the car goes. Such a system will have wiring as the first model, but behave more like the second - to run away from the light. But if the first speed decreased with the distance from the source, then this is the opposite: it will accelerate. Let's correct the code for calculating the module of the motion vector accordingly and voila:



    When I made this typewriter for the first time, it seemed to me that it was working correctly, but something was wrong ... This is the first version where I mixed up some kind of sign.



    It’s more beautiful to watch them in the recording mode of tracks - they draw something like an eye.



    Now the next machine. We cross the wires again, but with the neurodes on them (in the code, we remove the last reflection of the vector):



    This machine is wiser, it does not break into light, risking breaking a light bulb (but in a real model it would be), but stops at a distance when enough light gets on the sensors so that the braking signal completely stops the generation of signals for the motor.

    Number five. A machine with a complex system of neurodes. For a description, you can visit this article., and for now I’ll tell you how this is done in simple ways - a barrier is added by the amount of light, and the sign in the reflection operation changes, depending on whether the light level is higher than the threshold value or lower. The real machine should run away as the third, when there is little light, and go to the light as the fourth, when there is a lot of it. Somewhere there will also be an inner circle, where it will stop completely - I picked up the coefficients for a long time, often changed them, but I did not achieve a beautiful escape from the "edge of the world from the fire". Anyway, the inner circle of the stop should be wide enough (occupy more than half of the area) - this is due to the implementation of the quadratic attenuation of the light level with increasing distance, so the physics is to blame, not me =)



    And the last. This one should change its models according to the opposite principle - to reach for the light when it is not enough, and to run away when there is a lot. Admirers of Azimov will immediately understand that such a machine will constantly run in a circle on an equipotential line (a line of a constant level of illumination). And if we continue the direct “sensorless” model that I have used so far, then the machine will simply reach this line and stop. In the real world, its running in a circle will be due to the fact that one of the eyes is inside the circle and the other outside, and the internal neural structure will create a new case for the motion algorithm - it will make it move perpendicular to the direction to the light. To simulate this type of machine, I had to add a real description of two sensors, and so that on one of them the illumination value at some points would be below the threshold, when on the other - higher, it was necessary to place them at a certain distance. The physical distance between the sensors is calledparallax om (for example between the eyes of a person, or two telescopes in one system). Here is the machine after my drank (I did not draw eyes on the gooey).



    Code
    ...
    case6:
      calcangle();
      double paralax = 0.01;
      GetLights((angless) * paralax, (anglecs) * paralax);
      SetMod();
      double tempL = light; // значение интенсивности света в одном глазу из глобальной переменной переносится в темп - временную
      GetLights((-angless) * paralax, (-anglecs) * paralax);
      double CicleMaxSpeed = 4;
      int sw = 0;
      SetMod(); //после второго сетмода получаем два значения интенсивности света - одно в глобальной и одно во временной переменных, это значения на левом и правом глазу
      ...



    A change in parallax leads to a change in accuracy.





    For some values, the automaton moves along almost even arcs, while for others, it moves along wavy paths, constantly approaching and then moving away. Robots behave similarly along the line.

    Now we will throw a family of different types of machines on the field.



    The first version at the beginning of the article seemed a little boring to me, so I first made some lights go out and on from time to time ... And then I did a mixing algorithm , which once in a while changes the type of machine to some other one, so so that it goes through “all incarnations”: Without all this, you can look at the grid of all types in one field.










    After that, I thought about the machines having a physical size (so that they did not pass through each other), but collision calculation is a difficult task for a computer, especially with so many participants, so I just took a couple of shots and turned off the mode




    In principle , it was all the same, only the cars pushed around their asymptotic trajectories, and were not exactly on them, that's all. We return to the world without collisions)

    Now we will consider a system with a long shutter speed - what is it striving for?
    The switch mode of the bulbs does not allow the system to remain a static picture, but the photographers tried very hard - they clung to their lamps and did not have time to run away from them during the period when they were turned off.



    Their wiser version is in time, and in the end there is a flock that moves along a cyclic path between three lamps.




    Photophobia work differently. Since the protection system returns them at the same speed as their removal speed - at each level, they generate even noise, about half of the machines are slowly removed, the other half returns in protective mode.



    With their version pumped by neurodes, the situation is different - they quickly fly apart, but slowly gather back. I expected that they would eventually form an even tapering circle, but no. They retain an asymmetrical shape, and sometimes give beautiful pictures.



    Sometimes they look like the same chaos:



    A changing automaton often behaves the same. But in the end, they stray into very small groups that travel quite hefty from the bulb and to the bulb along these rails.



    In addition to several machines that caught "their wave" and spin in the right side of the room. I waited for them to join one of the three clans, but this did not happen after 2 hours of simulation, it seems this is the same case of strange dynamically stable trajectories, like that of an asteroid that flies around the earth’s gravitational well from right to left.

    The loop machines showed a telephone receiver (or a smiling face?), Heaped into a pile, and began to fold and unfold the tentacles in turn to the currently working lamps.
    Erysipelas



    Stable mode



    In the meantime, as long-running simulations were going on, I thought about other options and added three more non-standard types . They focus not on light, but on other machines.
    The first of them waits until machines appear in the neighborhood, and tries to follow the nearest of them. The rest of the time it’s worth and sad.



    You can call them dogs, because they need owners. I put them on the field with type 5, otherwise they would all just be standing.

    Another type - averages the coordinates of many machines and runs into the crowd - "extrovert."



    His antipode is an introvert who is trying to keep his distance.



    At the beginning, the lattice has translational symmetry and the central automata have nowhere to go - they would approach the neighbors in any direction, so they wait until the extreme ones scatter. It looks interesting in the mode of tracks - a furry chip turns out.



    Now put all 9 types (including new ones) and look at the grid. (mixing of types is included)



    And in the track mode they draw a dandelion.





    In the center I placed a light source with a negative power value. I don’t know what I expected, but the anti-light, though, attracts usually runaway machines, but their behavior does not become like “crossed” analogs of photophores, but it turns out that something third, more complicated.
    More dandelions that turned out.






    This also turns into a dandelion. I became interested when I saw the drawing of the "cobweb" in the corner of one of the simulations - the fugitives left the rays one after another, and the dogs did not keep up with them, and moved from one to the other with concave half-arches. I thought that if you do it in such a massive way, you get a spider web, as it always draws. Therefore, I threw only these two types of machine guns into the room - but something went wrong. In any configuration, the system is unstable and the dogs fall in some direction, as a result, just another dandelion comes out - and no web.



    Added another lamp.




    But ... Um ... Porcupine?



    In general, the behavior, as for my taste, is really quite complicated. But let's move on. Let's try to show nonlinearity. A scatter version is well suited for this. Divergence from the sphere (which is the surface around the bulb that is equipotential in illumination) almost guarantees the appearance of deterministic chaos.
    Let's run the same grid, but of a very small size - so that the initial conditions for the cars differ only a little (the machines leave almost one point), and see how the system develops and what it shows us.




    Now we’ll run the same small grid, but with different types of cars and the type mixing enabled.



    Such interesting pictures are obtained ... For a change, you can change the visualization model, say, connect all the cars with lines (as if they would pull one long thread). So it’s more convenient to watch how exactly the algorithm crumbles an initially smooth grid of machines, and where it sends its different parts - how they migrate around their world.



    It turns out sticky ones like the one in the media player.
    Sometimes interesting figures appear.







    Generallysuch a simulator. Feel free to suggest your ideas and suggestions in the comments, what else you can add, or what experiment to put. Personally, I think the resulting thing is a convenient demonstration for the theory of nonlinear systems - in it you can look for asymptotics, divergences, curious patterns that show the complexity of simple systems ... People can use the concept both in automation and beginners in building BEAM robots - to understand the essence, well, in general - see color pictures.

    Good to all, robot psychologists. It's all.


    Also popular now: