Skip to content

algorithm: add float maxvol support - #4

Merged
gaelic-ghost merged 1 commit into
mainfrom
algorithm/float-maxvol
Jul 1, 2026
Merged

algorithm: add float maxvol support#4
gaelic-ghost merged 1 commit into
mainfrom
algorithm/float-maxvol

Conversation

@gaelic-ghost

@gaelic-ghost gaelic-ghost commented Jul 1, 2026

Copy link
Copy Markdown
Owner

Summary

  • add explicit Float overloads for square MaxVol and RectMaxVol
  • share the algorithm through a minimal internal scalar abstraction for modern Accelerate getrf/getrs/ger calls
  • add NumPy/SciPy-generated float32 reference fixtures plus randomized Double/Float numerical coverage
  • update README, DocC, and ROADMAP for v0.7.0 and remaining v1.0 work

Verification

  • swiftformat Sources Tests
  • swift build
  • swift test
  • swift test -c release
  • swift package dump-package
  • swift build --target MaxVol -Xswiftc -emit-symbol-graph -Xswiftc -emit-symbol-graph-dir -Xswiftc .build/symbol-graphs
  • xcrun docc convert Sources/MaxVol/MaxVol.docc --fallback-display-name MaxVol --fallback-bundle-identifier com.gaelic-ghost.MaxVol --fallback-bundle-version 0.7.0 --additional-symbol-graph-dir .build/symbol-graphs --output-path .build/docc/MaxVol.doccarchive
  • scripts/repo-maintenance/validate-all.sh

Summary by CodeRabbit

  • New Features

    • Added single-precision support for the main volume-selection APIs, so both Double and Float matrices are now supported.
    • Expanded rectangular max-volume selection to work with both scalar types.
  • Bug Fixes

    • Improved numerical robustness and error handling for near-rank-deficient inputs.
    • Refined convergence and tolerance behavior across square and rectangular workflows.
  • Documentation

    • Updated README, roadmap, and API docs to clearly describe Double and Float usage, options, and algorithm guidance.
  • Tests

    • Added broader coverage for Float results, randomized matrix cases, and reconstruction accuracy.

@gaelic-ghost gaelic-ghost added the enhancement New feature or request label Jul 1, 2026
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Generalizes MaxVol and RectMaxVol algorithms from Double-only to a shared Double/Float implementation via a new MaxVolScalar protocol wrapping LAPACK/BLAS routines. Adds public Float overloads, generalizes options resolution, adds Float/numerical test suites, and updates README, ROADMAP, and DocC documentation.

Changes

Double/Float Generalization of MaxVol

Layer / File(s) Summary
MaxVolScalar protocol and bindings
Sources/MaxVol/MaxVolScalar.swift
New protocol abstracts getrf/getrs/rankOneUpdate, rank tolerance, and magnitude conversion; conforms Double (dgetrf_/dgetrs_/cblas_dger) and Float (sgetrf_/sgetrs_/cblas_sger); adds lapackInt and validateLapackInfo helpers.
Generic square MaxVol
Sources/MaxVol/MaxVol.swift
Adds public Float maxVol overload delegating to generic maxVolImpl; generalizes pivot initialization, coefficient solving, row/magnitude helpers, rank-one update, and singularity validation to use MaxVolScalar.
Generic RectMaxVol and options
Sources/MaxVol/RectMaxVol.swift, Sources/MaxVol/RectMaxVolOptions.swift
Adds public Float rectMaxVol overload delegating to generic rectMaxVolImpl; generalizes row-norm, basis-row append, and identity-coefficient helpers; refactors RectMaxVolOptions.resolved to validate bounds generically from rows/columns.
Float and numerical behavior tests
Tests/MaxVolTests/FloatMaxVolTests.swift, Tests/MaxVolTests/NumericalBehaviorTests.swift
Adds test suites validating maxVol/rectMaxVol for Float and Double against fixtures, reconstruction accuracy, and rank-deficiency error handling using deterministic orthonormal-matrix generation.
Documentation updates
README.md, ROADMAP.md, Sources/MaxVol/MaxVol.docc/*
Updates goal statement, implementation plan, roadmap milestones, and DocC pages to describe combined Double/Float support and explicit overload signatures.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant maxVol
  participant maxVolImpl
  participant MaxVolScalar

  Caller->>maxVol: maxVol(matrix, options)
  maxVol->>maxVolImpl: delegate with Scalar type (Double/Float)
  maxVolImpl->>MaxVolScalar: getrf (initial pivot rows)
  maxVolImpl->>MaxVolScalar: getrs (expansion coefficients)
  maxVolImpl->>MaxVolScalar: rankOneUpdate (row swap)
  maxVolImpl-->>Caller: MaxVolResult<Scalar>
Loading

Estimated code review effort: 4 (Complex) | ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding Float support to the MaxVol algorithm.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch algorithm/float-maxvol

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gaelic-ghost
gaelic-ghost merged commit d3cbc2e into main Jul 1, 2026
1 of 2 checks passed
@gaelic-ghost
gaelic-ghost deleted the algorithm/float-maxvol branch July 1, 2026 05:31

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Tests/MaxVolTests/FloatMaxVolTests.swift`:
- Around line 263-391: The helper logic for generating reproducible orthonormal
fixtures is duplicated between FloatMaxVolTests and NumericalBehaviorTests;
extract orthonormalColumns, dot, SeededGenerator, and
DenseColumnMajorMatrix<Double>.mapValues into a shared test-support location so
both suites use the same implementation. Move the duplicated definitions into a
common internal test helper (for example, a shared support file under
MaxVolTests) and update the test files to call the shared symbols instead of
maintaining separate copies.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d7daa57a-b585-4fc2-9163-cac66f6c4447

📥 Commits

Reviewing files that changed from the base of the PR and between 11c9288 and 0530a09.

📒 Files selected for processing (10)
  • README.md
  • ROADMAP.md
  • Sources/MaxVol/MaxVol.docc/MaxVol.md
  • Sources/MaxVol/MaxVol.docc/ToleranceAndConvergence.md
  • Sources/MaxVol/MaxVol.swift
  • Sources/MaxVol/MaxVolScalar.swift
  • Sources/MaxVol/RectMaxVol.swift
  • Sources/MaxVol/RectMaxVolOptions.swift
  • Tests/MaxVolTests/FloatMaxVolTests.swift
  • Tests/MaxVolTests/NumericalBehaviorTests.swift

Comment on lines +263 to +391
private func expectReconstruction(
of matrix: DenseColumnMajorMatrix<Float>,
using result: MaxVolResult<Float>,
tolerance: Float = 1e-5
) throws {
for row in 0..<matrix.rows {
for column in 0..<matrix.columns {
var reconstructed: Float = 0
for selectedColumn in 0..<result.selectedRows.count {
reconstructed += try result.coefficients.value(row: row, column: selectedColumn)
* matrix.value(row: result.selectedRows[selectedColumn], column: column)
}

let expected = try matrix.value(row: row, column: column)
#expect(abs(reconstructed - expected) <= tolerance)
}
}
}

private func expectCoefficients(
_ coefficients: DenseColumnMajorMatrix<Float>,
rowMajorValues: [Float],
tolerance: Float = 5e-6
) throws {
let expected = try DenseColumnMajorMatrix(
rows: coefficients.rows,
columns: coefficients.columns,
rowMajorValues: rowMajorValues
)

for row in 0..<coefficients.rows {
for column in 0..<coefficients.columns {
let actualValue = try coefficients.value(row: row, column: column)
let expectedValue = try expected.value(row: row, column: column)
#expect(abs(actualValue - expectedValue) <= tolerance)
}
}
}

private func expectSelectedRowsAreIdentity(_ result: MaxVolResult<Float>) throws {
for (identityColumn, selectedRow) in result.selectedRows.enumerated() {
for column in 0..<result.coefficients.columns {
let expected: Float = column == identityColumn ? 1 : 0
let actual = try result.coefficients.value(row: selectedRow, column: column)
#expect(abs(actual - expected) <= 1e-6)
}
}
}

private func maximumAbsoluteCoefficient(
in coefficients: DenseColumnMajorMatrix<Float>
) -> Double {
coefficients.values.map { Double(abs($0)) }.max() ?? 0
}

private func maximumUnselectedRowNorm(in result: MaxVolResult<Float>) -> Double {
let selected = Set(result.selectedRows)
return (0..<result.coefficients.rows)
.filter { !selected.contains($0) }
.map { row in
let normSquared = (0..<result.coefficients.columns).reduce(0.0) { total, column in
let coefficient = result.coefficients[row: row, column: column]
return total + Double(coefficient * coefficient)
}
return normSquared.squareRoot()
}
.max() ?? 0
}

private func orthonormalColumns(
rows: Int,
columns: Int,
seed: UInt64
) throws -> DenseColumnMajorMatrix<Double> {
var generator = SeededGenerator(state: seed)
var columnVectors = (0..<columns).map { column -> [Double] in
(0..<rows).map { row in
generator.nextDouble() + (row == column ? 1.0 : 0.0)
}
}

for column in 0..<columns {
for priorColumn in 0..<column {
let projection = dot(columnVectors[column], columnVectors[priorColumn])
for row in 0..<rows {
columnVectors[column][row] -= projection * columnVectors[priorColumn][row]
}
}

let norm = dot(columnVectors[column], columnVectors[column]).squareRoot()
for row in 0..<rows {
columnVectors[column][row] /= norm
}
}

return try DenseColumnMajorMatrix(
rows: rows,
columns: columns,
columnMajorValues: columnVectors.flatMap { $0 }
)
}

private func dot(_ left: [Double], _ right: [Double]) -> Double {
zip(left, right).reduce(0) { total, pair in
total + pair.0 * pair.1
}
}

private struct SeededGenerator {
var state: UInt64

mutating func nextDouble() -> Double {
state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
let scaled = Double(state >> 11) / Double(UInt64.max >> 11)
return scaled * 2 - 1
}
}

private extension DenseColumnMajorMatrix where Scalar == Double {
func mapValues<Output: Sendable>(
_ transform: (Double) -> Output
) throws -> DenseColumnMajorMatrix<Output> {
try DenseColumnMajorMatrix<Output>(
rows: rows,
columns: columns,
columnMajorValues: values.map(transform)
)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Test helper duplication across FloatMaxVolTests.swift and NumericalBehaviorTests.swift.

orthonormalColumns, dot, SeededGenerator, and the DenseColumnMajorMatrix<Double>.mapValues extension here are byte-for-byte duplicated in Tests/MaxVolTests/NumericalBehaviorTests.swift (lines 156-215). Two independent copies of the PRNG/orthogonalization logic risk silently diverging if one file is updated (e.g., changing the Gram-Schmidt normalization or PRNG constants) without the other, undermining the "reproducible fixture" guarantee both suites rely on.

Consider extracting these into a shared internal test-support file (e.g., Tests/MaxVolTests/TestSupport.swift) that both suites import.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Tests/MaxVolTests/FloatMaxVolTests.swift` around lines 263 - 391, The helper
logic for generating reproducible orthonormal fixtures is duplicated between
FloatMaxVolTests and NumericalBehaviorTests; extract orthonormalColumns, dot,
SeededGenerator, and DenseColumnMajorMatrix<Double>.mapValues into a shared
test-support location so both suites use the same implementation. Move the
duplicated definitions into a common internal test helper (for example, a shared
support file under MaxVolTests) and update the test files to call the shared
symbols instead of maintaining separate copies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant