CarlyneB's picture
[DOCS/FIX] First draft of Objective No. 5: TO FACILITATE MAINTENANCE AND UPDATES FOR CG STAFF. (No more hard-coded settings, libraries updated, instructions added to the README)
fa58ff0
|
Raw History Blame
25.3 kB
metadata
title: Carbon Dioxide Removal Toolkit
emoji: 🌍
colorFrom: green
colorTo: blue
sdk: streamlit
sdk_version: 1.58.0
app_file: app.py
pinned: false

Carbon Dioxide Removal Optimizer

A Streamlit app for optimizing carbon removal portfolios across different methods and constraints.


Data Maintenance Guide

This guide is for Carbon Gap staff who need to update the tool's data — no coding experience required for most tasks.


How it works (overview)

All the data the tool uses (CDR methods, resources, coefficients) comes from a single file:

data/inputs_aggregated.csv

Every time the app starts, it computes a fingerprint (hash) of the CSV and compares it to the last known value. If they differ — meaning the CSV has been modified — it regenerates all data files automatically before loading. You do not need to run anything manually.

There are two ways to update the data, depending on whether you are working directly on Hugging Face or on a local copy of the project.


Option 1 — Edit directly on Hugging Face (no local setup needed)

This is the simplest option for non-coders with admin access to the Hugging Face Space.

Steps:

  1. Go to the Hugging Face Space → click the Files tab
  2. Open data/inputs_aggregated.csv and click Edit (pencil icon), or upload a new version of the file
  3. Commit the change directly on Hugging Face — the Space will restart automatically
  4. Check the logs to confirm the update ran:
    • In the Space, click ⋮ (three dots) → Logs
    • You should see:
      inputs_aggregated.csv has changed — running data/update.py ...
      [... update details ...]
      Data files updated successfully.
      
  5. If the logs show this message, the app is running with the new data. If not, something went wrong — contact the developer.

Note: with this option, only inputs_aggregated.csv needs to be uploaded. The app handles the rest automatically on restart.


Option 2 — Work locally and push (recommended for larger changes)

Use this option when making bigger changes (new methods, new resources, reordering) where you want to preview the result before publishing.

Step 1 — Get the project on your machine

If you do not already have it:

  • Install GitHub Desktop (free, no command line needed)
  • Open GitHub Desktop → File → Clone repository → enter the repository URL → choose a local folder → click Clone

Step 2 — Edit the CSV

Open data/inputs_aggregated.csv in Excel or any spreadsheet editor. Make your changes and save.

Step 3 — Open a terminal in the project folder

  • Mac: right-click the project folder → New Terminal at Folder
  • Windows: open the folder, click in the address bar, type cmd, press Enter

Activate the Python environment:

source venv/bin/activate    # Mac / Linux
venv\Scripts\activate       # Windows

Step 4 — Run the update script

python data/update.py

This regenerates all data files and updates the internal fingerprint. Check the output — it should end with All files updated successfully.

Step 5 — Commit and push

In GitHub Desktop:

  • You will see all modified files listed on the left
  • Write a short description in the Summary field (e.g. "Update coefficients for Afforestation")
  • Click Commit to main
  • Click Push origin

Hugging Face will detect the push and rebuild the Space automatically.


Quick reference — where is each parameter?

I want to change… File Where exactly
A coefficient value (min / median / max) data/inputs_aggregated.csv Columns min, median, max — find the row by Implementation + Resource
The name of a CDR method data/inputs_aggregated.csv Column Implementation — use Find & Replace
Which group a CDR method belongs to data/inputs_aggregated.csv Column Method group
The name of a resource data/inputs_aggregated.csv Column Resource — use Find & Replace
Which group a resource belongs to data/inputs_aggregated.csv Column Resource group
The unit of a resource group data/inputs_aggregated.csv Column Unit — must be consistent across all rows for that group
Whether a resource is optional for a method data/inputs_aggregated.csv Column Is secondary — TRUE = optional, FALSE = always active
The display order of methods or resources data/inputs_aggregated.csv Row order — move rows up/down
The app's colours config/config.py CRRA_COLORS dictionary
The app's font config/config.py CRRA_FONT variable
The tooltip text on a method name data/tooltips.xlsx Sheet Methods — column Tooltip
The tooltip text on a resource name data/tooltips.xlsx Sheet Resources — column Tooltip
UI spacing, font sizes, button styles assets/styles.css Standard CSS — search for the element name
Python library versions requirements.txt One line per library — see Library Maintenance Guide below

After any change to inputs_aggregated.csv, run python data/update.py. After changes to config/config.py or assets/styles.css, simply restart the app.


Before you start

Open a terminal in the project folder. On Mac: right-click the folder → "New Terminal at Folder". On Windows: open the folder, then type cmd in the address bar.

Activate the Python environment (only needed once per session):

  • Mac / Linux: source venv/bin/activate
  • Windows: venv\Scripts\activate

You should now see (venv) at the start of your terminal line.


File structure (what each file does)

File What it is Do you edit it?
data/inputs_aggregated.csv Main data file — all methods, resources and coefficients ✅ Yes
data/update.py Script that regenerates everything from the CSV ❌ No
data/cost_sliders.json Auto-generated — coefficients used by the app ❌ No (auto)
data/method_groups.json Auto-generated — CDR method categories ❌ No (auto)
data/secondary_resources.json Auto-generated — optional resource assignments ❌ No (auto)
data/inputs_template.xlsx Auto-generated — Excel template for users ❌ No (auto)
data/resource_template.xlsx Auto-generated — Excel template for resources ❌ No (auto)
data/tooltips.xlsx Tooltip texts shown on hover in the app ✅ Yes — edit directly

⚠️ Never edit the auto-generated files directly — your changes will be overwritten the next time update.py is run.


Understanding inputs_aggregated.csv

Each row represents one resource used by one CDR method, with the following columns:

Column Description Example
Implementation Name of the CDR method Afforestation
Method group Category the method belongs to Forestry
Resource Name of the resource used Unspecified land
Resource group Category the resource belongs to Land
Type Physical type of the resource Physical
Unit Unit of the coefficient (per MtCO₂) Mha/MtCO2
min Minimum coefficient value 0.002
median Default (median) coefficient value 0.094927
max Maximum coefficient value 0.384615
Is secondary Whether this resource is optional for this method FALSE

Primary resources (Is secondary = FALSE) are always active in the model. Secondary resources (Is secondary = TRUE) are optional — users can toggle them on in the app.


Case 1 — Modify existing coefficient values

When to use: The literature has been updated and you want to change the min/median/max values for an existing method-resource pair.

Steps:

  1. Open data/inputs_aggregated.csv in Excel or a text editor.
  2. Find the row with the correct Implementation and Resource.
  3. Edit the min, median, and/or max columns.
  4. Save the file.
  5. In the terminal, run:
    python data/update.py
    

Case 2 — Add a new resource to an existing method

When to use: A CDR method now uses a resource that wasn't tracked before (e.g., adding water consumption to Afforestation).

Steps:

  1. Open data/inputs_aggregated.csv.

  2. Add a new row at the end (or anywhere in the file — order of rows determines display order in the app):

    Column What to enter
    Implementation Exact name of the existing method (copy it from another row to avoid typos)
    Method group Same group as the other rows for that method
    Resource Name of the resource (must match an existing resource exactly, or see Case 4 to add a new one)
    Resource group Same group as the other rows for that resource
    Type Physical or Energy
    Unit Must match the unit already used for that resource (e.g., Mha/MtCO2)
    min Minimum coefficient
    median Median coefficient
    max Maximum coefficient
    Is secondary TRUE if optional, FALSE if always required
  3. Save the file.

  4. Run python data/update.py.


Case 3 — Add a new CDR method

When to use: A new carbon removal approach needs to be added to the tool.

Steps:

  1. Open data/inputs_aggregated.csv.

  2. Add one row per resource used by the new method. For example, if your new method uses land and water, add 2 rows.

    For each row, fill in all columns. Use an existing Method group (e.g., Forestry) or create a new one (the name you write here becomes the category name in the app).

  3. Save the file.

  4. Run python data/update.py.

Note on display order: The new method will appear in the app in the same position it appears in the CSV. If you want it between two existing methods, insert the rows between those methods' rows.

⚠️ Special case — derived methods: see Case 3b below.


Case 3b — Add a derived CDR method (variant of an existing method)

What is a derived method? Some methods in the tool are not standalone entries in the CSV — they are automatically generated as variants of a base method. For example:

  • Bio-char in the CSV → generates 3 variants in the app: Bio-char - Forest biomass, Bio-char - Non-forest biomass, Bio-char - Unspecified biomass
  • Enhanced weathering in the CSV → generates 4 variants: one per mineral type

Each variant is identical to the base method except it only keeps the resource relevant to that variant (e.g. Bio-char - Forest biomass removes the non-forest and unspecified biomass resources).

When to use: You want to add a new variant of an existing method (e.g. a new mineral type for Enhanced weathering, or a new biomass type for Bio-char).

Steps:

  1. Open data/inputs_aggregated.csv and make sure the base method has a row for the new resource (e.g. add a row for Enhanced weathering with the new mineral).

  2. Open data/generate_model_data.py. Find the two structures at the top of the file:

    REPLACED_BY_DERIVED — lists base methods that are fully replaced by their variants (the base name disappears from the app):

    REPLACED_BY_DERIVED = {"Bio-char", "Enhanced weathering"}
    

    If your new base method should disappear from the app once variants exist, add its name here.

    DERIVED_FROM — maps each base method to its list of variant names (in display order):

    DERIVED_FROM = {
        "Bio-char": ["Bio-char - Forest biomass", ...],
        "Enhanced weathering": ["Enhanced weathering - Basalt mineral", ...],
        ...
    }
    

    Add the new variant name to the relevant list here.

  3. Further down in create_sliders_inputs(), add the derivation logic for your new variant — copy the pattern already used for Bio-char or Enhanced weathering: copy the base method's coefficients, then remove the resources that don't apply to this variant.

  4. Save generate_model_data.py and run:

    python data/update.py
    

⚠️ This case requires editing Python code. If you are not comfortable with this, contact the developer — provide the name of the new variant and which resource it should keep, and they can add the 5–10 lines needed.


Case 4 — Add a new resource

When to use: A resource that doesn't exist yet needs to be tracked (e.g., a new type of mineral or energy).

Steps:

  1. Decide which Resource group the new resource belongs to (e.g., Minerals, Energy, Land). If it belongs to an existing group, use the exact same group name. If it needs its own group, invent a new name.

  2. Open data/inputs_aggregated.csv and add one row per method that uses this resource (same as Case 2).

  3. Check the unit: the unit for all resources in a group must be the same (e.g., all Land resources use Mha/MtCO2). If your new resource has a different unit, it needs its own Resource group.

  4. Save the file and run python data/update.py.


Case 5 — Add a new resource group (new category)

When to use: Your new resource doesn't fit any existing category.

Steps:

Same as Case 4, but in the Resource group column, write a new group name that has never been used before. The app will automatically create a new section for it in the Resource Inputs tab.

The new group will appear in the app in the position of its first row in the CSV. Move the rows up or down to control where it appears.


Case 6 — Change whether a resource is optional (secondary) for a method

When to use: You want to make a resource optional (user can enable/disable it) or make it always required.

Steps:

  1. Open data/inputs_aggregated.csv.
  2. Find the row with the correct Implementation and Resource.
  3. Change the Is secondary column to TRUE (optional) or FALSE (always active).
  4. Save and run python data/update.py.

Case 7 — Rename a method or resource

When to use: Correcting a spelling mistake or updating nomenclature.

Steps:

  1. Open data/inputs_aggregated.csv.
  2. Use Find & Replace (Ctrl+H / Cmd+H) to replace the old name with the new name everywhere in the file. Make sure to replace it in both the Implementation column (for methods) or Resource column (for resources), and also in the Method group / Resource group columns if the group name changed.
  3. Save and run python data/update.py.

⚠️ If users have saved scenario files (.xlsx or .zip) that reference the old name, those files will no longer load correctly after the rename.


Case 8 — Edit tooltip texts (hover descriptions)

When to use: You want to add, update, or remove the short description that appears when a user hovers over a resource or method name in the app.

Steps:

  1. Open data/tooltips.xlsx.
  2. Go to the relevant sheet:
    • Resources — for the hover text on resource names (Tab 1 "Resource Inputs")
    • Methods — for the hover text on method names (Tab 2 "Method Constraints")
  3. Find the row with the name you want to edit. All resource and method names are already listed — you only need to fill in or change the Tooltip column.
  4. To add a tooltip: type the text in the Tooltip cell for that row.
  5. To remove a tooltip: leave the Tooltip cell empty.
  6. Save the file.
  7. Restart the app (no need to run update.py).

⚠️ The name in column Resource or Method must match exactly the name used in inputs_aggregated.csv (same spelling, same capitalisation). If you rename a method or resource in the CSV, remember to update the name in tooltips.xlsx too.


Case 10 — Change the display order of methods or resources

When to use: You want a method or resource group to appear earlier or later in the app.

Steps:

  1. Open data/inputs_aggregated.csv.
  2. Move the relevant rows up or down. The app displays methods and resource groups in the same order as they appear in the CSV.
  3. Save and run python data/update.py.

After any change — checklist

Option 1 (Hugging Face direct):

  • Edited and committed inputs_aggregated.csv on Hugging Face
  • Checked the Space logs — confirmed Data files updated successfully.
  • Verified the change appears correctly in the app

Option 2 (local):

  • Saved inputs_aggregated.csv
  • Ran python data/update.py with no errors
  • Committed all modified files (CSV, JSON files, templates) and pushed
  • Verified the change appears correctly in the app after the Space rebuilt

Common mistakes

Mistake What happens Fix
Typo in Method group or Resource group A new accidental group is created in the app Fix the typo and re-run update.py
Wrong unit (e.g., MWh/MtCO2 instead of Mha/MtCO2) The resource appears in the wrong group or breaks the unit display Correct the Unit column
Edited a JSON file directly Changes are overwritten next time update.py runs Always edit the CSV, never the JSON
Forgot to run update.py The app still shows the old data Run python data/update.py
min value equals max value The model automatically halves the min to create a range Intentional for fixed-value resources like Geologic storage — leave as is

Library Maintenance Guide

This section explains how to keep the tool's software dependencies up to date — safely and without breaking anything.


What is a library (dependency)?

The tool is built on top of external software packages ("libraries") that handle things like displaying the interface, reading Excel files, or running the optimization. These libraries are listed in requirements.txt with their exact version numbers (e.g., streamlit==1.45.1).

Libraries sometimes release updates — fixing bugs, patching security holes, or adding new features. The risk is that an update can also change how a library behaves and break the tool.


The key libraries and what they do

These are the libraries that matter most for this tool:

Library Role Risk if updated
streamlit Powers the entire web interface (tabs, sliders, buttons, charts) — currently 1.58.0 🔴 High — UI layout and widget behavior can change
streamlit-option-menu The navigation sidebar menu 🟡 Medium — must stay compatible with streamlit version
pandas Reads and processes CSV and Excel files 🟡 Medium — occasional API changes
numpy Numerical operations (arrays, math) 🟡 Medium — used by scipy and pandas
scipy Runs the LP optimization (linprog) 🟡 Medium — optimization results could change
plotly All charts and interactive graphs 🟡 Medium — chart API evolves
openpyxl Reads and writes Excel files (.xlsx) 🟢 Low — stable API
pillow Image handling (indirect use) 🟢 Low
requests / urllib3 / certifi Network and security 🟢 Low — update freely for security patches

Dependency chain (what depends on what)

Some libraries require specific versions of others to work. Updating one can force updates to others:

streamlit ──────────────► tornado (web server)
            ├───────────► altair (charts)
            ├───────────► pyarrow (data performance)
            ├───────────► narwhals (data compatibility)
            ├───────────► protobuf
            └───────────► cachetools, blinker, click, toml

pandas ─────────────────► numpy
        ├───────────────► pyarrow
        └───────────────► python-dateutil, pytz, tzdata

scipy ──────────────────► numpy

plotly ─────────────────► narwhals

openpyxl ──────────────► pillow

Practical implication: if you update streamlit, you may also need to update tornado, altair, pyarrow, etc. If you update pandas, you may need to update numpy. These cascading updates are handled automatically by pip (see below), but they can introduce unexpected changes.


When to update

✅ Update immediately

  • Security vulnerabilities in requests, urllib3, certifi, or pillow — these are reported publicly and should be patched fast.
  • Check https://pypi.org/project/[library-name] or subscribe to GitHub security alerts.

✅ Update when needed

  • Streamlit — when a new feature in the app requires it, or when a critical bug in the current version is causing problems.
  • pandas / numpy / scipy — when a bug in the current version is causing incorrect data processing or optimization results.
  • openpyxl — when Excel import/export breaks with newer .xlsx files.

❌ Do NOT update just because a newer version exists

  • "Latest is always better" is not true for production tools. An update that works fine in isolation can break interactions between libraries.
  • The tool has been tested with the versions in requirements.txt. Changing them without testing is risky.

How to safely update a library

Never update all libraries at once. Update one at a time, test the tool after each one.

Step 1 — Back up the current working state

cp requirements.txt requirements.txt.backup

Step 2 — Simulate first (dry run)

Before applying anything, check whether the update would cause conflicts:

pip install --upgrade streamlit --dry-run

If pip reports conflicts, investigate before proceeding.

Step 3 — Update the library

pip install --upgrade streamlit

Or to a specific version:

pip install streamlit==1.58.0

Step 4 — Verify no dependencies are broken

pip check

This confirms that all installed packages are mutually compatible. If it reports any conflict, do not proceed to the next step — restore the backup instead (see Step 6).

Step 5 — Freeze the new versions to requirements.txt

pip freeze > requirements.txt

Step 6 — Test the tool

  • Start the app: streamlit run app.py
  • Go through every tab
  • Import and export an Excel file
  • Run an optimization
  • Check that charts display correctly

Step 7 — If something breaks

Restore the backup:

pip install -r requirements.txt.backup
cp requirements.txt.backup requirements.txt

How to install all libraries on a new machine

python -m venv venv
source venv/bin/activate        # Mac/Linux
# or: venv\Scripts\activate     # Windows
pip install -r requirements.txt

Checking for outdated libraries

To see which installed libraries have newer versions available:

pip list --outdated

This shows a list with current and latest versions. Use this to identify what could be updated — but don't update everything at once.


Checking for known security vulnerabilities

Install the security scanner:

pip install pip-audit

Run it:

pip-audit

This will flag any library with a known security issue and suggest a fix. These should be addressed promptly.

Recommended frequency: run pip-audit at least once a year, even if the tool appears stable. Security vulnerabilities are discovered independently of whether the library has changed — a version that was safe last year may be flagged today.


Using an AI assistant to handle updates

Library updates sometimes require code changes alongside the pip update — for example, a deprecated function that was renamed, or a new argument that became required. Doing this manually requires reading changelogs, finding every affected line, and testing the result.

An AI coding assistant such as Claude Code (available at claude.ai/code) can handle this end-to-end:

  • Run pip-audit or pip list --outdated and paste the output into Claude Code
  • Describe the update you want to make (e.g., "update pandas and fix any deprecation warnings")
  • Claude Code will update the library, search the codebase for affected code, apply the necessary fixes, and update requirements.txt

This is especially useful when:

  • A deprecation warning points to a function that is used in multiple places across the codebase
  • A major version bump changes how a library behaves (e.g., pandas 3.x changing its default string backend)
  • You are not comfortable navigating the code yourself

The AI handles the mechanical parts; you remain responsible for testing the result with streamlit run app.py before committing and pushing.


Summary: update strategy

Security fix needed?  ──► Update immediately (requests, urllib3, certifi, pillow)
Something is broken?  ──► Update only the relevant library, test thoroughly
Nothing is broken?    ──► Do not update