Thursday, May 14

Back to the Future

One point twenty one gigaWatts!

Time travel. Okay, so here's the deal. There's really nothing in the laws of physics which explicity prevent it under any circumstance. In fact, there's an abundance of loopholes and nifty tricks you can theoretically perform using current theories and exotic measures.

First, the future.

This is easy. Einstein's Theory of Special Relativity tells us (and this is totally 100% true) that the faster things move, the heavier they get, the thinner they get, and they experience less time than someone standing still. This effect is only really noticable when you get near to light speed.

So, you could zoom around in a spaceship at say 90% of the speed of light, return to Earth one year later - but you'd find it was actually two years later on Earth! The faster you go, the further you travel forward in time relative to everyone else.

Of course, going that fast takes a huge amount of energy, and the faster you go, the harder it gets to go faster. You can't reach light speed. So it'd generally be better to not have to go so fast in order to travel forwards. Thanks to Einstein's Theory of General Relativity - we don't have to. Instead, we bend space-time around ourselves to get a similar effect.

This is what's known as a gravity well. All matter bends space-time around it, and the more of it you get in one place (density), the steeper the sides of the well. If you could compact, say, a large planet like Jupiter down to... about the size of the Atomium in Brussels, then get inside - you'd get a very similar effect.


A lot of time travel tricks revolve around bending this space-time membrane in such a way that our normal everyday view of the world becomes warped, and things that seem completely impossible are in fact the only mathematically valid solution. We've demonstrated the future, is easy enough, but what about the past?

Coming Soon: Back To The Future II - wormholes, cosmic strings and other cheap tricks

CovertHolistic

Sunday, May 10

The Most Beautiful Equations

Sometimes mathematics is beautiful. It's a hard thing to observe; you need to peer through various mystifying levels of symmetries and distractions, until you finally arrive at that most elusive moment where you suddenly realise it's all really simple.

Many of the greatest equations, theories and postulates have relied on the power of their beauty. Einstein's E=mc2 has entered the public consciousness like no other, while many others intrigued and delighted the scientific community without much publicity.

Gauss
Gauss's integral for example, reduces this technically baffling integral to a silly and simple number - albeit one which goes on forever.. 1.772453850905516027298167483314...

Comprehending the lateral method used to solve this problem was a major moment in my scientific education. The solution appears to be infinitely unsolvable, if you think of 'x' being a straight line, which as far as any really grasped, was mostly what integration seemed to be about.

However, if you instead think of this problem in two equal dimensions, you can bend the co-ordinates into a circle. Suddenly, as the circle closes, the difficult bit drops off and you can solve the bugger easily to get 1.77...

This identity is used heavily in quantum mechanics, in fact - the whole field is underpinned by the kind of logic used in this solution.

Euler

Euler also used circles to describe other strange and useful numbers. Imagine a second hand travelling round the clock face. Imagine a straight line drawn from 9 to 3. The question is, how far away from that line is the tip of the second hand, as it travels round? If you plot a graph of that distance against time, you'll get a sine wave:



If you instead imagine a straight line between 12 and 6, and plot that, you'll get the same thing, except the start point will be a quarter of a circle further round. These two waves, one '3 hours' out of phase with the other, are called sin and cos.

We would usually use an angle called a radian instead of the clock metaphor. A clock has 12 hours, a circle has radians - twice the number π. So the two waves are π/2 ( 2π / 4 ) out of phase, and the two waves are sinθ and cosθ where θ revolves all the way around from 0 to 2π, like the hand making a full revolution.

Euler showed us that you can treat sin and cos as really the same things, if you use something called an imaginary number.

Okay, I'm thinking of a number. What is it? "Well.. " you say, "it could be anywhere between zero and infinity!" What about negative numbers? "Well, minus infinity to infinity then!".

And you'd have me there. But suppose instead I was thinking of the square of a number, there'd be no point guessing a negative number because any number, positive or negative, gives you a positive number when you square it. In fact, if someone claims they've thought of one, well, it can't be real can it? No real numbers do that! Must be some kind of.. imaginary number, hah!

In mathematics, existing and being real thankfully don't have to mean the same thing, so we can imagine numbers which exist but aren't real. They'll actually really useful, and in fact have a lot to do with circles, and waves, and lots of really geeky physics stuff.


Don't worry if that's a bit confusing, The point is, when you combine in the radian idea, the sin and cos, the imaginary number idea, and the exponential (I won't go into that here - check the link at betterexplained.com) you arrive at the most startlingly simple statement:

This, I believe, is the most beautiful equation. The soaring exponential, the elusive imaginary, the reliable circle, the triumphant '1', then equality to nothing. It's the poetry of the universe, and it's just the first line.

Thursday, May 7

Learn PHP - 10 Things for a Beginner

I've been ranting about PHP quite a bit, demonstrating some of the ways I've used it in mashups and applications. I love it, because it's a great glue for ramming different bitz 'n' bobs into each other using the mimimum fuss.

I seem to have vomited scripts a bit too much, and thought it would be a good idea to get back to basics for anyone who doesn't know PHP but fancies learning - 10 simple things about it:

1 -- Variables! Put a dollar sign in front of any word. You'll need lots to hold all the data, e.g. $day for what day it is, $xml to hold an xml string, $salesLastWeek for.. you get the idea..

2 -- Arrays are variables that can hold lots of data - for example, an array $week which has seven values, the days of the week. So $week[0] is 'Sunday', $week[1] is 'Monday', or whatever you want really.

3 -- IF. If this, do that. If this, do that, if not, then if these, those, otherwise die. Or rather,

if($this == $everything)
$answer = that($it);
else if ($these == $those)
$answer = "those";
else
die();

or something along those lines...

4 -- Say Hello! echo makes stuff come out the other end. echo "Hello World!";

5 -- Instead of IF you can SWITCH.

switch ($today) {
case 'Saturday'
$txt = "I told those fucks down at the league office
a thousand times that I don't roll on Shabbos! ";
break;
case 'Friday'
$ txt = "cause it's Friday; you ain't got no job... and you ain't got shit to do.";
break;
default
$txt = "I can't think of a funny quote.";
}

6 -- So what day is it? idate gives you the bits you need. So:
echo(idate("Y"));
gives you the current year ie. 2009, and use a w intead of Y to get the day of the week. Sunday = 0 etc.

7 -- Make some IFS.
Greater than: if ($it > 45) { do_it($it); }
Or: if ($one > 1 || $two == 3) (do_something($one, $two); }
And is &&. Not is !, as in if (!$it > 45), otherwise known as <= 45.

8. Do Something. That was a function. You can tidy up your code by making bits of it functions. Particularily bits you use a lot or things that feel seperate.

function do_something($one, $two) {
$one.$two+12;
}

There. Now we can "do something" with $one and $two. The dot makes the variables write next to each other. So if $one = 1, and $two = 2, we get 12+12 = 24 when we say:

do something($one, $two);

9 -- SimpleXML. I work with data, and lots of data is XML. $xml = simplexml_load_file($file);

10 -- FOREACH - one of my favourite words. You can loop through each item in an array, or each node in an XML file. Check the link, as always w3schools is an excellent source for basic PHP reference.

There you have it! Did anyone learn anything? Let me know!

--CovertHolistic

Saturday, May 2

Please mind the gap between the software and the platform

Excuse the awful pun. Gapminder.org developed this really neat graphical flash engine back in 2006, Google were quick to snap it up the following year, and have also been so graciously kind as to publish an API for it under the guise of Motion Chart.

You can use this engine freely to include whatever data you want, though getting data in and out can be a pain, if, like me, you want to enable non-programmers to experiment with their own data.

So, the first step might be reconfiguring the source from explicit javascript declarations, to something a little more familiar - xml. I used a structure like this:

<?xml version="1.0" encoding="UTF-8"?>

<bubbleXml>
<title>Hello, this is my first motion chart!</title>
<dataContainer>
<dataRow>
<WeekNo>1</WeekNo>
<Category>Canned Fruit</Category>
<Metrics>Items Sold</Metrics>
<Value>17</Value>
</dataRow>
<dataRow>
<WeekNo>1</WeekNo>
<Category>Canned Fruit</Category>
<Metrics>Sales Value</Metrics>
<Value>23.78</Value>
and so on..

Which gives you a nice extensible data platform, although it is quite verbose (duh.. it's xml!).
Each dataRow captures the time variable (WeekNo), the entity names (Category), along with the name and value of each metric.

You can then write a parser for the xml in your favourite scripting language, and embed the results into the javascript. Here's an example for PHP - verbatim:

<?php

$xmlfile = "dataYouWantToUse.xml";
$data = simplexml_load_file($xmlfile);

$categories = $data->xpath("dataContainer/dataRow/Category");
$timestamp = $data->xpath("dataContainer/dataRow/WeekNo");
$values = $data->xpath("dataContainer/dataRow/Value");
$metrics = $data->xpath("dataContainer/dataRow/Metrics");
$title = $data->xpath("title");

$uCatN = count(array_unique($categories));
$uTimeN = count(array_unique($timestamp));
$uMet = array_unique($metrics);
$uMetN = count(array_unique($metrics));
$rowCount = $uCatN*$uMetN*$uTimeN-1;
$googleCount = $uCatN*$uTimeN;

function listColumns($uMet)
{
echo "\n";
foreach ($uMet as $thisMet) {
echo "\tdata.addColumn('number', \"$thisMet\");\n";
}
}
function generateJs($categories, $timestamp, $values, $rowCount, $uMetN)
{
echo "\n";
$c = 0;
for ($i=0; $i<=$rowCount; $i+=$uMetN) {
if ($timestamp[$i] < 10)
$time = "0".$timestamp[$i];
else
$time = $timestamp[$i];
echo "\tdata.setValue($c, 0, '$categories[$i]'); \n" ;
echo "\tdata.setValue($c, 1, '2009W$time'); \n" ;
for ($j=$i; $j<=$i+$uMetN-1; $j++) {
$n = $j-$i+$uMetN-1;
echo "\tdata.setValue($c, $n, $values[$j]); \n" ;
}
$c++;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><?php echo $title[0]; ?></title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['motionchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();

data.addRows(<?php echo $googleCount; ?>);
data.addColumn('string', 'Category');
data.addColumn('string', 'Time');
<?php listColumns($uMet);
generateJs($categories, $timestamp, $values, $rowCount, $uMetN); ?>

var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height:460});
}
</script>
<style type="text/css">
body {text-align: center;}
</style>
</head>

<body>
<h3><?php echo $title[0]; ?></h3>
<p> data in motion</p>
<div id="chart_div"></div>
<h5><a href="http://worldofones.blogspot.com">adam marshall 2009</a> | <a href="http://worldofones.blogspot.com">worldofones.blogspot.com</a> | <a href="http://code.google.com">powered by google</a></h5>
</body>
</html>
Notes:
That's set up to process time in the '2009W1' format - haven't got round to generalising that yet, but it's not too hard to modify if you want to use different formats. Likewise for the inclusion of text (colour category) metrics - you just need to modify the listColumns() function, and make sure you've got quotes around their values.
Phew! So, you can load that xml file directly into the page at runtime. Maybe you can get your IT guys to help making a current data source available as xml in this way; if not - here's a little script for converting a csv file to xml courtesy of Chris M over at bytemycode.com, with just a few modifications to create the chosen format.

<?php

// define params
$containerLabel = "dataContainer";
$rowLabel = "dataRow";
$fileLocation = "csvdata/".$_GET["from"].".csv";
$fileDestination = "xmldata/".$_GET["to"].".xml";
$title = $_GET["title"];
/**
* Converts a grid layout CSV to an XML
* Rows are nested within the container variable
* Column headers in the CSV become tags containing the data, within each row
*/
function csv2xml($file, $container = 'data', $rows = 'row')
{
$r = "\t<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();

$handle = @fopen($file, 'r');
if (!$handle) return $handle;

while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
if ($row > 0) $r .= "\t\t<{$rows}>\n";
if (!$cols) $cols = count($data);
for ($i = 0; $i < $cols; $i++) {
if ($row == 0) {
$titles[$i] = $data[$i];
continue;
}
$r .= "\t\t\t<{$titles[$i]}>";
$r .= $data[$i];
$r .= "</{$titles[$i]}>\n";
}
if ($row > 0) $r .= "\t\t</{$rows}>\n";
$row++;
}
fclose($handle);
$r .= "\t</{$container}>\n";
return $r;
}

$xml = csv2xml($fileLocation, $containerLabel, $rowLabel);
$fullxml = '<?xml version="1.0" encoding="UTF-8"?>'."\n
<bubbleXml>\n\t<title>$title</title>\n".$xml."</bubbleXml>";
file_put_contents($fileDestination,$fullxml);

?>


I've added GET parameters to this, so if you had a csv file caled 'data1' in a folder on the server called 'csvdata', you can call using the parameters:
?from=data1&to=fileYouWantToUse&title=Hello, this is my first motion chart!
to create the xml file. Now, you should be able to use excel/analytics software/business intelligence tools to produce the csv, compile it to xml, and display it in a cool motion chart!

Why not show your CEO his company's history in motion, or your sales team the last few weeks of consumer trends?