I have been working on this the last few weeks. It is an interactive deJong Attractor, developed using GLSL Shaders and C++ with openFrameworks.
The attractor is generated, then passed as a texture to a shader that builds a curl, then a bunch of particles float around that curl, changing color and opacity based on the attractor output.
It is also connected to a kinect, so the changes that you see on screen are coming from movement captured from the kinect.
I set it up on the dancefloor at a friends party, and included some iPhone footage of it in action at the end of the clip below.
Much of the detail gets lost when looking at the small vimeo embed, so please check out the larger HD version on vimeo here.
Attractor from dizzy pete
I think I have finally gotten deJong attractors and particle fields out of my system, on to the next thing.
Sunday, January 20, 2013
Monday, December 17, 2012
Density Plot with ggplot
This is a follow on from the post Using apply sapply and lappy in R.
The dataset we are using was created like so:
The dataset we are using was created like so:
m <- matrix(data=cbind(rnorm(30, 0), rnorm(30, 2), rnorm(30, 5)), nrow=30, ncol=3)
Three columns of 30 observations, normally distributed with means of 0, 2 and 5. We want a density plot to compare the distributions of the three columns using ggplot.
First let's give our matrix some column names:
colnames(m) <- c('method1', 'method2', 'method3')
head(m)
# method1 method2 method3
#[1,] 0.06288358 2.7413567 4.420209
#[2,] -0.11240501 3.4126550 4.827725
#[3,] 0.02467713 1.0868087 4.044101
ggplot has a nice function to display just what we were after geom_density and it's counterpart stat_density which has more examples.
ggplot likes to work on data frames and we have a matrix, so let's fix that first
df <- as.data.frame(m)
df
# method1 method2 method3
#1 0.06288358 2.7413567 4.420209
#2 -0.11240501 3.4126550 4.827725
#3 0.02467713 1.0868087 4.044101
#4 -0.73854932 -0.4618973 3.668004
Enter stack
What we would really like is to have our data in 2 columns, where the first column contains the data values, and the second column contains the method name.
Enter the base function stack, which is a great little function giving just what we need:
dfs <- stack(df)
dfs
# values ind
#1 0.06288358 method1
#2 -0.11240501 method1
#…
#88 5.55704736 method3
#89 6.40128267 method3
#90 3.18269138 method3
We can see the values are in one column named values, and the method names (the previous column names) are in the second column named ind. We can confirm they have been turned into a factor as well:
is.factor(dfs[,2])
#[1] TRUE
stack has a partner in crime, unstack, which does the opposite:
unstack(dfs)
# method1 method2 method3
#1 0.06288358 2.7413567 4.420209
#2 -0.11240501 3.4126550 4.827725
#3 0.02467713 1.0868087 4.044101
#4 -0.73854932 -0.4618973 3.668004
Back to ggplot
So, lets try plot our densities with ggplot:
ggplot(dfs, aes(x=values)) + geom_density()
The first argument is our stacked data frame, and the second is a call to the aes function which tells ggplot the 'values' column should be used on the x-axis.
However, our plot is not quite looking how we wish:
Hmm.
We want to group the values by each method used. To do this we will use the 'ind' column, and we tell ggplot about this by using aes in the geom_density call:
ggplot(dfs, aes(x=values)) + geom_density(aes(group=ind))
This is getting closer, but it's not easy to tell each one apart. Let's try colour the different methods, based on the ind column in our data frame.
ggplot(dfs, aes(x=values)) + geom_density(aes(group=ind, colour=ind))
Looking better. I'd like to have the density regions stand out some more, so will use fill and an alpha value of 0.3 to make them transparent.
ggplot(dfs, aes(x=values)) + geom_density(aes(group=ind, colour=ind, fill=ind), alpha=0.3)
That is much more in line with what I wanted to see. Note that the alpha argument is passed to geom_density() rather than aes().
That's all for now.
Using apply, sapply, lapply in R
This is an introductory post about using apply, sapply and lapply, best suited for people relatively new to R or unfamiliar with these functions. There is a part 2 coming that will look at density plots with ggplot, but first I thought I would go on a tangent to give some examples of the apply family, as they come up a lot working with R.
I have been comparing three methods on a data set. A sample from the data set was generated, and three different methods were applied to that subset. I wanted to see how their results differed from one another.
I would run my test harness which returned a matrix. The columns values were the metric used for evaluation of each method, and the rows were the results for a given subset. We have three columns, one for each method, and lets say 30 rows, representing 30 different subsets that the three methods were applied to.
It looked a bit like this
method1 method2 method3
[1,] 0.05517714 0.014054038 0.017260447
[2,] 0.08367678 0.003570883 0.004289079
[3,] 0.05274706 0.028629661 0.071323030
[4,] 0.06769936 0.048446559 0.057432519
[5,] 0.06875188 0.019782518 0.080564474
[6,] 0.04913779 0.100062929 0.102208706
We can simulate this data using rnorm, to create three sets of observations. The first has mean 0, second mean of 2, third of mean of 5, and with 30 rows.
m <- matrix(data=cbind(rnorm(30, 0), rnorm(30, 2), rnorm(30, 5)), nrow=30, ncol=3)
Apply
When do we use apply? When we have some structured blob of data that we wish to perform operations on. Here structured means in some form of matrix. The operations may be informational, or perhaps transforming, subsetting, whatever to the data.
As a commenter pointed out, if you are using a data frame the data types must all be the same otherwise they will be subjected to type conversion. This may or may not be what you want, if the data frame has string/character data as well as numeric data, the numeric data will be converted to strings/characters and numerical operations will probably not give what you expected.
As a commenter pointed out, if you are using a data frame the data types must all be the same otherwise they will be subjected to type conversion. This may or may not be what you want, if the data frame has string/character data as well as numeric data, the numeric data will be converted to strings/characters and numerical operations will probably not give what you expected.
Needless to say such circumstances arise quite frequently when working in R, so spending some time getting familiar with apply can be a great boon to our productivity.
Which actual apply function and which specific incantion is required depends on your data, the function you wish to use, and what you want the end result to look like. Hopefully the right choice should be a bit clearer by the end of these examples.
First I want to make sure I created that matrix correctly, three columns each with a mean 0, 2 and 5 respectively. We can use apply and the base mean function to check this.
We tell apply to traverse row wise or column wise by the second argument. In this case we expect to get three numbers at the end, the mean value for each column, so tell apply to work along columns by passing 2 as the second argument. But let's do it wrong for the point of illustration:
apply(m, 1, mean)
# [1] 2.408150 2.709325 1.718529 0.822519 2.693614 2.259044 1.849530 2.544685 2.957950 2.219874
#[11] 2.582011 2.471938 2.015625 2.101832 2.189781 2.319142 2.504821 2.203066 2.280550 2.401297
#[21] 2.312254 1.833903 1.900122 2.427002 2.426869 1.890895 2.515842 2.363085 3.049760 2.027570
Passing a 1 in the second argument, we get 30 values back, giving the mean of each row. Not the three numbers we were expecting, try again.
apply(m, 2, mean)
#[1] -0.02664418 1.95812458 4.86857792
Great. We can see the mean of each column is roughly 0, 2, and 5 as we expected.
Our own functions
Let's say I see that negative number and realise I wanted to only look at positive values. Let's see how many negative numbers each column has, using apply again:
apply(m, 2, function(x) length(x[x<0]))
#[1] 14 1 0
So 14 negative values in column one, 1 negative value in column two, and none in column three. More or less what we would expect for three normal distributions with the given means and sd of 1.
Here we have used a simple function we defined in the call to apply, rather than some built in function. Note we did not specify a return value for our function. R will magically return the last evaluated value. The actual function is using subsetting to extract all the elements in x that are less than 0, and then counting how many are left are using length.
The function takes one argument, which I have arbitrarily called x. In this case x will be a single column of the matrix. Is it a 1 column matrix or a just a vector? Let's have a look:
apply(m, 2, function(x) is.matrix(x))
#[1] FALSE FALSE FALSE
Not a matrix. Here the function definition is not required, we could instead just pass the is.matrix function, as it only takes one argument and has already been wrapped up in a function for us. Let's check they are vectors as we might expect.
apply(m, 2, is.vector)
#[1] TRUE TRUE TRUE
Why then did we need to wrap up our length function? When we want to define our own handling function for apply, we must at a minimum give a name to the incoming data, so we can use it in our function.
apply(m, 2, length(x[x<0]))
#Error in match.fun(FUN) : object 'x' not found
We are referring to some value x in the function, but R does not know where that is and so gives us an error. There are other forces at play here, but for simplicity just remember to wrap any code up in a function. For example, let's look at the mean value of only the positive values:
apply(m, 2, function(x) mean(x[x>0]))
#[1] 0.4466368 2.0415736 4.8685779
Using sapply and lapply
These two functions work in a similar way, traversing over a set of data like a list or vector, and calling the specified function for each item.
Sometimes we require traversal of our data in a less than linear way. Say we wanted to compare the current observation with the value 5 periods before it. Use can probably use rollapply for this (via quantmod), but a quick and dirty way is to run sapply or lapply passing a set of index values.
Here we will use sapply, which works on a list or vector of data.
sapply(1:3, function(x) x^2)
#[1] 1 4 9
lapply is very similar, however it will return a list rather than a vector:
lapply(1:3, function(x) x^2)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 9
Passing simplify=FALSE to sapply will also give you a list:
sapply(1:3, function(x) x^2, simplify=F)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 9
And you can use unlist with lapply to get a vector.
unlist(lapply(1:3, function(x) x^2))
#[1] 1 4 9
However the behviour is not as clean when things have names, so best to use sapply or lapply as makes sense for your data and what you want to receive back. If you want a list returned, use lapply. If you want a vector, use sapply.
Dirty Deeds
Anyway, a cheap trick is to pass sapply a vector of indexes and write your function making some assumptions about the structure of the underlying data. Let's look at our mean example again:
sapply(1:3, function(x) mean(m[,x]))
[1] -0.02664418 1.95812458 4.86857792
We pass the column indexes (1,2,3) to our function, which assumes some variable m has our data. Fine for quickies but not very nice, and will likely turn into a maintainability bomb down the line.
We can neaten things up a bit by passing our data in an argument to our function, and using the … special argument which all the apply functions have for passing extra arguments:
sapply(1:3, function(x, y) mean(y[,x]), y=m)
#[1] -0.02664418 1.95812458 4.86857792
This time, our function has 2 arguments, x and y. The x variable will be as it was before, whatever sapply is currently going through. The y variable we will pass using the optional arguments to sapply.
In this case we have passed in m, explicitly naming the y argument in the sapply call. Not strictly necessary but it makes for easier to read & maintain code. The y value will be the same for each call sapply makes to our function.
I don't really recommend passing the index arguments like this, it is error prone and can be quite confusing to others reading your code.
I hope you found these examples helpful. Please check out part 2 where we create a density plot of the values in our matrix.
If you are working with R, I have found this book very useful day-to-day R Cookbook (O'Reilly Cookbooks)
Tuesday, August 28, 2012
Generative Sphere 2
Hey all, thought I would take my fancy new hardware for a spin and made this
For those interested, it uses 2 GLSL Shaders, one that takes the spectral curve as input and uses a ping-pong FBO to calculate the offsets, and the other to turn those offsets into displacement, colour etc.
For those interested, it uses 2 GLSL Shaders, one that takes the spectral curve as input and uses a ping-pong FBO to calculate the offsets, and the other to turn those offsets into displacement, colour etc.
Tuesday, July 31, 2012
Apple is really cool
My secret shame
I am a hardware luddite, and have basically zero interest in gadgets for gadgets sake. Only in February this year did I upgrade from my Nokia 6600. I am also terrible at assembling things. Once I bought a plastic peg basket consisting of three separate parts, two sides and a flexible body bit you snapped in to the sides. Despite the apparent simplicity I somehow managed to fail while attempting its assembly. Got it the second time though. In my high school woodshop class, my final project got an A for the idea and a C for the execution ... it's just not my forte.
My new macbook finally arrived. When I am looking for hardware, I try to do the bare minimum to ensure what that I buy will do what I actually need, and that's it. I only really upgraded as I needed some specific hardware for some graphics stuff.
So for a one paragraph review, and as someone who doesn't really care about hardware, it is amazing. It is light, quiet and incredibly fast. The retina display is markedly better than anything I have seen, it is more or less impossible to not notice the difference, despite how little one thinks they care about such matters.
Junk
One of the things that has engaged my time the last month or so was visiting my parents and cleaning out a lot of my old junk, which has lain dormant at their house for who knows how many years. Although it pained me greatly at the time, I threw out the following machines:
These are all UNIX workstations. If you don't know what that is don't worry, they are all horribly obsolete and all of the companies that made them are either bust, bought out or have abandoned the ideas behind them.
The second one from the bottom of that stack is a HP Visualize C200 running HP-UX. It's huge and clocks in at 17 kg, all for a 200 MHz cpu. As a ballpark reference the A5 cpu in the iPhone can run at 800 - 1000 Mhz. The blue machines come from SGI, and behind them are 2 CRT monitors also from SGI which weigh about 20kg each. All up it's probably over 100 kg of hardware.
Having spent so much time with these machines, this macbook sitting next to me is seems other worldly. It is orders of magnitude faster than all of those machines combined. Due to the larger screen, it is bigger than my current laptop yet lighter, and height wise it's about half the width of my thumb. I can't help but be impressed by it's engineering, how did they get so much stuff in something so small and light?
Apple is cool for other reasons
I spent some time the last few days seeing just how much of an outlier Apple really is relative to other companies. It can be a little hard to get your head around why that may be, but this is how I think of it, and why I think they will continue to be successful for the foreseeable future.
Take the microcosm of a free to air TV station as an example. In a nutshell, a production company will make a show and license it to the station for a fee. The station will show it for free and sell advertising to companies wanting to reach the viewers who watch it.
Now instead, imagine that the production company bought the equipment to make the show from the station, paid the station to broadcast its show, and gives the station a cut of any revenue it generates. That revenue is generated from consumers who also bought their TV from station. Throw some advertisers giving the station money in the mix there as well. Actual TV is not yet where it could be, but for software and music, that's how it works for Apple. I can't help but find it kinda cool. TV and movies are there in some form, but so far only nerds and youngish people watch that stuff on their computer.
This also says nothing about Apple's control over supply of the components used to make their hardware, as well as their patents. There's a reason why the trackpad on every other brand of laptop sucks. The success could easily breed complacency, but that hasn't happened yet. They make good products that do what they say on the box, which is something that seems simple but so many other companies fail at.
No company is infallible, but they have a very strong position and have made a great success out of a new way to do things. I don't know of any other company that has been so successful while bringing about such a huge change (and it is a huge change). Amazon and Google have done a lot too, but I think Apple has gone further. I would love to hear of any others.
Monday, July 30, 2012
Multidimensional Scaling and Company Similarity
Background and idea
Often we are looking at a particular sector, and want to get a quick overview of a group of companies relative to one another. I thought I might apply Multidimensional Scaling (MDS) to various financial ratios and see if it gave us anything useful.
The premise is that companies in similar industries should all have a degree of sameness, so MDS might be useful to highlight the companies that stand out from the crowd, perhaps in some literal sense ...
Method
I mostly use the data functions from quantmod to retrieve the financial statements from Google Finance. As always with free data, the quality is variable, but good enough for our purpose today. We need to do a bit of dancing to get the market price at the time the results were released, and this uses data from Yahoo Finance. It was a little bit more work to implement, but worth it so we can include P/E in the comparison.
I looked at two groups of companies, tech stocks and financials/banks.
For the tech stocks I used ROE, EPS, P/E, Operating Margin, Current Ratio, Gearing, Asset Turnover and Debt Ratio. For the financials, I used ROE, EPS, P/E, Gearing and Debt Ratio, mainly because the data available did not have the line items required to calculate the other ratios.
The data from Google gives the last four periods, with the most recent coming first. It also gives Annual and Quarterly data and the charts below use the annual results. Annual Period 1 means the most recent results. Due to the scaling function, the actual scales on the graphs are not particularly meaningful, so I took them out.
Charts
These are the charts for the most recent results (so end of year 2011). Overall, I am quite pleased with the results. We can see how most of the companies cluster together, while a few seem to be quite different. This shows at a glance the companies that might be worthy of further investigation.
Tech Stocks
Financials
Outro
Code is up here MDS Company Similarity with R, it should hopefully be documented enough for others to mess around with. Any questions, comments or suggestions are very much appreciated as always.
As an aside, this is the first R program I wrote devoid of any for loops. I finally feel I am coming to grips with the language.
As an aside, this is the first R program I wrote devoid of any for loops. I finally feel I am coming to grips with the language.
Tuesday, July 24, 2012
Particle swarm and Perlin noise
It has been a little too quiet here for my liking. For better or worse I have just been caught up with real life matters, mostly boring stuff like studying and moving and helping people move, so not even any juicy gossip to share.
Actually last weekend my credit card number somehow got stolen, which meant the new laptop I had on order has been postponed while I wait for my new card. I had been planning to do a bunch more stuff once it arrived as my current one is showing its age a bit, but I ordered it in June and there was a 4 week wait till it shipped, then the card thing happened the day before it was going to ship! But that's about it.
I did manage to get this done over the weekend, it's 150k particles traversing a vector field generated from Perlin Noise. When the new machine arrives I want to delve into GPU programming and 1 million particles is the goal.
Anyway, it's a bit cold and wet here right now, hope you're somewhere sunny and warm.
Music is Olson by Boards of Canada.
Actually last weekend my credit card number somehow got stolen, which meant the new laptop I had on order has been postponed while I wait for my new card. I had been planning to do a bunch more stuff once it arrived as my current one is showing its age a bit, but I ordered it in June and there was a 4 week wait till it shipped, then the card thing happened the day before it was going to ship! But that's about it.
I did manage to get this done over the weekend, it's 150k particles traversing a vector field generated from Perlin Noise. When the new machine arrives I want to delve into GPU programming and 1 million particles is the goal.
Anyway, it's a bit cold and wet here right now, hope you're somewhere sunny and warm.
Music is Olson by Boards of Canada.
Subscribe to:
Posts (Atom)






