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.

            
              body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}


.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
}

.App-header {
  background-color: white;
  min-height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  /*align-items: center;*/
  /*justify-content: center;*/
  font-size: calc(10px + 2vmin);
  color: #282c34;
}

.App-title {
  background-color: #282c34;
  color: white;
}

.App-link {
  color: #61dafb;
}

.PredictionBox{
    box-sizing: border-box;
    width: 100%;
    height: 800px; /*600*/
    /*padding: 0;*/
    padding: 10px;
    text-align: center;
    justify-content: center;
}

.MinMaxTable{
    box-sizing: border-box;
    overflow: hidden;
    height: auto;
    margin-top: 5px;
    display: flex;
    justify-content: center;
    color: white;
    /*font-size: 100%;*/
}

.MinMaxTable_minimum_box{
    box-sizing: border-box;
    width: 40%;
    height: 100%;
}
.MinMaxTable_maximum_box{
    box-sizing: border-box;
    width: 40%;
    height: 100%;
}

.MinMaxTable_minimum_title {
    background-color: #12939a;
    float: left;
}

.MinMaxTable_maximum_title {
    background-color: #12939a;
    float: left;
}

.MinMaxTable_minimum_value {
    background-color: #12939a;
}

.MinMaxTable_maximum_value {
    background-color: #12939a;
}

.BarChart{
    box-sizing: border-box;
    height: 350px;
    overflow: auto;
    padding-top: 20px;
    /*justify-content: center;*/
    align-items: center;
    display: flex;
    /*padding-left: 20px;*/
}

@media only screen and (min-width: 800px) {
    .BarChart{
        justify-content: center;
    }
}

.ErrorBox_alert {
    padding: 20px;
    background-color: #f46717;
    color: white;
    margin-bottom: 15px;
    justify-content: center;
    position: fixed;
    bottom: 0;
    left:0;
    right: 0;
}

.ErrorBox_alertCloseBtn {
    margin-left: 15px;
    color: white;
    font-weight: bold;
    float: right;
    cursor: pointer;
}

.ErrorBox_alertCloseBtn:hover {
    color: black;
}

.Countdown{
    box-sizing: border-box;
    height: 4em;
    display: flex;
    justify-content: center;
    /*align-items: center;*/
}

.Countdown_value{
    box-sizing: border-box;
    font-size: 3em;
    /*border-radius:25px;*/
    /*border: solid 10px black;*/
}

@media only screen and (max-width: 600px) {
    .Countdown{
        height: 3em;
    }
}
            
          
!
            
              const { DataFactory } = N3;
const n3 = N3;
const { namedNode, literal } = DataFactory;
const {XYPlot, FlexibleXYPlot, VerticalBarSeries,LineSeries, LabelSeries, HorizontalGridLines, XAxis, YAxis} = reactVis;

class Downloader{
    static download(_url){
        return new Promise((resolve,reject) => {
            try {
                fetch(_url)
                    .then(function (response) {
                        resolve(response.text());
                    })
                    .catch(err => {
                        console.error(err);
                        reject(err)
                    });
            }catch (e) {
                console.error(e + " url: "+_url);
            }
        });
    }
}

class FragmentHandler {
    static async handleFragment(fragment) {
        let returnObject = {};

        let signalGroups = [];
        let {store, prefixes} = await Helper.parseAndStoreQuads(fragment);

        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);
        });

        //only use most recent observation
        let observation = await store.getQuads(null, namedNode('http://www.w3.org/ns/prov#generatedAtTime'), null).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];
        if(observation){
            let generatedAtTime = observation.object.value;

            signalGroups.forEach((signalGroup) => {
                let signalState = store.getQuads(namedNode(signalGroup), namedNode('https://w3id.org/opentrafficlights#signalState'), null, observation.subject)[0];
                if(signalState) {
                    let minEndTime = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#minEndTime'), null, observation.subject)[0].object.value;
                    let maxEndTime = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#maxEndTime'), null, observation.subject)[0].object.value;
                    let signalPhase = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#signalPhase'), null, observation.subject)[0].object.value;
                    let likelyTime = undefined;
                    try{
                        likelyTime = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#likelyTime'), null, observation.subject)[0].object.value;
                    }
                    catch (e) {
                                                
                    }

                    if(!returnObject[signalGroup]){
                        returnObject[signalGroup] = {};
                    }
                    returnObject[signalGroup] = {
                        "generatedAtTime": generatedAtTime && new Date(generatedAtTime),
                        "minEndTime": minEndTime && new Date(minEndTime),
                        "maxEndTime": maxEndTime && new Date(maxEndTime),
                        "signalPhase": signalPhase,
                        "likelyTime": likelyTime && new Date(likelyTime)
                    }

                }
            });
        }

        return returnObject;
    }
}

class Helper{
    static parseAndStoreQuads(_doc) {
        return new Promise(resolve => {
            const parser = new n3.Parser();
            const store = new n3.Store();
            parser.parse(_doc, (error, quad, prefixes) => {
                if (quad)
                    store.addQuad(quad);
                else
                    return resolve({"store": store, "prefixes": prefixes});
            });
        })
    }

    static writeN3Store(store, prefixes){
        return new Promise(async (resolve) => {
            const writer = new n3.Writer({ "prefixes": prefixes});
            for(let quad of store.getQuads()){
                writer.addQuad(quad);
            }

            await writer.end((error, result) => {resolve(result)});
        });
    }

    static splitDateInParts(timeDate){
        let result = {};
        let toDate = new Date(timeDate);
        result["hour"] = toDate.getUTCHours();
        result["month"] = toDate.getUTCMonth();
        result["minute"] = toDate.getUTCMinutes();
        result["day"] = toDate.getUTCDay();    //0 == sunday
        result["year"] = toDate.getUTCFullYear();
        return result;
    }
}

class TimeFrequencyDistribution {
    constructor(){
        this.frequencyDistribution = {};
    }

    add(signalGroup, signalPhase, year, month, day, hour, minutes, duration){
        if(!this.frequencyDistribution[signalGroup]){   //sg bestaat nog niet
            this.frequencyDistribution[signalGroup] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase]){
            this.frequencyDistribution[signalGroup][signalPhase] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year]){
            this.frequencyDistribution[signalGroup][signalPhase][year] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year][month]){
            this.frequencyDistribution[signalGroup][signalPhase][year][month] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year][month][day]){
            this.frequencyDistribution[signalGroup][signalPhase][year][month][day] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour]){
            this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes]){
            this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes] = {};
        }
        if(!this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes][duration]){
            this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes][duration] = 1;
        }
        else {
            this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes][duration]++;
        }
    }

    getDistributions(){
        return this.frequencyDistribution;
    }

    get(signalGroup, signalPhase, year, month, day, hour, minutes){
        if(this.frequencyDistribution[signalGroup]
            && this.frequencyDistribution[signalGroup][signalPhase]
            && this.frequencyDistribution[signalGroup][signalPhase][year]
            && this.frequencyDistribution[signalGroup][signalPhase][year][month]
            && this.frequencyDistribution[signalGroup][signalPhase][year][month][day]
            && this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour]
            && this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes]
        ){
            return this.frequencyDistribution[signalGroup][signalPhase][year][month][day][hour][minutes];
        }
    }
}

class PredictionCalculator{
   static calculateMedianDuration(frequencyDistribution){
        let count = 0;
        Object.keys(frequencyDistribution).forEach((duration) => {
            count+=frequencyDistribution[duration];
        });
        let runner = 0;
        let median = undefined;
        let i = 0;
        let list = Object.keys(frequencyDistribution);
        while(median === undefined && i<list.length){
            if(count/2 > runner && count/2 <= runner+frequencyDistribution[list[i]]){
                median = list[i];
            }
            runner+=frequencyDistribution[list[i]];
            i++;
        }
        if(count === 0){
            return undefined;
        }
        else {
            return parseInt(median, 10);
        }
    }
}

class PredictionManager{
    static predictLikelyTime(signalGroup, signalPhase, generatedAtTime, minEndTime, maxEndTime, phaseStart, distribution, predictionCalculatorFunction, maxDidIncrease){
        try {
            if (distribution && Object.keys(distribution).length > 0) {
                let result = new Date(phaseStart);
                let observationTime = new Date(generatedAtTime);
                let elapsedDuration = (observationTime.getTime() - result.getTime()) / 1000;
                let futureDistribution = {};
                Object.keys(distribution).forEach((key) => {
                    if (key >= elapsedDuration) {
                        futureDistribution[key] = distribution[key];
                    }
                });
                let likelyTime = undefined;

                let predictedDuration = predictionCalculatorFunction(distribution);
                if(predictedDuration < elapsedDuration){
                    predictedDuration = predictionCalculatorFunction(futureDistribution);
                }
                if(predictedDuration !== undefined){
                    result.setTime(result.getTime() + predictedDuration * 1000);
                    likelyTime = result.toISOString();
                }
                if (minEndTime && maxEndTime && minEndTime === maxEndTime) { //TODO: predict longer than max
                    likelyTime = minEndTime;
                } else if (likelyTime!== undefined && likelyTime < minEndTime) {
                    likelyTime = minEndTime;
                } else if (likelyTime !== undefined && !maxDidIncrease && likelyTime > maxEndTime ) {
                    likelyTime = maxEndTime;
                }
                return likelyTime;
            }
        } catch (e) {
            
        }
    }
}

class FragmentParser{
    constructor(showGeneratedAtTimeErrors = true, showPhaseErrors = true){
        this.phaseStart = {}; 
        this.lastPhase = {}; 
        this.lastMaxEndTime = {};   
        this.lastMinEndTime = {};
        this.lastObservation = {};
        this.maxDidIncrease = {};
        this.showGeneratedAtTimeErrors = showGeneratedAtTimeErrors;
        this.showPhaseErrors = showPhaseErrors;

        //debug
        this.startUpObservations = 0;   //count observations needed for startup at start or after reset
        this.generatedBeforeLastErrors = 0; //count if generatedAtTime > last observation generatedAtTime
        this.onSamePhaseResets = 0; //count samePhase resets
        this.onPhaseChangeResets = 0;   //count phaseChange resets
        this.observationSameAsLast = 0; //count when generatedAtTime is same as last observed generatedAtTime

        this.realStartUpObservations = 0;   //count observations needed for startup
        this.realStartUp = {};  //is true if startup completed
    }

    printDebugInfo(){
        console.log("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
        console.log("   FragmentParser debug info:");
        console.log("    - startUpObservations (reset included): "+this.startUpObservations);
        console.log("    - realStartUpObservations (startup only): "+this.realStartUpObservations);
        console.log("    - generatedBeforeLastErrors: "+this.generatedBeforeLastErrors);
        console.log("    - observationSameAsLast: "+this.observationSameAsLast);
        console.log("    - onSamePhaseResets: "+this.onSamePhaseResets);
        console.log("    - onPhaseChangeResets: "+this.onPhaseChangeResets);
        console.log("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
    }

    static _initReturnObject(){
        return {
            "signalGroup": undefined,   //signalGroup of current observation
            "signalPhase": undefined,   //signalPhase of current observation
            "signalState": undefined,   //signalState quad (not used)
            "generatedAtTime": undefined,   //generation time of current observation
            "minEndTime": undefined,    //minEndTime defined in current observation
            "maxEndTime": undefined,    //maxEndTime defined in current observation
            "observation": undefined,   //observation quad (not used)
            "store": undefined, //n3 store object
            "prefixes": undefined,  //prefixes in trig rdf fragment
            "phaseStart": undefined,    //start of phase of current observation
            "lastPhaseStart": undefined,    //start of phase of last observation
            "lastPhase": undefined,  //phase of last observation
            "maxDidIncrease": undefined //maxEndTime did increase for same phase
        };
    }

    static _setReturnObject(returnObject, signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, prefixes, phaseStart, lastPhaseStart, lastPhase, maxDidIncrease){
        returnObject["signalGroup"] = signalGroup;
        returnObject["signalPhase"] = signalPhase;
        returnObject["signalState"] = signalState;
        returnObject["generatedAtTime"] = generatedAtTime;
        returnObject["minEndTime"] = minEndTime;
        returnObject["maxEndTime"] = maxEndTime;
        returnObject["observation"] = observation;
        returnObject["store"] = store;
        returnObject["prefixes"] = prefixes;
        returnObject["phaseStart"] = phaseStart;
        returnObject["lastPhaseStart"] = lastPhaseStart;
        returnObject["lastPhase"] = lastPhase;
        returnObject["maxDidIncrease"] = maxDidIncrease;
    };

    async handleFragment(fragment, file, onPhaseChange, onSamePhase, onObservationBeforeValidityCheck, afterHandle, onFragmentError){
        let returnObject = FragmentParser._initReturnObject();
        let { store, prefixes } = await Helper.parseAndStoreQuads(fragment);

        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);
            if(!this.phaseStart[quad.subject.value]){
                this.phaseStart[quad.subject.value] = -1;
            }
            if(!this.lastPhase[quad.subject.value]){
                this.lastPhase[quad.subject.value] = -1;
            }
            if(!this.lastMaxEndTime[quad.subject.value]){
                this.lastMaxEndTime[quad.subject.value] = -1;
            }
            if(!this.lastMinEndTime[quad.subject.value]){
                this.lastMinEndTime[quad.subject.value] = -1;
            }
            if(!this.lastObservation[quad.subject.value]){
                this.lastObservation[quad.subject.value] = undefined;
            }
            if(!this.maxDidIncrease[quad.subject.value]){
                this.maxDidIncrease[quad.subject.value] = {};
            }
            if(!this.realStartUp[quad.subject.value]){
                this.realStartUp[quad.subject.value] = 0;
            }
        });

        let isFragmentValid = true;
        if(file){
            let firstObservation = await store.getQuads(null, namedNode('http://www.w3.org/ns/prov#generatedAtTime'), null).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];
            if(!firstObservation){
                isFragmentValid = false;
            }
            else{
                let firstObservationName = "fragment_" + (firstObservation.object.value).replace(/\:/g,"_").replace(/\./g,"_") + ".trig";
                if( firstObservationName !== file){
                    console.log("\x1b[31m","Filename is not correct: "+file + ", first observation: "+firstObservationName,"\x1b[0m");
                    isFragmentValid = false;
                }
            }
        }
        if(isFragmentValid) {
            //overlopen van alle observaties in een fragment, gesorteerd met oudste eerst
            await store.getQuads(null, namedNode('http://www.w3.org/ns/prov#generatedAtTime'), null).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 = observation.object.value;

                signalGroups.forEach(signalGroup => {
                    let error = 0;
                    if (this.lastObservation[signalGroup]) {
                        if (new Date(this.lastObservation[signalGroup]).getTime() > new Date(generatedAtTime).getTime()) {
                            this.showGeneratedAtTimeErrors && console.log(file + " : Observation: " + generatedAtTime + " signalGroup: " + signalGroup + " | last observation bigger than new: " + this.lastObservation[signalGroup] + " - " + generatedAtTime);
                            this.generatedBeforeLastErrors++;
                            error = 1;
                        }

                        if (generatedAtTime === this.lastObservation[signalGroup]) {
                            this.showGeneratedAtTimeErrors && console.log("generatedAtTime " + generatedAtTime + " is same as last " + this.lastObservation[signalGroup] + " sg: " + signalGroup);
                            this.observationSameAsLast++;
                        }
                    }

                    let signalState = store.getQuads(namedNode(signalGroup), namedNode('https://w3id.org/opentrafficlights#signalState'), null, observation.subject)[0];
                    if (signalState) {
                        let minEndTime = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#minEndTime'), null, observation.subject)[0].object.value;
                        let maxEndTime = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#maxEndTime'), null, observation.subject)[0].object.value;
                        let signalPhase = store.getQuads(signalState.object, namedNode('https://w3id.org/opentrafficlights#signalPhase'), null, observation.subject)[0].object.value;


                        if (generatedAtTime > maxEndTime) {
                            console.log("fragment contains observation generated after maxEndTime: " + file);
                        }

                        if (this.phaseStart[signalGroup] !== -1 && this.lastPhase[signalGroup] !== -1) {
                            if (this.realStartUp[signalGroup] === 0) {    //TODO: debug info
                                this.realStartUp[signalGroup] = 1;   //debug info
                            }
                            if (this.lastPhase[signalGroup] !== signalPhase) {
                                //phase change
                                if (onObservationBeforeValidityCheck) {
                                    FragmentParser._setReturnObject(returnObject, signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, prefixes, generatedAtTime, this.phaseStart[signalGroup], this.lastPhase[signalGroup], this.maxDidIncrease[signalGroup][signalPhase]);
                                    onObservationBeforeValidityCheck(returnObject);
                                }
                                if(!error) {
                                    if (new Date(generatedAtTime).getTime() > new Date(this.lastObservation[signalGroup]).getTime()+5000 &&
                                        ((this.lastMaxEndTime[signalGroup] !== -1 && new Date(generatedAtTime).getTime() > new Date(this.lastMaxEndTime[signalGroup]).getTime() + 210)
                                            || (this.lastMinEndTime[signalGroup] !== -1 && generatedAtTime < this.lastMinEndTime[signalGroup]))
                                    ) {
                                        this.lastPhase[signalGroup] = -1;
                                        this.phaseStart[signalGroup] = -1;
                                        this.onPhaseChangeResets++;
                                        this.showPhaseErrors && console.log("onPhaseChangeError: " + file + " generatedAtTime: " + generatedAtTime + " maxEndTime: " + maxEndTime + " lastMaxEndTime: " + this.lastMaxEndTime[signalGroup] + " lastMinEndTime: " + this.lastMinEndTime[signalGroup] + " last observation (gereratedAtTime): " + this.lastObservation[signalGroup]);
                                        if (onFragmentError) {
                                            onFragmentError(signalGroup);
                                        }
                                        this.lastMaxEndTime[signalGroup] = -1;
                                        this.lastMinEndTime[signalGroup] = -1;
                                    } else {
                                        if (onPhaseChange) {
                                            FragmentParser._setReturnObject(returnObject, signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, prefixes, generatedAtTime, this.phaseStart[signalGroup], this.lastPhase[signalGroup], this.maxDidIncrease[signalGroup][signalPhase]);
                                            onPhaseChange(returnObject);
                                        }

                                        this.lastPhase[signalGroup] = signalPhase;
                                        this.phaseStart[signalGroup] = generatedAtTime;

                                        this.lastMaxEndTime[signalGroup] = maxEndTime;
                                        this.lastMinEndTime[signalGroup] = minEndTime;
                                    }
                                }
                            } else {
                                if (onObservationBeforeValidityCheck) {
                                    FragmentParser._setReturnObject(returnObject, signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, prefixes, this.phaseStart[signalGroup], this.phaseStart[signalGroup], this.lastPhase[signalGroup], this.maxDidIncrease[signalGroup][signalPhase]);
                                    onObservationBeforeValidityCheck(returnObject);
                                }
                                if(!error) {
                                    if (new Date(generatedAtTime).getTime() > new Date(this.lastObservation[signalGroup]).getTime()+5000 &&
                                        ((this.lastMaxEndTime[signalGroup] !== -1 && new Date(maxEndTime).getTime() > new Date(this.lastMaxEndTime[signalGroup]).getTime() + 1005)
                                            || (this.lastMinEndTime[signalGroup] !== -1 && new Date(minEndTime).getTime() + 1005 < new Date(this.lastMinEndTime[signalGroup]).getTime()))
                                    ) {
                                        this.lastPhase[signalGroup] = -1;   //reset
                                        this.phaseStart[signalGroup] = -1;
                                        this.showPhaseErrors && console.log("onSamePhaseError: " + file + " generatedAtTime: " + generatedAtTime + " maxEndTime: " + maxEndTime + " lastMaxEndTime: " + this.lastMaxEndTime[signalGroup] + " minEndTime: " + minEndTime + " lastMinEndTime: " + this.lastMinEndTime[signalGroup] + " last observation (gereratedAtTime): " + this.lastObservation[signalGroup]);
                                        this.onSamePhaseResets++;

                                        if (onFragmentError) {
                                            onFragmentError(signalGroup);
                                        }
                                        this.lastMaxEndTime[signalGroup] = -1;
                                        this.lastMinEndTime[signalGroup] = -1;
                                    } else {
                                        if(this.maxDidIncrease[signalGroup][signalPhase] !== true){
                                            this.maxDidIncrease[signalGroup][signalPhase] = new Date(maxEndTime).getTime() > new Date(this.lastMaxEndTime[signalGroup]).getTime() + 1005;
                                        }
                                        if (onSamePhase) {
                                            FragmentParser._setReturnObject(returnObject, signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, prefixes, this.phaseStart[signalGroup], this.phaseStart[signalGroup], this.lastPhase[signalGroup], this.maxDidIncrease[signalGroup][signalPhase]);
                                            onSamePhase(returnObject);
                                        }
                                        this.lastMaxEndTime[signalGroup] = maxEndTime;
                                        this.lastMinEndTime[signalGroup] = minEndTime;
                                    }
                                }
                            }
                        } else {
                            if(!error) {
                                if (this.realStartUp[signalGroup] === 0) {
                                    this.realStartUpObservations++;
                                }
                                this.startUpObservations++;
                                if (this.phaseStart[signalGroup] === -1 && this.lastPhase[signalGroup] === -1) {
                                    this.lastPhase[signalGroup] = signalPhase;
                                } else if (this.lastPhase[signalGroup] !== signalPhase) {
                                    this.lastPhase[signalGroup] = signalPhase;
                                    this.phaseStart[signalGroup] = generatedAtTime;
                                }
                                this.lastMaxEndTime[signalGroup] = maxEndTime; 
                                this.lastMinEndTime[signalGroup] = minEndTime;
                            }
                        }
                        if(!error){
                            this.lastObservation[signalGroup] = generatedAtTime;
                        }
                    }

                });

            });
        }
        if(afterHandle){
            FragmentParser._setReturnObject(returnObject, undefined, undefined, undefined, undefined, undefined, undefined, undefined, store, prefixes, undefined, undefined, undefined, undefined);
            afterHandle(returnObject);
        }
    }

}
  
class PredictionGenerator{
    constructor() {
        this.realTimeFragmentParser = new FragmentParser(false, false);
        this.timeDistribution = new TimeFrequencyDistribution();
    }

    async generatePredictions(fragment) {
        let result = "";
        await this.realTimeFragmentParser.handleFragment(fragment, undefined,
            (returnObject) => {
                let { signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, lastPhaseStart, lastPhase, phaseStart, maxDidIncrease } = returnObject;
                let observationUTC = Helper.splitDateInParts(phaseStart);
                let phaseDuration = new Date(generatedAtTime).getTime() - new Date(lastPhaseStart).getTime();
                this.timeDistribution.add(signalGroup, lastPhase, observationUTC["year"], observationUTC["month"], observationUTC["day"], observationUTC["hour"], Math.floor(observationUTC["minute"]/20)*20, Math.round(phaseDuration/1000));
                let distribution = this.timeDistribution.get(signalGroup,signalPhase,observationUTC["year"],observationUTC["month"],observationUTC["day"],observationUTC["hour"],Math.floor(observationUTC["minute"]/20)*20);
                // console.log(distribution);
                let likelyTime = PredictionManager.predictLikelyTime(signalGroup, signalPhase, generatedAtTime, minEndTime, maxEndTime, lastPhaseStart, distribution, PredictionCalculator.calculateMedianDuration, maxDidIncrease);
                likelyTime && store.addQuad(signalState.object, namedNode('https://w3id.org/opentrafficlights#likelyTime'), literal(likelyTime,namedNode("http://www.w3.org/2001/XMLSchema#date")), observation.subject);

            },
            (returnObject) => {
                let { signalGroup, signalPhase, signalState, generatedAtTime, minEndTime, maxEndTime, observation, store, lastPhaseStart, lastPhase, phaseStart, maxDidIncrease } = returnObject;
                let observationUTC = Helper.splitDateInParts(phaseStart);
                let distribution = this.timeDistribution.get(signalGroup,signalPhase,observationUTC["year"],observationUTC["month"],observationUTC["day"],observationUTC["hour"],Math.floor(observationUTC["minute"]/20)*20);
                // console.log(distribution);
                let likelyTime = PredictionManager.predictLikelyTime(signalGroup, signalPhase, generatedAtTime, minEndTime, maxEndTime, lastPhaseStart, distribution, PredictionCalculator.calculateMedianDuration, maxDidIncrease);
                likelyTime && store.addQuad(signalState.object, namedNode('https://w3id.org/opentrafficlights#likelyTime'), literal(likelyTime,namedNode("http://www.w3.org/2001/XMLSchema#date")), observation.subject);
            },
            undefined
            ,
            async (returnObject) => {
                let { store, prefixes } = returnObject;
                await Helper.writeN3Store(store, prefixes).then((res) => {result = res});
            }
        );
        return result;
    };
}

//views
class Countdown extends React.Component{
    render(){
        let {count, color} = this.props;
        if(count === undefined){
            count = "X";
        }
        let textColor = "black";
        if(color === 0){
            textColor = "orange";
        }
        if(color === 3){
            textColor = "red";
        }
        if(color === 6){
            textColor = "green";
        }
        return (
            <div className="Countdown">
                <div className="Countdown_value" style={{color: textColor}}>{count}</div>
            </div>
        )
    }
}

class ErrorBox extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            show: true
        };
        this.onClick = this.onClick.bind(this);
    }

    onClick(){
        this.setState({
            show: false
        });
    }

    render(){
        let {show} = this.state;
        if(show !== false){
            return (
                <div className="ErrorBox_alert">
                    <span className="ErrorBox_alertCloseBtn" onClick={this.onClick}>&times;</span>
                    {this.props.message}
                </div>)
        }
        else{
            return null;
        }
    }
}

class BarChart extends React.Component {

    render() {
        const {minData, maxData, likelyData, title} = this.props;
        return (
            <div className="BarChart">
                <p>{title}</p>
                <XYPlot height={300} width={800} xType={"time"}>
                    <HorizontalGridLines />
                    <LineSeries data={minData} barWidth={0.95} color={"green"}/>
                    <LineSeries data={maxData} barWidth={0.95} color={"red"}/>
                    <LineSeries data={likelyData} barWidth={0.95} color={"blue"}/>
                    <XAxis title={"Time"}/>
                    <YAxis title={"Duration (s)"}/>
                </XYPlot>
            </div>
        );
    }
}

class MinMaxTable extends React.Component{
    render(){
        let {min, max} = this.props;
        if(min === undefined){
            min = "X";
        }
        if(max === undefined){
            max = "X";
        }
        return (
            <div className="MinMaxTable" >
                <div className="MinMaxTable_minimum_box">
                    <div className="MinMaxTable_minimum_title">Minimum</div><div className="MinMaxTable_minimum_value">{min}</div>
                </div>
                <div className="MinMaxTable_maximum_box">
                    <div className="MinMaxTable_maximum_title">Maximum</div><div className="MinMaxTable_maximum_value">{max}</div>
                </div>
            </div>
        )
    }
}

class PhaseColorGraph extends React.Component {

    render() {
        const {red, orange, green, title} = this.props;
        return (
            <div className="PhaseColorGraph">
                <p>{title}</p>
                <XYPlot height={100} width={800} xType={"time"}>
                    <LineSeries data={red} color={"red"}/>
                    <LineSeries data={orange} color={"orange"}/>
                    <LineSeries data={green} color={"green"}/>
                    <XAxis title={"Time"}/>
                    <YAxis title={"Color"} style={{
                         // line: {stroke: 'none'},
                        ticks: {stroke: 'none'},
                         text: {stroke: 'none', fill: 'none'}
                    }}/>
                </XYPlot>
            </div>
        );
    }
}

let Dropdown = (props) =>{
    let {activeValue, options, onChange} = props;
    return (
        <select value={activeValue} onChange={(event) => onChange(event.target.value)}>
            {Object.keys(options).map((key)=> {
                return <option value={key} id={key}>{key}</option>
            })}
        </select>
    );
};

class PredictionBox extends React.Component{
    constructor(props){
        super(props);
        this.DATASET_URL = props.datasetUrl;
        this._constructGraphData =this._constructGraphData.bind(this);
        this._constructSignalGroup = this._constructSignalGroup.bind(this);
        this.setActiveSignalGroup = this.setActiveSignalGroup.bind(this);
        if(props.clientSidePrediction){
            this.predictionGenerator = new PredictionGenerator();
        }
        this.state = {
            clientSidePrediction: props.clientSidePrediction,
            data: {},
            colorData: {},
            colorDataOldest: {},
            minEndTimeGraphData: {},
            maxEndTimeGraphData: {},
            likelyTimeGraphData: {},
            signalGroups: {},
            activeSignalGroup: "https://opentrafficlights.org/id/signalgroup/K648/4",
        };
    }

    componentDidMount() {
        let { clientSidePrediction } = this.state;
        setInterval(() => {
            Downloader.download(this.DATASET_URL).then(async (fragment) => {
                let parsed = fragment;
                if(clientSidePrediction){
                    parsed = await this.predictionGenerator.generatePredictions(fragment);
                }
                FragmentHandler.handleFragment(parsed).then((returnObject) => {
                    this.setState({
                        data: returnObject,
                    });
                    this._constructGraphData("minEndTime", "minEndTimeGraphData");
                    this._constructGraphData("maxEndTime", "maxEndTimeGraphData");
                    this._constructGraphData("likelyTime", "likelyTimeGraphData");
                    this._constructSignalGroup(Object.keys(returnObject));
                });
            }).catch((e) => {
                    this.setState({
                        data: {},
                    });
                    console.error("data error: "+this.DATASET_URL + " " + e);
                }
            );
        }, 1000);
    }

    _constructGraphData(type, graph){
        let {data} = this.state;
        let graphData = this.state[graph];
        Object.keys(data).forEach((signalGroup) => {
            if(data[signalGroup]){
                if(!graphData[signalGroup]){
                    graphData[signalGroup] = [];
                }
                if(graphData[signalGroup] && graphData[signalGroup].length > 20){
                    graphData[signalGroup].shift();
                }
                let generatedAtTime = data[signalGroup] && data[signalGroup].generatedAtTime;
                let countdown = data[signalGroup] && (new Date(data[signalGroup][type]).getTime() - new Date(data[signalGroup].generatedAtTime)) / 1000;
                if(!isNaN(countdown)) graphData[signalGroup].push({x: generatedAtTime, y: countdown});
            }
        });
        let newState = {};
        newState[graph] = graphData;
        this.setState(newState);
    }

    _constructSignalGroup(newSignalGroups){
        let { signalGroups, activeSignalGroup } = this.state;
        newSignalGroups.forEach((sg) => {
            signalGroups[sg] = 0;
            if(activeSignalGroup === undefined){
                activeSignalGroup = sg;
            }
        });
        this.setState({
            signalGroups: signalGroups,
            activeSignalGroup: activeSignalGroup,
        });
    }

    setActiveSignalGroup(signalGroup){
        console.log(signalGroup);
        this.setState({
            data: {},
            colorData: {},
            colorDataOldest: {},
            minEndTimeGraphData: {},
            maxEndTimeGraphData: {},
            likelyTimeGraphData: {},
            activeSignalGroup: signalGroup,
        });
    }

    render(){
        let { signalGroups, activeSignalGroup, data, minEndTimeGraphData, maxEndTimeGraphData, likelyTimeGraphData, colorData } = this.state;
        let signalGroup = activeSignalGroup;
        let countdown = data[signalGroup] && data[signalGroup].likelyTime && (data[signalGroup].likelyTime.getTime() - data[signalGroup].generatedAtTime) / 1000;
        if (countdown) countdown = Math.round(countdown*10)/10;
        let minEndTime = data[signalGroup] && (data[signalGroup].minEndTime.getTime() - data[signalGroup].generatedAtTime) / 1000;
        let maxEndTime = data[signalGroup] && (data[signalGroup].maxEndTime.getTime() - data[signalGroup].generatedAtTime) / 1000;
        let color = "-1";
        if(data[signalGroup]){
            if(data[signalGroup].signalPhase === "https://w3id.org/opentrafficlights/thesauri/signalphase/6"
                || data[signalGroup].signalPhase === "https://w3id.org/opentrafficlights/thesauri/signalphase/5"){
                color = 6;
            }
            else if(data[signalGroup].signalPhase === "https://w3id.org/opentrafficlights/thesauri/signalphase/3"
                || data[signalGroup].signalPhase === "https://w3id.org/opentrafficlights/thesauri/signalphase/2"){
                color = 3;
            }
            else if(data[signalGroup].signalPhase === "https://w3id.org/opentrafficlights/thesauri/signalphase/0"){
                color = 0;
            }
        }
        return (
            <div className="PredictionBox">
                <Dropdown options={signalGroups} activeValue={activeSignalGroup} onChange={this.setActiveSignalGroup}/>
                <Countdown count={countdown} color={color} className="PredictionBox_Countdown"/>
                <MinMaxTable min={minEndTime} max={maxEndTime} className="PredictionBox_MinMaxTable"/>
                <BarChart minData={minEndTimeGraphData[signalGroup]} maxData={maxEndTimeGraphData[signalGroup]} likelyData={likelyTimeGraphData[signalGroup]} className="PredictionBox_BarChart"/>
                <p>After refresh of the page, it can take a few minutes before the first predictions will appear.</p>
                {Object.keys(data).length === 0 && <ErrorBox message={"No data returned: "+this.DATASET_URL}/>}
            </div>
        )
    }
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <div className="App-title">OpenTrafficLightsPredictor</div>  
        <PredictionBox datasetUrl={'https://lodi.ilabt.imec.be/observer/rawdata/latest'} clientSidePrediction={true}/>
      </header>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
            
          
!
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