Nature of Code Final: Genetic Crossings

Professor Daniel Shiffman’s Nature of Code is outstanding.  Just check out the syllabus. And play with the Nature of Code repo Processing sketches hosted on Github. And be sure to get his book when it comes out! We covered some basic algorithms for simulating inside the Processing environment vectors and forces/repellers, genetical algorithms, Wolfram cellular automata, neural networks, autonomous agents, flocking behavior, particle systems.

Background

For me, the pull towards genetic algorithms, heredity, fitness, evolution, Punnett squares, etc. was great, so my project for my first intro to computational media class turned into my Nature of Code final.

My "EUDAIMONIA" Tattoo

My Genetic Crossings project attempts to create a simulated environment where people exist within a world connected to God, the peoples’ religions, their nationalities, and each other.  They produce offspring based on characteristic attraction rules (for my demo I only used “appearance”, “money”, and “religion”, but only to demonstrate what was possible –I would like to create a more fully-formed algorithm for my personal reputation/identity ecosystem Galapag.us to approximate and adjust to the infinite ways that people become attracted to each other and become married or have children or devote themselves to the other), and they can die.  Their well-being or happiness (what in Galapag.us will be eudaimonia) is dependent on their quality of living within their religions and nations.

Map View

A video from an older version:

See previous documentation on this project:

 

Here are the initial characteristics I created for each person.  There are so many more yet to add! Strength, intelligence, wisdom, charisma, stamina, wit, humor, education, creativity, responsibility, discipline, honesty, religiosity, entrepreneurialism, appearance, money, gracefulness, stress, health, luck, talent_math, talent_art, talent_sports.

Initial nationalities/regions: USA, China, EU, Africa, South America.  Characteristics of security, innovation, job opportunity, immigration policy, life expectancy, education, sanitation, standard of living, pollution, biodiversity, crime, political freedom, and nutrition.  By no means comprehensive.

Initial religions/spiritualities: Christianity, Judaism, Islam, Taoism, Confucianism, Hinduism, Buddhism.  With characteristics of commercialism, morality, hierarchy, portability.  Obviously these need some tightening up/additions/discarding.

Final Project

So in my midterm I managed to add Verlet 2D physics to the sketch so that people, nations, and religions have connections to each other which make them bounce around like they’re on springs, relative to their attractions and strength of ties to each other.

In my final proposal, I sought to add the following:

  1. Wolfram cellular automata
  2. Connect to external database
  3. A selection algorithm to choose certain parts from parents based on mutation rate and fitness to pass along to new offspring
  4. Interaction sliders to change variables
  5. Macro events that affect well-being of all objects in the world, such as earthquakes or war
  6. Micro events that affect individual well-being, like rites of passage
  7. Discrete clusters of people, mostly based on familial strength of ties, instead of one big clump of people in the middle like in my midterm

 

I managed to get most of this done.

I enjoyed adding Wolfram CA.  I wrote a node.js app for express which would act as a JSON middleman between my main genetic crossings sketch and a wolfram sketch.  Basically, when viewing the chromosomal stainings (genotypes), you can click on the CA button to the left of a person’s staining, and this will pass a JSON object (using Prof. John Schimmel’s Processing-Nodejs code) to the node server, which is detected within 5 seconds by a polling timer within the wolfram sketch.  The wolfram sketch then uses the JSON object as its data to apply rules to to construct a pattern unique to the selected person’s genetic characteristic code.

1) I added a third parameter to the rules which would display as either black or aqua, depending on the CA rules.  Prof. Shiffman’s code used base-2 groups of 3, which had 2^3, or 8 total possible combinations (using only the digits 0 and 1), but I used base-3 (0 = white, 1 = black, 2 = aqua), so it became 3^3, or 27 possible combinations.  For this ruleset, I duplicated Wolfram rule 90 three times, then added a few extra codes.  The triangular look seemed the most visually interesting for what I was doing.  Anyway, what was cool about Prof. Shiffman’s code was that it keeps streaming the pattern from bottom to top.  So when a new person is clicked on, that person’s signature is integrated into the flow seamlessly once the sketch loads the JSON off the node server.  I don’t know that any of this actually is useful except that it looks cool and uses principles from class and maybe, just maybe, shows someone’s digital characteristic “signature”.

Streaming Wolfram CA on top of Processing sketch code. Console of Processing shows a passed JSON object.

2) I’m happy I was able to set up a MongoDB to be accessed via node as well as by my Processing sketches.  When I build out Galapag.us, I’ll be able to pump out JSON objects of actual users into these sketches for data visualization.  I’d been wanting to do this since my first semester and now it’s done.  Most credit goes to John Schimmel though for writing the hook into node though!

node.js instance output including passed JSON object

3) I realized that I already had some mutation within my matingDance.sex() function, once the two parents’ characteristics were passed to a matingDance.punnettSquare() function.  Before, the function would just average the two parents’ characteristic values together and then add or subtract a random amount from them for mutation.  What I changed was making the function choose randomly from either parent’s base characteristic.  So if one parent had 10, and the other had 1, the result would not be 5 (rough average) but either 1 or 10.  Then I would offset a random amount (hardcoded as 4) if mutation kicked in (if a random number between 0 and 50 was less than 2, for approximately a 1 in 25 chance of mutation per characteristic).  What this ended up doing was increase the diversity within the genepool and more accurately reflect reproduction.  I still need to tweak these numbers to get more consistent levels of variety but the algorithm is mostly there.

Here’s a view of the chromosomal stainings before I changed the algorithm — here it averaged the parents’ traits, which, in the case of this sketch’s iteration’s octomom, created many extremely similar offspring:

Before

And here’s the view after picking from either parent and allowing for a slim chance of mutation:

After

I feel as though the end result has a more diversified population with more variability between generations and individuals.  I need to tweak this so that if the value from a parent is at 1 or 10, it may mutate in only one direction, but here’s the matingDance.punnettSquare() function:

int punnettSquare(int comp1, int comp2) {
    int mutation = (int)random(0, 50);
    int dominance = floor(random(0, 1.99));
    int crossover = 0;
    if (dominance == 0) {
      crossover = comp1;
    }
    else {
      crossover = comp2;
    }
    if (mutation < 2) {
      crossover += (int)random(-4, 4);
    }
    // don't want it to be out of bounds
    // TODO: fix so it can mutate only one way if parent is 1 or 10
    if (crossover < 1) { crossover = 1; } else if (crossover > 10) { crossover = 10; }
    return crossover;
  }

4) I didn’t add sliders to change variables mid-sketch — at this point I can use variables pre-set in the main class but I’d like to make the interface more user-friendly and interactive later.

5 and 6) I didn’t do macro and micro events because I figured they’d just require making a button that, when pressed, would cause particles’ values to change.  What would be interesting would be to have random events happen based on their likelihood to occur and then some events would have permanent effects (damage to peoples’ personalities) or temporary effects (nationalities’ well-being that would later recover).  This kind of introduces the possibility for individual peoples’ health and whether they have injuries/disabilities/diseases/gifts/talents.

I did add a Ritual class though, which only includes right now a funeral function.  When funerals are recognized by a culture (by pressing ‘f’), the dead are removed from view on the map and their attraction springs are removed as well.  What this is supposed to represent is that funerals are a way for the living to remember the dead and then put them to rest so that the living can move on and create new ties with the living.  I do like the idea that we retain our ties to the past, which can sometimes become weaker in death and sometimes become even stronger.  I didn’t model that yet.

public class Rituals {

  Rituals() {
  }

  void funeral(boolean funeralsRecognized) {
    println(funeralsRecognized);
    for (int i=0; i<numPeople; i++) {
      if (person[i].parent1 != -1 && person[i].parent2 != -1 && person[i].alive == false) {
        if (funeralsRecognized == true) {
          physics.removeSpring(parentSpringArray.get(person[i].parent1Spring));
          physics.removeSpring(parentSpringArray.get(person[i].parent2Spring));
          physics.removeSpring(parentMinDistanceSpringArray.get(person[i].parent1MinDistanceSpring));
          physics.removeSpring(parentMinDistanceSpringArray.get(person[i].parent2MinDistanceSpring));
          person[i].lock();
          person[i].display(0);
        }
        else { // TODO: re-reference spring after it's recreated?
          parentSpringArray.add(new VerletConstrainedSpring2D(person[i], person[person[i].parent1], person[i].parent1RL, random(parentGravity1, parentGravity2)));
          person[i].parent1Spring = parentSpringArray.size()-1;
          physics.addSpring(parentSpringArray.get(parentSpringArray.size()-1));
          parentSpringArray.add(new VerletConstrainedSpring2D(person[i], person[person[i].parent2], person[i].parent2RL, random(parentGravity1, parentGravity2)));
          person[i].parent2Spring = parentSpringArray.size()-1;
          physics.addSpring(parentSpringArray.get(parentSpringArray.size()-1));
          parentMinDistanceSpringArray.add(new VerletMinDistanceSpring2D(person[i], person[person[i].parent1], random(parentMinDistanceRL1, parentMinDistanceRL2), random(parentGravity1, parentGravity2)));
          physics.addSpring(parentMinDistanceSpringArray.get(parentMinDistanceSpringArray.size()-1));
          parentMinDistanceSpringArray.add(new VerletMinDistanceSpring2D(person[i], person[person[i].parent2], random(parentMinDistanceRL1, parentMinDistanceRL2), random(parentGravity1, parentGravity2)));
          physics.addSpring(parentMinDistanceSpringArray.get(parentMinDistanceSpringArray.size()-1));
          person[i].unlock();
          person[i].display(1);
        }
      }
    }
  }
}

7) Discrete clusters.  I ended up adding relationships between people and their parents from just constrained springs to a combination of constrained springs and minimum distance springs.  What this would change is that a person’s distance from his parents is both constrained to no more than a certain length but also more than a minimum length, so that they can both be more visible instead of overlapping visually, and also be more clustered together.  I found that this makes certain groups on the map appear more clustered instead of forming a big ball in the middle.  I still need to do more work on this though because as there are more people in the sketch, the big clusterfuck returns (because there are too many connections between everything and I can’t zoom in closer to see the gaps and relative spacing between different networks).

I converted a lot of my arrays of spring connections over to one large ArrayList, which I think was easier to deal with in the end in terms of manipulating them after they were initiated into the environment.  I did find, however, that I had to pass a reference to the spring’s number (since it was just an ArrayList entry) to the person’s class instance so it could refer to it later.  A problem with this though, as I realize just now, is that if I remove springs (as I do in the funeral ritual), I’ll lose the correct references.  So I have to make sure that when the springs are added again, when funerals are disabled, that a pass a new reference to the ArrayList.

I also found that there tends to be super-breeders every time I run the sketch, with certain people tending to produce tons of offspring while others produce none.  I’m talking like 1 or 2 people will produce 10 kids, which tends to make the sketch appear too tightly clustered because everyone is closely linked.  Perhaps this is a feature, rather than a bug, of reproduction?

Code

You can download the code from Github.  You’ll probably want to start up a node instance and then start the genetic crossings sketch, then finally the wolfram sketch.  Instructions are in the README.md.

Github: https://github.com/Xeus/Genetic-Crossing

Conclusion

And this leads me to some closing notes. I shied away from adding fitness yet again to my reproduction algorithms because I felt like “fitness” in the short-term was too much like large-scale evolution theory and autonomous agent simulation.  In my sketch there wasn’t really an ideal fitness state, with no limitations or rules imposed on the larger scale.  What I wanted was to break into modeling some culture into the simulation, so that choices were made between sexual partners based on cultural norms and not as much on randomized reproduction. Obviously modeling culture would work best if it were overlaid on top of basic biological reproductive theory such as choosing the fittest partner and whatnot, but I felt that was too much for the scope of this simulation, which I wanted mainly to focus on social networks.

JavaScript has come a long way.  It’s now the same on the backend and the frontend.  Processing can be exported to JavaScript in some capacity, and dataviz libraries such as D3 are taking off.  Soon we will be able to introduce more fluid, data, physics, and particle system simulations within a browser.  It’s too early for my sketch yet (ToxicLibs takes some finagling) but this is a glimpse of the web to come.

As I begin to do more serious work on the internal mechanics of Galapag.us, it’s stuff like this Processing project that makes me appreciate how careful I’ll have to be with positioning different factors against each other so that people can create their own formulae/evolutions to weight different priorities how they deem fit.

Looks like this book out of the Harvard Berkman Center, “Interop: The Promise and Perils of Highly Interconnected Systems”, by John Palfrey and Urs Gasser, is a must-read.

What I do feel is that current online social networks have not really tried to map out the complex interweaving, competing, variable connections and attractions we have between ourselves and others, between the different identities we all have, between the things we care about more or less at different times in our lives, etc.  To facilitate something like this, I can’t help but feel there needs to be a massive API that allows people to access all this data (if privacy settings allow it) so that we can take advantage of the multi-dimensional nature of our species.

You can think of someone’s identity as a meshed web that is being pulled apart by the external world and people and ideas and being pulled together by muscle and ligament and cartilage and sense of self and personality and such.  You can think of a community as a bunch of these springy people pulling on and apart from each other constantly, but at a stronger tension than from other communities.  Communities form religions and nations and cultures, again with that same network of relationships and competing identities. I hope that’s the dynamic I was able to capture in doing this project.

Credit

Special thanks to:

  • Prof. Dan Shiffman for all his documentation and code from Nature of Code, particularly his chapters on forces, genetic algorithms, ToxicLibs, and cellular automata
  • Prof. John Schimmel for his Processing-Nodejs code

Nature of Code: Final Proposal

For my Nature of Code final, I plan to continue the Genetic Crossings Processing sketch project and incorporate some of the concepts from the second half of the course.

Previous documentation for this project: Nature of Code & Intro to Computational Media

Specifically, I want to do the following:

  • Use each person’s characteristics (rated from 1-10, and numbering a total of about 20 characteristics per person) as a ruleset for the Wolfram Cellular Automata structures.  I will have to adapt the code by remapping the 1-10 scale either to a binary state or by making more complex rules (perhaps using color instead of white/black or on/off).  I don’t know that there’s any benefit to the overall project from implementing Wolfram CA here, but perhaps it might give each person within the sketch a unique signature or fractal pattern.

  • Of the three characteristics of genetic algorithms — heredity, variation, and selection — I have implemented my own versions for heredity and variation, but have not really introduced much selection.  The only selection that seems to take place is that, because I have more heavily weighted religion, appearance, and money in the sex() algorithm, those with high stats in those areas will probably reproduce easier.  But this is not equivalent to having an actual fitness algorithm that determines “ideal” environmental success.  As Professor Shiffman writes in his notes, “There must be a mechanism by which some members of a population have the opportunity to be parents and pass down their genetic information and some do not. This is typically referred to as “survival of the fittest.””  I might also try to implement a mutate() function as used in example code, since all I do at the moment is take the average of the parents’ characteristics and then randomize an offset to come up with “mutation”.  Very hacky.
  • System variables and sliders: I liked the Processing sketch “flocking_sliders.pde” from the Shiffman’s chapter 6, “Autonomous Agents” because it let you play with variables on the fly to see how it would affect the simulation: how would you get boids to fly together, but not too close together, and could you enforce more solo or flocking behavior easily?  So I think I would like to use the God person or perhaps a fake country or religion to simulate how wild changes in traits or characteristics of a larger group-level entity could markedly affect individual persons linked to them.  Could I even have individuals leave group-level entities in search of more favorable ones?  What I picture is the person objects bouncing around the environment as the strengths of their relationships change between others, their parents, religions, and countries.  This also introduces the idea of migration patterns.
  • Similarly, I would like to be able to introduce world-level events such as earthquakes, global warming, war, Renaissance, etc. which add or subtract from multiple entities all at once, or even over iterations/time.
  • On an individual level, I wonder if I could implement rites of passage, liminal events in persons’ lives such as turning 21, getting married, having children, etc. that affect their relationships to their communities and increase/decrease their stats.  Would this necessitate perception of stats as opposed to actual stats?  In my Galapag.us project, I’m trying to study the multi-dimensional nature of our presence in the world — what we think of ourselves, what we actually are (objective truth/science?), and what others think about us. Reputation within a community is not often of one mind — one can hold various degrees of influence and respect among different components of the same community.  How does one code this?
  • Visually, I am hoping to make the networks a little more discrete.  For my midterm, the sketch ended up looking mostly like a hub (God) and spokes as more persons were introduced.  What it should be, though, are clusters of parents and offspring, dispersed between different group-level clusters.

 

Other influences:

  •  Joshua Epstein’s “Growing Artificial Societies: Social Science from the Bottom Up”, loaned to me by my classmate James Borda.
  • Prof. Shiffman posted this video of a talk by Bret Victor, which argues for real-time feedback for coding, so we can visualize the results of our code and experiment with unintended changes or extremes testing or rapid prototyping for artistic-based projects such as building animations.  Blew my mind.  Seriously, I don’t watch many long lecture vids anymore, but this was awesome:

Nature of Code Midterm: Genetic Crossing with Verlet Physics

For my Nature of Code midterm, I added a physics world to my genetic crossing project from last semester.

A short video, sped up quite a bit because my MacBook Air + QuickTime screencap choked on it:

Here’s some past posts on the project: http://blog.benturner.com/category/itp/icm/

Professor Shiffman‘s notes from his Nature of Code book were invaluable in understanding vector- and particle- based systems, so by the time we got to Box2D and ToxicLibs, understanding the underlying framework needed to make a world that reacts to physical forces was far easier.

My genetic crossing project, which allowed for people to reproduce and carry characteristics from their parents and their religious and national environments, was a perfect project for last semester but also a perfect transition project for a physics system, because I was trying to study the natural flow and connection between many different objects with differing characteristics.

I chose to use ToxicLibs’ VerletPhysics2D library because all I had to do was have my Person, Nation, and Religion objects to inherit the VerletParticle2D class, and then be added as particles with connecting springs in order to have them react to each other.

class Person extends VerletParticle2D {
  Hashtable trait = new Hashtable();
  String namePerson, gender;
  int parent1, parent2, uniqueID, pWeight, pHeight, age, mbti, lastBaby,
  nationality, religion, children,strength,intelligence,wisdom,charisma,stamina,wit,
  humor,education,creativity,responsibility,discipline,honesty,religiosity,entrepreneurialism,
  appearance,money,gracefulness,stress,health,luck,talentMath,talentArt,talentSports, happiness, employed;
  int[] colorBaseArray = new int[3]; // need base colors for each person
  float[][] traitPosArray = new float[numCharacteristics][2]; // save x,y for all characteristics
  float[][] traitPosArray_orig = new float[numCharacteristics][2]; // original copy of coords
  boolean alive;

  // constructor
  Person(int _uniqueID, int _mbti, int _stress, int _health, int _gracefulness, int _luck, int _talentMath, int _talentArt, int _talentSports, int _strength,
  int _intelligence, int _wisdom, int _charisma, int _stamina, int _wit, int _humor, int _pWeight, int _pHeight,
  int _education, int _age, int _creativity, int _responsibility, int _discipline, int _honesty, int _religiosity,
  int _entrepreneurialism, int _appearance, int _money, String _namePerson, String _gender, int _parent1,
  int _parent2, int _nationality, int lastBaby, int _religion, int _children, int _employed, float x, float y) {
    super(x, y);

Two things I found out pretty quickly.  First, I made this project with arrays and a hashtable but had I known better, I would have used ArrayList and no hashtables (just variables with integer values.  The other?  I had to rewrite my class xPos, yPos variables as x,y and include them as direct variables instead of references to new variables, in order for the objects to be recognized in the physics world.  Basically, my objects would drop like a stone in a pond because they were not connected to the system but still were “particles” in a world with gravity.

I still have a problem with bizarre array counting for adding the large amount of springs that connect every person, nation, and religion to each other, and more added as each new person is born into the world.  I’m probably wasting tons of memory and overwriting certain springs because I didn’t make entirely unique arrays.

But the simulation is now operating within a 2D world and now I can go through the process of tweaking the relationships between the objects to more clearly match up with the characteristics/heredity/uniqueness that I coded into the simulation last semester.  God is located in the center now, instead of in the bottom right, so he is a fixture within the world, with the nations and religions along the periphery of the map (no meaning behind that!) to space out the particles which are tethered by their springs.

Relevant code:

  physics.addParticle(god);
  god.lock();

  // #PeopleChange init all person objects & nations
  for (int i=0;i<numPeople;i++) {
    physics.addParticle(person[i]);
  }

  for (int k=0;k<numPeople;k++) {
    springArray[k] = new VerletConstrainedSpring2D(god, person[k], godRL, godGravity);
    physics.addSpring(springArray[k]);
  }

  int z=0;
  for (int k=0;k<numPeople-1;k++) {
    if (z < numPeople) {
      for (int l=0;l<numPeople;l++) {
        newPersonSpringArray[z] = new VerletConstrainedSpring2D(person[l], person[k], int(random(250, 650)), random(0.001, 0.003));
        physics.addSpring(newPersonSpringArray[z]);
        z++;
      }
    }
  }

Code is on Github.  I recommend running this in Processing since I have it set to something like 1200×700 pixels.

Nature of Code Week #4: Particle Systems

Nature of Code continues to be fascinating.  Professor Shiffman’s notes are incredibly well-done and very easy to understand as he explains pretty dense physics problems sequentially — the forthcoming kickstarted Nature of Code book will be well worth its price.

This week we covered particle systems, inheritance, and polymorphism.  The particle systems go hand in hand with repelling forces, which were built upon applying forces to other objects, which was built upon vector movement.  I’ve been having to re-read the notes for each chapter several times each week to make sure I understand it.

Our homework:

“At this point we’re a bit deeper in the semester and approaching the midterm project. Feel free to simply start on a midterm idea or continue something you’ve been working on previously. If you would like to try an exercise related to particle systems, here are some suggestions:

  • Use a particle system in the design of a “Mover” object. In other words take, say, one of our earlier examples and instead of rendering a Mover object as a simple circle, emit particles from the mover’s location. Consider using the Asteroids example and emit particles from the ship when a thrust force is applied.
  • Create a particle system where the particles respond to each other via forces. For example, what if you connect the particles with spring forces? Or an attraction / repulsion force?
  • Model a specific visual effect using a particle system — fire, smoke, explosion, waterfall, etc.
  • Create a simulation of an object shattering into many pieces. How can you turn one large shape into thousands of small particles?
  • Create a particle system in which each particle responds to every other particle. (Note we’ll be doing this in detail in Week 6.)”

 

I immediately started playing with creating systems of systems of particles, using Prof. Shiffman’s example code.  I turned down the particle size, increased the constrained force distance, and also increased the number of repelling objects to 60.  I had some particle systems randomly placed upon sketch startup, but also made it so you could add more systems upon mousePressed().  I tweaked the color and background to look more like fading embers or fire, then made the repeller objects very faint.  The particles gradually fade away until they die, using opacity as a measure of life strength, so that when opacity reaches 0, the particle dies.  This helps to preserve framerate.

The result is that the system ends up looking like Dorsey-ish flows of traffic, or seeing dynamic internet traffic as it passes through the world’s backbones at night.  Feedback in class suggested that I try to add repeller forces as geometrical shapes, to guide the particles instead of having random patterns generated.

Particle(PVector l) {
    acceleration = new PVector(0,0);
    velocity = new PVector(random(-.3,0.3),random(-.1,.1));
    location = l.get();
    lifespan = 200.0;
    randColor = color(int(random(150,230)),int(random(90,130)),int(random(25, 90)));
}

and

for (ParticleSystem2 psX: systems) {
    psX.run();
    psX.addParticle();
    for (int i = 0; i < repellers.length; i++) {
      psX.applyRepeller(repellers[i]);
    }
}

A video:

Code at Github & OpenProcessing.org.

What I’m thinking now is that, for my NoC midterm and final, I can adapt my final from Intro to Computational Media last semester so that all my objects are essentially particles exerting forces on each other.

For a recap of my project, read this long blog post.  Simply put, the project was a simulation incorporating the traits of people, nations, and religions, creating offspring who are summations of their genetics and environments.

I might try to make the text labels for each person orbit the particles, but this might result in a massive drop in framerate.  Here’s a screenshot of what my final project looked like.

What’s good is that I didn’t attempt movement last semester, since I didn’t really know how to dynamically and smoothly move the “people” using vectors.  I am a little worried I’ll have to re-write some deep parts of the code in order to get this to work, but it’s a worthy project.

Nature of Code: Forces & Physics

Our homework this week was pretty wild, after going over some pretty epic notes on forces, physics, Newton’s laws, etc.  Here were the suggested exercises for homework:

  • Rework your motion sketch from week 1 using PVector. Try incorporating the concept of forces into the environment by affecting only the acceleration. Create a formula for calculating a dynamic acceleration, one that changes over time based on any number of factors. What happens if you make more than one object via an array.
  • Using forces, simulate a helium-filled balloon floating upward (and bouncing off the top of a window). Can you add a wind force which changes over time, perhaps according to Perlin noise?
  • Create an example where instead of objects bouncing off the edge of the wall, an invisible force pushes back on the objects to keep them in the window. Can you weight the force according to how far the object is from an edge, i.e. the closer it is, the stronger the force?
  • Create pockets of air resistance / friction in a Processing sketch. Try using circles instead of rectangles, i.e. pockets of mud (or ice). What if you vary the strength (drag / friction coefficient) of each circle? What if you make some of them the opposite of drag—i.e., when you enter a given pocket you actually speed up instead of slow down?
  • Can you create an example where all of the Mover objects are attracted to the mouse, but repel each other? Think about how you need to balance the relative strength of the forces and how to most effectively use distance in your force calculations.
  • Research a force not covered in class and implement it as a vector.
  • Use the concept of forces to visualize some input (could be data, literal example would be get windspeed online and translate to a wind force in Processing, but feel free to think more abstractly)
  • Build a sketch that has both “Movers” and “Attractors”. What if you make the Attractors invisible? Can you create a pattern / design from the trails of objects moving around attractors? See the Metropop Denim project by Clayton Cubitt and Tom Carden for an example.

 

The above link is pretty cool.  It shows the possibilities for working with forces, attractors, and particles, combined with the more organic, natural shapes and motions that we’re learning in Nature of Code.  I think I want to start incorporating something like this into my 2D designs.

Prof. Shiffman’s notes from his upcoming Nature of Code book are outstanding.  We’re currently learning how to affect objects using added forces which affect location, acceleration, and velocity with vectors.  So, just this type of code starts to create a more realistic physical environment: [code clipped for brevity]

PVector wind = new PVector(0.001,0);
PVector gravity = new PVector(0,0.1);
m.applyForce(wind);

void applyForce(PVector force) {
  PVector f = PVector.div(force,mass);
  acceleration.add(f);
}

I had already converted my first homework assignment into an array of objects and added some extra forces and reactions for the penguins.  But I also wanted to try some other forces, without delving into some of the homework suggestions that seemed a little too complex right now for me (still need to play with orbits, motion in liquid, etc.).  The sketch I made is just a simple balloon with a random walk floating up, bouncing off the top of the screen.

Sketch is running at OpenProcessing.org, and code is at Github and below the jump:

Read More »

Nature of Code: Random Walks

For my first homework assignment in Nature of Code, I had to create a random walk of my choosing.  I found Mark Kleback’s self-avoiding walk code (github) to be helpful for having a good example of a clean, easy-to-view walker.

I wanted to practice using the classes and constructors for the movers, so I created my own, using Prof. Shiffman’s examples as guidance.  I also wanted to create multiple movers, so I put them into an array of Mover objects.  For my Movers, I decided to use the Socially-Awkward Penguin from meme-lore.

The thing about SAP is that it lives out all of our insecurities and attempts to avoid looking silly, stupid, or foolish in front of others, often making us resort to ridiculously absurd avoidances of interaction.  So I wanted to see if I could recreate this social awkwardness as part of my Movers.

I think I partly succeeded, though I can tell there’s bugginess in the avoidOthers() function of the constructor because sometimes the penguins get trapped along the sides (probably their velocities have them collide against the walls at a greater speed than they’re pushing off the wall, or something).  I also don’t think the penguins perfectly avoid each other in order to get to the most distant space from each other.  They just reverse their direction whenever they get too close to other penguins.  Still I think the effect worked.

Code and demo at OpenProcessing and code at github, as well as posted below the jump:

Read More »