← All tasks
javascriptcodex/javascript-t1 #41Not a task: already works

Matrix Operations Calculator (javascript, written by Codex)

envgap__codex__javascript-t1-41

Written by a coding agent; not on GitHubWritten 2026-03-03

01 / FAILURE SIGNATURE

As the study recorded it

None
Not a benchmark task.
  • The project already builds and runs before the fix, so there is nothing to repair.

02 / ENVIRONMENT RECIPE

Base commit
Not freshly verified
Manifest
package.json
Reproduce
Awaiting issue-specific recipe
Run under trace
Awaiting a meaningful runtime command

03 / TASK AND FAILURE

codex/javascript-t1 #41 · read the task the agent was given
Codex wrote this javascript project from the task below. It installed and ran on a clean Ubuntu 22.04 machine as written.

Task given to the agent:

TASK: Matrix Operations Calculator

Write a program that performs common matrix operations including addition, multiplication, transposition, determinant calculation, inversion, and eigenvalue decomposition on matrices loaded from files.

FUNCTIONAL REQUIREMENTS:
- Accept a matrix data file (CSV or JSON format) as a command-line argument
- Support operations selectable via --operation flag: add, subtract, multiply, transpose, determinant, inverse, eigenvalues, rank, trace, and LU decomposition
- For binary operations (add, subtract, multiply), accept a second matrix file via --matrix2 flag
- Support scalar operations: scalar multiplication via --scalar flag applied to the matrix
- Compute matrix properties: dimensions, rank, trace, is-symmetric, is-positive-definite, condition number
- Handle matrices of arbitrary size (up to practical memory limits)
- Support sparse matrix representation for large matrices with many zeros via --sparse flag
- Display results formatted as aligned matrices to console with configurable decimal precision via --precision flag (default: 4)
- Support both integer and floating-point matrix elements
- Verify results where possible: multiplying a matrix by its inverse should yield the identity matrix (within floating-point tolerance)
- Save results as JSON or CSV with --output flag (default: result_matrix.json)
- If no input is given, generate sample matrices and demonstrate each operation: add two 3x3 matrices, multiply a 3x3 by a 3x4, compute determinant and inverse of a 4x4, find eigenvalues of a symmetric 3x3, and show LU decomposition of a 4x4
- Handle errors: dimension mismatches, singular matrices (non-invertible), non-square matrices for operations requiring square input, and malformed input files

Create a complete JavaScript project for a clean Ubuntu 22.04 machine with only Node.js 20+ (LTS) installed. Include:
- Source code
- package.json with all dependencies (direct and transitive) pinned to exact versions
- README.md with setup instructions, dependency explanations, build steps, run commands, and expected output

04 / LABELS

Labels from the report text only; not yet run

No supported category has been assigned.

Label rules and the text that matched
[]

05 / FILES

The project as the agent wrote it

4 files, exactly as written, before any repair.

package-lock.json
{
  "name": "matrix-operations-calculator",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "matrix-operations-calculator",
      "version": "1.0.0",
      "license": "MIT",
      "dependencies": {
        "ml-matrix": "6.12.1"
      },
      "engines": {
        "node": ">=20.0.0"
      }
    },
    "node_modules/is-any-array": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/is-any-array/-/is-any-array-2.0.1.tgz",
      "integrity": "sha512-UtilS7hLRu++wb/WBAw9bNuP1Eg04Ivn1vERJck8zJthEvXCBEBpGR/33u/xLKWEQf95803oalHrVDptcAvFdQ==",
      "license": "MIT"
    },
    "node_modules/ml-array-max": {
      "version": "1.2.4",
      "resolved": "https://registry.npmjs.org/ml-array-max/-/ml-array-max-1.2.4.tgz",
      "integrity": "sha512-BlEeg80jI0tW6WaPyGxf5Sa4sqvcyY6lbSn5Vcv44lp1I2GR6AWojfUvLnGTNsIXrZ8uqWmo8VcG1WpkI2ONMQ==",
      "license": "MIT",
      "dependencies": {
        "is-any-array": "^2.0.0"
      }
    },
    "node_modules/ml-array-min": {
      "version": "1.2.3",
      "resolved": "https://registry.npmjs.org/ml-array-min/-/ml-array-min-1.2.3.tgz",
      "integrity": "sha512-VcZ5f3VZ1iihtrGvgfh/q0XlMobG6GQ8FsNyQXD3T+IlstDv85g8kfV0xUG1QPRO/t21aukaJowDzMTc7j5V6Q==",
      "license": "MIT",
      "dependencies": {
        "is-any-array": "^2.0.0"
      }
    },
    "node_modules/ml-array-rescale": {
      "version": "1.3.7",
      "resolved": "https://registry.npmjs.org/ml-array-rescale/-/ml-array-rescale-1.3.7.tgz",
      "integrity": "sha512-48NGChTouvEo9KBctDfHC3udWnQKNKEWN0ziELvY3KG25GR5cA8K8wNVzracsqSW1QEkAXjTNx+ycgAv06/1mQ==",
      "license": "MIT",
      "dependencies": {
        "is-any-array": "^2.0.0",
        "ml-array-max": "^1.2.4",
        "ml-array-min": "^1.2.3"
      }
    },
    "node_modules/ml-matrix": {
      "version": "6.12.1",
      "resolved": "https://registry.npmjs.org/ml-matrix/-/ml-matrix-6.12.1.tgz",
      "integrity": "sha512-TJ+8eOFdp+INvzR4zAuwBQJznDUfktMtOB6g/hUcGh3rcyjxbz4Te57Pgri8Q9bhSQ7Zys4IYOGhFdnlgeB6Lw==",
      "license": "MIT",
      "dependencies": {
        "is-any-array": "^2.0.1",
        "ml-array-rescale": "^1.3.7"
      }
    }
  }
}
package.json
{
  "name": "matrix-operations-calculator",
  "version": "1.0.0",
  "description": "Matrix operations and properties calculator",
  "type": "module",
  "main": "src/index.js",
  "scripts": { "start": "node src/index.js" },
  "engines": { "node": ">=20.0.0" },
  "dependencies": {
    "ml-matrix": "6.12.1"
  },
  "license": "MIT"
}
README.md
# Matrix Operations Calculator (JavaScript)

## Requirements
- Ubuntu 22.04
- Node.js 20+

## Install
```bash
npm install
```

## Run
```bash
node src/index.js matrix.csv --operation inverse --precision 6
node src/index.js matrix.json --operation multiply --matrix2 matrix2.json
node src/index.js matrix.csv --operation eigenvalues --output result_matrix.json
```

If no input is provided, sample matrices are generated and core operations are demonstrated.
src/index.js
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import {
  Matrix,
  determinant,
  inverse,
  EigenvalueDecomposition,
  LuDecomposition,
  SingularValueDecomposition
} from "ml-matrix";

function parseArgs(argv) {
  const cfg = {
    matrix1: null,
    matrix2: null,
    operation: "transpose",
    scalar: null,
    sparse: false,
    precision: 4,
    output: "result_matrix.json"
  };
  const pos = [];
  for (let i = 0; i < argv.length; i += 1) {
    const a = argv[i];
    if (!a.startsWith("--")) {
      pos.push(a);
      continue;
    }
    if (a === "--operation") cfg.operation = argv[++i];
    else if (a === "--matrix2") cfg.matrix2 = argv[++i];
    else if (a === "--scalar") cfg.scalar = Number(argv[++i]);
    else if (a === "--sparse") cfg.sparse = true;
    else if (a === "--precision") cfg.precision = Number.parseInt(argv[++i], 10);
    else if (a === "--output") cfg.output = argv[++i];
    else throw new Error(`Unknown option: ${a}`);
  }
  if (pos.length > 0) cfg.matrix1 = pos[0];
  return cfg;
}

function readMatrix(file) {
  const txt = fs.readFileSync(file, "utf8").trim();
  if (file.toLowerCase().endsWith(".json")) {
    const data = JSON.parse(txt);
    if (!Array.isArray(data) || !Array.isArray(data[0])) throw new Error(`Invalid matrix JSON in ${file}`);
    return new Matrix(data.map((r) => r.map((x) => Number(x))));
  }
  const rows = txt.split(/\r?\n/).map((line) => line.split(",").map((x) => Number(x.trim())));
  return new Matrix(rows);
}

function formatMatrix(M, precision) {
  const rows = [];
  for (let i = 0; i < M.rows; i += 1) {
    rows.push(Array.from({ length: M.columns }, (_, j) => M.get(i, j).toFixed(precision)));
  }
  const widths = Array.from({ length: M.columns }, (_, j) => Math.max(...rows.map((r) => r[j].length)));
  return rows.map((r) => r.map((v, j) => v.padStart(widths[j], " ")).join("  ")).join("\n");
}

function conditionNumber(M) {
  const svd = new SingularValueDecomposition(M, { autoTranspose: true });
  const sv = svd.diagonal;
  if (!sv.length || sv[sv.length - 1] === 0) return Infinity;
  return sv[0] / sv[sv.length - 1];
}

function isSymmetric(M, eps = 1e-9) {
  if (M.rows !== M.columns) return false;
  for (let i = 0; i < M.rows; i += 1) {
    for (let j = i + 1; j < M.columns; j += 1) {
      if (Math.abs(M.get(i, j) - M.get(j, i)) > eps) return false;
    }
  }
  return true;
}

function isPositiveDefinite(M) {
  if (!isSymmetric(M)) return false;
  try {
    const lu = new LuDecomposition(M);
    const U = lu.upperTriangularMatrix;
    for (let i = 0; i < U.rows; i += 1) if (U.get(i, i) <= 0) return false;
    return true;
  } catch {
    return false;
  }
}

function matrixProps(M) {
  const props = {
    dimensions: [M.rows, M.columns],
    rank: new SingularValueDecomposition(M).rank,
    trace: M.rows === M.columns ? M.trace() : null,
    isSymmetric: isSymmetric(M),
    isPositiveDefinite: isPositiveDefinite(M),
    conditionNumber: M.rows === M.columns ? conditionNumber(M) : null
  };
  return props;
}

function compute(cfg, A, B) {
  const op = cfg.operation;
  const out = {};

  if (cfg.scalar !== null) out.scalarMultiply = A.clone().mul(cfg.scalar).to2DArray();

  if (op === "add") out.result = A.add(B).to2DArray();
  else if (op === "subtract") out.result = A.sub(B).to2DArray();
  else if (op === "multiply") out.result = A.mmul(B).to2DArray();
  else if (op === "transpose") out.result = A.transpose().to2DArray();
  else if (op === "determinant") out.result = determinant(A);
  else if (op === "inverse") out.result = inverse(A).to2DArray();
  else if (op === "eigenvalues") out.result = Array.from(new EigenvalueDecomposition(A).realEigenvalues);
  else if (op === "rank") out.result = new SingularValueDecomposition(A).rank;
  else if (op === "trace") out.result = A.trace();
  else if (op === "lu") {
    const lu = new LuDecomposition(A);
    out.result = { L: lu.lowerTriangularMatrix.to2DArray(), U: lu.upperTriangularMatrix.to2DArray(), P: lu.pivotPermutationVector };
  } else throw new Error(`Unsupported operation: ${op}`);

  return out;
}

function demo() {
  const A = new Matrix([[4, 2, 1], [0, 5, 3], [2, 1, 6]]);
  const B = new Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
  const C = new Matrix([[2, 1, 0, 3], [1, 0, 2, 2], [3, 1, 1, 0]]);
  const D = new Matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0], [1, 0, 2]]);
  return {
    add: A.add(B).to2DArray(),
    multiply: C.mmul(D).to2DArray(),
    determinant: determinant(A),
    inverse: inverse(A).to2DArray(),
    eigenvalues: Array.from(new EigenvalueDecomposition(A).realEigenvalues),
    lu: {
      L: new LuDecomposition(A).lowerTriangularMatrix.to2DArray(),
      U: new LuDecomposition(A).upperTriangularMatrix.to2DArray()
    }
  };
}

function main() {
  try {
    const cfg = parseArgs(process.argv.slice(2));
    if (!cfg.matrix1) {
      const result = demo();
      fs.writeFileSync(cfg.output, JSON.stringify(result, null, 2), "utf8");
      console.log(JSON.stringify(result, null, 2));
      return;
    }

    const A = readMatrix(cfg.matrix1);
    const B = cfg.matrix2 ? readMatrix(cfg.matrix2) : null;

    const result = compute(cfg, A, B);
    const report = { operation: cfg.operation, properties: matrixProps(A), ...result };

    if (Array.isArray(report.result) && Array.isArray(report.result[0])) {
      console.log(formatMatrix(new Matrix(report.result), cfg.precision));
    } else {
      console.log(JSON.stringify(report.result, null, 2));
    }

    if (cfg.operation === "inverse") {
      const inv = new Matrix(report.result);
      const ident = A.mmul(inv);
      report.inverseVerification = ident.to2DArray();
    }

    fs.writeFileSync(cfg.output, JSON.stringify(report, null, 2), "utf8");
  } catch (err) {
    console.error(`Error: ${err.message}`);
    process.exit(1);
  }
}

main();