Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created August 18, 2013 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/6263927 to your computer and use it in GitHub Desktop.
Save tmcw/6263927 to your computer and use it in GitHub Desktop.

npm install glob canvas leftpad rainbow-dash moment

var glob = require('glob'),
fs = require('fs'),
dsv = require('dsv'),
moment = require('moment');
var paths = [];
var stops = dsv(',').parse(fs.readFileSync('../data/stop_times.txt', 'utf8'));
var stopid = null, points = [];
function timeSeconds(s) {
var pts = s.split(':');
return (parseInt(pts[0], 10) * 60 * 60) +
(parseInt(pts[1], 10) * 60) +
(parseInt(pts[2], 10));
}
for (var i = 0; i < stops.length; i++) {
if (stopid !== stops[i].trip_id && points.length) {
paths.push(points);
points = [];
stopid = stops[i].trip_id;
}
points.push({
dist: parseFloat(stops[i].shape_dist_traveled),
time: timeSeconds(stops[i].arrival_time),
});
}
var curves = [];
for (var i = 0; i < paths.length; i++) {
if (paths[i].length > 1) {
var curve = [];
for (var j = 1; j < paths[i].length; j++) {
curve.push([
paths[i][j].time - paths[i][0].time,
Math.floor((paths[i][j].time - paths[i][j - 1].time) /
(paths[i][j].dist - paths[i][j - 1].dist))
]);
}
curves.push(curve);
}
}
fs.writeFileSync('curves.json', JSON.stringify(curves));
var Canvas = require('canvas'),
glob = require('glob'),
fs = require('fs'),
rainbowDash = require('rainbow-dash'),
leftpad = require('leftpad'),
width = 2560,
height = 1280,
moment = require('moment'),
radius = 100,
c = new Canvas(width, height + 100),
ctx = c.getContext('2d');
var speeds = JSON.parse(fs.readFileSync('curves.json'));
var hexOut = rainbowDash({ outputFormat: 'hex' }, {
0: '#0000ff',
0.5: 'rgb(0,255,0)',
1: '#ff0000'
});
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = hexOut(0);
ctx.globalAlpha = 0.1;
ctx.globalCompositeOperation = 'multiply';
console.log(speeds.length, ' to do');
for (var i = 0; i < speeds.length; i++) {
if (i % 800 === 0) {
console.log(i, ' done');
ctx.strokeStyle = hexOut(i / speeds.length);
}
ctx.beginPath();
for (var x = 0; x < speeds[i].length; x++) {
ctx.lineTo(~~(speeds[i][x][0] / 2.5), ~~(height - (speeds[i][x][1])));
}
ctx.stroke();
}
fs.writeFileSync('speed.png', c.toBuffer());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment