Code viewer for World: Character recognition neur...
// Cloned by Dheeraj Putta on 26 Nov 2020 from World "Character recognition neural network" by "Coding Train" project 
// Please leave this clone trail here.


// Port of Character recognition neural network from here:
// https://github.com/CodingTrain/Toy-Neural-Network-JS/tree/master/examples/mnist
// with many modifications 


// --- defined by MNIST - do not change these ---------------------------------------

const PIXELS = 28;                       // images in data set are tiny 
const PIXELSSQUARED = PIXELS * PIXELS;

// number of training and test exemplars in the data set:
const NOTRAIN = 60000;
const NOTEST = 10000;

let do_training = false;
let restore = !do_training;

// how many to train and test per timestep 
const TRAINPERSTEP = 30;
const TESTPERSTEP = 5;

// multiply it by this to magnify for display 
const ZOOMFACTOR = 7;
const ZOOMPIXELS = ZOOMFACTOR * PIXELS;

// 3 rows of
// large image + 50 gap + small image    
// 50 gap between rows 

const canvaswidth = (PIXELS + ZOOMPIXELS) + 50;
const canvasheight = (ZOOMPIXELS * 3) + 100;


const DOODLE_THICK = 18;    // thickness of doodle lines 
const DOODLE_BLUR = 3;      // blur factor applied to doodles 

let mnist;

let trainrun = 1;
let train_index = 0;

let testrun = 1;
let test_index = 0;
let total_tests = 0;
let total_correct = 0;

// images in LHS:
let doodle, demo;
let doodle_exists = false;
let demo_exists = false;

let mousedrag = false;      // are we in the middle of a mouse drag drawing?  

// CSS trick 
// make run header bigger 
$("#runheaderbox").css({ "max-height": "95vh" });



//--- start of AB.msgs structure: ---------------------------------------------------------
// We output a serious of AB.msgs to put data at various places in the run header 
var thehtml;

// 1 Doodle header 
thehtml = "<hr> <h1> 1. Doodle </h1> Top row: Doodle (left) and shrunk (right). <br> " +
    " Draw your doodle in top LHS. <button onclick='wipeDoodle();' class='normbutton' >Clear doodle</button> <br> ";
AB.msg(thehtml, 1);

// 2 Doodle variable data (guess)

// 3 Training header
thehtml = "<hr> <h1> 2. Training </h1> Middle row: Training image magnified (left) and original (right). <br>  " +
    " <button onclick='do_training = false;' class='normbutton' >Stop training</button> <br> ";
AB.msg(thehtml, 3);

// 4 variable training data 

// 5 Testing header
thehtml = "<h3> Hidden tests </h3> ";
AB.msg(thehtml, 5);

// 6 variable testing data 

// 7 Demo header 
thehtml = "<hr> <h1> 3. Demo </h1> Bottom row: Test image magnified (left) and  original (right). <br>" +
    " The network is <i>not</i> trained on any of these images. <br> " +
    " <button onclick='makeDemo();' class='normbutton' >Demo test image</button> <br> ";
AB.msg(thehtml, 7);

const greenspan = "<span style='font-weight:bold; font-size:x-large; color:darkgreen'> ";

var layer_defs, net, trainer;
var t = layer_defs = [];
layer_defs.push({ type: 'input', out_sx: 24, out_sy: 24, out_depth: 1 });
layer_defs.push({ type: 'conv', sx: 5, filters: 8, stride: 1, pad: 2, activation: 'relu' });
layer_defs.push({ type: 'pool', sx: 2, stride: 2 });
layer_defs.push({ type: 'conv', sx: 5, filters: 16, stride: 1, pad: 2, activation: 'relu' });
layer_defs.push({ type: 'pool', sx: 3, stride: 3 });
layer_defs.push({ type: 'softmax', num_classes: 10 });

var to_train;
var tested = 0;
var to_test;
var trained = 0;

function setup() {
    createCanvas(canvaswidth, canvasheight);

    doodle = createGraphics(ZOOMPIXELS, ZOOMPIXELS);       // doodle on larger canvas 
    doodle.pixelDensity(1);
    doodle.canvas.id = "doodle_canvas";

    // JS load other JS 
    // maybe have a loading screen while loading the JS and the data set 

    AB.loadingScreen();

    $.getScript("/uploads/codingtrain/matrix.js", function () {
        $.getScript("/uploads/codingtrain/nn.js", function () {
            $.getScript("uploads/djputta/opencv.js", function () {
                $.getScript("/uploads/djputta/convnet-min.js", function () {
                    $.getScript("/uploads/codingtrain/mnist.js", function () {
                        console.log("All JS loaded");
                        net = new convnetjs.Net();
                        loadData();
                        if (!restore) {
                            net.makeLayers(layer_defs);
                            trainer = new convnetjs.SGDTrainer(net, { method: 'adadelta', l2_decay: 0.001 });
                        }
                        if (restore) {
                            $.getJSON("/uploads/djputta/_data.3956514145.json", function (json) {
                                net.fromJSON(JSON.parse(json)); // this will show the info it in firebug console
                            });
                        }
                    });
                });
            });
        })
    });
}

function loadData() {
    loadMNIST(function (data) {
        mnist = data;
        console.log("All data loaded into mnist object:")
        console.log(mnist);
        to_train = shuffle([...Array(mnist.train_labels.length).keys()]);
        to_test = shuffle([...Array(mnist.test_labels.length).keys()]);
        AB.removeLoading();     // if no loading screen exists, this does nothing 
    });
}

function getImage(img)      // make a P5 image object from a raw data array   
{
    let theimage = createImage(PIXELS, PIXELS);    // make blank image, then populate it 
    theimage.loadPixels();

    for (let i = 0; i < PIXELSSQUARED; i++) {
        let bright = img[i];
        let index = i * 4;
        theimage.pixels[index + 0] = bright;
        theimage.pixels[index + 1] = bright;
        theimage.pixels[index + 2] = bright;
        theimage.pixels[index + 3] = 255;
    }

    theimage.updatePixels();
    return theimage;
}

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

function sample_training_instance() {
    var index = to_train.shift();
    trained++;

    var img = mnist.train_images[index];
    var x = new convnetjs.Vol(28, 28, 1, 0.0);
    var W = 28 * 28;
    for (var i = 0; i < W; i++) {
        x.w[i] = img[i] / 255.0;
    }
    x = convnetjs.augment(x, 24);

    return { x: x, label: mnist.train_labels[index], index: index };
}

function sample_test_instance(ind) {
    var index;
    if (ind !== undefined) {
        index = ind;
    }
    else {
        index = to_test.shift();
    }

    var img = mnist.test_images[index];
    var x = new convnetjs.Vol(28, 28, 1, 0.0);
    var W = 28 * 28;
    for (var i = 0; i < W; i++) {
        x.w[i] = img[i] / 255.0;
    }

    var xs = [];
    for (var i = 0; i < 4; i++) {
        xs.push(convnetjs.augment(x, 24));
    }

    return { x: xs, label: mnist.test_labels[index], index: index };
}

function trainit(show)        // train the network with a single exemplar, from global var "train_index", show visual on or off 
{
    let img = sample_training_instance();

    // optional - show visual of the image 
    if (show) {
        var theimage = getImage(mnist.train_images[img.index]);    // get image from data array 
        image(theimage, 0, ZOOMPIXELS + 50, ZOOMPIXELS, ZOOMPIXELS);      // magnified 
        image(theimage, ZOOMPIXELS + 50, ZOOMPIXELS + 50, PIXELS, PIXELS);      // original
    }

    step(img)

    thehtml = " trainrun: " + trainrun + "<br> no: " + train_index;
    AB.msg(thehtml, 4);

    train_index++;
    if (train_index == NOTRAIN) {
        train_index = 0;
        console.log("finished trainrun: " + trainrun);
        trainrun++;
        AB.saveData(JSON.stringify(net.toJSON()));
    }
}

let trainResult = [];

function step(sample) {
    var x = sample.x;
    var y = sample.label;

    var stats = trainer.train(x, y);
    var lossx = stats.cost_loss;
    var lossw = stats.l2_decay_loss;

    var yhat = net.getPrediction();
    trainResult.push(yhat === y ? 1.0 : 0.0);
}

function avg(arr) {
    return arr.reduce((a, b) => a + b, 0) / arr.length;
}

function testit(ind) {
    var num_classes = net.layers[net.layers.length - 1].out_depth;
    var sample = sample_test_instance(ind);
    var y = sample.label;

    var aavg = new convnetjs.Vol(1, 1, num_classes, 0.0);
    // ensures we always have a list, regardless if above returns single item or list
    var xs = [].concat(sample.x);
    var n = xs.length;
    for (var i = 0; i < n; i++) {
        var a = net.forward(xs[i]);
        aavg.addFrom(a);
    }

    var preds = []
    for (var k = 0; k < aavg.w.length; k++) {
        preds.push({ k: k, p: aavg.w[k] });
    }
    preds.sort(function (a, b) { return a.p < b.p ? 1 : -1 });

    if (ind === undefined) {
        if (test_index < NOTEST) {
            total_tests++;
            if (preds[0].k == y) total_correct++;

            let percent = (total_correct / total_tests) * 100;
            thehtml = " testrun: " + testrun + "<br> no: " + total_tests + " <br> " +
                " correct: " + total_correct + "<br>" +
                "  score: " + greenspan + percent.toFixed(2) + "</span>";
            AB.msg(thehtml, 6);

            test_index++;
        }
        else if (test_index == NOTEST) {
            console.log("finished testrun: " + testrun + " score: " + percent.toFixed(2));
            testrun++;
            test_index = 0;
            total_tests = 0;
            total_correct = 0;
        }
    }

    return preds;
}

function draw() {
    // check if libraries and data loaded yet:
    if (typeof mnist == 'undefined') return;


    // how can we get white doodle on black background on yellow canvas?
    //        background('#ffffcc');    doodle.background('black');

    background('black');

    if (do_training) {
        // do some training per step 

        for (let i = 0; i < TRAINPERSTEP; i++) {
            if (i == 0) trainit(true);    // show only one per step - still flashes by  
            else trainit(false);
        }

        // do some testing per step 
        for (let i = 0; i < TESTPERSTEP; i++)
            testit();
    }

    // keep drawing demo and doodle images 
    // and keep guessing - we will update our guess as time goes on 

    if (demo_exists) {
        drawDemo();
        guessDemo();
    }
    if (doodle_exists) {
        drawDoodle();
        guessDoodle();
    }


    // detect doodle drawing 
    // (restriction) the following assumes doodle starts at 0,0 

    if (mouseIsPressed)         // gets called when we click buttons, as well as if in doodle corner  
    {
        // console.log ( mouseX + " " + mouseY + " " + pmouseX + " " + pmouseY );
        var MAX = ZOOMPIXELS + 20;     // can draw up to this pixels in corner 
        if ((mouseX < MAX) && (mouseY < MAX) && (pmouseX < MAX) && (pmouseY < MAX)) {
            mousedrag = true;       // start a mouse drag 
            doodle_exists = true;
            doodle.stroke('white');
            doodle.strokeWeight(DOODLE_THICK);
            doodle.line(mouseX, mouseY, pmouseX, pmouseY);
        }
    }
    else {
        // are we exiting a drawing
        if (mousedrag) {
            mousedrag = false;
            // console.log ("Exiting draw. Now blurring.");
            // doodle.filter(DILATE);
            // doodle.filter(BLUR, 2);
            // doodle.filter (ERODE);    // just blur once 
            //   console.log (doodle);
        }
    }
}

function makeDemo() {
    demo_exists = true;
    demo = AB.randomIntAtoB(0, NOTEST - 1);

    thehtml = "Test image no: " + demo + "<br>" +
        "Classification: " + mnist.test_labels[demo] + "<br>";
    AB.msg(thehtml, 8);

    // type "demo" in console to see raw data 
}


function drawDemo() {
    var theimage = getImage(mnist.test_images[demo]);
    //  console.log (theimage);

    image(theimage, 0, canvasheight - ZOOMPIXELS, ZOOMPIXELS, ZOOMPIXELS);      // magnified 
    image(theimage, ZOOMPIXELS + 50, canvasheight - ZOOMPIXELS, PIXELS, PIXELS);      // original
}


function guessDemo() {
    // let inputs = getInputs(demo);

    // demo_inputs = inputs;  // can inspect in console 

    let prediction = testit(demo);       // array of outputs 
    let guess = prediction[0].k      // the top output 

    thehtml = " We classify it as: " + greenspan + guess + "</span>";
    AB.msg(thehtml, 9);
}

function drawDoodle() {
    // doodle is createGraphics not createImage
    let theimage = doodle.get();
    // console.log (theimage);

    image(theimage, 0, 0, ZOOMPIXELS, ZOOMPIXELS);      // original 
    image(theimage, ZOOMPIXELS + 50, 0, PIXELS, PIXELS);      // shrunk
}


function guessDoodle() {
    // doodle is createGraphics not createImage
    let img = doodle.get();

    img.resize(PIXELS, PIXELS);
    img.loadPixels();

    // set up inputs   
    var x = new convnetjs.Vol(28, 28, 1, 0.0);

    for (let i = 0; i < PIXELSSQUARED; i++) {
        x.w[i] = img.pixels[i * 4] / 255;
    }

    var xs = [];
    for (var i = 0; i < 4; i++) {
        xs.push(convnetjs.augment(x, 24));
    }

    doodle_inputs = xs;     // can inspect in console 

    // feed forward to make prediction 
    var aavg = new convnetjs.Vol(1, 1, 10, 0.0);
    // ensures we always have a list, regardless if above returns single item or list
    var ys = [].concat(xs);
    var n = ys.length;
    for (var i = 0; i < n; i++) {
        var a = net.forward(ys[i]);
        aavg.addFrom(a);
    }

    var preds = []
    for (var k = 0; k < aavg.w.length; k++) {
        preds.push({ k: k, p: aavg.w[k] });
    }
    preds.sort(function (a, b) { return a.p < b.p ? 1 : -1 });

    let b = [preds[0].k, preds[1].k];

    thehtml = " We classify it as: " + greenspan + b[0] + "</span> <br>" +
        " No.2 guess is: " + greenspan + b[1] + "</span>";
    AB.msg(thehtml, 2);
}


function wipeDoodle() {
    doodle_exists = false;
    doodle.background('black');
}