Code viewer for World: Enhanced Character recogni...
// Cloned by Deniss Strods on 3 Dec 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; // 24873;//60000;
const NOTEST = 10000;


//--- can modify all these --------------------------------------------------

// no of nodes in network 
const noinput = PIXELSSQUARED;
const nohidden = 200;
const nooutput = 10;

const learningrate = 0.01; // default 0.1
let decayLearningRate = learningrate;

// should we train every timestep or not 
let do_training = false;

// how many to train and test per timestep
const TRAINPERSTEP = 20;
const TESTPERSTEP = 3;

// multiply it by this to magnify for display 
const ZOOMFACTOR = 10;
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 //18 originally
const DOODLE_BLUR = 3; // blur factor applied to doodles 


let mnist;
// all data is loaded into this 
// mnist.train_images
// mnist.train_labels
// mnist.test_images
// mnist.test_labels


let nn;

let percent;

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?


// save inputs to global var to inspect
// type these names in console 
var train_inputs, test_inputs, demo_inputs, doodle_inputs;


// Matrix.randomize() is changed to point to this. Must be defined by user of Matrix. 

function randomWeight() {
    return (AB.randomFloatAtoB(-0.5, 0.5));
    // Coding Train default is -1 to 1
}


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

$('#ab-runheaderbox').attr('style', 'position: initial !important; max-height:95vh; margin-left: 350px');



//--- 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> " +
    `<div><h3>Processed image</h3><canvas id="can" width="280" height="280"></canvas></div>`

AB.msg(thehtml, 1);

// 2 Doodle variable data (guess)

// 3 Training header

// Generating table with good models, Author Deniss Strods
const createTableOfSavedModels = (savedModels, modelLoaded) => {

    let table =
        `<h3>Saved Models ${modelLoaded ? '<span style="color:green;">(Model loaded)</span>' : ''}<h3><table>`;
    table += '<tr><th>Action</th><th>Date</th><th>Acuracy</th><th>Comment</th></tr>';

    if (savedModels) {
        savedModels.forEach((model, index) => {
            const button =
                `<button onclick='loadDataIntoModel(savedItems[${index}]);' class='normbutton' >Load</button>`;
            table +=
                `<tr><td>${button}</td><td>${model.date}</td><td>${model.lastPercent && model.lastPercent.toFixed(2)}</td><td>${model.comment ? model.comment : 'other user created' }</td></tr>`;
        })
    }

    table += '</table>';

    return table;
}
// Refreshing saved table, Author Deniss Strods
let savedItems;
const refreshItems = (savedItems, modelLoaded = false) => {
    let thehtml =
        "<hr> <h1> 2. Training </h1> Middle row: Training image magnified (left) and original (right). <br>  " +
        " <button onclick='do_training = !do_training;' class='normbutton' >Stop / Start training</button><br> <button hidden onclick='saveCurrentWeights()' class='normbutton' >Save model</button> <br>";
    //<button onclick='saveCurrentWeights()' class='normbutton' >Save model</button> //removing this button so good model would not be owerwritten
    thehtml += createTableOfSavedModels(savedItems, modelLoaded);
    AB.msg(thehtml, 4);
}
refreshItems();

// Pulling out saved items, Author Deniss Strods
const getSavedItems = () => {
    
    AB.getAllData(objects => {
        console.log("Getting Saved Items", objects);
        const items = objects.map( o => o[2]);
        
        const elements = [];
        items.forEach(i=> {
            elements.push(...i);
        })
        savedItems = elements;
        refreshItems(savedItems);
    })
    
}

// Save current weights, Author Deniss Strods
const saveCurrentWeights = () => {
    if (AB.runloggedin) {
        const newItem = {
            date: new Date(),
            layers: nn.layers,
            lastPercent: percent,
            comment: 'Mark, use this for test'
        };

        savedItems = [newItem];

        console.log("Saving Data:", savedItems);

        AB.saveData(savedItems);
        refreshItems(savedItems);
    }
}
// Loading data into the model, Author Deniss Strods
const loadDataIntoModel = (model) => {
    do_training = false;
    //allow time to finish all the operations
    setTimeout(() => {
        nn.loadModel(model);
        refreshItems(savedItems, true);
    }, 500);

    //Reset all the params
    trainrun = 1;
    train_index = 0;
    testrun = 1;
    test_index = 0;
    total_tests = 0;
    total_correct = 0;
}

// 4 variable training data 

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

// 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, 8);

// 8 Demo variable data (random demo ID)
// 9 Demo variable data (changing guess)

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

//--- end of AB.msgs structure: ---------------------------------------------------------




function setup() {

    getSavedItems();
    createCanvas(canvaswidth, canvasheight);

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

    // 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/codingtrain/mnist.js",
            function() {
                console.log("All JS loaded");
                nn = new NeuralNetwork(noinput, nohidden,
                    nooutput);
                nn.setLearningRate(learningrate);
                loadData();
            });
        //  });
    });
    wipeDoodle();
}


let specificIndexes = [];
// load data set from local file (on this server)
function loadData() {
    loadMNIST(function(data) {
        mnist = data;
        console.log("All data loaded into mnist object:")
        console.log(mnist);
        AB
            .removeLoading(); // if no loading screen exists, this does nothing 


        // Selective training, pick what additional numbers to train upon, Author Deniss Strods...

        // let img = mnist.train_images[train_index];
        // let label = mnist.train_labels[train_index];

        // mnist.train_labels.forEach( (l,index)=> {
        //     if (l == 9 || l == 6 || l == 7 || l == 1){
        //         specificIndexes.push(index);
        //     }
        // });

        // console.log("INDEXES...", specificIndexes.length);


    });
}



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 getInputs(
    img) // convert img array into normalised input array 
{
    let inputs = [];
    for (let i = 0; i < PIXELSSQUARED; i++) {
        let bright = img[i];
        inputs[i] = bright / 255; // normalise to 0 to 1
    }
    return (inputs);
}



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

    // const index = specificIndexes[train_index];

    let img = mnist.train_images[train_index];
    let label = mnist.train_labels[train_index];

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

    // set up the inputs
    let inputs = getInputs(img); // get inputs from data array 

    // set up the outputs
    let targets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    targets[label] =
        1; // change one output location to 1, the rest stay at 0 


    train_inputs = inputs; // can inspect in console 
    nn.train(inputs, targets);

    thehtml = " trainrun: " + trainrun + "<br> no: " + train_index + ` / learning rate: ${decayLearningRate}`;
    AB.msg(thehtml, 5);

    train_index++;
    if (train_index == NOTRAIN) {
        train_index = 0;
        console.log("finished trainrun: " + trainrun);
        trainrun++;
        // learning decay added
        decayLearningRate = stepDecay(trainrun, learningrate);
        nn.setLearningRate(decayLearningRate);
        console.log("setting learning rate: ", decayLearningRate);
    }
}

// Investigated dynamic learning rate and identified that there may be benifit in adding learning rate decay
// https://towardsdatascience.com/learning-rate-schedules-and-adaptive-learning-rate-methods-for-deep-learning-2c8f433990d1
// Author Deniss Strods
const stepDecay = (epoch, initialRate) => {
    const drop = 0.5
    const epochsDrop = 10

    const lrate = initialRate * Math.pow(drop,
        Math.floor((1 + epoch) / epochsDrop))
    return lrate
}


function testit() // test the network with a single exemplar, from global var "test_index"
{
    let img = mnist.test_images[test_index];
    let label = mnist.test_labels[test_index];

    // set up the inputs
    let inputs = getInputs(img);

    test_inputs = inputs; // can inspect in console 
    let prediction = nn.predict(inputs); // array of outputs 
    let guess = findMax(prediction); // the top output 

    total_tests++;
    if (guess == label) total_correct++;

    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++;
    if (test_index == NOTEST) {
        console.log("finished testrun: " + testrun + " score: " +
            percent.toFixed(2));
        testrun++;
        test_index = 0;
        total_tests = 0;
        total_correct = 0;
    }
}




//--- find no.1 (and maybe no.2) output nodes ---------------------------------------
// (restriction) assumes array values start at 0 (which is true for output nodes) 


function find12(
    a) // return array showing indexes of no.1 and no.2 values in array 
{
    let no1 = 0;
    let no2 = 0;
    let no1value = 0;
    let no2value = 0;

    for (let i = 0; i < a.length; i++) {
        if (a[i] > no1value) {
            no1 = i;
            no1value = a[i];
        } else if (a[i] > no2value) {
            no2 = i;
            no2value = a[i];
        }
    }

    var b = [no1, no2];
    return b;
}


// just get the maximum - separate function for speed - done many times 
// find our guess - the max of the output nodes array

function findMax(a) {
    let no1 = 0;
    let no1value = 0;

    for (let i = 0; i < a.length; i++) {
        if (a[i] > no1value) {
            no1 = i;
            no1value = a[i];
        }
    }

    return no1;
}




// --- the draw function -------------------------------------------------------------
// every step:

function perdictDoodle() {
    guessDoodle();
}

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




//--- demo -------------------------------------------------------------
// demo some test image and predict it
// get it from test set so have not used it in training


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

    demo = mnist.test_images[i];
    var label = mnist.test_labels[i];

    thehtml = "Test image no: " + i + "<br>" +
        "Classification: " + label + "<br>";
    AB.msg(thehtml, 9);

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


function drawDemo() {
    var theimage = getImage(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 

    showInputs(demo_inputs);
    let prediction = nn.predict(inputs); // array of outputs 
    let guess = findMax(prediction); // the top output 

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



//--- doodle -------------------------------------------------------------
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.loadPixels();

    // Processing the doodle image
    img = getCanvasImagePixels(img);

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

    doodle_inputs = inputs; // can inspect in console

    // feed forward to make prediction 
    let prediction = nn.predict(inputs); // array of outputs 
    let b = find12(prediction); // get no.1 and no.2 guesses  

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


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




// --- debugging --------------------------------------------------
// in console
// showInputs(demo_inputs);
// showInputs(doodle_inputs);


function showInputs(inputs)
// display inputs row by row, corresponding to square of pixels 
{
    var str = "";
    for (let i = 0; i < inputs.length; i++) {
        if (i % PIXELS == 0) str = str +
            "\n"; // new line for each row of pixels 
        var value = inputs[i];
        str = str + " " + value.toFixed(2);
    }
    console.log(str);
}


// Other techniques for learning
class ActivationFunction {
    constructor(func, dfunc) {
        this.func = func;
        this.dfunc = dfunc;
    }
}

let sigmoid = new ActivationFunction(
    x => 1 / (1 + Math.exp(-x)),
    y => y * (1 - y)
);

let tanh = new ActivationFunction(
    x => Math.tanh(x),
    y => 1 - (y * y)
);

const softmax = (arr) => {
    const C = Math.max(...arr);
    const d = arr.map((y) => Math.exp(y - C)).reduce((a, b) => a + b);
    return arr.map((value, index) => {
        return Math.exp(value - C) / d;
    })
}

const softmaxJacobian = (arr) => {

    let jacobian = [...new Array(arr.length)].map(x => new Array(arr.length));
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            if (i == j) {
                jacobian[i][j] = arr[i] * (1 - arr[i]);
            } else {
                jacobian[i][j] = -arr[i] * arr[j];
            }
        }
    }

    return jacobian;
}

// We are not using error function in softmax deriviative, Author Deniss Strods
const errorFunction = (y, o) => -y * Math.log(o); // y expected correct value, o actual output value

// Softmax deriviative, Author Deniss Strods
const dSoftmax = (y, o) => o - y; // y expected correct value, o actual output value

// NN LAyer representation class, author Deniss Strods
class NeuralNetworkLayer {
    constructor(in_nodes, hid_nodes, activationFunction) {
        this.input_nodes = in_nodes;
        this.hidden_nodes = hid_nodes;

        this.weights_ih = new Matrix(this.hidden_nodes, this
            .input_nodes);
        this.weights_ih.randomize();

        this.bias_h = new Matrix(this.hidden_nodes, 1);
        this.bias_h.randomize();

        this.activationFunction = activationFunction;
    }
}

// HEavily modified by Deniss Strods, almost nothing left from original,
class NeuralNetwork {
    constructor(in_nodes, hid_nodes, out_nodes) {

        // adding softmax layer and 2 hidden layers, selecting activation function for layers

        const hiddenLayer = new NeuralNetworkLayer(in_nodes,
            hid_nodes, 'sigmoid');

        const secondHiddenLayer = new NeuralNetworkLayer(hid_nodes,
            hid_nodes, 'sigmoid');

        const outputLayer = new NeuralNetworkLayer(hid_nodes, out_nodes, 'softmax');

        this.layers = [hiddenLayer, secondHiddenLayer, outputLayer];

        this.setLearningRate();
    }

    // passing trough the layers in the layers list, calculaing and getting perdiction
    forwardPass(inputs, layers) {

        // Iterating trough all the layers forward
        let previousLayer;
        // allowing to set up differen activation function per layer
        const calculatedLayers = layers.map((layer, index) => {
            let matrix = Matrix.multiply(layer.weights_ih,
                !previousLayer ? inputs : previousLayer
            );
            matrix.add(layer.bias_h);
            // adding ability to identify
            if (layer.activationFunction === 'softmax') {
                const softmaxData = softmax(matrix.data).map(e => [e]);
                matrix.data = softmaxData;
            } else if (layer.activationFunction === 'sigmoid') {
                matrix.map(sigmoid.func);
            } else if (layer.activationFunction === 'tanh') {
                matrix.map(tanh.func);
            }

            previousLayer = matrix;
            return matrix;
        })

        return calculatedLayers;
    }

    predict(input_array) {

        // // Generating the Hidden Outputs
        let inputs = Matrix.fromArray(input_array);

        const calculatedLayers = this.forwardPass(inputs, this.layers)

        // Sending back to the caller!
        return calculatedLayers[calculatedLayers.length - 1].toArray();
    }

    setLearningRate(learning_rate = 0.1) {
        this.learning_rate = learning_rate;
    }

    setActivationFunction(func = sigmoid) {
        this.activation_function = func;
    }

    train(input_array, target_array) {
        // Generating the Hidden Outputs
        let inputs = Matrix.fromArray(input_array);

        const calculatedLayers = this.forwardPass(inputs, this.layers)

        // This is backwards pass
        let error;
        for (let i = calculatedLayers.length - 1; i >= 0; i--) {
            const layer = calculatedLayers[i];

            const previousLayer = (i - 1) < 0 ? inputs :
                calculatedLayers[i - 1];

            let e;
            if (!error) {
                e = Matrix.subtract(Matrix.fromArray(
                    target_array), layer);
            } else {
                const nextLayer = this.layers[i + 1];
                e = Matrix.multiply(Matrix.transpose(nextLayer
                    .weights_ih), error);
            }
            error = e;
            let gradients;
            // allowing to set up differen activation function per layer
            if (this.layers[i].activationFunction === 'softmax') {
                let errorSumm = 0;

                const gSoftmax = target_array.map((item, index) => {
                    return [dSoftmax(item, layer.data[index]) * -1];
                });

                const softmaxGradients = new Matrix(10, 1);
                softmaxGradients.data = gSoftmax;
                gradients = softmaxGradients;

            } else if (this.layers[i].activationFunction === 'sigmoid') {
                gradients = Matrix.map(layer,
                    sigmoid.dfunc);
                gradients.multiply(e);
            } else if (this.layers[i].activationFunction === 'tanh') {
                gradients = Matrix.map(layer,
                    tanh.dfunc);
                gradients.multiply(e);
            }


            gradients.multiply(this.learning_rate);

            // Calculate deltas
            let weight_ho_deltas = Matrix.multiply(gradients,
                Matrix.transpose(previousLayer));


            // Adjust the weights by deltas
            this.layers[i].weights_ih.add(weight_ho_deltas);
            // Adjust the bias by its deltas (which is just the gradients)
            this.layers[i].bias_h.add(gradients);
        }
    }

    // Accept an arbitrary function for mutation
    mutate(func) {
        this.weights_ih.map(func);
        this.weights_ho.map(func);
        this.bias_h.map(func);
        this.bias_o.map(func);
    }


    remapMatricFromObject(matrix, object) {
        const {
            data,
            rows,
            cols
        } = object;
        matrix.data = data;
        matrix.rows = rows;
        matrix.cols = cols;
    }

    // Loading model, Author Deniss Strods
    loadModel(model) {
        const {
            layers
        } = model
        if (this.layers.length === layers.length) {
            console.log("Loading model", model);

            this.layers.forEach((layer, index) => {
                const {
                    weights_ih,
                    bias_h,
                    input_nodes,
                    hidden_nodes,
                    activationFunction
                } = layers[index];

                this.remapMatricFromObject(layer.weights_ih, weights_ih);
                this.remapMatricFromObject(layer.bias_h, bias_h);
                layer.activationFunction = activationFunction;
                layer.input_nodes = input_nodes;
                layer.hidden_nodes = hidden_nodes;
            });
        }
    }
}

/// this was takken from myselph.de/neuralNet.html
// given grayscale image, find bounding rectangle of digit defined
// by above-threshold surrounding
function getBoundingRectangle(img, threshold) {
    var rows = img.length;
    var columns = img[0].length;
    var minX = columns;
    var minY = rows;
    var maxX = -1;
    var maxY = -1;
    for (var y = 0; y < rows; y++) {
        for (var x = 0; x < columns; x++) {
            if (img[y][x] > threshold) {
                if (minX > x) minX = x;
                if (maxX < x) maxX = x;
                if (minY > y) minY = y;
                if (maxY < y) maxY = y;
            }
        }
    }
    return {
        minY: minY,
        minX: minX,
        maxY: maxY,
        maxX: maxX
    };
}

/// this was takken from myselph.de/neuralNet.html
// take canvas image and convert to grayscale. Mainly because my
// own functions operate easier on grayscale, but some stuff like
// resizing and translating is better done with the canvas functions
function imageDataToGrayscale(imgData) {
    const grayscaleImg = [];
    for (var y = 0; y < imgData.height; y++) {
        grayscaleImg[y] = [];
        for (var x = 0; x < imgData.width; x++) {
            var offset = y * 4 * imgData.width + 4 * x;
            var alpha = imgData.data[offset + 3];
            // weird: when painting with stroke, alpha == 0 means white;
            // alpha > 0 is a grayscale value; in that case I simply take the R value
            if (alpha == 0) {
                imgData.data[offset] = 255;
                imgData.data[offset + 1] = 255;
                imgData.data[offset + 2] = 255;
            }
            imgData.data[offset + 3] = 255;
            // simply take red channel value. Not correct, but works for
            // black or white images.
            grayscaleImg[y][x] = imgData.data[y * 4 * imgData.width + x * 4 + 0] / 255;
        }
    }
    return grayscaleImg;
}

// example input {minY: 44, minX: 137, maxY: 249, maxX: 162}
// finding necesarry shift based on the min max of X and Y author Deniss Strods
const findShiftAndScale = ({
    minY,
    minX,
    maxY,
    maxX
}) => {

    const subSquareSize = 200;
    const squareSize = 280;

    const objHeight = maxY - minY;
    const objWidth = maxX - minX;
    const idealGapY = Math.floor((squareSize - objHeight) / 2);
    const idealGapX = Math.floor((squareSize - objWidth) / 2);

    // shift needed to center
    const minYdelta = idealGapY - minY;
    const minXdelta = idealGapX - minX;

    // scale needed
    const ratioY = subSquareSize / objWidth;
    const ratioX = subSquareSize / objHeight;

    const sortedList = [ratioY, ratioX].sort();

    return {
        minYdelta,
        minXdelta,
        scale: sortedList[0]
    }
}

// Shifting context, author Deniss Strods
const shiftContext = (ctx, w, h, dx, dy) => {
    const imageData = ctx.getImageData(0, 0, w, h);
    ctx.strokeStyle = "black";
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, w, h);
    ctx.putImageData(imageData, dx, dy);
}

// Resizing image based on ratio, author Deniss Strods
const resizeTo = (canvas, pct) => {
    const tempCanvas = document.createElement("canvas");
    const tctx = tempCanvas.getContext("2d");
    const cw = canvas.width;
    const ch = canvas.height;

    tempCanvas.width = cw;
    tempCanvas.height = ch;

    tctx.setTransform(pct, 0, 0, pct, tctx.canvas.width / 2, tctx.canvas.height / 2);
    tctx.drawImage(canvas, -canvas.width / 2, -canvas.height / 2); // draw the image offset by half

    const ctx = canvas.getContext('2d');
    ctx.drawImage(tempCanvas, 0, 0);
}

// Getting pixels for comparison, author Deniss Strods
const getCanvasImagePixels = (image) => {

    let {
        imageData: imgData,
        canvas
    } = image;

    let grayscaleImg = imageDataToGrayscale(imgData);

    imgData = image.drawingContext.getImageData(0, 0, 280, 280);
    const boundingRectangle = getBoundingRectangle(grayscaleImg, 0.02);

    const canvasCopy = document.createElement("canvas");
    canvasCopy.width = imgData.width;
    canvasCopy.height = imgData.height;
    const copyCtx = canvasCopy.getContext("2d");
    copyCtx.drawImage(image.drawingContext.canvas, 0, 0);


    const {
        minYdelta,
        minXdelta,
        scale
    } = findShiftAndScale(boundingRectangle)
    shiftContext(copyCtx, canvasCopy.width, canvasCopy.height, minXdelta, minYdelta);
    resizeTo(canvasCopy, scale);


    // now bin image into 10x10 blocks (giving a 28x28 image)
    // fragment takken from myselph.de/neuralNet.html
    imgData = copyCtx.getImageData(0, 0, 280, 280);
    grayscaleImg = imageDataToGrayscale(imgData);
    let nnInput = new Array(784);
    for (let y = 0; y < 28; y++) {
        for (let x = 0; x < 28; x++) {
            let mean = 0;
            for (let v = 0; v < 10; v++) {
                for (let h = 0; h < 10; h++) {
                    mean += grayscaleImg[y * 10 + v][x * 10 + h];
                }
            }
            mean = (1 - mean / 100); // average and invert
            nnInput[x * 28 + y] = (mean - .5) / .5;
        }
    }

    // Drawing, fragment takken from myselph.de/neuralNet.html
    const imgCanvas = document.getElementById('can');
    const ctx = imgCanvas.getContext("2d");
    ctx.clearRect(0, 0, imgCanvas.width, imgCanvas.height);
    ctx.drawImage(canvas, 0, 0);
    for (var y = 0; y < 28; y++) {
        for (var x = 0; x < 28; x++) {
            var block = ctx.getImageData(x * 10, y * 10, 10, 10);
            var newVal = 255 * (0.5 - nnInput[x * 28 + y] / 2);
            for (var i = 0; i < 4 * 10 * 10; i += 4) {
                block.data[i] = newVal;
                block.data[i + 1] = newVal;
                block.data[i + 2] = newVal;
                block.data[i + 3] = 255;
            }
            ctx.putImageData(block, x * 10, y * 10);
        }
    }

    const img = createImage(canvas.width, canvas.height);
    img.drawingContext.drawImage(imgCanvas, 0, 0);
    img.resize(PIXELS, PIXELS);
    img.loadPixels();
    return img;
}