Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/stoichiometry for Animals #726

Open
wants to merge 17 commits into
base: develop
Choose a base branch
from

Conversation

TaranRallings
Copy link
Collaborator

Description

This PR contains the transition from a purely carbon mass system to a carbon, nitrogen, phosphorus (cnp) system.

Key Changes:

  • the cnp mass dictionary is now the core mass used in most methods
  • mass_current (total mass) is now a property, as is reproductive_mass, as the total values are sometimes needed
  • a 'grow' method has been implemented in AnimalCohort to ensure stoichiometric ratios are adhered to
  • a lot of tests were reworked and expanded.

Fixes # (issue)

Type of change

  • New feature (non-breaking change which adds functionality)
  • Optimization (back-end change that speeds up the code)
  • Bug fix (non-breaking change which fixes an issue)

Key checklist

  • Make sure you've run the pre-commit checks: $ pre-commit run -a
  • All tests pass: $ poetry run pytest

Further checks

  • Code is commented, particularly in hard-to-understand areas
  • Tests added that prove fix is effective or that feature works
  • Relevant documentation reviewed and updated

@codecov-commenter
Copy link

codecov-commenter commented Feb 5, 2025

Codecov Report

Attention: Patch coverage is 92.13483% with 21 lines in your changes missing coverage. Please review.

Project coverage is 94.40%. Comparing base (39f2f88) to head (241c5a0).

Files with missing lines Patch % Lines
virtual_ecosystem/models/animal/animal_cohorts.py 92.20% 12 Missing ⚠️
virtual_ecosystem/models/animal/decay.py 91.89% 6 Missing ⚠️
virtual_ecosystem/models/animal/plant_resources.py 88.88% 2 Missing ⚠️
virtual_ecosystem/models/animal/animal_model.py 94.44% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #726      +/-   ##
===========================================
- Coverage    94.70%   94.40%   -0.30%     
===========================================
  Files           73       73              
  Lines         4946     5059     +113     
===========================================
+ Hits          4684     4776      +92     
- Misses         262      283      +21     

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

Copy link
Collaborator

@jacobcook1995 jacobcook1995 left a comment

Choose a reason for hiding this comment

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

I've looked at the exchanges with the litter/soil model and I am happy that information will still get passed into my models in the format I want it in. I'm not approving as I don't feel well placed to give feedback on the overall structure/approach.

I had one specific comment which directly contradicts what I told you on teams earlier, sorry!

self.leaf_waste_pools[cell_id].mass_cnp["carbon"]
/ self.leaf_waste_pools[cell_id].mass_cnp["phosphorus"]
if self.leaf_waste_pools[cell_id].mass_cnp["phosphorus"] > 0
else 0.0
Copy link
Collaborator

Choose a reason for hiding this comment

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

Sorry despite what I said earlier using 0.0 here doesn't really work, but obviously using inf for the divide by zero case would break the downstream calculations. Not 100% sure what the best approach is here, I guess this is a value that you should never expect, so maybe we just accept this as a weird edge case?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Okay actually think you want to add the following between the if and the else

elif self.leaf_waste_pools[cell_id].mass_cnp["carbon"] > 0 np.inf```

Copy link
Collaborator

Choose a reason for hiding this comment

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

(the above might not be valid, but you get the idea)

This means that if there is a carbon flow with no associated nitrogen/phosphorus an infinite value gets returned (which then raises an error downstream). And this makes sense because biological matter always contains N and P.

But this handles the "there's no phosphorus because there's no organic matter at all" case gracefully

efficiency = detritivore.functional_group.mechanical_efficiency
actual_consumed_mass = actually_available_mass * efficiency

# Avoid division by zero in nutrient fractions calculation
Copy link
Collaborator

Choose a reason for hiding this comment

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

You actually take a step to avoid division errors here, is there a reason not to do this in the plant waste products case above?

Copy link
Collaborator

@dalonsoa dalonsoa left a comment

Choose a reason for hiding this comment

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

I have not gone into the detail of the code, but don't have much time today and wanted to give you some early feedback. This very much calls for a dedicated class in which to put together all the cnp related manipulations. Something like the following will also facilitate manipulation and type checks:

@dataclass 
class CNP:
    carbon: float
    nitrogen: float
    phosphorus: float

    @property
    def total(self) -> float:
        return self.carbon + self.nitrogen + self.phosphorus

    def __getitem__(self, key):
        """In case you want dictionary-style access."""
        return getattr(self, key)

Or, conversely, you can make it inherit from dict and add properties, as needed:

class CNP(dict):

    @property
    def carbon(self) -> float:
        return self["carbon"]

    @property
    def nitrogen(self) -> float:
        return self["nitrogen"]

    @property
    def phosphorus(self) -> float:
        return self["phosphorus"]

    @property
    def total(self) -> float:
        return sum(self.values())

Given that CNP is something that seems to have some entity as a group, I think it deserves to be treated as such in the code, also facilitating its documentation.

@TaranRallings
Copy link
Collaborator Author

This very much calls for a dedicated class in which to put together all the cnp related manipulations.

@dalonsoa This is a really good idea and I'm annoyed that I didn't think of it! I'll make the adjustments.

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.

4 participants