001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package org.wpilib.math.autodiff; 006 007import org.ejml.data.DMatrixSparseCSC; 008import org.ejml.data.DMatrixSparseTriplet; 009import org.ejml.ops.DConvertMatrixStruct; 010import org.ejml.simple.SimpleMatrix; 011 012/** 013 * Wrapper for sparse matrix triplets from JNI. 014 * 015 * <p>We can't use DMatrixSparseTriplet because it doesn't have a method for bulk-initialization 016 * from triplet arrays. 017 * 018 * @param rows Triplet rows. 019 * @param cols Triplet columns. 020 * @param values Triplet values. 021 */ 022public record NativeSparseTriplets(int[] rows, int[] cols, double[] values) { 023 /** 024 * Returns a SimpleMatrix wrapper for this set of triplets. 025 * 026 * @param rows Number of rows in sparse SimpleMatrix. 027 * @param cols Number of columns in sparse SimpleMatrix. 028 * @return A SimpleMatrix wrapper for this set of triplets. 029 */ 030 public SimpleMatrix toSimpleMatrix(int rows, int cols) { 031 var ejmlTriplets = new DMatrixSparseTriplet(rows, cols, values().length); 032 for (int i = 0; i < values().length; ++i) { 033 ejmlTriplets.addItem(rows()[i], cols()[i], values()[i]); 034 } 035 return new SimpleMatrix(DConvertMatrixStruct.convert(ejmlTriplets, (DMatrixSparseCSC) null)); 036 } 037}