Matrix Operations Calculator (java, written by Codex)
envgap__codex__java-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
pom.xml- Reproduce
Awaiting issue-specific recipe- Run under trace
Awaiting a meaningful runtime command
03 / TASK AND FAILURE
codex/java-t1 #41 · read the task the agent was given
Codex wrote this java 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 Java project for a clean Ubuntu 22.04 machine with only JDK 17+ installed. Include: - Source code - pom.xml 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
3 files, exactly as written, before any repair.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.tmlr</groupId>
<artifactId>matrix-operations-calculator</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.7.1</version>
<configuration>
<archive>
<manifest>
<mainClass>MatrixOperationsCalculator</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>
README.md
# Matrix Operations Calculator (Java) ## Requirements - Ubuntu 22.04 - JDK 17+ - Maven 3.8+ ## Build ```bash mvn -q -DskipTests package assembly:single ``` ## Run ```bash java -cp target/matrix-operations-calculator-1.0.0-jar-with-dependencies.jar MatrixOperationsCalculator matrix.csv --operation inverse --precision 6 java -cp target/matrix-operations-calculator-1.0.0-jar-with-dependencies.jar MatrixOperationsCalculator matrix.json --operation multiply --matrix2 matrix2.json ``` If no input is passed, sample matrices are generated and demonstrated.
src/main/java/MatrixOperationsCalculator.java
import org.apache.commons.math3.linear.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
public class MatrixOperationsCalculator {
private static class Config {
String matrix1;
String matrix2;
String operation = "transpose";
Double scalar;
boolean sparse;
int precision = 4;
String output = "result_matrix.json";
}
public static void main(String[] args) {
try {
Config cfg = parseArgs(args);
if (cfg.matrix1 == null) {
Map<String, Object> demo = demo();
Files.writeString(Paths.get(cfg.output), toJson(demo), StandardCharsets.UTF_8);
System.out.println(toJson(demo));
return;
}
RealMatrix A = readMatrix(Paths.get(cfg.matrix1));
RealMatrix B = cfg.matrix2 != null ? readMatrix(Paths.get(cfg.matrix2)) : null;
Map<String, Object> report = new LinkedHashMap<>();
report.put("generatedAt", Instant.now().toString());
report.put("operation", cfg.operation);
report.put("properties", props(A));
report.putAll(compute(cfg, A, B));
Object result = report.get("result");
if (result instanceof List<?> list && !list.isEmpty() && list.get(0) instanceof List<?>) {
System.out.println(formatMatrix((List<List<Double>>) result, cfg.precision));
} else {
System.out.println(toJson(result));
}
Files.writeString(Paths.get(cfg.output), toJson(report), StandardCharsets.UTF_8);
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
System.exit(1);
}
}
private static Config parseArgs(String[] args) {
Config cfg = new Config();
List<String> pos = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
String a = args[i];
if (!a.startsWith("--")) { pos.add(a); continue; }
switch (a) {
case "--operation" -> cfg.operation = args[++i];
case "--matrix2" -> cfg.matrix2 = args[++i];
case "--scalar" -> cfg.scalar = Double.parseDouble(args[++i]);
case "--sparse" -> cfg.sparse = true;
case "--precision" -> cfg.precision = Integer.parseInt(args[++i]);
case "--output" -> cfg.output = args[++i];
default -> throw new IllegalArgumentException("Unknown option: " + a);
}
}
if (!pos.isEmpty()) cfg.matrix1 = pos.get(0);
return cfg;
}
private static RealMatrix readMatrix(Path p) throws IOException {
String txt = Files.readString(p, StandardCharsets.UTF_8).trim();
if (p.toString().toLowerCase().endsWith(".json")) {
return MatrixUtils.createRealMatrix(parseJsonMatrix(txt));
}
String[] lines = txt.split("\\R");
double[][] m = new double[lines.length][];
for (int i = 0; i < lines.length; i++) {
String[] parts = lines[i].split(",");
m[i] = new double[parts.length];
for (int j = 0; j < parts.length; j++) m[i][j] = Double.parseDouble(parts[j].trim());
}
return MatrixUtils.createRealMatrix(m);
}
private static double[][] parseJsonMatrix(String txt) {
// Minimal JSON matrix parser for [[...], [...]]
txt = txt.replaceAll("\\s+", "");
if (!txt.startsWith("[[") || !txt.endsWith("]]")) throw new IllegalArgumentException("Invalid JSON matrix");
txt = txt.substring(2, txt.length() - 2);
String[] rows = txt.split("\\],\\[");
double[][] out = new double[rows.length][];
for (int i = 0; i < rows.length; i++) {
String[] vals = rows[i].split(",");
out[i] = new double[vals.length];
for (int j = 0; j < vals.length; j++) out[i][j] = Double.parseDouble(vals[j]);
}
return out;
}
private static Map<String, Object> compute(Config cfg, RealMatrix A, RealMatrix B) {
Map<String, Object> out = new LinkedHashMap<>();
if (cfg.scalar != null) out.put("scalarMultiply", toList(A.scalarMultiply(cfg.scalar)));
switch (cfg.operation) {
case "add" -> out.put("result", toList(A.add(B)));
case "subtract" -> out.put("result", toList(A.subtract(B)));
case "multiply" -> out.put("result", toList(A.multiply(B)));
case "transpose" -> out.put("result", toList(A.transpose()));
case "determinant" -> out.put("result", new LUDecomposition(A).getDeterminant());
case "inverse" -> {
RealMatrix inv = new LUDecomposition(A).getSolver().getInverse();
out.put("result", toList(inv));
out.put("inverseVerification", toList(A.multiply(inv)));
}
case "eigenvalues" -> {
EigenDecomposition ed = new EigenDecomposition(A);
double[] vals = ed.getRealEigenvalues();
List<Double> v = new ArrayList<>();
for (double x : vals) v.add(x);
out.put("result", v);
}
case "rank" -> out.put("result", new SingularValueDecomposition(A).getRank());
case "trace" -> out.put("result", A.getTrace());
case "lu" -> {
LUDecomposition lu = new LUDecomposition(A);
out.put("result", Map.of("L", toList(lu.getL()), "U", toList(lu.getU()), "P", toList(lu.getP())));
}
default -> throw new IllegalArgumentException("Unsupported operation: " + cfg.operation);
}
return out;
}
private static Map<String, Object> props(RealMatrix A) {
int r = A.getRowDimension(), c = A.getColumnDimension();
boolean sym = r == c && A.subtract(A.transpose()).getNorm() < 1e-9;
boolean posDef = false;
if (sym) {
try {
new CholeskyDecomposition(A);
posDef = true;
} catch (Exception ignored) {}
}
Double cond = r == c ? new SingularValueDecomposition(A).getConditionNumber() : null;
Map<String, Object> m = new LinkedHashMap<>();
m.put("dimensions", List.of(r, c));
m.put("rank", new SingularValueDecomposition(A).getRank());
m.put("trace", r == c ? A.getTrace() : null);
m.put("isSymmetric", sym);
m.put("isPositiveDefinite", posDef);
m.put("conditionNumber", cond);
return m;
}
private static List<List<Double>> toList(RealMatrix M) {
List<List<Double>> out = new ArrayList<>();
for (int i = 0; i < M.getRowDimension(); i++) {
List<Double> row = new ArrayList<>();
for (int j = 0; j < M.getColumnDimension(); j++) row.add(M.getEntry(i, j));
out.add(row);
}
return out;
}
private static String formatMatrix(List<List<Double>> data, int precision) {
int rows = data.size();
int cols = data.get(0).size();
String[][] text = new String[rows][cols];
int[] w = new int[cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
text[i][j] = String.format(Locale.ROOT, "%." + precision + "f", data.get(i).get(j));
w[j] = Math.max(w[j], text[i][j].length());
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows; i++) {
if (i > 0) sb.append('\n');
for (int j = 0; j < cols; j++) {
if (j > 0) sb.append(" ");
sb.append(String.format("%" + w[j] + "s", text[i][j]));
}
}
return sb.toString();
}
private static Map<String, Object> demo() {
RealMatrix A = MatrixUtils.createRealMatrix(new double[][] {{4,2,1},{0,5,3},{2,1,6}});
RealMatrix B = MatrixUtils.createRealMatrix(new double[][] {{1,2,3},{4,5,6},{7,8,9}});
RealMatrix C = MatrixUtils.createRealMatrix(new double[][] {{2,1,0,3},{1,0,2,2},{3,1,1,0}});
RealMatrix D = MatrixUtils.createRealMatrix(new double[][] {{1,2,3},{0,1,4},{5,6,0},{1,0,2}});
EigenDecomposition ed = new EigenDecomposition(A);
LUDecomposition lu = new LUDecomposition(A);
Map<String, Object> out = new LinkedHashMap<>();
out.put("add", toList(A.add(B)));
out.put("multiply", toList(C.multiply(D)));
out.put("determinant", lu.getDeterminant());
out.put("inverse", toList(lu.getSolver().getInverse()));
out.put("eigenvalues", Arrays.stream(ed.getRealEigenvalues()).boxed().toList());
out.put("lu", Map.of("L", toList(lu.getL()), "U", toList(lu.getU())));
return out;
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof String s) return '"' + s.replace("\\", "\\\\").replace("\"", "\\\"") + '"';
if (obj instanceof Number || obj instanceof Boolean) return obj.toString();
if (obj instanceof Map<?, ?> m) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : m.entrySet()) {
if (!first) sb.append(',');
first = false;
sb.append(toJson(String.valueOf(e.getKey()))).append(':').append(toJson(e.getValue()));
}
sb.append('}');
return sb.toString();
}
if (obj instanceof Iterable<?> it) {
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (Object x : it) {
if (!first) sb.append(',');
first = false;
sb.append(toJson(x));
}
sb.append(']');
return sb.toString();
}
return toJson(String.valueOf(obj));
}
}