Skip to content

feat: add comprehensive test suite and verification helper for Part 1 #83

Merged
aFlyingSeal merged 8 commits into
devfrom
feat/update-part1
Apr 19, 2026
Merged

feat: add comprehensive test suite and verification helper for Part 1 #83
aFlyingSeal merged 8 commits into
devfrom
feat/update-part1

Conversation

@spongeofop-rgb

@spongeofop-rgb spongeofop-rgb commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator

Linked issue

Closes #20

This PR completes the comprehensive walkthrough for Part 1 and verify

Checklist

Code

  • All acceptance criteria on the linked issue are checked off
  • No numpy.linalg, scipy.linalg, or sympy solver calls in implementation code
  • All file paths use pathlib.Path, no hardcoded OS separators
  • No commented-out code committed
  • No debugging print() statements left in

Tests

  • At least 5 test cases per new function
  • Edge cases covered (singular matrix, zero input, identity, etc.)
  • All tests pass without errors

Summary by CodeRabbit

  • Tests
    • Replaced determinant-only harness with a comprehensive interactive validation notebook covering Gaussian elimination, inversion, determinants, rank/null-space, and ill-conditioned cases; added stricter residual and assertion checks across square, rectangular, singular, and near‑singular scenarios
  • New Features
    • Added an interactive verification helper that runs case suites and emits concise pass/fail logs
  • Documentation
    • Notebook now initializes the environment, prints an “environment ready” status, per-suite status messages, and a final conclusion section

@coderabbitai

coderabbitai Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Replaces a determinant-only loop in part1/part1_demo.ipynb with a full verification notebook: adds %load_ext autoreload, imports project implementations (gaussian_eliminate, back_substitute, determinant, inverse, rank_and_basis), a verify_system(A, x, b, label="Case") helper, and multiple test suites for solve/determinant/inverse/ill-conditioning/rank-nullspace checks.

Changes

Cohort / File(s) Summary
Demo Notebook
part1/part1_demo.ipynb
Reworked notebook into a comprehensive verification harness. Added autoreload, imports of linear-algebra implementations, verify_system(A, x, b, label="Case"), Gaussian-elimination test suite (many matrix cases), determinant comparisons with np.linalg.det, inverse checks including singular-case assertions, ill-conditioned sensitivity test, and rank/null-space verification. Replaced prior determinant-only loop with per-suite logging and final status output.

Sequence Diagram(s)

sequenceDiagram
    participant Runner as Test Runner
    participant Notebook as part1_demo.ipynb
    participant Algo as LinearAlg (gaussian_eliminate / inverse / rank_and_basis / determinant)
    participant Verifier as verify_system
    participant NumPy as NumPy

    Runner->>Notebook: execute notebook suites
    Notebook->>Algo: call gaussian_eliminate / back_substitute / determinant / inverse / rank_and_basis
    Algo-->>Notebook: return results (x, det, A_inv, rank, basis)
    Notebook->>Verifier: verify_system(A, x, b, label)
    Verifier->>NumPy: attempt np.linalg.solve / compute residuals / np.linalg.det
    NumPy-->>Verifier: results or LinAlgError
    Verifier-->>Notebook: assert pass or raise
    Notebook-->>Runner: print per-suite status and final conclusion
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • aFlyingSeal

Poem

🐰 I hopped through matrices late at night,

I checked each residual till it looked right,
I solved and inverted with a curious twitch,
Found null-space whispers in every ditch,
Notebook polished — tests ready to flight.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main change: adding a comprehensive test suite and verification helper for Part 1, which aligns perfectly with the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feat/update-part1

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@part1/part1_demo.ipynb`:
- Around line 95-110: The test cells (e.g., test_gaussian_cases which calls
gaussian_eliminate and verify_solution) currently only print results so failures
don't stop the notebook; change them to real assertions by having
verify_solution raise an AssertionError on mismatch or by wrapping its result
with assert (e.g., assert verify_solution(A, x, b)), and replace any prints of
"✅/❌" with assert statements that include a helpful message (e.g., assert
condition, f"Case {name} failed: ..."). Do the same refactor for the other test
blocks referenced (the cells around lines 134-147, 171-186, 210-228, 257-271) so
any failing case raises an exception and halts execution rather than only
printing.
- Around line 212-226: The test block never hits the singular-matrix path of
inverse (function inverse) so add a singular case to the cases list (e.g., a
rank-deficient 2x2 like [[1,2],[2,4]]) and update the exception handling: when
inverse raises ValueError for that case, treat the result as a passing test
(print a PASS message) rather than a bare error; keep the existing np.allclose
check for non-singular cases and only consider ValueError as expected/pass for
the newly added singular case.
🪄 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

Run ID: b5fde895-bd15-4ba9-8aaf-febdb7426800

📥 Commits

Reviewing files that changed from the base of the PR and between d0ad745 and e910d8f.

📒 Files selected for processing (1)
  • part1/part1_demo.ipynb

Comment thread part1/part1_demo.ipynb Outdated
Comment thread part1/part1_demo.ipynb Outdated
@spongeofop-rgb spongeofop-rgb changed the title feat: complete part1 demo with 5 test cases feat: part1_demo Apr 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@part1/part1_demo.ipynb`:
- Around line 10-13: The notebook claims to validate the determinant but never
actually runs assertions; add an assertion-based test suite that calls the
imported determinant function (determinant) and verifies expected outputs for
representative matrices (identity, triangular, singular with det=0, and a small
ill-conditioned example) and compares against known values or numpy.linalg.det
with an appropriate tolerance; place this assertion block near where determinant
is imported and alongside the existing tests for gauss/elimination so the
determinant algorithm is actually verified in the executed flow.
- Around line 114-118: The test suite's test_cases list (variable test_cases in
part1_demo.ipynb) only contains three cases and fails to meet the target of at
least five cases per function path (Gaussian elimination, inverse, rank/basis);
expand each relevant test list (the Gaussian tests around the shown test_cases,
and the similar lists at the other locations referenced) to include at least
five varied matrices per path — e.g., add cases for larger sizes (4x4), singular
variants, near-singular/ill-conditioned, zero/duplicate rows, negative/float
entries, and a random seeded matrix — so each tested function (Gaussian
elimination, matrix inverse, rank/basis functions) has >=5 representative test
inputs.
🪄 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

Run ID: 3ae9a285-cb7c-4ec3-a007-e26d69487a2b

📥 Commits

Reviewing files that changed from the base of the PR and between adf06f1 and b062bc1.

📒 Files selected for processing (1)
  • part1/part1_demo.ipynb

Comment thread part1/part1_demo.ipynb
Comment thread part1/part1_demo.ipynb Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
part1/part1_demo.ipynb (1)

8-13: ⚠️ Potential issue | 🟠 Major

Add the missing determinant assertion suite.

The notebook still claims Part 1 is verified end-to-end, but determinant(...) is never exercised anywhere in the executed flow. That leaves one core algorithm unverified despite the intro and import block claiming otherwise.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@part1/part1_demo.ipynb` around lines 8 - 13, The notebook never exercises
determinant(...), so add an assertion-based test suite that calls determinant
for representative cases and integrates with the existing Part 1 assertion
runner (e.g., add tests inside the current assert_suite or run_part1_assertions
function/block); specifically include checks for identity matrices (det=1),
triangular matrices (product of diagonal), singular matrices (det=0), small
known examples (explicit integer determinants), and several random and
ill-conditioned matrices validated against numpy.linalg.det with a
floating-point tolerance (use abs(a-b) < tol). Ensure each assertion references
determinant(...) by name and that failures raise informative AssertionErrors so
the existing end-to-end verification truly covers determinant.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@part1/part1_demo.ipynb`:
- Around line 79-84: The helper currently treats a shape mismatch (len(x) !=
len(A)) as an acceptable success in the except block for np.linalg.LinAlgError;
instead, make the residual the sole deciding condition by removing the shape
check and asserting only that error < 1e-5 (use the existing variables x, A,
error, label in the except block after np.linalg.LinAlgError) so
rectangular/wide systems fail when Ax != b.

---

Duplicate comments:
In `@part1/part1_demo.ipynb`:
- Around line 8-13: The notebook never exercises determinant(...), so add an
assertion-based test suite that calls determinant for representative cases and
integrates with the existing Part 1 assertion runner (e.g., add tests inside the
current assert_suite or run_part1_assertions function/block); specifically
include checks for identity matrices (det=1), triangular matrices (product of
diagonal), singular matrices (det=0), small known examples (explicit integer
determinants), and several random and ill-conditioned matrices validated against
numpy.linalg.det with a floating-point tolerance (use abs(a-b) < tol). Ensure
each assertion references determinant(...) by name and that failures raise
informative AssertionErrors so the existing end-to-end verification truly covers
determinant.
🪄 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

Run ID: 1e2676b6-2f37-4cea-b491-2401b5c6f014

📥 Commits

Reviewing files that changed from the base of the PR and between b062bc1 and 16af54b.

📒 Files selected for processing (1)
  • part1/part1_demo.ipynb

Comment thread part1/part1_demo.ipynb Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
part1/part1_demo.ipynb (1)

70-86: ⚠️ Potential issue | 🟠 Major

Documentation/code mismatch and residual check bypass still present.

Two issues in verify_system:

  1. Lines 57-60 vs 77: The markdown documentation states the error is computed as relative residual ||Ax-b||/||b||, but line 77 computes absolute residual np.linalg.norm(residual) without normalization.

  2. Line 84: The condition or len(x) != len(A) still bypasses the residual check for non-square systems. This was flagged in a previous review (marked as addressed) but remains in the code. The "Rectangular Wide" test case (line 125) can pass even if Ax ≠ b.

Proposed fix
 def verify_system(A, x, b, label="Case"):
     A_np = np.array(A, dtype=float)
     x_np = np.array(x, dtype=float)
     b_np = np.array(b, dtype=float)
     
     # Tính sai số Ax - b
     residual = np.dot(A_np, x_np) - b_np
-    error = np.linalg.norm(residual)
+    error = np.linalg.norm(residual) / max(np.linalg.norm(b_np), 1.0)
     
     try:
         x_ref = np.linalg.solve(A_np, b_np)
         assert np.allclose(x_np, x_ref, atol=1e-5), f"❌ {label}: Nghiệm không khớp với Numpy!"
     except np.linalg.LinAlgError:
         # Nếu hệ vô định/vô nghiệm, kiểm tra xem x có thỏa mãn tối ưu không
-        assert error < 1e-5 or len(x) != len(A), f"❌ {label}: Sai số quá lớn!"
+        assert error < 1e-5, f"❌ {label}: Sai số quá lớn!"
     
     print(f"   [OK] {label}: Verified (Error: {error:.2e})")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@part1/part1_demo.ipynb` around lines 70 - 86, The verify_system function
currently computes an absolute residual and bypasses checks for non-square
systems; change it to compute a relative residual by setting error =
np.linalg.norm(residual) / (np.linalg.norm(b_np) + eps) (use a small eps to
avoid division by zero) instead of error = np.linalg.norm(residual), and remove
the len(x) != len(A) bypass; for rectangular or singular cases, compute a
reference solution x_ref via np.linalg.lstsq(A_np, b_np, rcond=None)[0] (fall
back to np.linalg.solve when appropriate) and compare x_np to x_ref with
np.allclose using the same atol, and keep the LinAlgError handling only for
genuine solve failures while using the relative error for assertions and
reporting.
🧹 Nitpick comments (1)
part1/part1_demo.ipynb (1)

152-155: Redundant imports.

math and numpy are already imported at lines 34-35. These re-imports are unnecessary.

Proposed fix
-    "import math\n",
-    "import numpy as np\n",
-    "\n",
     "print(\"--- Testing Determinant Suite ---\")\n",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@part1/part1_demo.ipynb` around lines 152 - 155, Remove the redundant
re-imports of math and numpy by deleting the repeated lines "import math" and
"import numpy as np" found in the cell that repeats those imports; keep the
original imports at their first occurrence (the earlier cell where math and
numpy are imported) so any code using math or np continues to work, and run the
notebook to confirm no NameError occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@part1/part1_demo.ipynb`:
- Around line 70-86: The verify_system function currently computes an absolute
residual and bypasses checks for non-square systems; change it to compute a
relative residual by setting error = np.linalg.norm(residual) /
(np.linalg.norm(b_np) + eps) (use a small eps to avoid division by zero) instead
of error = np.linalg.norm(residual), and remove the len(x) != len(A) bypass; for
rectangular or singular cases, compute a reference solution x_ref via
np.linalg.lstsq(A_np, b_np, rcond=None)[0] (fall back to np.linalg.solve when
appropriate) and compare x_np to x_ref with np.allclose using the same atol, and
keep the LinAlgError handling only for genuine solve failures while using the
relative error for assertions and reporting.

---

Nitpick comments:
In `@part1/part1_demo.ipynb`:
- Around line 152-155: Remove the redundant re-imports of math and numpy by
deleting the repeated lines "import math" and "import numpy as np" found in the
cell that repeats those imports; keep the original imports at their first
occurrence (the earlier cell where math and numpy are imported) so any code
using math or np continues to work, and run the notebook to confirm no NameError
occurs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cc3d418c-472a-487e-83d1-06b3b8959b57

📥 Commits

Reviewing files that changed from the base of the PR and between 16af54b and 6eeb560.

📒 Files selected for processing (1)
  • part1/part1_demo.ipynb

@TanKhoiTV TanKhoiTV changed the title feat: part1_demo feat: add comprehensive test suite and verification helper for Part 1 Apr 18, 2026
@aFlyingSeal aFlyingSeal merged commit 6436e76 into dev Apr 19, 2026
3 checks passed
@aFlyingSeal aFlyingSeal deleted the feat/update-part1 branch April 19, 2026 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[2pts] verify_solution(A, x, b) + part1_demo.ipynb

2 participants