Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!DOCTYPE html>
<html>
<head>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script src="https://brechtvdv.github.io/demo-data/n3-browser.js"></script>
  <script src="https://brechtvdv.github.io/demo-data/metricsgraphics.min.js"></script>
  <link href='https://brechtvdv.github.io/demo-data/metricsgraphics.css' rel='stylesheet' type='text/css'>
  <style>
  .flex-container-row {
    display: flex;
    flex-flow: wrap row;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    height:auto;
    margin-bottom: 10px;

  }
  .flex-container-column {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

  }
  .flex-item {
    display: flex;
    margin: 10px 10px;
  }
  .chart {
    margin: auto;
  }
  #orange_light, #red_light, #green_light {
    margin-left: 5%; 
    height: auto; 
    width: 10%; 
    min-width: 75px;
    display: none;
  }
  #ligth_info {
    font-size: 70px;
  }
  }
</style>
</head>
<body>
  <div class="flex-container-column">
    <div class="flex-container-row">
      <div class="vertrek flex-item">
        <p>Departure:&nbsp;</p>
        <select id="vertreklaan">
        </select>
      </div>

      <div class="aankomst flex-item">
        <p>Arrival:&nbsp;</p>
        <select id="aankomstlaan">
        </select>
      </div>
    </div>
    <div class="flex-container-row">
      <img class="flex-item" id="orange_light" src="https://brechtvdv.github.io/demo-data/orange.jpg"/>
      <img class="flex-item" id="red_light" src="https://brechtvdv.github.io/demo-data/red.jpg"/>
      <img class="flex-item" id="green_light" src="https://brechtvdv.github.io/demo-data/green.jpg"/>
      <h3 class="flex-item" id="light_info"/>
    </div>

    <div class="chart" id="chart">
    </div>
  </div>

</body>
</html>
            
          
!
            
              // Make sure Codepen doesn't stop refreshing the data
window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000;

const { DataFactory } = N3;
const { namedNode, literal, defaultGraph, quad } = DataFactory;

//let DATASET_URL = 'http://localhost:8081/rawdata/latest';
let DATASET_URL = 'https://lodi.ilabt.imec.be/observer/rawdata/latest';

let sg = 'https://opentrafficlights.org/id/signalgroup/K648/1';
let SPEED = 100;
let first = true;
let signalgroups = [];
let prevGatGreen = [];
let lastGat, iLastGat, nextLastGat;
let AMOUNT_OF_FRAGMENTS = 15;

let WIDTH, HEIGHT;
if (window.innerWidth > 600) WIDTH = 600;
else WIDTH = 2*window.innerWidth;

if (window.innerHeight > 240) HEIGHT = 240;
else HEIGHT = window.innerHeight;

document.getElementById('chart').style.width = WIDTH;

let vertreklanen = {};

let data = {};

function updateDataGraphic() {
	if (data[sg] && data[sg].length > 0) {
		MG.data_graphic({
		    title: "Waiting time for green light",
		    description: "Amount of seconds to wait before the traffic light shows green.",
        	chart_type: 'point',
          	//markers: [{'generatedAtTime': new Date("2019-01-28T17:09:00"), 'label': 'Nu'}],
            point_size: '1',
		    data: data[sg],
            top: 70,
            width: WIDTH,
            height: HEIGHT,
	        right: 40,
		    target: '.chart',
		    x_accessor: 'generatedAtTime',
		    y_accessor: 'timeTillGreen',
	     	mouseover: function(d, i) {
            let format = d3.timeFormat("%Hh %Mm %Ss");
            d3.select('.chart svg .mg-active-datapoint')
                .text(Math.round(d.data.timeTillGreen) + " seconds at " + format(d.data.generatedAtTime));
        	},
        	xax_format: function (d, i) {
        		let format = d3.timeFormat("%H:%M:%S");
                return format(d);
        	}
		});
	}
}

function setDataGraphicEmpty() {
	MG.data_graphic({
		 title: "Waiting time for green light",
    description: "Amount of seconds to wait before the traffic light shows green.",
        error: 'No data found.',
    	chart_type: 'missing-data',
    	top: 70,
        width: 600,
        height: 240,
        right: 40,
	    target: '.chart',
    	missing_text: 'No data found.'
    });
}

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}


start();

async function start() {
	let doc = await download(DATASET_URL)
	let store = await parseAndStoreQuads(doc);
	signalgroups = await getSignalgroups(store);
	initConfiguration(store);

	// Init
	signalgroups.forEach((sg) => {
		prevGatGreen[sg] = null;
		data[sg] = [];
	});

	while(true) {
		await calcHistoricData(store);
		showLatest(store);

		let count = 0;

		// HISTORY
		let prev = store.getQuads(null, namedNode('http://www.w3.org/ns/hydra/core#previous'), null)[0];
		while (prev && count < AMOUNT_OF_FRAGMENTS) {
			count++;

			doc = await download(prev.object.value);
			store = await parseAndStoreQuads(doc);

			await calcHistoricData(store);

			prev = store.getQuads(null, namedNode('http://www.w3.org/ns/hydra/core#previous'), null)[0];
		}

		updateDataGraphic();

		doc = await download(DATASET_URL)
		store = await parseAndStoreQuads(doc);
		
		signalgroups.forEach((sg) => {
			prevGatGreen[sg] = null;
			data[sg] = [];
		});

		await sleep(SPEED)
	}
}

async function calcHistoricData(_store) {
	// Loop over observations order descending
	let observations = _store.getQuads(null, namedNode('http://www.w3.org/ns/prov#generatedAtTime'), null);
	observations.sort(function(a, b) {
		a = new Date(a.object.value).getTime();
		b = new Date(b.object.value).getTime();

		return a>b ? -1 : a<b ? 1 : 0;
	}).forEach((observation) => {
		let generatedAtTime = new Date(observation.object.value);

		if (!lastGat) lastGat = generatedAtTime;

		// Loop over all signalstates in the observation
		_store.getQuads(null, namedNode('https://w3id.org/opentrafficlights#signalState'), null, observation.subject).forEach((signalstateQuad) => {
			let signalgroup = signalstateQuad.subject.value;
			let signalphase = _store.getQuads(signalstateQuad.object, namedNode('https://w3id.org/opentrafficlights#signalPhase'), null, observation.subject)[0];
			let timeTillGreen;
			// When green
			if (signalphase.object.value === 'https://w3id.org/opentrafficlights/thesauri/signalphase/6' || signalphase.object.value === 'https://w3id.org/opentrafficlights/thesauri/signalphase/5') {
				prevGatGreen[signalgroup] = generatedAtTime;
				timeTillGreen = 0;
			}

			if (prevGatGreen[signalgroup] != null){
				timeTillGreen = (prevGatGreen[signalgroup].getTime() - generatedAtTime.getTime())/1000;

				// There's probably a data gap when this is very big
				if (timeTillGreen < 100) {
					if (!data[signalgroup]) data[signalgroup] = [];

					data[signalgroup].unshift({
						'generatedAtTime': new Date(generatedAtTime),
						'timeTillGreen': timeTillGreen
					})
				}
			}
		});
	});
}

async function getSignalgroups(_store) {
	let signalgroups = [];
	await _store.getQuads(null, namedNode('http://www.w3.org/2000/01/rdf-schema#type'), namedNode('https://w3id.org/opentrafficlights#Signalgroup')).forEach( (quad) => {
		signalgroups.push(quad.subject.value);
	});
	return signalgroups;
}

function download(_url) {
  return new Promise(resolve => {
    fetch(_url)
	  .then(function(response) {
	  	return response.text();
	  })
	  .then(function(text) {
	  	resolve(text);
	  });
  });
}	

function parseAndStoreQuads(_doc) {
	return new Promise(resolve => {
		const parser = new N3.Parser();
		const store = N3.Store();
		parser.parse(_doc, (error, quad, prefixes) => {
		    if (quad)
				store.addQuad(quad);
			else
				return resolve(store);
		});
	})
}

function initConfiguration(_store) {
	// Set departure lanes
	let options = '';
	let processedDepartureLanes = [];
	_store.getQuads(null, namedNode('https://w3id.org/opentrafficlights#departureLane'), null).forEach((quad) => {
			_store.getQuads(quad.object, namedNode('http://purl.org/dc/terms/description'), null).forEach( (quad) => {
		if (!processedDepartureLanes.includes(quad.object.value)){
							processedDepartureLanes.push(quad.object.value);

					options +=
					'<option value="' +
					quad.subject.value +
					'">' +
					quad.object.value +
					"</option>";
		}

				// Load arrival lanes
				_store.getQuads(null, namedNode('https://w3id.org/opentrafficlights#departureLane'), quad.subject).forEach((connectie) => {
					let signalgroup = _store.getQuads(connectie.subject, namedNode('https://w3id.org/opentrafficlights#signalGroup'), null)[0].object.value;
					_store.getQuads(connectie.subject, namedNode('https://w3id.org/opentrafficlights#arrivalLane'), null).forEach( (arrivalLane) => {
						_store.getQuads(arrivalLane.object, namedNode('http://purl.org/dc/terms/description'), null).forEach( (descr) => {
							if(!vertreklanen[quad.subject.value]) vertreklanen[quad.subject.value] = [];
							vertreklanen[quad.subject.value][arrivalLane.object.value] = {
								'@id': arrivalLane.object.value,
								'http://purl.org/dc/terms/description': descr.object.value,
								'https://w3id.org/opentrafficlights#signalGroup': signalgroup
							};
						});
					});
				});
			});
	});
	document.getElementById("vertreklaan").innerHTML = options;

	// Load arrival lanes dropdown list
	changeAankomstlanen();
}

$("#vertreklaan").on("change", function() {
	changeAankomstlanen();

	// Set active signalgroup for visualization
	checkActiveSignalgroup();
});

$("#aankomstlaan").on("change", function() {
	checkActiveSignalgroup();
});

function changeAankomstlanen() {
	let aankomstlanen = [];
	const vertreklaan = document.getElementById("vertreklaan").value;
	let options = '';
	for (let aankomstlaan in vertreklanen[vertreklaan]) {
		if (!aankomstlanen.includes(vertreklanen[vertreklaan][aankomstlaan]['http://purl.org/dc/terms/description'])) {
			options +=
			'<option value="' +
			vertreklanen[vertreklaan][aankomstlaan]['@id'] +
			'">' +
			vertreklanen[vertreklaan][aankomstlaan]['http://purl.org/dc/terms/description'] +
			"</option>";
			aankomstlanen.push(vertreklanen[vertreklaan][aankomstlaan]['http://purl.org/dc/terms/description']);
		}
	}
		
	document.getElementById("aankomstlaan").innerHTML = options;
}

function checkActiveSignalgroup() {
	const vertreklaan = document.getElementById("vertreklaan").value;
	const aankomstlaan = document.getElementById("aankomstlaan").value;
	if (vertreklanen[vertreklaan][aankomstlaan]['https://w3id.org/opentrafficlights#signalGroup']) {
		sg = vertreklanen[vertreklaan][aankomstlaan]['https://w3id.org/opentrafficlights#signalGroup'];
		updateDataGraphic();
	} else {
		setDataGraphicEmpty()
	}
}

async function showLatest(_store) {
	// Loop over observations order descending
	let observations = _store.getQuads(null, namedNode('http://www.w3.org/ns/prov#generatedAtTime'), null);
	let latest = observations.sort(function(a, b) {
		a = new Date(a.object.value).getTime();
		b = new Date(b.object.value).getTime();

		return a>b ? -1 : a<b ? 1 : 0;
	})[0];

	let generatedAtTime = latest.object.value;

	// Get state of active signalgroup
	let signalstate = _store.getQuads(namedNode(sg), namedNode('https://w3id.org/opentrafficlights#signalState'), null, latest.subject)[0];
	if (signalstate) {
		let minEndTime = _store.getQuads(signalstate.object, namedNode('https://w3id.org/opentrafficlights#minEndTime'), null, latest.subject)[0];
		let maxEndTime = _store.getQuads(signalstate.object, namedNode('https://w3id.org/opentrafficlights#maxEndTime'), null, latest.subject)[0];
		let signalPhase = _store.getQuads(signalstate.object, namedNode('https://w3id.org/opentrafficlights#signalPhase'), null, latest.subject)[0];
		
		let count = Math.round((new Date(minEndTime.object.value).getTime() - new Date(generatedAtTime).getTime())/1000);
		if (minEndTime.object.value === maxEndTime.object.value) {
			showCounterLabel(count, signalPhase.object.value);	
		} else {
			showCounterLabel("> " + count, signalPhase.object.value);
		}
	}
}

function showCounterLabel(counter_, label_) {
      const info = '<h3>&nbsp;&nbsp;' + counter_ + " seconds</h3>";

      // const info = '<h3 style="float: left">' + label_ + '</h3><h1 style="font-size: 100px;">' + counter_ + '</h1></div>';
      if (label_ === 'https://w3id.org/opentrafficlights/thesauri/signalphase/2' || label_ === 'https://w3id.org/opentrafficlights/thesauri/signalphase/3') {
        // Red
        document.getElementById("orange_light").style.display = "none";
        document.getElementById("green_light").style.display = "none";
        document.getElementById("red_light").style.display = "flex";
      }
      else if (label_ === 'https://w3id.org/opentrafficlights/thesauri/signalphase/5' || label_ === 'https://w3id.org/opentrafficlights/thesauri/signalphase/6') {
        // green
        document.getElementById("red_light").style.display = "none";
        document.getElementById("orange_light").style.display = "none";
        document.getElementById("green_light").style.display = "flex";
      }
      else {
        // orange
        document.getElementById("red_light").style.display = "none";
        document.getElementById("green_light").style.display = "none";
        document.getElementById("orange_light").style.display = "flex";
      }
      
      document.getElementById('light_info').innerHTML = info;
    }
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console