From 2e44c8bec01183eb2de9ac816a3cca8110eb8a3b Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 16:32:05 -0400 Subject: [PATCH 01/11] ReferenceError: pow is not defined --- nn.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nn.js b/nn.js index a09c10f..a3112d4 100644 --- a/nn.js +++ b/nn.js @@ -12,7 +12,7 @@ // This is used for activation // https://en.wikipedia.org/wiki/Sigmoid_function NeuralNetwork.sigmoid = function(x) { - var y = 1 / (1 + pow(Math.E, -x)); + var y = 1 / (1 + Math.pow(Math.E, -x)); return y; } @@ -27,7 +27,7 @@ NeuralNetwork.tanh = function(x) { } NeuralNetwork.dtanh = function(x) { - var y = 1 / (pow(Math.cosh(x), 2)); + var y = 1 / (Math.pow(Math.cosh(x), 2)); return y; } From c8c106c47eabd7b05136043585ff34b68460b158 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 16:46:33 -0400 Subject: [PATCH 02/11] Add comments to all nn functions --- nn.js | 57 +++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 10 deletions(-) diff --git a/nn.js b/nn.js index a3112d4..daff632 100644 --- a/nn.js +++ b/nn.js @@ -8,30 +8,50 @@ // This version of nn.js adds some functionality for evolution // copy() and mutate() -// Sigmoid function -// This is used for activation -// https://en.wikipedia.org/wiki/Sigmoid_function +/** + * Sigmoid function + * This is used for activation + * https://en.wikipedia.org/wiki/Sigmoid_function + * @param {Number} x + * @return {Number} + */ NeuralNetwork.sigmoid = function(x) { var y = 1 / (1 + Math.pow(Math.E, -x)); return y; } -// This is the Sigmoid derivative! +/** + * This is the Sigmoid derivative! + * @param {Number} x + * @return {Number} + */ NeuralNetwork.dSigmoid = function(x) { return x * (1 - x); } +/** + * @param {Number} x + * @return {Number} + */ NeuralNetwork.tanh = function(x) { var y = Math.tanh(x); return y; } +/** + * @param {Number} x + * @return {Number} + */ NeuralNetwork.dtanh = function(x) { var y = 1 / (Math.pow(Math.cosh(x), 2)); return y; } -// This is how we adjust weights ever so slightly +/** + * This is how we adjust weights ever so slightly + * @param {Number} x + * @return {Number} + */ function mutate(x) { if (random(1) < 0.1) { var offset = randomGaussian() * 0.5; @@ -43,7 +63,14 @@ function mutate(x) { } } -// Neural Network constructor function +/** + * Neural Network constructor function + * @param {Number} inputnodes + * @param {Number} hiddennodes + * @param {Number} outputnodes + * @param {Number} learning_rate + * @param {String} activation + */ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, activation) { // If it's a copy of another NN @@ -93,6 +120,9 @@ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, acti } +/** + * @return {NeuralNetwork} + */ NeuralNetwork.prototype.copy = function() { return new NeuralNetwork(this); } @@ -102,7 +132,11 @@ NeuralNetwork.prototype.mutate = function() { this.who = Matrix.map(this.who, mutate); } -// Train the network with inputs and targets +/** + * Train the network with inputs and targets + * @param {Array} inputs_array + * @param {Array} targets_array + */ NeuralNetwork.prototype.train = function(inputs_array, targets_array) { // Turn input and target arrays into matrices @@ -153,8 +187,11 @@ NeuralNetwork.prototype.train = function(inputs_array, targets_array) { this.wih.add(deltaW_hidden); } - -// Query the network! +/** + * Query the network! + * @param {Array} inputs_array + * @return {Array} + */ NeuralNetwork.prototype.query = function(inputs_array) { // Turn input array into a matrix @@ -173,4 +210,4 @@ NeuralNetwork.prototype.query = function(inputs_array) { // Return the result as an array return outputs.toArray(); -} +} \ No newline at end of file From 5185dad562116f3a347ad21f6a5b3af4cdb6a698 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 16:46:45 -0400 Subject: [PATCH 03/11] Tabified using Visual Studio --- nn.js | 258 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 129 insertions(+), 129 deletions(-) diff --git a/nn.js b/nn.js index daff632..1a8ca80 100644 --- a/nn.js +++ b/nn.js @@ -15,9 +15,9 @@ * @param {Number} x * @return {Number} */ -NeuralNetwork.sigmoid = function(x) { - var y = 1 / (1 + Math.pow(Math.E, -x)); - return y; +NeuralNetwork.sigmoid = function (x) { + var y = 1 / (1 + Math.pow(Math.E, -x)); + return y; } /** @@ -25,26 +25,26 @@ NeuralNetwork.sigmoid = function(x) { * @param {Number} x * @return {Number} */ -NeuralNetwork.dSigmoid = function(x) { - return x * (1 - x); +NeuralNetwork.dSigmoid = function (x) { + return x * (1 - x); } /** * @param {Number} x * @return {Number} */ -NeuralNetwork.tanh = function(x) { - var y = Math.tanh(x); - return y; +NeuralNetwork.tanh = function (x) { + var y = Math.tanh(x); + return y; } /** * @param {Number} x * @return {Number} */ -NeuralNetwork.dtanh = function(x) { - var y = 1 / (Math.pow(Math.cosh(x), 2)); - return y; +NeuralNetwork.dtanh = function (x) { + var y = 1 / (Math.pow(Math.cosh(x), 2)); + return y; } /** @@ -53,14 +53,14 @@ NeuralNetwork.dtanh = function(x) { * @return {Number} */ function mutate(x) { - if (random(1) < 0.1) { - var offset = randomGaussian() * 0.5; - // var offset = random(-0.1, 0.1); - var newx = x + offset; - return newx; - } else { - return x; - } + if (random(1) < 0.1) { + var offset = randomGaussian() * 0.5; + // var offset = random(-0.1, 0.1); + var newx = x + offset; + return newx; + } else { + return x; + } } /** @@ -73,63 +73,63 @@ function mutate(x) { */ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, activation) { - // If it's a copy of another NN - if (arguments[0] instanceof NeuralNetwork) { - var nn = arguments[0]; - this.inodes = nn.inodes; - this.hnodes = nn.hnodes; - this.onodes = nn.onodes; - this.wih = nn.wih.copy(); - this.who = nn.who.copy(); - this.activation = nn.activation; - this.derivative = nn.derivative; - this.lr = this.lr; - } else { - // Number of nodes in layer (input, hidden, output) - // This network is limited to 3 layers - this.inodes = inputnodes; - this.hnodes = hiddennodes; - this.onodes = outputnodes; - - // These are the weight matrices - // wih: weights from input to hidden - // who: weights from hidden to output - // weights inside the arrays are w_i_j - // where link is from node i to node j in the next layer - // Matrix is rows X columns - this.wih = new Matrix(this.hnodes, this.inodes); - this.who = new Matrix(this.onodes, this.hnodes); - - // Start with random values - this.wih.randomize(); - this.who.randomize(); - - // Default learning rate of 0.1 - this.lr = learning_rate || 0.1; - - // Activation Function - if (activation == 'tanh') { - this.activation = NeuralNetwork.tanh; - this.derivative = NeuralNetwork.dtanh; - } else { - this.activation = NeuralNetwork.sigmoid; - this.derivative = NeuralNetwork.dSigmoid; - } - - } + // If it's a copy of another NN + if (arguments[0] instanceof NeuralNetwork) { + var nn = arguments[0]; + this.inodes = nn.inodes; + this.hnodes = nn.hnodes; + this.onodes = nn.onodes; + this.wih = nn.wih.copy(); + this.who = nn.who.copy(); + this.activation = nn.activation; + this.derivative = nn.derivative; + this.lr = this.lr; + } else { + // Number of nodes in layer (input, hidden, output) + // This network is limited to 3 layers + this.inodes = inputnodes; + this.hnodes = hiddennodes; + this.onodes = outputnodes; + + // These are the weight matrices + // wih: weights from input to hidden + // who: weights from hidden to output + // weights inside the arrays are w_i_j + // where link is from node i to node j in the next layer + // Matrix is rows X columns + this.wih = new Matrix(this.hnodes, this.inodes); + this.who = new Matrix(this.onodes, this.hnodes); + + // Start with random values + this.wih.randomize(); + this.who.randomize(); + + // Default learning rate of 0.1 + this.lr = learning_rate || 0.1; + + // Activation Function + if (activation == 'tanh') { + this.activation = NeuralNetwork.tanh; + this.derivative = NeuralNetwork.dtanh; + } else { + this.activation = NeuralNetwork.sigmoid; + this.derivative = NeuralNetwork.dSigmoid; + } + + } } /** * @return {NeuralNetwork} */ -NeuralNetwork.prototype.copy = function() { - return new NeuralNetwork(this); +NeuralNetwork.prototype.copy = function () { + return new NeuralNetwork(this); } -NeuralNetwork.prototype.mutate = function() { - this.wih = Matrix.map(this.wih, mutate); - this.who = Matrix.map(this.who, mutate); +NeuralNetwork.prototype.mutate = function () { + this.wih = Matrix.map(this.wih, mutate); + this.who = Matrix.map(this.who, mutate); } /** @@ -137,54 +137,54 @@ NeuralNetwork.prototype.mutate = function() { * @param {Array} inputs_array * @param {Array} targets_array */ -NeuralNetwork.prototype.train = function(inputs_array, targets_array) { - - // Turn input and target arrays into matrices - var inputs = Matrix.fromArray(inputs_array); - var targets = Matrix.fromArray(targets_array); - - // The input to the hidden layer is the weights (wih) multiplied by inputs - var hidden_inputs = Matrix.dot(this.wih, inputs); - // The outputs of the hidden layer pass through sigmoid activation function - var hidden_outputs = Matrix.map(hidden_inputs, this.activation); - - // The input to the output layer is the weights (who) multiplied by hidden layer - var output_inputs = Matrix.dot(this.who, hidden_outputs); - - // The output of the network passes through sigmoid activation function - var outputs = Matrix.map(output_inputs, this.activation); - - // Error is TARGET - OUTPUT - var output_errors = Matrix.subtract(targets, outputs); - - // Now we are starting back propogation! - - // Transpose hidden <-> output weights - var whoT = this.who.transpose(); - // Hidden errors is output error multiplied by weights (who) - var hidden_errors = Matrix.dot(whoT, output_errors) - - // Calculate the gradient, this is much nicer in python! - var gradient_output = Matrix.map(outputs, this.derivative); - // Weight by errors and learing rate - gradient_output.multiply(output_errors); - gradient_output.multiply(this.lr); - - // Gradients for next layer, more back propogation! - var gradient_hidden = Matrix.map(hidden_outputs, this.derivative); - // Weight by errors and learning rate - gradient_hidden.multiply(hidden_errors); - gradient_hidden.multiply(this.lr); - - // Change in weights from HIDDEN --> OUTPUT - var hidden_outputs_T = hidden_outputs.transpose(); - var deltaW_output = Matrix.dot(gradient_output, hidden_outputs_T); - this.who.add(deltaW_output); - - // Change in weights from INPUT --> HIDDEN - var inputs_T = inputs.transpose(); - var deltaW_hidden = Matrix.dot(gradient_hidden, inputs_T); - this.wih.add(deltaW_hidden); +NeuralNetwork.prototype.train = function (inputs_array, targets_array) { + + // Turn input and target arrays into matrices + var inputs = Matrix.fromArray(inputs_array); + var targets = Matrix.fromArray(targets_array); + + // The input to the hidden layer is the weights (wih) multiplied by inputs + var hidden_inputs = Matrix.dot(this.wih, inputs); + // The outputs of the hidden layer pass through sigmoid activation function + var hidden_outputs = Matrix.map(hidden_inputs, this.activation); + + // The input to the output layer is the weights (who) multiplied by hidden layer + var output_inputs = Matrix.dot(this.who, hidden_outputs); + + // The output of the network passes through sigmoid activation function + var outputs = Matrix.map(output_inputs, this.activation); + + // Error is TARGET - OUTPUT + var output_errors = Matrix.subtract(targets, outputs); + + // Now we are starting back propogation! + + // Transpose hidden <-> output weights + var whoT = this.who.transpose(); + // Hidden errors is output error multiplied by weights (who) + var hidden_errors = Matrix.dot(whoT, output_errors) + + // Calculate the gradient, this is much nicer in python! + var gradient_output = Matrix.map(outputs, this.derivative); + // Weight by errors and learing rate + gradient_output.multiply(output_errors); + gradient_output.multiply(this.lr); + + // Gradients for next layer, more back propogation! + var gradient_hidden = Matrix.map(hidden_outputs, this.derivative); + // Weight by errors and learning rate + gradient_hidden.multiply(hidden_errors); + gradient_hidden.multiply(this.lr); + + // Change in weights from HIDDEN --> OUTPUT + var hidden_outputs_T = hidden_outputs.transpose(); + var deltaW_output = Matrix.dot(gradient_output, hidden_outputs_T); + this.who.add(deltaW_output); + + // Change in weights from INPUT --> HIDDEN + var inputs_T = inputs.transpose(); + var deltaW_hidden = Matrix.dot(gradient_hidden, inputs_T); + this.wih.add(deltaW_hidden); } /** @@ -192,22 +192,22 @@ NeuralNetwork.prototype.train = function(inputs_array, targets_array) { * @param {Array} inputs_array * @return {Array} */ -NeuralNetwork.prototype.query = function(inputs_array) { +NeuralNetwork.prototype.query = function (inputs_array) { - // Turn input array into a matrix - var inputs = Matrix.fromArray(inputs_array); + // Turn input array into a matrix + var inputs = Matrix.fromArray(inputs_array); - // The input to the hidden layer is the weights (wih) multiplied by inputs - var hidden_inputs = Matrix.dot(this.wih, inputs); - // The outputs of the hidden layer pass through sigmoid activation function - var hidden_outputs = Matrix.map(hidden_inputs, this.activation); + // The input to the hidden layer is the weights (wih) multiplied by inputs + var hidden_inputs = Matrix.dot(this.wih, inputs); + // The outputs of the hidden layer pass through sigmoid activation function + var hidden_outputs = Matrix.map(hidden_inputs, this.activation); - // The input to the output layer is the weights (who) multiplied by hidden layer - var output_inputs = Matrix.dot(this.who, hidden_outputs); + // The input to the output layer is the weights (who) multiplied by hidden layer + var output_inputs = Matrix.dot(this.who, hidden_outputs); - // The output of the network passes through sigmoid activation function - var outputs = Matrix.map(output_inputs, this.activation); + // The output of the network passes through sigmoid activation function + var outputs = Matrix.map(output_inputs, this.activation); - // Return the result as an array - return outputs.toArray(); + // Return the result as an array + return outputs.toArray(); } \ No newline at end of file From 7c27eeac43fd10776ae8e52d5b667345e2067c2b Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 16:49:10 -0400 Subject: [PATCH 04/11] Applied correct spacing to comments --- nn.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/nn.js b/nn.js index 1a8ca80..8f66898 100644 --- a/nn.js +++ b/nn.js @@ -85,6 +85,7 @@ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, acti this.derivative = nn.derivative; this.lr = this.lr; } else { + // Number of nodes in layer (input, hidden, output) // This network is limited to 3 layers this.inodes = inputnodes; @@ -115,9 +116,7 @@ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, acti this.activation = NeuralNetwork.sigmoid; this.derivative = NeuralNetwork.dSigmoid; } - } - } /** @@ -145,6 +144,7 @@ NeuralNetwork.prototype.train = function (inputs_array, targets_array) { // The input to the hidden layer is the weights (wih) multiplied by inputs var hidden_inputs = Matrix.dot(this.wih, inputs); + // The outputs of the hidden layer pass through sigmoid activation function var hidden_outputs = Matrix.map(hidden_inputs, this.activation); @@ -161,17 +161,20 @@ NeuralNetwork.prototype.train = function (inputs_array, targets_array) { // Transpose hidden <-> output weights var whoT = this.who.transpose(); + // Hidden errors is output error multiplied by weights (who) var hidden_errors = Matrix.dot(whoT, output_errors) // Calculate the gradient, this is much nicer in python! var gradient_output = Matrix.map(outputs, this.derivative); + // Weight by errors and learing rate gradient_output.multiply(output_errors); gradient_output.multiply(this.lr); // Gradients for next layer, more back propogation! var gradient_hidden = Matrix.map(hidden_outputs, this.derivative); + // Weight by errors and learning rate gradient_hidden.multiply(hidden_errors); gradient_hidden.multiply(this.lr); @@ -199,6 +202,7 @@ NeuralNetwork.prototype.query = function (inputs_array) { // The input to the hidden layer is the weights (wih) multiplied by inputs var hidden_inputs = Matrix.dot(this.wih, inputs); + // The outputs of the hidden layer pass through sigmoid activation function var hidden_outputs = Matrix.map(hidden_inputs, this.activation); From 459af6ac0f00281328af6f569f83cc244e9be6f3 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 16:55:03 -0400 Subject: [PATCH 05/11] Add return to constructor --- nn.js | 1 + 1 file changed, 1 insertion(+) diff --git a/nn.js b/nn.js index 8f66898..5ba4b31 100644 --- a/nn.js +++ b/nn.js @@ -70,6 +70,7 @@ function mutate(x) { * @param {Number} outputnodes * @param {Number} learning_rate * @param {String} activation + * @return {NeuralNetwork} */ function NeuralNetwork(inputnodes, hiddennodes, outputnodes, learning_rate, activation) { From 0e569a76c1e722331ba49d94090b5c1a6d998f7e Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 17:00:28 -0400 Subject: [PATCH 06/11] Add comments --- matrix.js | 74 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/matrix.js b/matrix.js index 4c694ce..52fd6a1 100644 --- a/matrix.js +++ b/matrix.js @@ -8,7 +8,12 @@ // This is my own ridiculous Matrix implemenation // Would probably make more sense to use math.js or something else! -// Make a matrix full of zeros +/** + * Make a matrix full of zeros + * @param {Number} rows + * @param {Number} cols + * @return {Matrix} + */ function Matrix(rows, cols) { this.rows = rows; this.cols = cols; @@ -21,7 +26,9 @@ function Matrix(rows, cols) { } } -// This fills the matrix with random values (gaussian distribution) +/** + * This fills the matrix with random values (gaussian distribution) + */ Matrix.prototype.randomize = function() { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.cols; j++) { @@ -31,7 +38,10 @@ Matrix.prototype.randomize = function() { } } -// Take the matrix and make it a 1 dimensional array +/** + * Take the matrix and make it a 1 dimensional array + * @return {Array} + */ Matrix.prototype.toArray = function() { // Add all the values to the array var arr = []; @@ -43,9 +53,11 @@ Matrix.prototype.toArray = function() { return arr; } - -// This transposes a matrix -// rows X cols --> cols X rows +/** + * This transposes a matrix + * rows X cols --> cols X rows + * @return {Matrix} + */ Matrix.prototype.transpose = function() { var result = new Matrix(this.cols, this.rows); for (var i = 0; i < result.rows; i++) { @@ -56,7 +68,10 @@ Matrix.prototype.transpose = function() { return result; } -// This makes a copy of the matrix +/** + * This makes a copy of the matrix + * @return {Matrix} + */ Matrix.prototype.copy = function() { var result = new Matrix(this.rows, this.cols); for (var i = 0; i < result.rows; i++) { @@ -67,7 +82,10 @@ Matrix.prototype.copy = function() { return result; } -// This adds another matrix or a single value +/** + * This adds another matrix or a single value + * @param {Matrix} other + */ Matrix.prototype.add = function(other) { // Are we trying to add a Matrix? if (other instanceof Matrix) { @@ -86,8 +104,11 @@ Matrix.prototype.add = function(other) { } } -// This multiplies another matrix or a single value -// This is different than the dot() function! +/** + * This multiplies another matrix or a single value + * This is different than the dot() function! + * @param {Matrix} other + */ Matrix.prototype.multiply = function(other) { // Are we trying to multiply a Matrix? if (other instanceof Matrix) { @@ -106,11 +127,12 @@ Matrix.prototype.multiply = function(other) { } } - -// These are some static functions to operate on a matrix - -// This is the trickiest one -// Takes a function and applies it to all values in the matrix +/** + * This is the trickiest one + * Takes a function and applies it to all values in the matrix + * @param {Matrix} m + * @param {Function} fn + */ Matrix.map = function(m, fn) { var result = new Matrix(m.rows, m.cols); for (var i = 0; i < result.rows; i++) { @@ -121,7 +143,12 @@ Matrix.map = function(m, fn) { return result; } -// Subtracts one matrix from another +/** + * Subtracts one matrix from another + * @param {Matrix} a + * @param {Matrix} b + * @return {Matrix} + */ Matrix.subtract = function(a, b) { var result = new Matrix(a.rows, a.cols); for (var i = 0; i < result.rows; i++) { @@ -132,8 +159,12 @@ Matrix.subtract = function(a, b) { return result; } - -// Multiplies two matrices together +/** + * Multiplies two matrices together + * @param {Matrix} a + * @param {Matrix} b + * @return {Matrix} + */ Matrix.dot = function(a, b) { // Won't work if columns of A don't equal columns of B if (a.cols != b.rows) { @@ -156,8 +187,11 @@ Matrix.dot = function(a, b) { return result; } - -// Turn a 1 dimensional array into a matrix +/** + * Turn a 1 dimensional array into a matrix + * @param {Array} + * @return {Matrix} + */ Matrix.fromArray = function(array) { var m = new Matrix(array.length, 1); for (var i = 0; i < array.length; i++) { From c36d7f3d3fbc7720b8bc0b45ec89acbda2d93181 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 17:00:44 -0400 Subject: [PATCH 07/11] Format using Visual Studio Code --- matrix.js | 232 +++++++++++++++++++++++++++--------------------------- 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/matrix.js b/matrix.js index 52fd6a1..244e905 100644 --- a/matrix.js +++ b/matrix.js @@ -15,42 +15,42 @@ * @return {Matrix} */ function Matrix(rows, cols) { - this.rows = rows; - this.cols = cols; - this.matrix = new Array(rows); - for (var i = 0; i < this.rows; i++) { - this.matrix[i] = new Array(cols); - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] = 0; - } - } + this.rows = rows; + this.cols = cols; + this.matrix = new Array(rows); + for (var i = 0; i < this.rows; i++) { + this.matrix[i] = new Array(cols); + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] = 0; + } + } } /** * This fills the matrix with random values (gaussian distribution) */ -Matrix.prototype.randomize = function() { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] = randomGaussian(); - //this.matrix[i][j] = random(-1, 1); - } - } +Matrix.prototype.randomize = function () { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] = randomGaussian(); + //this.matrix[i][j] = random(-1, 1); + } + } } /** * Take the matrix and make it a 1 dimensional array * @return {Array} */ -Matrix.prototype.toArray = function() { - // Add all the values to the array - var arr = []; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - arr.push(this.matrix[i][j]); - } - } - return arr; +Matrix.prototype.toArray = function () { + // Add all the values to the array + var arr = []; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + arr.push(this.matrix[i][j]); + } + } + return arr; } /** @@ -58,50 +58,50 @@ Matrix.prototype.toArray = function() { * rows X cols --> cols X rows * @return {Matrix} */ -Matrix.prototype.transpose = function() { - var result = new Matrix(this.cols, this.rows); - for (var i = 0; i < result.rows; i++) { - for (var j = 0; j < result.cols; j++) { - result.matrix[i][j] = this.matrix[j][i]; - } - } - return result; +Matrix.prototype.transpose = function () { + var result = new Matrix(this.cols, this.rows); + for (var i = 0; i < result.rows; i++) { + for (var j = 0; j < result.cols; j++) { + result.matrix[i][j] = this.matrix[j][i]; + } + } + return result; } /** * This makes a copy of the matrix * @return {Matrix} */ -Matrix.prototype.copy = function() { - var result = new Matrix(this.rows, this.cols); - for (var i = 0; i < result.rows; i++) { - for (var j = 0; j < result.cols; j++) { - result.matrix[i][j] = this.matrix[i][j]; - } - } - return result; +Matrix.prototype.copy = function () { + var result = new Matrix(this.rows, this.cols); + for (var i = 0; i < result.rows; i++) { + for (var j = 0; j < result.cols; j++) { + result.matrix[i][j] = this.matrix[i][j]; + } + } + return result; } /** * This adds another matrix or a single value * @param {Matrix} other */ -Matrix.prototype.add = function(other) { - // Are we trying to add a Matrix? - if (other instanceof Matrix) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] += other.matrix[i][j]; - } - } - // Or just a single scalar value? - } else { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] += other; - } - } - } +Matrix.prototype.add = function (other) { + // Are we trying to add a Matrix? + if (other instanceof Matrix) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] += other.matrix[i][j]; + } + } + // Or just a single scalar value? + } else { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] += other; + } + } + } } /** @@ -109,22 +109,22 @@ Matrix.prototype.add = function(other) { * This is different than the dot() function! * @param {Matrix} other */ -Matrix.prototype.multiply = function(other) { - // Are we trying to multiply a Matrix? - if (other instanceof Matrix) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] *= other.matrix[i][j]; - } - } - // Or just a single scalar value? - } else { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.cols; j++) { - this.matrix[i][j] *= other; - } - } - } +Matrix.prototype.multiply = function (other) { + // Are we trying to multiply a Matrix? + if (other instanceof Matrix) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] *= other.matrix[i][j]; + } + } + // Or just a single scalar value? + } else { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.cols; j++) { + this.matrix[i][j] *= other; + } + } + } } /** @@ -133,14 +133,14 @@ Matrix.prototype.multiply = function(other) { * @param {Matrix} m * @param {Function} fn */ -Matrix.map = function(m, fn) { - var result = new Matrix(m.rows, m.cols); - for (var i = 0; i < result.rows; i++) { - for (var j = 0; j < result.cols; j++) { - result.matrix[i][j] = fn(m.matrix[i][j]); - } - } - return result; +Matrix.map = function (m, fn) { + var result = new Matrix(m.rows, m.cols); + for (var i = 0; i < result.rows; i++) { + for (var j = 0; j < result.cols; j++) { + result.matrix[i][j] = fn(m.matrix[i][j]); + } + } + return result; } /** @@ -149,14 +149,14 @@ Matrix.map = function(m, fn) { * @param {Matrix} b * @return {Matrix} */ -Matrix.subtract = function(a, b) { - var result = new Matrix(a.rows, a.cols); - for (var i = 0; i < result.rows; i++) { - for (var j = 0; j < result.cols; j++) { - result.matrix[i][j] = a.matrix[i][j] - b.matrix[i][j]; - } - } - return result; +Matrix.subtract = function (a, b) { + var result = new Matrix(a.rows, a.cols); + for (var i = 0; i < result.rows; i++) { + for (var j = 0; j < result.cols; j++) { + result.matrix[i][j] = a.matrix[i][j] - b.matrix[i][j]; + } + } + return result; } /** @@ -165,26 +165,26 @@ Matrix.subtract = function(a, b) { * @param {Matrix} b * @return {Matrix} */ -Matrix.dot = function(a, b) { - // Won't work if columns of A don't equal columns of B - if (a.cols != b.rows) { - console.log("Incompatible matrix sizes!"); - return; - } - // Make a new matrix - var result = new Matrix(a.rows, b.cols); - for (var i = 0; i < a.rows; i++) { - for (var j = 0; j < b.cols; j++) { - // Sum all the rows of A times columns of B - var sum = 0; - for (var k = 0; k < a.cols; k++) { - sum += a.matrix[i][k] * b.matrix[k][j]; - } - // New value - result.matrix[i][j] = sum; - } - } - return result; +Matrix.dot = function (a, b) { + // Won't work if columns of A don't equal columns of B + if (a.cols != b.rows) { + console.log("Incompatible matrix sizes!"); + return; + } + // Make a new matrix + var result = new Matrix(a.rows, b.cols); + for (var i = 0; i < a.rows; i++) { + for (var j = 0; j < b.cols; j++) { + // Sum all the rows of A times columns of B + var sum = 0; + for (var k = 0; k < a.cols; k++) { + sum += a.matrix[i][k] * b.matrix[k][j]; + } + // New value + result.matrix[i][j] = sum; + } + } + return result; } /** @@ -192,10 +192,10 @@ Matrix.dot = function(a, b) { * @param {Array} * @return {Matrix} */ -Matrix.fromArray = function(array) { - var m = new Matrix(array.length, 1); - for (var i = 0; i < array.length; i++) { - m.matrix[i][0] = array[i]; - } - return m; -} +Matrix.fromArray = function (array) { + var m = new Matrix(array.length, 1); + for (var i = 0; i < array.length; i++) { + m.matrix[i][0] = array[i]; + } + return m; +} \ No newline at end of file From a58202202afa7233dffdbd26dba47a74570263d6 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 17:04:31 -0400 Subject: [PATCH 08/11] Applied comment spacing --- matrix.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/matrix.js b/matrix.js index 244e905..673ddfd 100644 --- a/matrix.js +++ b/matrix.js @@ -43,6 +43,7 @@ Matrix.prototype.randomize = function () { * @return {Array} */ Matrix.prototype.toArray = function () { + // Add all the values to the array var arr = []; for (var i = 0; i < this.rows; i++) { @@ -87,15 +88,17 @@ Matrix.prototype.copy = function () { * @param {Matrix} other */ Matrix.prototype.add = function (other) { - // Are we trying to add a Matrix? if (other instanceof Matrix) { + + // Are we trying to add a Matrix? for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.cols; j++) { this.matrix[i][j] += other.matrix[i][j]; } } - // Or just a single scalar value? } else { + + // Or just a single scalar value? for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.cols; j++) { this.matrix[i][j] += other; @@ -110,15 +113,17 @@ Matrix.prototype.add = function (other) { * @param {Matrix} other */ Matrix.prototype.multiply = function (other) { - // Are we trying to multiply a Matrix? if (other instanceof Matrix) { + + // Are we trying to multiply a Matrix? for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.cols; j++) { this.matrix[i][j] *= other.matrix[i][j]; } } - // Or just a single scalar value? } else { + + // Or just a single scalar value? for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.cols; j++) { this.matrix[i][j] *= other; @@ -166,20 +171,24 @@ Matrix.subtract = function (a, b) { * @return {Matrix} */ Matrix.dot = function (a, b) { + // Won't work if columns of A don't equal columns of B if (a.cols != b.rows) { console.log("Incompatible matrix sizes!"); return; } + // Make a new matrix var result = new Matrix(a.rows, b.cols); for (var i = 0; i < a.rows; i++) { for (var j = 0; j < b.cols; j++) { + // Sum all the rows of A times columns of B var sum = 0; for (var k = 0; k < a.cols; k++) { sum += a.matrix[i][k] * b.matrix[k][j]; } + // New value result.matrix[i][j] = sum; } From aee48b9059374959fb30e5726d54d5ab7c3ed426 Mon Sep 17 00:00:00 2001 From: Nato Boram Date: Mon, 18 Sep 2017 17:08:27 -0400 Subject: [PATCH 09/11] Applied automatic indentation to whole repo --- examples/mnist/index.html | 24 +- examples/mnist/libraries/p5.dom.js | 4316 +- examples/mnist/libraries/p5.js | 70156 ++++++++-------- examples/mnist/libraries/p5.sound.js | 18664 ++-- examples/mnist/sketch.js | 472 +- examples/neuro-evolution/flappy/bird.js | 166 +- examples/neuro-evolution/flappy/ga.js | 92 +- examples/neuro-evolution/flappy/index.html | 40 +- .../flappy/libraries/p5.dom.js | 4316 +- .../neuro-evolution/flappy/libraries/p5.js | 70156 ++++++++-------- .../flappy/libraries/p5.sound.js | 18664 ++-- examples/neuro-evolution/flappy/pipe.js | 92 +- examples/neuro-evolution/flappy/sketch.js | 256 +- .../neuro-evolution/line_circle/index.html | 12 +- .../line_circle/libraries/p5.dom.js | 4316 +- .../line_circle/libraries/p5.js | 70156 ++++++++-------- .../line_circle/libraries/p5.sound.js | 18664 ++-- .../neuro-evolution/line_circle/sketch.js | 170 +- examples/neuro-evolution/steering/geometry.js | 88 +- examples/neuro-evolution/steering/index.html | 38 +- .../steering/libraries/p5.dom.js | 4316 +- .../neuro-evolution/steering/libraries/p5.js | 70156 ++++++++-------- .../steering/libraries/p5.sound.js | 18664 ++-- examples/neuro-evolution/steering/sketch.js | 200 +- examples/neuro-evolution/steering/vehicle.js | 330 +- 25 files changed, 187273 insertions(+), 187251 deletions(-) diff --git a/examples/mnist/index.html b/examples/mnist/index.html index 5ef65da..ce9223b 100755 --- a/examples/mnist/index.html +++ b/examples/mnist/index.html @@ -2,27 +2,25 @@ - - p5 Neural Network Example - - - - - + + p5 Neural Network Example + + + + + - + Fork me on GitHub -

Neural Network built with p5

+

Neural Network built with p5

-

This is a demonstration of a neural network trained to recognize digits using - the MNIST database. It's based - Tariq Rashid's book Make Your Own Neural Network.

+

This is a demonstration of a neural network trained to recognize digits using the MNIST database. It's based Tariq Rashid's book Make Your Own Neural Network.

- + \ No newline at end of file diff --git a/examples/mnist/libraries/p5.dom.js b/examples/mnist/libraries/p5.dom.js index 561d300..22a304e 100644 --- a/examples/mnist/libraries/p5.dom.js +++ b/examples/mnist/libraries/p5.dom.js @@ -26,2165 +26,2165 @@ */ (function (root, factory) { - if (typeof define === 'function' && define.amd) - define('p5.dom', ['p5'], function (p5) { (factory(p5));}); - else if (typeof exports === 'object') - factory(require('../p5')); - else - factory(root['p5']); + if (typeof define === 'function' && define.amd) + define('p5.dom', ['p5'], function (p5) { (factory(p5)); }); + else if (typeof exports === 'object') + factory(require('../p5')); + else + factory(root['p5']); }(this, function (p5) { -// ============================================================================= -// p5 additions -// ============================================================================= - - /** - * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' - * prefixes to specify an ID or class respectively, and none for a tag) and returns it as - * a p5.Element. If a class or tag name is given with more than 1 element, - * only the first element will be returned. - * The DOM node itself can be accessed with .elt. - * Returns null if none found. You can also specify a container to search within. - * - * @method select - * @param {String} name id, class, or tag name of element to search for - * @param {String} [container] id, p5.Element, or HTML element to search within - * @return {Object|p5.Element|Null} p5.Element containing node found - * @example - *
- * function setup() { - * createCanvas(100,100); - * //translates canvas 50px down - * select('canvas').position(100, 100); - * } - *
- *
- * // these are all valid calls to select() - * var a = select('#moo'); - * var b = select('#blah', '#myContainer'); - * var c = select('#foo', b); - * var d = document.getElementById('beep'); - * var e = select('p', d); - *
- * - */ - p5.prototype.select = function (e, p) { - var res = null; - var container = getContainer(p); - if (e[0] === '.'){ - e = e.slice(1); - res = container.getElementsByClassName(e); - if (res.length) { - res = res[0]; - } else { - res = null; - } - }else if (e[0] === '#'){ - e = e.slice(1); - res = container.getElementById(e); - }else { - res = container.getElementsByTagName(e); - if (res.length) { - res = res[0]; - } else { - res = null; - } - } - if (res) { - return wrapElement(res); - } else { - return null; - } - }; - - /** - * Searches the page for elements with the given class or tag name (using the '.' prefix - * to specify a class and no prefix for a tag) and returns them as p5.Elements - * in an array. - * The DOM node itself can be accessed with .elt. - * Returns an empty array if none found. - * You can also specify a container to search within. - * - * @method selectAll - * @param {String} name class or tag name of elements to search for - * @param {String} [container] id, p5.Element, or HTML element to search within - * @return {Array} Array of p5.Elements containing nodes found - * @example - *
- * function setup() { - * createButton('btn'); - * createButton('2nd btn'); - * createButton('3rd btn'); - * var buttons = selectAll('button'); - * - * for (var i = 0; i < buttons.length; i++){ - * buttons[i].size(100,100); - * } - * } - *
- *
- * // these are all valid calls to selectAll() - * var a = selectAll('.moo'); - * var b = selectAll('div'); - * var c = selectAll('button', '#myContainer'); - * var d = select('#container'); - * var e = selectAll('p', d); - * var f = document.getElementById('beep'); - * var g = select('.blah', f); - *
- * - */ - p5.prototype.selectAll = function (e, p) { - var arr = []; - var res; - var container = getContainer(p); - if (e[0] === '.'){ - e = e.slice(1); - res = container.getElementsByClassName(e); - } else { - res = container.getElementsByTagName(e); - } - if (res) { - for (var j = 0; j < res.length; j++) { - var obj = wrapElement(res[j]); - arr.push(obj); - } - } - return arr; - }; - - /** - * Helper function for select and selectAll - */ - function getContainer(p) { - var container = document; - if (typeof p === 'string' && p[0] === '#'){ - p = p.slice(1); - container = document.getElementById(p) || document; - } else if (p instanceof p5.Element){ - container = p.elt; - } else if (p instanceof HTMLElement){ - container = p; - } - return container; - } - - /** - * Helper function for getElement and getElements. - */ - function wrapElement(elt) { - if(elt.tagName === "INPUT" && elt.type === "checkbox") { - var converted = new p5.Element(elt); - converted.checked = function(){ - if (arguments.length === 0){ - return this.elt.checked; - } else if(arguments[0]) { - this.elt.checked = true; - } else { - this.elt.checked = false; - } - return this; - }; - return converted; - } else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { - return new p5.MediaElement(elt); - } else { - return new p5.Element(elt); - } - } - - /** - * Removes all elements created by p5, except any canvas / graphics - * elements created by createCanvas or createGraphics. - * Event handlers are removed, and element is removed from the DOM. - * @method removeElements - * @example - *
- * function setup() { - * createCanvas(100, 100); - * createDiv('this is some text'); - * createP('this is a paragraph'); - * } - * function mousePressed() { - * removeElements(); // this will remove the div and p, not canvas - * } - *
- * - */ - p5.prototype.removeElements = function (e) { - for (var i=0; i - * var myDiv; - * function setup() { - * myDiv = createDiv('this is some text'); - * } - * - */ - - /** - * Creates a <p></p> element in the DOM with given inner HTML. Used - * for paragraph length text. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createP - * @param {String} html inner HTML for element created - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var myP; - * function setup() { - * myP = createP('this is some text'); - * } - *
- */ - - /** - * Creates a <span></span> element in the DOM with given inner HTML. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createSpan - * @param {String} html inner HTML for element created - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var mySpan; - * function setup() { - * mySpan = createSpan('this is some text'); - * } - *
- */ - var tags = ['div', 'p', 'span']; - tags.forEach(function(tag) { - var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); - p5.prototype[method] = function(html) { - var elt = document.createElement(tag); - elt.innerHTML = typeof html === undefined ? "" : html; - return addElement(elt, this); - } - }); - - /** - * Creates an <img> element in the DOM with given src and - * alternate text. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createImg - * @param {String} src src path or url for image - * @param {String} [alt] alternate text to be used if image does not load - * @param {Function} [successCallback] callback to be called once image data is loaded - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var img; - * function setup() { - * img = createImg('http://p5js.org/img/asterisk-01.png'); - * } - *
- */ - p5.prototype.createImg = function() { - var elt = document.createElement('img'); - var args = arguments; - var self; - var setAttrs = function(){ - self.width = elt.offsetWidth || elt.width; - self.height = elt.offsetHeight || elt.height; - if (args.length > 1 && typeof args[1] === 'function'){ - self.fn = args[1]; - self.fn(); - }else if (args.length > 1 && typeof args[2] === 'function'){ - self.fn = args[2]; - self.fn(); - } - }; - elt.src = args[0]; - if (args.length > 1 && typeof args[1] === 'string'){ - elt.alt = args[1]; - } - elt.onload = function(){ - setAttrs(); - } - self = addElement(elt, this); - return self; - }; - - /** - * Creates an <a></a> element in the DOM for including a hyperlink. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createA - * @param {String} href url of page to link to - * @param {String} html inner html of link element to display - * @param {String} [target] target where new link should open, - * could be _blank, _self, _parent, _top. - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var myLink; - * function setup() { - * myLink = createA('http://p5js.org/', 'this is a link'); - * } - *
- */ - p5.prototype.createA = function(href, html, target) { - var elt = document.createElement('a'); - elt.href = href; - elt.innerHTML = html; - if (target) elt.target = target; - return addElement(elt, this); - }; - - /** INPUT **/ - - - /** - * Creates a slider <input></input> element in the DOM. - * Use .size() to set the display length of the slider. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createSlider - * @param {Number} min minimum value of the slider - * @param {Number} max maximum value of the slider - * @param {Number} [value] default value of the slider - * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var slider; - * function setup() { - * slider = createSlider(0, 255, 100); - * slider.position(10, 10); - * slider.style('width', '80px'); - * } - * - * function draw() { - * var val = slider.value(); - * background(val); - * } - *
- * - *
- * var slider; - * function setup() { - * colorMode(HSB); - * slider = createSlider(0, 360, 60, 40); - * slider.position(10, 10); - * slider.style('width', '80px'); - * } - * - * function draw() { - * var val = slider.value(); - * background(val, 100, 100, 1); - * } - *
- */ - p5.prototype.createSlider = function(min, max, value, step) { - var elt = document.createElement('input'); - elt.type = 'range'; - elt.min = min; - elt.max = max; - if (step === 0) { - elt.step = .000000000000000001; // smallest valid step - } else if (step) { - elt.step = step; - } - if (typeof(value) === "number") elt.value = value; - return addElement(elt, this); - }; - - /** - * Creates a <button></button> element in the DOM. - * Use .size() to set the display size of the button. - * Use .mousePressed() to specify behavior on press. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createButton - * @param {String} label label displayed on the button - * @param {String} [value] value of the button - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var button; - * function setup() { - * createCanvas(100, 100); - * background(0); - * button = createButton('click me'); - * button.position(19, 19); - * button.mousePressed(changeBG); - * } - * - * function changeBG() { - * var val = random(255); - * background(val); - * } - *
- */ - p5.prototype.createButton = function(label, value) { - var elt = document.createElement('button'); - elt.innerHTML = label; - elt.value = value; - if (value) elt.value = value; - return addElement(elt, this); - }; - - /** - * Creates a checkbox <input></input> element in the DOM. - * Calling .checked() on a checkbox returns if it is checked or not - * - * @method createCheckbox - * @param {String} [label] label displayed after checkbox - * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var checkbox; - * - * function setup() { - * checkbox = createCheckbox('label', false); - * checkbox.changed(myCheckedEvent); - * } - * - * function myCheckedEvent() { - * if (this.checked()) { - * console.log("Checking!"); - * } else { - * console.log("Unchecking!"); - * } - * } - *
- */ - p5.prototype.createCheckbox = function() { - var elt = document.createElement('div'); - var checkbox = document.createElement('input'); - checkbox.type = 'checkbox'; - elt.appendChild(checkbox); - //checkbox must be wrapped in p5.Element before label so that label appears after - var self = addElement(elt, this); - self.checked = function(){ - var cb = self.elt.getElementsByTagName('input')[0]; - if (cb) { - if (arguments.length === 0){ - return cb.checked; - }else if(arguments[0]){ - cb.checked = true; - }else{ - cb.checked = false; - } - } - return self; - }; - this.value = function(val){ - self.value = val; - return this; - }; - if (arguments[0]){ - var ran = Math.random().toString(36).slice(2); - var label = document.createElement('label'); - checkbox.setAttribute('id', ran); - label.htmlFor = ran; - self.value(arguments[0]); - label.appendChild(document.createTextNode(arguments[0])); - elt.appendChild(label); - } - if (arguments[1]){ - checkbox.checked = true; - } - return self; - }; - - /** - * Creates a dropdown menu <select></select> element in the DOM. - * @method createSelect - * @param {boolean} [multiple] true if dropdown should support multiple selections - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var sel; - * - * function setup() { - * textAlign(CENTER); - * background(200); - * sel = createSelect(); - * sel.position(10, 10); - * sel.option('pear'); - * sel.option('kiwi'); - * sel.option('grape'); - * sel.changed(mySelectEvent); - * } - * - * function mySelectEvent() { - * var item = sel.value(); - * background(200); - * text("it's a "+item+"!", 50, 50); - * } - *
- */ - p5.prototype.createSelect = function(mult) { - var elt = document.createElement('select'); - if (mult){ - elt.setAttribute('multiple', 'true'); - } - var self = addElement(elt, this); - self.option = function(name, value){ - var opt = document.createElement('option'); - opt.innerHTML = name; - if (arguments.length > 1) - opt.value = value; - else - opt.value = name; - elt.appendChild(opt); - }; - self.selected = function(value){ - var arr = []; - if (arguments.length > 0){ - for (var i = 0; i < this.elt.length; i++){ - if (value.toString() === this.elt[i].value){ - this.elt.selectedIndex = i; - } - } - return this; - }else{ - if (mult){ - for (var i = 0; i < this.elt.selectedOptions.length; i++){ - arr.push(this.elt.selectedOptions[i].value); - } - return arr; - }else{ - return this.elt.value; - } - } - }; - return self; - }; - - /** - * Creates a radio button <input></input> element in the DOM. - * The .option() method can be used to set options for the radio after it is - * created. The .value() method will return the currently selected option. - * - * @method createRadio - * @param {String} [divId] the id and name of the created div and input field respectively - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * var radio; - * - * function setup() { - * radio = createRadio(); - * radio.option("black"); - * radio.option("white"); - * radio.option("gray"); - * radio.style('width', '60px'); - * textAlign(CENTER); - * fill(255, 0, 0); - * } - * - * function draw() { - * var val = radio.value(); - * background(val); - * text(val, width/2, height/2); - * } - *
- *
- * var radio; - * - * function setup() { - * radio = createRadio(); - * radio.option('apple', 1); - * radio.option('bread', 2); - * radio.option('juice', 3); - * radio.style('width', '60px'); - * textAlign(CENTER); - * } - * - * function draw() { - * background(200); - * var val = radio.value(); - * if (val) { - * text('item cost is $'+val, width/2, height/2); - * } - * } - *
- */ - p5.prototype.createRadio = function() { - var radios = document.querySelectorAll("input[type=radio]"); - var count = 0; - if(radios.length > 1){ - var length = radios.length; - var prev=radios[0].name; - var current = radios[1].name; - count = 1; - for(var i = 1; i < length; i++) { - current = radios[i].name; - if(prev != current){ - count++; - } - prev = current; - } - } - else if (radios.length == 1){ - count = 1; - } - var elt = document.createElement('div'); - var self = addElement(elt, this); - var times = -1; - self.option = function(name, value){ - var opt = document.createElement('input'); - opt.type = 'radio'; - opt.innerHTML = name; - if (arguments.length > 1) - opt.value = value; - else - opt.value = name; - opt.setAttribute('name',"defaultradio"+count); - elt.appendChild(opt); - if (name){ - times++; - var ran = Math.random().toString(36).slice(2); - var label = document.createElement('label'); - opt.setAttribute('id', "defaultradio"+count+"-"+times); - label.htmlFor = "defaultradio"+count+"-"+times; - label.appendChild(document.createTextNode(name)); - elt.appendChild(label); - } - return opt; - }; - self.selected = function(){ - var length = this.elt.childNodes.length; - if(arguments.length == 1) { - for (var i = 0; i < length; i+=2){ - if(this.elt.childNodes[i].value == arguments[0]) - this.elt.childNodes[i].checked = true; - } - return this; - } else { - for (var i = 0; i < length; i+=2){ - if(this.elt.childNodes[i].checked == true) - return this.elt.childNodes[i].value; - } - } - }; - self.value = function(){ - var length = this.elt.childNodes.length; - if(arguments.length == 1) { - for (var i = 0; i < length; i+=2){ - if(this.elt.childNodes[i].value == arguments[0]) - this.elt.childNodes[i].checked = true; - } - return this; - } else { - for (var i = 0; i < length; i+=2){ - if(this.elt.childNodes[i].checked == true) - return this.elt.childNodes[i].value; - } - return ""; - } - }; - return self - }; - - /** - * Creates an <input></input> element in the DOM for text input. - * Use .size() to set the display length of the box. - * Appends to the container node if one is specified, otherwise - * appends to body. - * - * @method createInput - * @param {Number} [value] default value of the input box - * @param {String} [type] type of text, ie text, password etc. Defaults to text - * @return {Object|p5.Element} pointer to p5.Element holding created node - * @example - *
- * function setup(){ - * var inp = createInput(''); - * inp.input(myInputEvent); - * } - * - * function myInputEvent(){ - * console.log('you are typing: ', this.value()); - * } - * - *
- */ - p5.prototype.createInput = function(value, type) { - var elt = document.createElement('input'); - elt.type = type ? type : 'text'; - if (value) elt.value = value; - return addElement(elt, this); - }; - - /** - * Creates an <input></input> element in the DOM of type 'file'. - * This allows users to select local files for use in a sketch. - * - * @method createFileInput - * @param {Function} [callback] callback function for when a file loaded - * @param {String} [multiple] optional to allow multiple files selected - * @return {Object|p5.Element} pointer to p5.Element holding created DOM element - * @example - * var input; - * var img; - * - * function setup() { - * input = createFileInput(handleFile); - * input.position(0, 0); - * } - * - * function draw() { - * if (img) { - * image(img, 0, 0, width, height); - * } - * } - * - * function handleFile(file) { - * print(file); - * if (file.type === 'image') { - * img = createImg(file.data); - * img.hide(); - * } - * } - */ - p5.prototype.createFileInput = function(callback, multiple) { - - // Is the file stuff supported? - if (window.File && window.FileReader && window.FileList && window.Blob) { - // Yup, we're ok and make an input file selector - var elt = document.createElement('input'); - elt.type = 'file'; - - // If we get a second argument that evaluates to true - // then we are looking for multiple files - if (multiple) { - // Anything gets the job done - elt.multiple = 'multiple'; - } - - // Function to handle when a file is selected - // We're simplifying life and assuming that we always - // want to load every selected file - function handleFileSelect(evt) { - // These are the files - var files = evt.target.files; - // Load each one and trigger a callback - for (var i = 0; i < files.length; i++) { - var f = files[i]; - var reader = new FileReader(); - function makeLoader(theFile) { - // Making a p5.File object - var p5file = new p5.File(theFile); - return function(e) { - p5file.data = e.target.result; - callback(p5file); - }; - }; - reader.onload = makeLoader(f); - - // Text or data? - // This should likely be improved - if (f.type.indexOf('text') > -1) { - reader.readAsText(f); - } else { - reader.readAsDataURL(f); - } - } - } - - // Now let's handle when a file was selected - elt.addEventListener('change', handleFileSelect, false); - return addElement(elt, this); - } else { - console.log('The File APIs are not fully supported in this browser. Cannot create element.'); - } - }; - - - /** VIDEO STUFF **/ - - function createMedia(pInst, type, src, callback) { - var elt = document.createElement(type); - - // allow src to be empty - var src = src || ''; - if (typeof src === 'string') { - src = [src]; - } - for (var i=0; i