Life as Clay

Archive for the ‘Processing’ Category

Silly small Processing sketch for trig reference

leave a comment »

This is just a small Processing sketch that I’m throwing up here for reference. It seems that every time I’m trying to calculate the point on a circle, I forget whether I’m working in angles or radians, etc…


int     radius, lines;
float   angle;
PVector center;

void setup() {
  size(600, 600); 
  
  lines = (int)random(4, 20);
  
  if (lines % 2 > 0) {
    lines += 1;
  }
  
  radius = 200;
  angle  = 360.0 / lines;
  center = new PVector(width/2.0,height/2,0);
  
  smooth();
}

void draw() {
  background(255);
  fill(0);
  noStroke();
  ellipse(width/2, height/2, radius*2, radius*2);
  
  stroke(255);
  strokeWeight(2);
  
  for(int i = 0; i < lines; i++){
    float thisAngle = i * angle;
    float ptX = center.x + sin(radians(thisAngle))*radius;
    float ptY = center.y + cos(radians(thisAngle))*radius;
    line(center.x,center.y,ptX,ptY);
  }
}

Written by Clay

February 20, 2014 at 10:55

Posted in Processing, Reference

Tagged with ,

Processing class for finding normal vectors

leave a comment »

Processing uses the PVector class to store vector data. The .normalize() method will normalize any PVector to a unit vector. What I needed to do was to find the normal of a vector — a vector perpendicular to the original vector. This is easy enough to do with some simple math. However, I wanted to encapsulate the logic into a class so that I could store multiple perpendicular vectors (to an original vector) and different locations along the original vector, and at different magnitudes. That is what this class does:

 

class PerpVectorPack {
  // Store the original data
  PVector originalVector;

  // Keep track of values used to calculate points
  ArrayList<Float>   percentOfOriginalVector;
  ArrayList<Float>   magnitudeOfPerpendicularVector;
  ArrayList<Boolean> onRightSide;

  // Storage of calculated perpendicular line points
  ArrayList pointsOnLine;
  ArrayList perpVectorPoints;


  // Constructors
  PerpVectorPack(PVector origVector) {
    initializeLists();
    originalVector = origVector.get();
  }

  PerpVectorPack(PVector origVector, float perpVectDist, float perpVectMag, boolean rightSide) {    
    initializeLists();
    originalVector = origVector.get();
    addPerpVector(perpVectDist, perpVectMag, rightSide);
  }

  private void initializeLists() {
    pointsOnLine                    = new ArrayList();
    perpVectorPoints                = new ArrayList();

    percentOfOriginalVector         = new ArrayList<Float>();
    magnitudeOfPerpendicularVector  = new ArrayList<Float>();
    onRightSide                     = new ArrayList<Boolean>();
  }


  // Methods
  public void addPerpVector(float perpVectDist, float perpVectMag, boolean rightSide) {

    // Keep track of the values used to create the perpendicular points
    percentOfOriginalVector.add(perpVectDist);
    magnitudeOfPerpendicularVector.add(perpVectMag);
    onRightSide.add(rightSide);

    PVector full    = originalVector.get();
    float   fullMag = full.mag();

    // Determine where along the original vector the perpendicular vector should lie (lay?)
    full.normalize();
    full.mult(perpVectDist * fullMag);

    // Set the first local variable
    pointsOnLine.add(full.get());

    // Get the normal of the original full vector and normalize it
    PVector perpVector  = new PVector(-originalVector.y, originalVector.x);
    perpVector.normalize();

    // Determine if it should be on the right or left side of the original vector
    int dir = 1;
    if (!rightSide) dir = -1;

    // Make it the proper length
    perpVector.mult(fullMag * perpVectMag * dir);

    // Offset it from the origin
    perpVector.add(full);

    // Set the second local variable
    perpVectorPoints.add(perpVector.get());
  }

  public PVector ptOnOriginalLine() { 
    return ptOnOriginalLine(0);
  };
  
  public PVector ptOnOriginalLine(int idx) {
    PVector thePoint = (PVector)pointsOnLine.get(idx);
    return thePoint.get();
  }

  public PVector perpVectorPt() { 
    return perpVectorPt(0);
  };
  
  public PVector perpVectorPt(int idx) {
    PVector thePoint = (PVector)perpVectorPoints.get(idx);
    return thePoint.get();
  }
}

Written by Clay

February 21, 2013 at 22:44

Posted in Code, Processing, Resource

Tagged with ,

Processing: HTML table monster concept

leave a comment »

I was working on a website for a client the other day when I sketched out a table that I needed to code in ERB / HTML. I doodled a bit, filling it in with patterns for the various header levels. I liked the appearance and decided to write a Processing script that would generate similar doodles.

Here is the original

 

Here’s an example of the output from the script:

Read the rest of this entry »

Written by Clay

February 21, 2012 at 19:29

Posted in Code, Processing

Tagged with ,

Learn to program: tips for the very beginners and things that I wish somebody had explained to me

with one comment

Learning to program is a frustrating and fun process. I think the frustration comes from the fact that the concepts are not particularly difficult or tricky, but it is hard to express them as a beginner. It is akin to trying to learn basic philosophy in a foreign language that you do not speak. There comes a point, however, when the concepts click, and all that remains is to learn the language. The good news is that many programming languages are similar. Learn one and you can hop to another with ease. Mastering programming, on the other hand, will take the rest of your life.

You probably want to learn to program if you are reading this. You may not have chosen a language and you may be confused by some of the jargon surrounding the concepts. You also may be confused by the tools needed. I am going to simplify a few concepts and give you a list of the things that I wish that I understood when I started, and lessons that I’ve learned. Keep in mind that I’m still learning, so this is a message from somebody for whom the concepts have clicked, but expertise has yet to settle in. These are the first steps that you should take.

Steps to Take

  1. It is far easier to learn to program when you can see immediate visual feedback of the code you’ve written. Combine this with:
  2. Programming tools, also known frequently as IDEs, are extremely confusing for beginners. If you do not understand the concepts, then the vast numbers of windows and widgets that help you deconstruct those concepts are only a distraction. Hence:
  3. Start with Processing. You may never have heard of it, but there are several reasons to start here.
    • Per point 1, you will receive immediate visual feedback.
    • Per point 2, the development environment is dead simple and it comes with a lot of working code examples.
    • It is object oriented. You might not know what this means, and you might read a lot of suggestions to start learning with a procedural language (like C), but ignore those suggestions. You can write procedural code in Processing, too. In fact, you definitely will. There’s a brief explanation of this below.
    • It is a superset of Java, a language which many people make a good living coding. Learn Processing and you can hop right into Java without blinking an eye.
    • The best programming book for beginners is Learning Processing, by Daniel Shiffman. If you only ever buy a single programming book, buy this one. It is worth the money.
    • Everything about Processing is free (except the book I recommended).
    • There are thousands of working code examples that run in your browser on Processing.org and OpenProcessing.org.
    • If you do not want Processing to be your primary language, you can migrate from it as soon as you get to the point where things click; a dedicated beginner need not spend more than 2-3 weeks with the language before moving on. I truly believe you can get to the point where things click in that period of time, if you spend time with it each day.
    • Processing is related to Arduino, meaning that you can make small robots and electronic gadgets using the knowledge you learn with processing. Processing and Arduino are a great entry to the “hacking” community.
  4. Pick a very simple project that interests you and start working on it immediately. You may veer away from any book or text that you are following, but your own project will capture your imagination far more than book projects. I have an interest in simulating populations for public health purposes, so I decided to write a small program that would generate populations.
  5. Allow yourself to get frustrated and when you do, step away. Sleep on it. Come back in the morning with a cup of coffee.
  6. Draw flowcharts of what you are trying to achieve and use the flowcharts as a checklist to make certain you are writing what you need in your code.

Ok, here are a few concepts that you will see immediately. Don’t let the language or unfamiliar terms confuse you. Again, these are simplifications. As you learn a language (hopefully Processing), you will understand nuances of these concepts that I am not going to bother to explain here.

A Few Concepts to Consider

  • Method: This is a fancy word for an action. A method is like a verb. Want to make something happen with code? Then you have to write a method or use a method that somebody else wrote to make it happen.
  • Class: Think back to biology and the use of this work in taxonomy. A class is a grouping of properties that describe one or more things. “Mammal” is a class that describes many animals. A class is sort of like a blueprint for a building. Which brings us to:
  • Inheritance: If something is a member of a class, it inherits the properties of that class. The “mammals” class describes animals that have breasts and produce milk. Cows, monkeys, and humans all inherit the property of the mammals class; they are distinct beings, but they all produce milk. When you program, you will write classes. You will write sub-classes. For instance, “cats” is a sub-class of “mammals.”
  • Instance: If a class is a blueprint for a building, and instance is the actual building. You can use the same blueprint to build multiple copies of the building. Such is it in programming: you create ‘instances’ of ‘classes.’ Also known as:
  • Object: You know… this is pretty much what it sounds like. An instance of a class is an object. I have a cat named Robot. He is an instance of the “cat” class. The cat class inherits from the mammals class, etc. If “car” is a class and “mustang” is a sub-class of car, your 1969 red Mustang in the driveway is an object: an instance of the Mustang class.

Now, let’s go to a more specific example:

  • Human: this is a super-class that includes another class:
    • Basketball Player: Any instance of the basketball player automatically inherits the properties of a Human, it’s parent class. This is a class that has some specific actions that it takes. Any instance of the basketball player class should be able to perform actions related to the game of basketball. Those actions are referred to as the class methods. The class methods might include:
      • Pass the ball
      • Catch the ball
      • Shoot the ball
      • Steal the ball
      • Etc…
    • Each individual basketball player that is created is an object. Players know how to interact with each other. In other words, if one player passes the ball, another player catches the ball. This is the fundamental concept behind object-oriented programming. Objects know how to interact with other objects when relevant. Some objects do not know how to interact with each other. If a basketball player through a ball at my cat, Robot, it would bonk him in the head. That’s because Robot does not know how to catch the ball. In other words, the Cat class does not have a “catch the ball” method. However, all mammals know how to eat. So “eat food” is a method of the “mammal” class (in this example). Since the cat class and the basketball player class both are sub-classes of the mammal class, they both inherit the properties and actions of that class, hence, they both know how to eat. The great thing about inheritance is that if you teach a “mammal” how to eat, then all of the sub-classes of “mammal” already know how to eat and you do not have to teach them how to do it again. Cool, huh?

Explanations of Concepts that Confused Me

Now to one of the most confusing things for new programmers: the word void. I cannot tell you how long the word void confused me. This is one of the great barriers to learning how to program and one of the reasons why non-programmers cannot read code. They get caught on the word void. I’ll explain the meaning, but I have to explain a few more things, first.

Back to basketball. For a basketball game you need to track the points scored for each player and for each team. At the end of the game, you choose the winner by comparing team points. A player on the losing team can have the highest individual points scored, though, right? In the case of basketball, “points scored” is what we call a variable. We know at the beginning of the game that we need to track it for each team and for each player, so we have to declare the variable called pointsScored. When you declare a variable, it looks something like this.

int pointsScored;

The int part means that the variable will always store an integer value. The name of the variable is pointsScored. We will used the variable pointsScored to store …. you got it: the number of points that a player or team has scored. Variables can have “scope.” That means that the value associated with the variable falls within a hierarchy so that the variable is only relevant to the object or class that it is associated with. We assign values to variables like this:

pointsScored = 0;

Here is a major difference between normal people and programmers. The equal sign does not mean “equal” in programming. It is called the “assignment operator” because you use it to assign values to variables. The line above means “assign the value of zero to the variable pointsScored.” The “equality operator” is used to check if values are equal to each other. It is represented by two equal signs in a row: ==

The equality operator usually is used in “if” statements. “If myCar == Ferrari then drive fast, otherwise, drive slowly.”

So, back to the assignment operator. The following code would always add 2 points to the value of pointsScored:

pointsScored = pointsScored + 2;

This frequently is shortened to:

pointsScored += 2;

That’s a bit funky and you might have to think about it for a minute. Objects usually have variables associated with them. In some programming languages, you can retrieve or set the value of that variable using a dot operator syntax.

Clay.pointsScored += 2;

Mike.pointsScored += 2;

Since the scope of pointsScored is at the object level, both objects of the same type have a pointsScored variable. Clay and Mike are both instances of the BasketballPlayer object. To calculate the total for the team, you might have:

Team.pointsScored = Clay.pointsScored + Mike.pointsScored;

In other words, set the value of the Team’s pointsScored variable to the sum of Clay’s pointsScored variable and Mike’s pointsScored variable. Now, Team probably is not an instance of the BasketballPlayer class. Since the scope of the pointsScored variable is held at the class level, we can have multiple variables of the same name throughout the application. You probably wouldn’t want to do this, just for clarity’s sake, but it’s one of the possibilities within object oriented programming.

Now, let’s assume that we have another sub-class of “mammal” called mathematician. Create an instance of the mathematician class: let’s call him Newton. His sole purpose in life is to do what you tell him to do. These actions, methods that he can perform, either require him to return results back to you or they don’t. If you tell Newton to go eat dinner, he does not return anything back to you: he simply goes to dinner. However, when you need Newton to add two numbers together, you expect a result back.

To make him return the result, you have to tell him the two numbers that you want him to add together and then you have to tell him the format of the number that you want him to return to you. Let’s say that you want him to add two integers together and return a number to you that is the sum of those integers. You would write a method for Newton called addTwoNumbers(). When you see parenthesis following a word, it’s probably a method.

You have to do a few things here: tell Newton that you want him to addTwoNumbers, tell him what the numbers are that you want him to add, and tell him that you want an integer in return. When you describe the addTwoNumbers method in the mathematician class, that is where you specify how you want the action to happen and what type of number you want in return. The code in the mathematician class would look something like this:

int addTwoNumbers(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

Whoa! What’s going on? First of all, “int” means “integer.” The red int specifies the type of number that you want your mathematician to return to you when you ask him to addTwoNumbers(). You are saying that you want an integer back in return. The blue parts are the parameters that you are giving to the mathematician — the numbers that you want added. You have to tell the mathematician that you are handing him two integers, called firstNumber and secondNumber. The blue part in addTwoNumbers(int firstNumber, int secondNumber) describes the types of parameters that you are giving to the mathematician. So the first line effectively says, “Hey mathematician, I want you to addTwoNumbers, an integer firstNumber and an integer secondNumber, and tell me the result as an integer.”

Now, when you write the code for this method, you have to realize that the variables within the parenthesis are local to the method, with regards to scope. That means that you can refer to firstNumber and secondNumber anywhere within the curly braces { }, but you cannot refer to it anywhere else because the computer will not know what you are talking about. In fact, when you wrote the method, you declared the variables, for the very first time, within the addTwoNumbers() parenthesis. More on scope in a minute.

Computers are stupid, but they are VERY obedient. They do EXACTLY what you tell them to do. If you make a mistake, they make a mistake. The computer does not understand what addTwoNumbers() means. Luckily, it understands the + sign and how to do addition. Hence, you have to tell it what to do when you ask it to addTwoNumbers(). The code inside of the { } brackets tells it what to do in that instance. { return firstNumber + secondNumber; } means that this method should add the integer firstNumberto the integer secondNumber and then it is done. Since you told it that you wanted an integer back, it sends you the value of firstNumber + secondNumber as an integer.

One more thing: the computer is so stupid that it doesn’t know when to stop, so you have to put a semicolon at the end of each statement to let it know that it’s done with that statement. Some languages do not require this! You’ll discover which do and which don’t as you learn to program.

Ok, so we taught the mathematician class how to addTwoNumbers(). If you remember, we created a mathematician instance called Newton. How do you tell Newton that you want him to addTwoNumbers and how to you tell him which numbers? Like everything else, this will vary from language to language. It is, however, common to see code that looks like this:

x = Newton.addTwoNumbers(10, 5);

Here you asked Newton to tell you what 10 + 5 equals and to store that value in the variable x. A variable is basically a container. Think of x as a post-it note: the above code causes Newton to write the number 15 on a post-it note. The cool thing is that you can send the post-it note into the same method again, even multiple times! So, you could do either of these:

y = Newton.addTwoNumbers(x5);

or

z = Newton.addTwoNumbers(xx);

The first would cause Newton to write the number 20 on a different post-it note (y) and the second would cause him to write 30 on yet another post-it (z).

A word of caution here: the parameters can only be integers because that is how you defined the method. This would cause an error:

x = Newton.addTwoNumbers(3.145);

3.14 is NOT an integer. It is referred to as a floating point number. Computers are stupid, remember… None of your mathematicians will know what to do with the above statement. They will just tell you “Error! Error!” And here you thought Newton was smarter than that…

Programming languages that are very strict about the differences between integers and floating point numbers (among other things) are considered to be “strongly typed.” Some languages are better at figuring out what’s going on: Ruby is one of those languages. It makes a good second language after Processing, though you will not receive visual feedback from your code – mainly feedback in a command window or in Terminal.app.

Void

Hey! I didn’t forget. Remember that we want Newton to eat dinner, too. When we tell him to eat dinner, we don’t need him to return a result to us — you don’t want the dirty dishes, do you? I didn’t think so. In the mathematician class, we might have another method called eatDinner(). Computers being stupid, we have to explicitly state that we do not want the dirty dishes brought to us — or that we do not want a value returned from the method, and that’s what the word void means when you see it in programming. The method would look something like this:

void eatDinner()
{
// Some code that explains how to eat dinner would be here
}

Pretty simple, eh? The eatDinner() method does not have any parameters. If we wanted to be able to tell our mathematicians to eat something specific for dinner, we might have another method that looked like this:

void eatThisForDinner(a food item that you specify)
{
// Some code that explains how to eat a specific food item
}

You know what is cool here? You could have another class called “food items” and then you could create specific instances of the food item class, maybe one called tunafish. If you told Newton.eatThisForDinner(tunafish); it would send instructions to Newton to absorb the nutritional properties that the tunafish has and then you could make the specific instance of tunafish disappear. Cool!

Public and Private

These are two other terms that you will see when you first start programming. “Public” basically means “anybody can perform this method” and “private” means “this is a secret method that only people of my class can perform.” Let’s assume for a second that we have a method called performCalculus(). I don’t know about you, but I think that Calculus is difficult. It’s pretty much a secret to most people — if they want to performCalculus(), they have to be a member of the mathematician class. That being the case, when you define the method in the mathematician class, you would make it private. The method code might look like this:

private float performCalculus(one number, another number)
{
// Secret calculus code would be here
}

In this case, I could write Newton.performCalculus(xy); or Leibniz.performCalculus(x, y); but I would not be able to write Clay.performCalculus(x, y); because I am not of the mathematician class. Newton or Leibniz would return a floating point number to you in this case.

Now, if you want anybody to be able to tell Newton or Leibniz to eat dinner, you would make it a public method so that people in other classes could call it. I’m not a mathematician, so I would not be able to tell Newton to eatDinner() unless it was a public method. This is  a great simplification of a concept called encapsulation. You also will hear the term scope used in these discussions. For example, “What is the scope of that variable or method?” The method might appear something as follows:

public void eatDinner()
{
// Code that  explains how to eat dinner
}

Finally, you can set the scope of variables in a similar manner. Sometimes you will have “global” variables that every object in your application needs to reference. Back to basketball… everybody from the ref to the players to the coach need to know the time remaining in the game. They may call plays differently, change strategy, decide whether to foul, etc… differently depending on how much time remains. In this instance, you would make a global variable for timeRemaining.

That’s about it!

Go download Processing, buy Shiffman’s book if you can, and get started! It’s easier than it seems, especially if you understand what some of these words mean as you get into it! Good luck and let me know if this was helpful. If you upload anything to openprocessing.org, let me know – I’d love to take a look. :) If there’s anything else (simple) that you don’t understand, let me know and I will take a stab at explaining it.

Written by Clay

January 22, 2010 at 15:32

And the flu slowed me down…

with one comment

I’ve been living in a Dayquil haze for the past several days, unable to do much other than look forward to the departure of this cold/flu that I have. I hope it’s H1N1, just to get that out of the way, but who knows? Between bouts of delirium, I’ve managed to update the population generator a little. It now assigns a weight and height to everybody, based on national statistics. Weight and height for children under 18 are assigned based on CDC growth charts, whereby the children are put on a course to achieve a BMI that corresponds with the national average. BMI reads differently for children, so it is not displayed for them. The chart on the lower-left is the distribution of the population based on BMI. It’s not perfect, but comes close to mimicking the US data.

bmi calcs

Written by Clay

November 11, 2009 at 16:01

When random is funny

leave a comment »

I had to chuckle… Continuing the Population Generator, I grabbed lists of the most common names in the United States (1000 for male and female, plus 1000 surnames) and wrote a function to assign a name to everybody in my pseudo populations. On the first test of this, what do I get out of all of the randomness but baby Anthony Hopkins. That’s not to mention Cindy Bird and Heath Byrd… Random isn’t feeling so random.

Anthony HopkinsI encountered an error when trying to import a file into Processing. This silly dialog box popped up, which also made me chuckle, because it reminds me of some of the temp dialog boxes that I used to include in Access apps that I wrote. From time to time I forgot to remove them or change the text and I always had a confused/bemused person calling to ask what it meant.

funny dialogIt lied, though… It deleted the file in place and I had to recreate it.

Written by Clay

November 6, 2009 at 18:15

Population Generator

leave a comment »

Well, I’ve been away, working on a larger project. It’s less artsy but more practical towards my interests in simulation. Interestingly, it takes only mild deviations away from the world of data art to begin to realize the limitations of Processing. (That’s not entirely fair: Processing can import and use Java libraries, so there is more available that I currently am using. I have not, however, played with importing other libraries yet.)

I created a population generator that randomly generates a population of a specified size. It then displays 4 random members of the population above the demographics of the population. Clicking (can’t do it here, on the image….) rotates different members of the population into the slots above the demographics. Age 18 is considered full grown. People under 18 are displayed relative to the size of a full adult, scaled based on their age. Eventually, I will build in variation for height, weight, and other demographics. The colors of their shirts are randomly generated when they are created, but the tone of the skin on their head is randomly chosen from only 3 colors.

The demographics display is a technique used frequently in public health and demography, called a population pyramid. I think mine is upside down, but that’s an easy fix. In fact, I already fixed it in the code, but didn’t want to take a new screenshot. :)

So, why do this? My hope is to be able to create digital populations of people that I can use to simulate a variety of things related to public health, disease, and complex emergencies. That’s a long way down the road, but I think that I’ve done pretty well for the two days that I’ve spent working on it so far — especially for a programming newbie!

This definitely remains a work in progress, but this is what it currently looks like:

Population Generator

Written by Clay

November 5, 2009 at 22:03