Showing posts with label cellular automata. Show all posts
Showing posts with label cellular automata. Show all posts

Perfect unusable code: or how to modelize code and distributivity

So let's speak of what and un/deterministic code really are.

I am gonna prove that you can achieve nearly chaotic series of states with deterministic code \o/

Definitions:

Deterministic: code is deterministic if the same input always yield the same output

Chaotic: a time serie of value is considered chaotic if knowing of sample of t-n samples cannot make you able to predict the t+1 term. 

Turing Machine: a computer that does not worth more than a cassette player.

Complex system: a set of simple deterministic object connected together that can result in non deterministic behavior.

lambda function: stateless functions without internal states.

FSM (finite state machine): a stuff necessary in electronic because time is relativistic (Einstein).

Mapping: a mathematical operation/computer stuff that describes a projection of input discrete dimension A to output discrete dimension B. 


Now let's play real life turing machine.

Imagine I give you an old K7 player with a band of 30 minutes and every minutes I tell the result of n x 3.
If you go at minutes 3 the K7 will tell 9.
If you go at minutes 5 you will hear 15. 

This is the most stupid computer you can have. 
My tape is a program. The index (minutes) is the input, and the output is the what is said. 

So let's do a python Basically we did a mapping from the index on the tape in minutes to integers that yields index(in minutes) x 3. 



So what do we learn with this?

That I can turn code into turing machines, that I can use as a code with a 1:1 relationship, I have a ... mapping \o/

What does compile does?
It evaluates for all the input possible that is an integer belongs to [0:255] all the output possible of boolean function. It is a projection of [2^8] input => 2 output
I projected a discrete space of input to a discrete space of output.

Let's see why it is great

My code is fully deterministic and is threadsafe because my code is stateless.

It is an index of all the 256 solutions for f(x) for every possible values.

if I encode a function that tells if a number can be divided by X another one by Y to have the function that tells if a number can be divided by (X * Y) I just have to apply then & (bitwise and operator) to the int representing the code.

An int is a very cool for a storage of function.
With div2 / div 3 I can by applying all the «common bitwise operator» create a lot of interesting functions:

div2xor3 : a code that indicates number that can be divided by 2 or 3 but not 6
not div2: every even/odd number
div2or3: multiple of 2, 3 and 6
div2and3: multiple of 6 only
....

I can combine the 16 bliter operations to directly obtain functions.

In functional programming you do partial function that you apply in a pipe of execution, here you can directly combine the code at «implementation level»


My evaluation is always taking the same number of cycles, I don't have to worry about worst case, and my code will never suffer from indetermination (neither in execution time nor results). My code is ultimately threadsafe as long as my code storage and my inputs are immutables. 


My function are commutative thus I can distribute them.

div2(div3(val)) == div3(div2(val)) (== div6(val))

=> combining function is a simple and of the code

Why we don't use that in real life

First there is a big problem of size.

To store all the results for all the possible inputs, I have to allocate the cross product of size of input * size of output.

A simple multiplication table by 3 for all the 32 bits integers would be 32 bit * 32 bits = an array of 4billions worlds of 32 bits. 16Gbytes!

Not very efficient.

But if we work on a torus of discrete value, it can work :)

Imagine my FPU is slow and I need cos(x) with an error margin sufficient to only work in 1/256 of radians? I can store my results as an array of precomputed cosinus value expressed in fraction of 256%256 :)

A cache with memoization is also using the same principle.
You replace computing code that is long by a lookup in a table.

It might be a little more evoluted than reading a bit in an integer, but it is globally the same principle.

So actually, that is one of the biggest use of the turing machine: efficient caching of pre computed values.

Another default, is that the mapping make you lose information on what the developer meant.

If you just have the integer representing your code, more than one function can yield the same code. The mapping from the space of the possible function to the space of the solutions is a surjection.

Thus if you have a bug in this code, you cannot revert back to the algorithm and fix it.

if I consider I have not a number of n bit as an input but n input of 1 bit constituting my state input vector,  and the output is my internal state, than I am modeling a node of a parallel computer. This «code» can be wired (few clocks costs) as a muxer that is deterministic in its execution time and dazzling fast.


What is the use of this anyway?

Well, it models deterministic code.

I can generate random code and see how they interact.

The Conway's Game of life is a setup of turing machine interconnected to each other in a massively parallel fashion.

So my next step is to prove I can generate pure random numbers with totally deterministic code.

And I can tell you I can prove the condition for my modified game of life to yield chaotic like results is that the level of similarity for every code on every automaton is low (entropy of patterns is high) AND 50% of the bits are 0/1 in code (maximizing the entropy of the code in ratio of bits).

 






Heavyside function: a systemic mathematical root of social inequity

Abstract 

Just a random theory for fun, nothing really serious.

Assumption

  1. I hate analytics, so it will be a formal reasoning;
  2. We consider that social inequity is the inequity in front of the differential between tax being paid, and tax being received as n nth order;
  3. We consider that the social agents interact has entities formed in a network and that they tend to be over represented the more «utility/wealth» they have (I still don't know of any hobo making it to the parliament);
  4. We consider that part of this interaction are with a special entity called «state» that have feedback loops on the agent:
    1. some for taking (VAT, IRS ...);
    2. some for giving back (education, health...)
    3. all these agents are interconnected and may have delay in propagation of the feedbacks;
  5. We consider that there is an agent called parliament that can interact with the «state» in such a way it can changes the network and functioning of the agent;
  6. We consider that each the utility function for a given agent to set his choices are based on a rationnality that is based on 
    1. sum of dis/imitation of a neighbourhood, 
    2. global rationnality (the mathematical choice that maximize my utility);
    3. and temperature (random factor where you put moral and stuff);
    4. temporal rationnality (based on a short term memory);
    5. partial access to the information related to utility/state vector of the agent;

By the systemic nature of tax reversation our societies are bound to tend towards extremely inequal society

So basically we have a complex system. A set of simple systems interconnected together. It belongs to a young branch of mathematics called «complex system».

These systems are quite unnice, it is very hard to analyse them mathematically even though some statiscal physics can help. Simulation can help. But reasoning is better.

So what my beef is all about?

The BAD Guy

This is the problem !


This function is a non linear function. If I introduce it in any equation, I cannot use any mathematical means to predict tendancies. Averages, trends, estimations cannot work per nature with these functions. So it means, mostly all predictive models based on «linear algebrae» such as matrix, average, derivate, estimation don't work.

And, I pretend I can solve it.

Juste let's acknowledge that laws have effects.
Let's acknowledge that law is often formulated with stuff such has : IF Income > xk$; THEN pay x% taxes;  ELSE pay y% taxes.

So we have clearly my bad guy hidden every where.

Now, let's be fun and imagine the utility (money) flowing from each of these cellular automata based on the hypothesis there are evenly distributed wealth at the origin and that interaction are randomly distrinuted.
At some turn out of n taxes are paid,
At n turns income can be randomly given based on the discrete state of the automata;
At some turns the automata rules are changed by a subset of the people with more utility.

So the question, is how will it evolve?

Well it is like visualizing a huge body with cells and  heart pumping. Which is nice.


I can predict that if there are heavyside functions used by the «state», then it will evolve more often, and with bigger amplitude towards unfair system than system with linear functions and no binary criterions...

The problem lies in the fact there are «acausal» stuffs in this system. Or retroaction delayed loop. And they tends to amplificate violently.

Acausality means that an effect can have an effect on the cause (but always later in time). Taxing too much people will impact next years potential income. The state wealth is like a gigantic bath tub but globally it requires sum(income) == sum(outcome) and the income are solely taxes (I cheat, I know, I am closing the «state» system whereas it is an open system).

You will notice that the time constant for a feedback loop varies. The Revenue taxes will need one year to retro propagate, while VAT feedbacks almost immediatly. Thus there are asymmetries both in time constant, and amplitudes of the feedbacks.

So know, We hit the run button of the simulation.

We follow agent 1 that is randomely chosen to need money from the state (food stamp? parental break? Sickness?...).Utility increase.

Another agent may lose money coincidentally at the same moment (parking ticket, donation, ...). Utility decrease.

Now, we could imagine it is already the turn for paying your annual income tax.

And, there is this heavyside function tearing appart 2, 1 and the rest into a cluster...

Time in this asynchronuous system, is the accident of the accident.  Every time a transaction is made amongst agents, time increases (discretly).

Randomly things will happens; with the same odd for everyone, unless their utility is null. When utility is null, you can't play outgoing interaction.

Now, 3rd turn, we are already playing the election, 1, 2 are either above or below the utility of the crowd, so their odds of playing the election games are disctinct.

At 0 utility you cannot play the game of election.

I make the following assumption: probability of being elected is represented by a non linear but growing function of the utility (wealth) that is 0 for 0. Given the right utility (if you have money, but no time, you don't have «available wealth» for an outgoing interaction). Rules name : "pas de bras, pas de chocolat".

So in the decision of presenting myself I have to set my decision based:
on my current mathematical interest;
odds of winning;
and my «imitation factors».

Statistically, it is small, and should be considered as the same kind of noise as random photons exciting the oxygen in the sky...

But, let's add a little realistic bias to the agents:
they have a small term memory;
they have all the more chance to predict future that they have education.
In fact, this is too much a strong hypothesis. Let's just say something regulated by the state create an assymmetry of information. I won't treat the case of multiverse rationnality per agent, but it should be treated. You can modelize them as sets of relationship to information some being random (religious interpretation or a star being behind the sun), some being relevant (bribery) plus a set of rules to edict a future outcome based on «values». These have of course a feedback loop from the taxes. These surset of individuals are moral persons, thus almost regular agents (polymorphism), like religion/schools/companies. For each of the surset an indivual is in, the agent has an access to rules and information based on a ratio  of «fit with my own interest according to my memory». And this agent can't be at the parliament, but they can increase the odds of winning for people belonging to their surset.

For the sake of realism, we will consider the lower this fitness variable is, the more an alteration of the information is, so we corrupt randomly either a relationship or a rule.

But, it is way to hard to code, so let's try the simple model that does not change much: a global major education (jacobinism) for the network of agent, and that education is mostly a question of where you live, inclusive or of how much money you have (through both your patrimponial, and indirect income).

The agent still have a short term memory and partial access to the information based on flags describing its cluster.

Well at turn free I have 2 possibles outcome: 2 clusters of 1 and 1 cluster of n - 2, and 1 cluster of 2 plus the other ones.

Not much.

But everytime an event happens with the simple fact there this gaps, it repropagates.

And since we said nothing about the height of this gap, it can make the difference between Charydbe and  Scilla.

Imagine that you go in jail? You cannot earn money, you can't play the game of election.

Imagine thanks to the tax system you have a wonderful contract from the DARPA. You are a cluster of one, but your utility for trying to change the system because of potential bad suprises raises. Who wants to pay taxes when you can rationnaly avoid it with less investment in utility?

Plus the more education you have, the more you share you rationnality with other agents the more you see the retroaction loops and can predict the future (given your rationnalilty favours your agent) and you acknowledge teh utility of sticking together. Karl Max's Capital at my opinion was more useful for the powerful to understand the need to act as a class because they benefit the most of it. I sometimes wonder how much Karl Marx helped the emergence of the capitalism he was strongly denouncing.

And remember, my situation impacts the neighbours on the network (wife, family ...).

Then the more you see the retroaction feedback loop join interest with yours, the more likely you are to adopt interacting with the agent... fast, and spreads the more in amplitude. It is strongly contaminating the more it benefits you.

Every agents have their time of reactions, based on the channel of informations.

Ex: some people knows the Fed's new rate before they are even announced on the market. [find the link with order at 14:00 in NY while announce at 14:00 Chicago]

So ... why does Heavyside make a difference?

This wheel of fortune non linear effects happens also in a system without gaps.

The difference is that if you happen to put a continuous function, the result will results in smoothing the non linear effect after n turn. New comers will come and live with the favored according to a progressive effect.

Their will still be local optimum with linear functions that will make small valleys of clusters. But the depth of the will be smaller. 

The heavyside function will of course clusterize MORE the population with more impacts. Putting a binary flag state for every single steps introducing discrete domains with distinct rationnalities, you try to know best the channel that favours you best while risking less. Some will have interest in changing the laws to favour the conservatism of the situation based on their interests, others will have a rationnality of changing the «winning domains». Just random stuff you could modelize. Without knowing anything you already know that the good rationality will have to favour cluster effects. Because the symmetry in the cause will have an impact in the effect. And it will be all the more efficient that it feedbacks positively. All winning rationalities in an Heavyside based complex system WILL favours strong discriminations that favours the clusters created by the intial Heavyside function. Here is the Capital's central thesis: there is a clear mathematical incentive for the more powerful to regroup together and since they are favoured in their probability of having a positive action on the system for them, to favour clustering for their better good. They should favours laws that works all the society if is (arbitrarily) fractionned by bigger gap.

I don't say every agents in the same conditions share the same rationalities. Warren Buffet or Bill Gates asking to pay more taxes seems to contradict me.

It is just an effect of number. Of imitation, spreading of information, of majority of behaviour, and of cumulative re enforcing effects.

The existence of the bias in the representation/power, favour the systemically the strong clustering of conflicting rationalities artificially. And it is at my opinion very hard to say whether education makes wealth or the opposite.
So saying the favoured clusters in terms of wealth OR education will have a tendency to be over represented in parliament is clearly the right way to say it.

Saying the more represented will favour their interest is kind of a trivial fact.

Rich people without education (no information, just lucky guys (won loto) won't care.

Poor people without education won't care.

Rich (favored by the clustering) and relatively poor people but acknowledging the bias (un favored by the clustering) with education will care to change the system.

Now, if we introduce the fact there is a clash when the tension is too big (we can measure an antagonist rationality between two clusters that is more than a certain amplitude) then it is becoming unstable.

Every agent will tend to try to choose the information node/rule set that will best its interests according to its rationnality.   

But, thanks to the cluster and the nature of the heavyside function and all this binary flags introduced by the heavyside functions, people will punctionate their income through differents paths that requires differents sets of informations.

Thus we have diverging rationnalities. And given enough education, their must be a conflict. If you see you have no chance of filling a gap, you don't try to filll the gap, you just change the gap.  People will mechanically fight other belonging to arbitrary domains.

The funniest conclusion is that in my model, the 99% should be called the 1%, and the 1% should be called the .01%

1% vs .01% is the fight between (have favouring clusters and access to information) vs (don't belong to the more interesting clusters but have access to enough information to see it, or is favoured but has an opposed rationnality).

The simple fact of criticizing the 1% is already a proof you belong to the 1%.

The 99% movement, the occupy wall street stuff is not about trying to solve the inequity problem, it is about asking for a new order because it is a rationnal choice for people that just want to be in the .01% and don't have access to it, yet.

Political disclaimer: I belong to the movement «we should all be the 100% and living happily ever after». The 100% in short.

So now, one big question. Is it intrinsically bad to have a system that is more unstable than it should be overwhise? Is the discrete clustering bad?

Let's rephrase, do you prefer the funkyness of war, or the boringness of happyness and peace? Well it depends of course if you have to die at war or earn money from it.

A system that induces systematically arbitrary clusters of population that amplifies have less chance to be stable than a system without clustering.

In natural language; a society were rules are applied without any discrimination on the nature of the citizen is less likely to tend towards unstability and strong auto amplifying discriminations.  These discriminations are purely mathematical amplified artefacts. Should we let artefacts rule our lives?

It is is kind of better when in a society people share the same rationality, and there is less paranoïa when the information is more symmetric.

Our systems are thus chaotic by nature, and more stochastically behaviouring than they should, just because of a stupid function that introduces an arbitrary amplification on discrimination. It should be fixed. The laws should be rewritten to get rid of the all the possible formulation like: IF BLah THEN this ELSE that.

I am agreeing strongly on the importance of sanctioning wrong behaviours or protecting the youngest (which are strong heavyside function), I don't agree with the multiplication of unnecessary non linear clauses (IF SEX | EARN more than x$.... THEN ....) in our social systems. They cluster us, and they make the effect of the law unpredictable thus arbitrary. And as a human, I prefer control.

How could I prove I am right/wrong?


Well, if I were serious I would bring proof. So I would have to make a simulation, give data, and make a model. Than I would claim to the world that I am an unrecognized genius, but I don't care. I am just waiting for my wife to come back, and it is my way of relieving the stress.


However, I gave a try at multi agent simulation. https://github.com/jul/KISSMyAgent
It could be used to modelise this. And, I am pretty sure by running a lot of simulation we will find the properties of our whole known systems (democratic, republicans, communists, monarchists) will be prone to this effect.

But I hated the programmation of this stuff. So I don't recommend it.

I went on an implementation based on distributed agent: https://github.com/jul/dsat

I began to use it in conjunction with graphite/carbon to store results. But, it is faster to run the simulations in my head than on the computer, so I prefer to go directly to the results. ;)

So there it was, a recreational theory that probably is useless, but it was in my brain. So I unloaded it. 

Just for fun, I just described a purely asynchronuous distributed system.
It means, that with too much non linear interactions, any real distributed systems (the cloud, big clusters of distributed applications) also have this unstability properties. 

Just think about it: I am saying that the cloud will be unstable one day by nature, I am saying the day it will break it will break in a massive violent snowball effects the more non linear rules are introduced (non linear: swithching traffic from interface, rejecting jobs on timeout, according more resources to tasks that are already greedy on CPU instead of fixing the algo...). And since the effect is non linear we have no assessment possible of when and how. I have a strong suspicion the breakout will be violent and undetectable. One day, you will wake up with an irreversible situation that will affect you without any possibility to foretell it.  Thus, no insurance can cover this phenomenon. No science... yet. We don't have mature analytical, theoretical and empirical tools to studies these. 

I would be you, I would not rely on systems that are chaotic and built by engineers that don't seem to see any problem with that. You just are having a system that is stable as long as a given piece of network equipment in China doesn't flap its small BGP wings too much but oddly resists to people trying to destroy its backbone with nukes....

I just hope it does not happen before I am retired. ;) On the other hand, I am just a single guy without any credibility, and I seem to be a little to dramatic. So, let's say it is just another stupid theory with no interest.

Having fun and making fun with game of life.

Summary of the previous episode



In the previous episode we made a simple game of life called GoF because I am dyslexic and Game Of Life became Game Of liFe. The purpose of the exercise was to demonstrate that an abstraction ought not to be complicated but ought to dissociate the intuitive way to use the code and its implementation. Now, our new mission, is even funnier: it is to show how a simple toy program can teach us serious things.


Introducing the game of life console 



I have made a small tutorial here : http://gof.readthedocs.org/en/latest/quickstart.html

My game of life implementation is deliberately faulty in its implementation, is a little bit of a troll, but it is has an amazing power to illustrate some key concepts of developing (I prefer factorizing):
  • it is an introduction to non linear algebra a field in which computer analysis is a must;
  • it is a massively parallel model hence a way of thinking problems in order to defeat concurrency problems;
  • it is a very simple way to begin manipulating python;
  • there are some smart tricks based on abstractions; 
  • it is an introduction to discrete cellular automata / multi agent simulations.


The troll in the code



I am not an Object Oriented developer. I am an old old developer coming from the old time, we use to say : «show me your code, and I shall be mystified, show me your data, and I know how your code really works». Since OOP and encapsulation has been massively adopted, data and code are mixed up in the same files. As a result, it has become impossible to tell code from data.

My code is old fashioned : data on one side (the matrix), and functions on the other side (evolve, bleach, dirty). But, is not.

If you type :

matrix.play = evolve
matrix.reset = bleach
matrix.random_fill = dirty

grid.reset(15,20)
grid.random_fill(10)
grid.play(200,3)


Then, now all the tutorial can be rewritten in a plain OOP fashion. So, the troll in my code is about stating that coding is not about using a paradigm, it is about making code that works, and that OOP and imperative programming can be equivalent.

Since I miss the separation of data and code, I do advocate separating data and behaviour in distinct files and that is why I love python dynamic typing but you could also use inheritance to achieve the same result. One illustration of this principle is archery that use traits (mixins) to give behaviours to inert objects (Mutable Mappings in this case).

I deliberately left a mistake in my code to illustrate my point: my Game Of Life's implementation cannot be used for a generic 2D cellular automaton networks because I left a method for counting living neighbors that is specific to Conway's game of life. I intend to use it make a point later if I have the time to develop on cellular automata, and on the proper separation of methods in an object.


Readying the path for some analysis



Imagine you want to make an histogram of the number of cells that are ALIVE after 0, 50, 100, 200 iterations. For the sake of fun, I use gof.weird_array.SparseArray. Hence you just have to count the number of items in the set to count the living cells this way:

import matplotlib.pyplot as plt
from gof.matrix import matrix 
from archery.bow import Daikyu
from archery.barrack import bowyer
from gof.gof import dirty, bleach, evolve
from gof.weird_array import SparseArray
from json import dump
result= Daikyu({})

for _try in range(100):
    ### {0}^{0} is more friendly thant the boring set()
    grid = matrix(20, 16, SparseArray({0}^{0}))
    dirty(grid, 10)
    result+= bowyer(Daikyu, {0: {len(grid.matrix._set): 1 }})
    evolve(grid, 50, 'unseeable')
    result+= bowyer(Daikyu, {50: {len(grid.matrix._set): 1 }})
    evolve(grid, 50, 'unseeable')
    result+= bowyer(Daikyu, {100: {len(grid.matrix._set): 1 }})
    evolve(grid, 100, 'unseeable')
    result+= bowyer(Daikyu, {200: {len(grid.matrix._set): 1 }}) 

fig = plt.figure()
for i, label in enumerate([0, 50, 100, 200]):    
    ax = fig.add_subplot( len(result), 1, i+1)
    if not i:
        ax.set_title("Number of living cells for 100 random configurations")
    p = None
    x,y=[],[]
    for k,v in sorted(result[label].iteritems()):
        x+= [k]
        y+= [v]
    ax.plot(x, y, label="%d iterations" % label)
    ax.legend()

plt.savefig("histo.png")


And Tada o/



What is so special about these plots ?
  1. there is no nice distribution of the number of the accessible configurations after initial  time  (gaussian or any other distributions);
  2. the configurations that were pretty homogeneous in terms of 0/1 are now more spread (the entropy of each initial patterns decreases, but the result are less homogeneous in terms of 0/1 ratio than the initial patterns)  ;
  3. the number of configurations increases, and then decreases : we have a transition! 
At iteration 200, patterns should be converging to their  attraction basin. With a network of simple systems interacting with each other, you have a complex system. These rules being non linear, they cannot be addressed with linear tools (matrices, Fourier...). It is thus quite hard to predict their behaviors.

If you have the audacity to speak French ;) you can read this : http://www.lps.ens.fr/~weisbuch/cha2/02.html

Now you have a lot of challenge to solve :
  • is there a domain in which the system is chaotic (given a distance of 1 for two distinct patterns, how does final distance evolve?);
  • Are there more chaotic rules than Conway's?
  • If we change the actual neighborhood for a random neighborhood how does the system change? 
  • how many stable attractors exists, what are they size? 
  • how many precursors exists for a basin, how these are distributed?
  • if we consider the grid as a vector of 1/0, then it is a number. Can we construct a chaotic enough cellular automata that would make a good cryptographic hashing function (hint : rule30) ?

What about GPU?



Another cellular automata that is fun is the lattice gas automaton. And it is suited for GPU : Data-Parallelism and GPUs for Lattice Gas Fluid Simulations Since the same causes produces the same effects, most of the cellular automata networks will be easily implemented on GPU.

 

And what about Finance? 



I have found G. Weisbuch works inspiring :  hits and flops dynamics by G. Weisbuch. Financial phenomenon are pretty much based on a lot of agent with their own rationalities, some global beliefs and a neighbourhood. It seems very tempting to use a cellular automata to model financial phenomenon (which seems non linear).

Plus cellular automata are pretty easy to code, easy to parallelize with CUDA. So maybe we can do fun things. At least I tried with a very ugly first code in python of a multi agent simulation with a fanciful utility : http://wiki.github.com/jul/KISSMyAgen


And now?



Well, I hope you enjoyed, that's all.

PS Special thanks  to Alejandro Weinstein, Bmispelon for the corrections...