Skip to content

Refactor manure NH3 EF logic; update tests; add perf test fields#288

Merged
SvenVw merged 8 commits into
mainfrom
FDM286
Oct 1, 2025
Merged

Refactor manure NH3 EF logic; update tests; add perf test fields#288
SvenVw merged 8 commits into
mainfrom
FDM286

Conversation

@SvenVw
Copy link
Copy Markdown
Collaborator

@SvenVw SvenVw commented Oct 1, 2025

Summary by CodeRabbit

  • New Features
    • Expanded support for fertilizer application methods across grassland, cropland, and bare soil.
    • Fertilizer applications now include method, display name, and ID fields.
  • Bug Fixes
    • More accurate ammonia emission results via updated emission factors and baseline nitrogen contributions.
    • Clear errors for unsupported application methods (replacing silent warnings).
  • Data
    • Improved handling of unknown crop metrics by using median values within rotations.
  • Documentation
    • Changelogs updated across packages.
  • Chores
    • Dependency and version updates.

Closes #286

@SvenVw SvenVw self-assigned this Oct 1, 2025
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Oct 1, 2025

⚠️ No Changeset found

Latest commit: b23fdbc

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 1, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This PR revises ammonia emission factor determination for fertilizers by introducing rotation-based land-type detection and a centralized method × land-type dispatch, updates tests accordingly (including new scenarios and stricter error handling), extends performance test inputs with three fields, adjusts .changeset config, and bumps package versions with changelog updates.

Changes

Cohort / File(s) Summary
Ammonia EF logic (calculator)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts
Replaced legacy checks with rotation-based land-type detection (grassland/cropland/bare soil) and a centralized switch dispatch over application methods and land types; unsupported combos now throw errors; explicit EF mappings added for many methods.
Tests (fertilizers + performance)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts, fdm-calculator/src/balance/nitrogen/performance.test.ts
Updated tests to new identifiers, EF values, and precision; replaced warn-spy with thrown-error assertions for unsupported methods; expanded scenarios across land types and methods; performance test input items now include p_app_method, p_name_nl, p_id (public FieldInput shape extended).
Changeset config
.changeset/config.json
updateInternalDependencies changed from "patch" to "minor".
App versioning and changelog
fdm-app/package.json, fdm-app/CHANGELOG.md
Version bumped to 0.23.1; added 0.23.1 changelog with dependency updates.
Calculator versioning and changelog
fdm-calculator/package.json, fdm-calculator/CHANGELOG.md
Version bumped to 0.7.1; added changelog entry with patch notes.
Core versioning and changelog
fdm-core/package.json, fdm-core/CHANGELOG.md
Version bumped to 0.25.1; devDependency on @svenvw/fdm-data updated; changelog entry added.
Data changelog and version
fdm-data/CHANGELOG.md, fdm-data/package.json
Added 0.17.1 changelog noting median replacement for unknown yield/HI/N values; version bumped to 0.17.1.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant F as determineManureAmmoniaEmissionFactor
  participant D as cultivationDetails (b_lu_croprotation)

  C->>F: fertilizerApplication, activeCultivations, cultivationDetails
  F->>D: Inspect active cultivations' rotation values
  Note right of F: Classify land type via sets:<br/>- Grassland: grass, clover<br/>- Cropland: potato, rapeseed, starch, maize, cereal, sugarbeet, catchcrop, alfalfa<br/>- Else: bare soil
  F->>F: Switch on application method
  alt Supported method
    F->>F: Nested switch on land type
    alt Supported land type
      F-->>C: Return Decimal EF
    else Unsupported land type
      F-->>C: Throw Error("Unsupported method for land type")
    end
  else Unknown method
    F-->>C: Throw Error("Unknown application method")
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

branch:main

Suggested reviewers

  • BoraIneviNMI
  • gerardhros

Poem

Little rabbit taps the ground—thump, thump—OK!
Rotations sorted, land types lead the way.
Methods line up, factors fall in row,
Errors hop out when they’re told “no.”
Versions nibble upward, neat and tight—
Fresh greens of logic, crisp and right.
Hippity hop, tests pass tonight.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR includes a data imputation changeset for the fdm-data package and adds performance test fields p_name_nl and p_id, which are unrelated to fixing the manure ammonia emission logic described in issue #286. The unrelated fdm-data imputation change and extraneous performance test fields should be removed or moved to a separate PR to keep this change focused on the emission factor refactor required by issue #286.
✅ 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 succinctly describes the core refactoring of the ammonia emission factor logic while also noting the necessary test updates and performance field additions, and it clearly relates to the changeset without extraneous noise.
Linked Issues Check ✅ Passed The refactored determineManureAmmoniaEmissionFactor now uses explicit rotationEnum mappings to correctly detect cropland, grassland, and bare soil and has been updated to apply proper emission factors, fulfilling all objectives from issue #286.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 05759b7 and b23fdbc.

📒 Files selected for processing (9)
  • .changeset/config.json (1 hunks)
  • fdm-app/CHANGELOG.md (1 hunks)
  • fdm-app/package.json (1 hunks)
  • fdm-calculator/CHANGELOG.md (1 hunks)
  • fdm-calculator/package.json (1 hunks)
  • fdm-core/CHANGELOG.md (1 hunks)
  • fdm-core/package.json (2 hunks)
  • fdm-data/CHANGELOG.md (1 hunks)
  • fdm-data/package.json (1 hunks)

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 and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Oct 1, 2025

Codecov Report

❌ Patch coverage is 81.60920% with 32 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.07%. Comparing base (f39a5e5) to head (05759b7).

Files with missing lines Patch % Lines
...c/balance/nitrogen/emission/ammonia/fertilizers.ts 81.60% 32 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #288      +/-   ##
==========================================
- Coverage   93.26%   93.07%   -0.20%     
==========================================
  Files          81       81              
  Lines       13014    13118     +104     
  Branches     1306     1326      +20     
==========================================
+ Hits        12137    12209      +72     
- Misses        875      907      +32     
  Partials        2        2              
Flag Coverage Δ
fdm-calculator 94.65% <81.60%> (-0.52%) ⬇️
fdm-core 91.92% <ø> (ø)
fdm-data 94.40% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@SvenVw SvenVw changed the base branch from development to main October 1, 2025 08:15
@coderabbitai coderabbitai Bot changed the title @coderabbitai Refactor manure NH3 EF logic; update tests; add perf test fields Oct 1, 2025
@coderabbitai coderabbitai Bot added branch:development Issue only affecting development, not the main branch (yet) bug Something isn't working fdm-calculator fdm-data labels Oct 1, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (1)

20-28: Fix invalid mock data for cropland cultivation.

Line 22 uses b_lu_croprotation: "crop", which is not a valid value according to the schema. Per the PR objectives, valid cropland rotation values are: "potato", "rapeseed", "starch", "maize", "cereal", "sugarbeet", "catchcrop", "alfalfa". This test data should use one of these valid enum values to properly test the corrected land-type detection logic.

Apply this diff to use a valid cropland rotation value:

     mockCultivationDetailsMap.set("cropland-cultivation", {
         b_lu_catalogue: "cropland-cultivation",
-        b_lu_croprotation: "crop",
+        b_lu_croprotation: "maize",
         b_lu_yield: 0,
         b_lu_hi: 0,
         b_lu_n_harvestable: 0,
         b_lu_n_residue: 0,
         b_n_fixation: 0,
     })
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b60662e and e4ce36a.

📒 Files selected for processing (7)
  • .changeset/dark-feet-join.md (1 hunks)
  • .changeset/stale-knives-run.md (1 hunks)
  • .changeset/sweet-ways-itch.md (1 hunks)
  • .changeset/wicked-bikes-march.md (1 hunks)
  • fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (10 hunks)
  • fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts (1 hunks)
  • fdm-calculator/src/balance/nitrogen/performance.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-02-13T08:35:59.306Z
Learnt from: SvenVw
PR: SvenVw/fdm#71
File: fdm-app/app/routes/farm.$b_id_farm.field.$b_id.cultivation.$b_lu.harvest.$b_id_harvesting.tsx:114-124
Timestamp: 2025-02-13T08:35:59.306Z
Learning: The HarvestForm component in fdm-app expects undefined (not 0) for b_lu_yield when no yield information is available, as 0 would incorrectly imply that yield data exists.

Applied to files:

  • .changeset/sweet-ways-itch.md
🧬 Code graph analysis (1)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (1)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts (1)
  • calculateNitrogenEmissionViaAmmoniaByFertilizers (21-135)
🔇 Additional comments (7)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (5)

689-698: Improved error handling for unsupported application methods.

The tests now correctly expect thrown errors for unsupported application methods instead of console warnings. This is a significant improvement in error handling that makes invalid configurations fail fast rather than silently using default values.

Also applies to: 713-722, 737-746


673-674: Confirm updated emission factor for bare soil incorporation.
Both the implementation and tests now use 0.46 (previously 0.22) for bare-soil incorporation—please verify this aligns with your source data or domain requirements.


233-237: ```bash
#!/bin/bash

Locate fertilizers.ts

file=$(fd -e ts 'fertilizers.ts' | head -n1)
echo "Located file: $file"

Verify function implementation

rg -nP 'determineManureAmmoniaEmissionFactor' -C2 "$file"

Check emission factor mappings for bare soil and slotted coulter

rg -nC3 'bare soil' "$file"
rg -nC3 'slotted coulter' "$file"


---

`409-410`: **Emission factors for narrowband and slotted coulter on grassland match the implementation.** Verified that in `fertilizers.ts` both “narrowband” (lines 359–364) and “slotted coulter” (lines 232–237) return `0.17` for grassland.

---

`519-520`: **Emission factor mappings are correct as implemented.** The cases for “slotted coulter” and “shallow injection” return 0.24 for both cropland and bare soil, matching the updated tests.

</blockquote></details>
<details>
<summary>.changeset/wicked-bikes-march.md (1)</summary><blockquote>

`1-5`: **LGTM - Changeset accurately describes the improvement.**

The changeset correctly identifies this as a patch-level improvement where `determineManureAmmoniaEmissionFactor` now guarantees a return value through structured switch-case logic with explicit error handling for unsupported combinations.

</blockquote></details>
<details>
<summary>fdm-calculator/src/balance/nitrogen/performance.test.ts (1)</summary><blockquote>

`134-136`: **LGTM - Added required fields for updated emission calculations.**

The addition of `p_app_method`, `p_name_nl`, and `p_id` fields is necessary to support the refactored emission factor calculation logic. The mock values are appropriate for performance testing.

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4ce36a and 8883d70.

📒 Files selected for processing (1)
  • fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (11 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (2)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts (1)
  • calculateNitrogenEmissionViaAmmoniaByFertilizers (21-135)
fdm-calculator/src/balance/nitrogen/types.d.ts (1)
  • FieldInput (395-415)

@SvenVw SvenVw removed the branch:development Issue only affecting development, not the main branch (yet) label Oct 1, 2025
@SvenVw SvenVw requested a review from gerardhros October 1, 2025 09:58
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8883d70 and 05759b7.

📒 Files selected for processing (3)
  • .changeset/hungry-rice-taste.md (1 hunks)
  • fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (18 hunks)
  • fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.test.ts (2)
fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts (1)
  • calculateNitrogenEmissionViaAmmoniaByFertilizers (21-135)
fdm-calculator/src/balance/nitrogen/types.d.ts (1)
  • FieldInput (395-415)

Comment thread fdm-calculator/src/balance/nitrogen/emission/ammonia/fertilizers.ts
Copy link
Copy Markdown
Collaborator

@gerardhros gerardhros left a comment

Choose a reason for hiding this comment

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

Thanks.

@SvenVw SvenVw merged commit 6ab7750 into main Oct 1, 2025
6 of 7 checks passed
@coderabbitai coderabbitai Bot added the branch:main An issue, affecting the main branch, that requires an hotfix label Oct 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

branch:main An issue, affecting the main branch, that requires an hotfix bug Something isn't working fdm-calculator fdm-data

Projects

None yet

Development

Successfully merging this pull request may close these issues.

determineManureAmmoniaEmissionFactor uses incorrect value for b_lu_croprotation to determine land type

2 participants