All files / lib/math matrix.js

99.21% Statements 126/127
95.38% Branches 62/65
100% Functions 21/21
99.19% Lines 122/123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341                                              30x                         51641x 37956x   13685x                 37956x 1x   37955x 37955x     37955x 37955x 24502x 460921x   24502x   13453x 243701x   13453x                 97x 1x   96x                 97x 1x   96x 96x 942x   96x               20452x                     98x 98x 946x   98x                   1x                   96x                 96x 96x 96x 96x 1889x 1889x 43075x     96x                   13450x 13450x 13450x 13450x 172971x 172971x 172982x     13450x                 86482x                   98x 98x 3x   98x 98x 98x 98x 98x 1x       97x 944x 42137x     97x                 6729x 6729x 4032x   6729x                         5x 5x 1x   5x               6726x 4x   6725x 6725x 6723x   6725x 1x   86486x                     4x 4x   3x 3x 2x   3x 1x   2x 2x 4x 4x 6x 6x 12x   6x   4x   2x                   20170x 6723x 6723x 157199x 157201x     6723x   13447x 13447x 6724x   13447x 1x   13446x 13446x 13446x 13446x 13446x 243679x 243679x 243681x 243681x 8777718x   243681x 86478x   243681x   243679x   13446x       30x  
/*
 * Copyright (c) AXA Shared Services Spain S.A.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
 
const Vector = require('./vector');
 
/**
 * Class representing a Matrix and some of the possible operations.
 */
class Matrix {
  /**
   * Constructor of the class
   * @param {Number[][] | Matrix} elements Elements for initializing the matrix.
   * @param {boolean} useClone If true, the input array is cloned. If false, it uses
   *                     the elements input directly by reference.
   */
  constructor(elements, useClone = true) {
    if (useClone) {
      this.setElements(elements);
    } else {
      this.elements = elements.elements || elements;
    }
  }
 
  /**
   * Clone the input elemnts and assign to this instance elements.
   * @param {Number[][] | Matrix} els Input elements.
   */
  setElements(els) {
    if (!els) {
      return this;
    }
    const elements = els.elements || els;
    Iif (!elements || elements.length === 0) {
      return this;
    }
    this.elements = [];
    if (elements[0][0] !== undefined) {
      for (let i = 0; i < elements.length; i += 1) {
        this.elements.push(elements[i].slice());
      }
      return this;
    }
    for (let i = 0; i < elements.length; i += 1) {
      this.elements.push([elements[i]]);
    }
    return this;
  }
 
  /**
   * Return a row of the matrix as a vector.
   * @param {Number} i Row number.
   * @returns {Vector} Row of the matrix as a vector.
   */
  row(i) {
    if (i < 0 || i >= this.elements.length) {
      return undefined;
    }
    return new Vector(this.elements[i]);
  }
 
  /**
   * Return a column of the matrix as a vector.
   * @param {Number} j Column number.
   * @returns {Vector} Column of the matrix as a vector.
   */
  column(j) {
    if (j < 0 || j >= this.elements[0].length) {
      return undefined;
    }
    const result = [];
    for (let i = 0; i < this.elements.length; i += 1) {
      result.push(this.elements[i][j]);
    }
    return new Vector(result);
  }
 
  /**
   * Return the amount of rows of the matrix.
   * @returns {Number} Amount of rows of the matrix.
   */
  rowCount() {
    return this.elements.length;
  }
 
  /**
   * Creates a new Matrix with given dimensions and filled with the cell value.
   * @param {Number} n Amount of rows.
   * @param {Number} m Amount of columns.
   * @param {Number} v Cell value.
   * @returns {Number[][] | Matrix} Matrix with given dimensions and cell value.
   */
  static fill(n, m, v) {
    const elements = [];
    for (let i = 0; i < n; i += 1) {
      elements.push(Vector.createArray(m, v));
    }
    return new Matrix(elements, false);
  }
 
  /**
   * Creates a new Matrix with given dimensions and filled with 0.
   * @param {Number} n Amount of rows.
   * @param {Number} m Amount of columns.
   * @returns {Matrix} Matrix with given dimensions filled with 0.
   */
  static zero(n, m) {
    return Matrix.fill(n, m, 0);
  }
 
  /**
   * Creates a new Matrix with given dimensions and filled with 1.
   * @param {Number} n Amount of rows.
   * @param {Number} m Amount of columns.
   * @returns {Matrix} Matrix with given dimensions filled with 1.
   */
  static one(n, m) {
    return Matrix.fill(n, m, 1);
  }
 
  /**
   * Creates a new Matrix that is the transposed of this one
   * (rows become columns).
   * @returns {Matrix} Matrix that is transposed of this one.
   */
  transpose() {
    const numRows = this.elements.length;
    const numColumns = this.elements[0].length;
    const elements = [];
    for (let i = 0; i < numColumns; i += 1) {
      elements.push([]);
      for (let j = 0; j < numRows; j += 1) {
        elements[i][j] = this.elements[j][i];
      }
    }
    return new Matrix(elements, false);
  }
 
  /**
   * Creates a new matrix where each element is the result of executiong
   * the provided function with signature (element, i, j).
   * @param {Function} fn Function for calculating each element.
   * @returns {Matrix} Resulting mapped matrix.
   */
  map(fn) {
    const numRows = this.elements.length;
    const numColumns = this.elements[0].length;
    const elements = [];
    for (let i = 0; i < numRows; i += 1) {
      elements.push([]);
      for (let j = 0; j < numColumns; j += 1) {
        elements[i][j] = fn(this.elements[i][j], i, j);
      }
    }
    return new Matrix(elements, false);
  }
 
  /**
   * Returns a new matrix where each cell is the natural logarithm
   * of the input element.
   * @returns {Matrix} Logarithm matrix.
   */
  log() {
    return this.map(x => Math.log(x));
  }
 
  /**
   * Return a matrix where is row is augmented with the corresponding
   * row of the input matrix.
   * @param {Number[][] | Matrix} matrix Input matrix.
   * @returns {Matrix} Matrix that is this one augmented with the input one.
   */
  augment(matrix) {
    let elements = matrix.elements || matrix;
    if (!elements[0][0]) {
      ({ elements } = new Matrix(elements));
    }
    const clone = new Matrix(this.elements);
    const numColumns = clone.elements[0].length;
    const numRows = clone.elements.length;
    const elementColumns = elements[0].length;
    if (numRows !== elements.length) {
      throw new Error(
        'Cannot operate two matrix with different amount of rows.'
      );
    }
    for (let i = 0; i < numRows; i += 1) {
      for (let j = 0; j < elementColumns; j += 1) {
        clone.elements[i][numColumns + j] = elements[i][j];
      }
    }
    return clone;
  }
 
  /**
   * Indicates if another matrix has exactly same dimensions as this one.
   * @param {Number[][] | Number[] | Matrix | Vector} matrix Input matrix.
   * @returns {boolean} True if both have same number of rows and columns.
   */
  isSameSizeAs(matrix) {
    let elements = matrix.elements || matrix;
    if (!elements[0][0]) {
      ({ elements } = new Matrix(elements));
    }
    return (
      this.elements.length === elements.length &&
      this.elements[0].length === elements[0].length
    );
  }
 
  /**
   * Indicates if another matrix has exactly same amount of rows as this
   * matrix amount of columns.
   * @param {Number[][] | Number[] | Matrix | Vector} matrix Input matrix.
   * @returns {boolean} True if this one column count equals input row count.
   */
  isSameColumnToRowSize(matrix) {
    let elements = matrix.elements || matrix;
    if (!elements[0][0]) {
      ({ elements } = new Matrix(elements));
    }
    return this.elements[0].length === elements.length;
  }
 
  /**
   * Performs a substraction element by element between two matrix.
   * @param {Matrix} matrix Input matrix.
   */
  subtract(matrix) {
    if (typeof matrix === 'number') {
      return this.map(x => x - matrix);
    }
    let elements = matrix.elements || matrix;
    if (!elements[0][0]) {
      ({ elements } = new Matrix(elements));
    }
    if (!this.isSameSizeAs(elements)) {
      throw new Error('Cannot operate two matrix with different dimensions.');
    }
    return this.map((x, i, j) => x - elements[i][j]);
  }
 
  /**
   * Given a matrix an an operation function, applies this operation
   * multiplying this matrix with the provided one.
   * @param {Matrix} matrix Matrix to operate with this.
   * @param {Function} op Multiply operation.
   * @returns {Matrix} Result matrix of multiplying both matrix.
   */
  mulOp(matrix, op) {
    if (typeof matrix === 'number') {
      return this.map((x, i, j) => op(x, matrix, i, j));
    }
    let inputElements = matrix.elements || matrix;
    if (!inputElements[0][0]) {
      inputElements = new Matrix(inputElements).elements;
    }
    if (!this.isSameColumnToRowSize(inputElements)) {
      throw new Error('Number of rows of A should match number of cols of B.');
    }
    const result = [];
    for (let i = 0; i < this.elements.length; i += 1) {
      const currentRow = [];
      for (let j = 0; j < inputElements[0].length; j += 1) {
        let sum = 0;
        for (let k = this.elements[0].length - 1; k >= 0; k -= 1) {
          sum += op(this.elements[i][k], inputElements[k][j]);
        }
        currentRow[j] = sum;
      }
      result[i] = currentRow;
    }
    return new Matrix(result);
  }
 
  /**
   * Multiply two matrix.
   * @param {Matrix} matrix Input matrix.
   * @param {Function} activation Optional activation fucntion.
   * @returns {Matrix} Multiplication of the matrix.
   */
  multiply(matrix, activation) {
    if (typeof matrix === 'number') {
      const result = new Matrix(this.elements, true);
      for (let i = 0, li = result.elements.length; i < li; i += 1) {
        for (let j = 0, lj = result.elements[0].length; j < lj; j += 1) {
          result.elements[i][j] *= matrix;
        }
      }
      return result;
    }
    let inputElements = matrix.elements || matrix;
    if (!inputElements[0][0]) {
      inputElements = new Matrix(inputElements).elements;
    }
    if (this.elements[0].length !== inputElements.length) {
      throw new Error('Number of rows of A should match number of cols of B.');
    }
    const li = this.elements.length;
    const lj = inputElements[0].length;
    const lk = this.elements[0].length - 1;
    const result = [];
    for (let i = 0; i < li; i += 1) {
      const currentRow = [];
      for (let j = 0; j < lj; j += 1) {
        let sum = 0;
        for (let k = lk; k >= 0; k -= 1) {
          sum += this.elements[i][k] * inputElements[k][j];
        }
        if (activation) {
          sum = activation(sum);
        }
        currentRow[j] = sum;
      }
      result[i] = currentRow;
    }
    return new Matrix(result);
  }
}
 
module.exports = Matrix;