From af7b2234086cc155368d10d0128b3534d8da6fb5 Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:33:28 +0000 Subject: [PATCH 1/3] Compare the extracted costs with Berkeley Lab's PJM cost data python -m src.extract --validate looked for hand-read costs in the Queued Up spreadsheet, which has none, so it never compared anything. It now sets each extracted cost per kW beside the one in Berkeley Lab's PJM cost data (January 2023), with the difference, the megawatts each side divided by, and the study Berkeley Lab read. The file is pinned by address and SHA-256 like the workbook, downloaded into data/raw/costs/ the first time, and never committed. The command calls no model. The file covers 13 of the 25 default projects and AF1-236, and for all 14 the downloaded report is the study Berkeley Lab read. Run on a scratch panel holding the cost read by hand from AF1-236's report, it printed $391.35 per kW beside Berkeley Lab's $418.46, both over 1,210 MW. --- README.md | 7 ++- docs/decisions.md | 25 ++++++++ docs/future_work.md | 7 +-- src/config.py | 12 ++++ src/extract.py | 116 +++++++++++++++++++++++--------------- src/fetch_queue.py | 51 +++++++++++++---- tests/test_extract.py | 60 +++++++++++++------- tests/test_fetch_queue.py | 13 ++++- 8 files changed, 209 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index 66ef326..2a9b5d1 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,8 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed `make eval DRY_RUN=false` puts six questions to the real agent. It prints each answer, the result of each check, and the tokens and cost. The checks test, for example, that the agent used the right tool, stated the right count, and didn't present one line of a report as a project's total. Four checks compare answers with the extracted costs. Until there are costs to compare with, the evaluation skips these checks and says so, rather than passing them. One of them is about AF1-236, whose report isn't in the default sample, so it stays skipped until you add that report and extract its costs (see the Quickstart). The wind question's check follows the panel too: until a wind project's extracted cost is above $300 per kW, it expects the answer to say there is none. I haven't run the evaluation yet, because it needs the paid steps first. +`python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's [PJM cost data](https://emp.lbl.gov/interconnection_costs), which its researchers read by hand from PJM's studies. It calls no model. The first time, it downloads Berkeley Lab's file and checks that it's the expected copy. The file covers 13 of the 25 default projects, and AF1-236. For each one, it prints the two costs, the difference, the megawatts each was divided by, and the study Berkeley Lab read. The two costs are defined differently (see [Limitations](#limitations)), so they can differ even when both are read correctly. For AF1-236, the cost I read from its report by hand comes to $391.35 per kW, and Berkeley Lab's to $418.46 ([more](docs/decisions.md#checking-the-extracted-costs-against-berkeley-labs)). + ## Limitations - **Study costs are preliminary estimates, not final bills.** They are the grid operator's estimates at the time of the study, and a later study can change them. @@ -120,7 +122,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed - **`make fetch` only looks for reports of projects in the AG1 window or an earlier one, and the default sample is narrow.** See [What the data holds now](#what-the-data-holds-now). - **The paid steps haven't run yet.** Embedding the reports, extracting their costs, asking the agent questions and the evaluation all call OpenAI's paid models, and I haven't run any of them. The agent and the extraction use `gpt-6-luna` ([why](docs/decisions.md#the-models-gpt-6-luna-with-reasoning-off)), and no request has gone to it yet. So I haven't confirmed that OpenAI accepts the settings the code sends, or that the costs the code reports match OpenAI's bill. Nor have I measured how accurately the model extracts costs, how well the agent answers, or what either costs. The offline tests use a stand-in for OpenAI, so they check what the code sends, not what OpenAI does with it. - **The model can misread a report.** It can miss or misread a figure, and its output can vary between runs, so check any cost that matters against its report. -- **My cost per kW is defined differently from Berkeley Lab's.** Berkeley Lab counts every cost except attachment facilities as network cost, divides by the plant's nameplate capacity (its rated maximum output) and converts to 2022 dollars. I use the report's own network upgrade total, or if it gives none, its total minus the cost of the physical connection. Either can leave out connection work that Berkeley Lab counts. I divide by the megawatts the study assessed, or by the panel's capacity if it gives none, and don't adjust for inflation. +- **My cost per kW is defined differently from Berkeley Lab's.** Berkeley Lab counts every cost except attachment facilities as network cost, divides by the plant's nameplate capacity (its rated maximum output) and converts to 2022 dollars. I use the report's own network upgrade total, or if it gives none, its total minus the cost of the physical connection. Either can leave out connection work that Berkeley Lab counts. I divide by the megawatts the study assessed, or by the panel's capacity if it gives none, and don't adjust for inflation. `--validate` shows both costs for each project Berkeley Lab covers. - **Two background findings in the agent's instructions don't match Berkeley Lab's PJM study.** One says cost is "the dominant driver" of withdrawal, where the study says high costs are "likely a key driver". The other says network upgrades are about 70% of recently withdrawn projects' costs, where the study's figure is 94%. - **Withdrawal risk is reasoning, not prediction.** The agent weighs a project's costs against research findings and describes the risk. It is told never to say a project will certainly withdraw. It isn't a statistical model trained on past withdrawals. @@ -129,7 +131,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed ``` src/ config.py every setting, path, model name and price - fetch_queue.py downloads Berkeley Lab's queue spreadsheet + fetch_queue.py downloads Berkeley Lab's queue spreadsheet and PJM cost data ingest_queue.py builds the panel, and runs the agent's SQL safely fetch_pdfs.py downloads PJM's study reports ingest_pdfs.py splits the reports into passages and embeds them @@ -155,6 +157,7 @@ Python 3.11 to 3.14, LangChain and LangGraph for the agent, and OpenAI's models: | Data | What I use it for | Licence and terms | |---|---|---| | [Berkeley Lab, Queued Up: 2026 Edition](https://emp.lbl.gov/publications/queued-2026-edition-characteristics) ([data file](https://eta-publications.lbl.gov/sites/default/files/2026-05/lbnl_ix_queue_data_file_thru2025.xlsx)) | The panel, and the national figures on completion and withdrawal | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), credited to Lawrence Berkeley National Laboratory and GridTracker. `make data` downloads it, and Git ignores it. | +| [Berkeley Lab, PJM interconnection cost data](https://emp.lbl.gov/interconnection_costs) ([data file](https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx)), by Seel and others, with Exeter Associates (January 2023) | The costs `--validate` compares with: network costs read by hand from PJM's studies of 1,127 projects | It states no open licence. Its copyright notice only covers the US government's right to publish it. `--validate` downloads it for your own use, and Git ignores it. | | PJM study reports, such as [AC2-093's](https://www.pjm.com/pjmfiles/pub/planning/project-queues/impact_studies/ac2093_imp.pdf) | The passages the agent reads, and the costs | © PJM Interconnection, all rights reserved. `make fetch` downloads them for your own use, and Git ignores them. | | PJM's live queue, through [gridstatus](https://github.com/gridstatus/gridstatus) (optional) | An alternative to Berkeley Lab's data | PJM's terms apply (see its [legal page](https://www.pjm.com/about-pjm/legal.aspx)). The data stays on your computer. | diff --git a/docs/decisions.md b/docs/decisions.md index 5c434cb..a79c7a2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -178,6 +178,31 @@ The model names and prices live in `src/config.py`. - If PJM publishes later windows' reports at these addresses, `pdf_last_window` has to be moved on by hand. - A passing error, such as a request to slow down, stops the fetch too. Running it again carries on, skipping the reports already downloaded. +## Checking the extracted costs against Berkeley Lab's + +**Decision.** `python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's PJM cost data, which its researchers read by hand from PJM's studies of 1,127 projects. For each project in both, it prints the two costs, the difference, the megawatts each was divided by, and the study Berkeley Lab read. Like the Queued Up spreadsheet, the file is pinned by its address and SHA-256 checksum in `src/config.py` (`lbnl_costs_url` and `lbnl_costs_sha256`). It is downloaded into `data/raw/costs/` the first time it's needed. The command calls no model. + +**Why.** +- **An independent check on more projects.** The file covers 13 of the 25 default projects, and AF1-236. I read three reports by hand. +- **The same studies.** For all 14, the report `make fetch` or `--ids` downloads is the study Berkeley Lab read: the same type and the same month. So a gap comes from the definitions or from a misread, not from comparing different studies. +- **The megawatts matter as much as the dollars.** AF1-236's report gives 1,210 MW of output, of which PJM counts 459.8 MW as capacity, and Berkeley Lab divides by the 1,210. Divided by 459.8 MW, the same cost would be $1,029.86 per kW. Showing the megawatts each side used makes a gap like this easy to trace. + +**Alternatives.** +- **Only the three projects I read by hand** (AC2-093, AF1-236 and AF2-353). That check stays, but three projects that I chose say little about the rest. +- **Converting both costs to one definition first,** for example mine to 2022 dollars. It would hide where the two differ, and it needs figures the extraction doesn't collect, such as each study's date. Settling the definition is [future work](future_work.md). +- **The Queued Up spreadsheet.** It holds no costs. +- **Committing the file.** It states no open licence, so, like PJM's reports, it is downloaded for local use and kept out of Git. + +**Evidence.** +- On 30 November 2026 I ran `--validate` on a copy of the panel holding only the cost I read by hand from AF1-236's report. It downloaded the file, matched its checksum, and printed $391.35 per kW beside Berkeley Lab's $418.46, both divided by 1,210 MW. +- I set the first page of each of the 14 reports beside the study type and date Berkeley Lab gives. Seven of the default projects' reports are system impact studies, and six combine a feasibility study with a system impact study, which Berkeley Lab lists as system impact. AF1-236's is a system impact study. +- Tests check that only projects in both are compared, that the file's own sheet and column names are read, that nothing is downloaded when there are no extracted costs, that a failed download is reported, and that a file with another checksum is refused. + +**Trade-offs.** +- A gap isn't by itself a mistake, because the definitions differ. The output says so. +- The file only covers projects that applied by 31 March 2021, with studies up to September 2022, so it can't check later projects. +- If Berkeley Lab replaces the file, the address and checksum have to be updated by hand. + ## The chat page **Decision.** Alongside the terminal chat, the agent has a chat page in the browser, started with `make app`. diff --git a/docs/future_work.md b/docs/future_work.md index 7d87390..8df086a 100644 --- a/docs/future_work.md +++ b/docs/future_work.md @@ -4,15 +4,14 @@ Changes I plan or propose, starting with the most urgent. ## Next -- **Run the paid steps.** Embed the reports, extract their costs and run the evaluation. Then add the reports of AC2-093, AF1-236 and AF2-353, which aren't in the default sample, and check their extracted costs against the figures I read from them by hand. This needs OpenAI credits. +- **Run the paid steps.** Embed the reports, extract their costs and run the evaluation. Then add the reports of AC2-093, AF1-236 and AF2-353, which aren't in the default sample, check their extracted costs against the figures I read from them by hand, and compare the 14 projects that Berkeley Lab covers with its costs (`python -m src.extract --validate`). This needs OpenAI credits. - **Correct the agent's instructions.** Two of its background findings don't match Berkeley Lab's PJM study (see the README's limitations), so I'll correct them and give each finding its source. I'll also remove the instruction to treat a quoted cost as an upper bound, which no cited source supports. ## Method - **Choose a more varied sample of reports.** Of the default 25, 22 applied on the same day, and 12 are 5 MW or smaller. A better rule could set a minimum size, prefer system impact studies and spread the choice across queue windows. -- **Compare the extracted costs with Berkeley Lab's.** Its [PJM cost data](https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx) has costs read by hand for 1,127 projects, including AF1-236 and 13 of the default 25. `python -m src.extract --validate` looks for these costs in the Queued Up spreadsheet, which doesn't have them, so it never compares anything. -- **Settle the cost definition.** Either match Berkeley Lab's (every cost except attachment facilities, divided by nameplate capacity, in 2022 dollars) or keep mine and show the difference. -- **Check which megawatts the extraction copies.** AC2-093's report gives 675 MW of output, of which PJM counts 429.4 MW as capacity. Its cost per kW depends on which one the model takes. +- **Settle the cost definition.** Either match Berkeley Lab's (every cost except attachment facilities, divided by nameplate capacity, in 2022 dollars) or keep mine. `--validate` will show how far apart the two are once costs are extracted. +- **Check which megawatts the extraction copies.** AC2-093's report gives 675 MW of output, of which PJM counts 429.4 MW as capacity. Its cost per kW depends on which one the model takes. `--validate` shows the megawatts used beside Berkeley Lab's. - **Compare PDF readers.** On my laptop, PyMuPDF took about 140 seconds to read AG1-321's 65-page report with its tables added in Markdown, a simple text format, and gave 365,148 characters. Without the Markdown tables it took under half a second and gave 133,495. I haven't measured whether the tables help the extraction. - **Move off `langchain-community`,** which provides the PDF readers and is [no longer actively maintained](https://github.com/langchain-ai/langchain-community/issues/674). - **Let `search_studies` search one project's report,** so a question about one project doesn't bring back passages from others. diff --git a/src/config.py b/src/config.py index eec255a..0587717 100644 --- a/src/config.py +++ b/src/config.py @@ -135,6 +135,14 @@ class Settings(BaseSettings): # release needs its own date, and so does a workbook passed with --file (set LBNL_DATA_END). lbnl_data_end: date = date(2025, 12, 31) + # the reference for --validate, Berkeley Lab's PJM cost data (January 2023, + # https://emp.lbl.gov/interconnection_costs), with costs read by hand from PJM's studies of + # 1,127 projects. it states no open licence, so it is downloaded for local use, never committed. + lbnl_costs_url: str = ( + "https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx" + ) + lbnl_costs_sha256: str = "50a363318b18e36418ac1af4f7afb923998c0863d990a73b59816d014c0af245" + # cost caps. dry_run true means no paid call runs until it is flipped on a small sample. max_pdfs: int = 25 dry_run: bool = True @@ -180,6 +188,10 @@ def lbnl_workbook_path(self) -> Path: # named after the file in the url, so a newly pinned release keeps its own name. return self.queue_raw_dir / self.lbnl_workbook_url.rsplit("/", 1)[-1] + @property + def lbnl_costs_path(self) -> Path: + return self.raw_dir / "costs" / self.lbnl_costs_url.rsplit("/", 1)[-1] + @property def pdf_raw_dir(self) -> Path: return self.raw_dir / "pdfs" diff --git a/src/extract.py b/src/extract.py index 2c9c51d..06f4321 100644 --- a/src/extract.py +++ b/src/extract.py @@ -12,6 +12,7 @@ from pathlib import Path import duckdb +import httpx import pandas as pd import tiktoken from langchain_chroma import Chroma @@ -31,13 +32,9 @@ token_cost, usage_cost, ) +from src.fetch_queue import REQUEST_TIMEOUT_SECONDS, fetch_lbnl_costs from src.ingest_pdfs import existing_queue_ids, open_store -from src.ingest_queue import ( - CREATE_STUDY_EXTRACTS_TABLE, - LBNL_HEADER_ROW, - LBNL_SHEET, - query_projects, -) +from src.ingest_queue import CREATE_STUDY_EXTRACTS_TABLE, query_projects # a fixed vocabulary query, not a per project question, so retrieval stays cheap and consistent. RETRIEVAL_QUERY = "network upgrade cost estimate point of interconnection" @@ -75,9 +72,25 @@ # not in tiktoken 0.14. it is the encoding tiktoken gives the gpt-4o, gpt-4.1, gpt-5 and o series. FALLBACK_ENCODING = "o200k_base" -# the current lbnl snapshot carries no hand extracted cost column, so this only matters -# if a future release of the workbook adds one under this name. -LBNL_COST_COLUMN = "ix_cost_per_kw" +# berkeley lab's pjm cost data has one row per project on this sheet. its network cost counts +# every cost but the attachment facilities, in 2022 dollars per kW of nameplate capacity. +LBNL_COSTS_SHEET = "data" +LBNL_COSTS_COLUMNS = { + "Project #": "queue_id", + "Study Type": "study_type", + "Study Date": "study_date", + "Nameplate MW": "nameplate_mw", + "$2022 Network Cost/kW": "network_cost_per_kw", +} + +# each extracted cost beside the megawatts it was divided by, by the rule in compute_cost_per_kw. +VALIDATION_SQL = """ + SELECT projects.queue_id, projects.cost_per_kw, + coalesce(nullif(study_extracts.studied_mw, 0), projects.capacity_mw) AS divided_by_mw + FROM projects LEFT JOIN study_extracts USING (queue_id) + WHERE projects.cost_per_kw IS NOT NULL + ORDER BY projects.queue_id +""" class StudyExtract(BaseModel): @@ -382,50 +395,65 @@ def _run_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: return {"projects": extracted, "input_tokens": usage["input_tokens"], "cost": cost} -def find_lbnl_workbook() -> Path | None: - """The first LBNL workbook in the queue raw directory, or None if there is none.""" - matches = sorted(settings.queue_raw_dir.glob("*.xlsx")) - return matches[0] if matches else None - - -def load_lbnl_reference(path: Path) -> dict[str, float] | None: - """Map queue id to LBNL's hand extracted cost per kw. None if the workbook has no such column.""" - raw = pd.read_excel(path, sheet_name=LBNL_SHEET, header=LBNL_HEADER_ROW, engine="openpyxl") - if LBNL_COST_COLUMN not in raw.columns: - return None - reference = raw[["q_id", LBNL_COST_COLUMN]].dropna() - return dict(zip(reference["q_id"], reference[LBNL_COST_COLUMN])) +def load_lbnl_costs(path: Path) -> dict[str, tuple[float, float, str]]: + """Map queue id to Berkeley Lab's network cost per kW, the nameplate MW it divides by, and the + study it read the cost from, such as "System Impact, August 2021".""" + raw = pd.read_excel( + path, sheet_name=LBNL_COSTS_SHEET, usecols=list(LBNL_COSTS_COLUMNS), engine="openpyxl" + ) + costs = raw.rename(columns=LBNL_COSTS_COLUMNS).dropna(subset=["network_cost_per_kw"]) + return { + str(row.queue_id).strip(): ( + row.network_cost_per_kw, + row.nameplate_mw, + f"{row.study_type}, {row.study_date:%B %Y}", + ) + for row in costs.itertuples() + } def run_validation() -> None: - """Print extracted cost_per_kw next to LBNL's reference figure for every project where both exist.""" - workbook = find_lbnl_workbook() - if workbook is None: - print("no LBNL workbook in data/raw/queue, skipping validation") + """Print each extracted cost per kW beside Berkeley Lab's, for the projects it read by hand. + + Downloads Berkeley Lab's PJM cost data the first time, and makes no call to OpenAI. + """ + extracted = query_projects(VALIDATION_SQL) + if not extracted: + print("no project has an extracted cost yet, so there is nothing to compare") return - reference = load_lbnl_reference(workbook) - if reference is None: - print("LBNL workbook has no hand extracted cost column, skipping validation") + headers = {"User-Agent": settings.pdf_user_agent} + try: + with httpx.Client( + headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True + ) as client: + path = fetch_lbnl_costs(client) + except (httpx.HTTPError, ValueError) as error: + print(f"could not download Berkeley Lab's PJM cost data: {error}") return - - extracted = query_projects( - "SELECT queue_id, cost_per_kw FROM projects WHERE cost_per_kw IS NOT NULL" + reference = load_lbnl_costs(path) + rows = [(row, reference[row["queue_id"]]) for row in extracted if row["queue_id"] in reference] + print( + f"{len(rows)} of {len(extracted)} projects with an extracted cost are in Berkeley Lab's " + "PJM cost data. Costs are in dollars per kW." ) - rows = [ - (row["queue_id"], row["cost_per_kw"], reference[row["queue_id"]]) - for row in extracted - if row["queue_id"] in reference - ] if not rows: - print("no overlap between extracted projects and the LBNL reference") return - - print(f"{'queue_id':<12}{'extracted':>14}{'reference':>14}{'difference':>14}") - for queue_id, extracted_value, reference_value in rows: + print( + f"{'queue_id':<12}{'extracted':>11}{'Berkeley Lab':>14}{'difference':>12}" + f"{'MW used':>10}{'nameplate MW':>14} Berkeley Lab's study" + ) + for row, (lbnl_cost, nameplate_mw, study) in rows: print( - f"{queue_id:<12}{extracted_value:>14.2f}{reference_value:>14.2f}" - f"{extracted_value - reference_value:>14.2f}" + f"{row['queue_id']:<12}{row['cost_per_kw']:>11.2f}{lbnl_cost:>14.2f}" + f"{row['cost_per_kw'] - lbnl_cost:>12.2f}{row['divided_by_mw']:>10.1f}" + f"{nameplate_mw:>14.1f} {study}" ) + print( + "Berkeley Lab counts every cost except attachment facilities, divides by nameplate capacity " + "and gives 2022 dollars. The extracted cost is the study's network upgrades in its own year's " + "dollars, divided by the MW used. So the two can differ even when both are read correctly, " + "and more so if Berkeley Lab read a different study from the report in data/raw/pdfs." + ) def main() -> None: @@ -435,7 +463,7 @@ def main() -> None: parser.add_argument( "--validate", action="store_true", - help="compare extracted cost_per_kw against LBNL reference figures", + help="set each extracted cost per kW beside the one Berkeley Lab read by hand", ) parser.add_argument( "--rebuild", action="store_true", help="reprocess projects that already have a stored extract" diff --git a/src/fetch_queue.py b/src/fetch_queue.py index 432209b..5ea8001 100644 --- a/src/fetch_queue.py +++ b/src/fetch_queue.py @@ -3,7 +3,8 @@ The panel is built from one pinned release of the workbook, so every build starts from the same data. Each download is checked against the SHA-256 in config, which catches a partial download or a file Berkeley Lab has since replaced. A copy that already matches -is left alone, so the step costs nothing to rerun. +is left alone, so the step costs nothing to rerun. Berkeley Lab's PJM cost data, which +the extraction's --validate compares with, is pinned and downloaded the same way. """ import argparse @@ -33,31 +34,33 @@ def workbook_is_verified(path: Path) -> bool: return path.exists() and sha256_of(path) == settings.lbnl_workbook_sha256 -def fetch_workbook(client: httpx.Client) -> Path: - """Download the pinned workbook unless a verified copy is already on disk, and return its path.""" - destination = settings.lbnl_workbook_path - if workbook_is_verified(destination): +def _fetch_pinned( + client: httpx.Client, url: str, sha256: str, destination: Path, if_replaced: str +) -> Path: + """Download a pinned file unless a verified copy is already on disk, and return its path. + + if_replaced says what to do when the download doesn't match the pinned checksum. + """ + if destination.exists() and sha256_of(destination) == sha256: print(f"{destination.name} is already downloaded and matches the pinned checksum") return destination if destination.exists(): print(f"{destination.name} does not match the pinned checksum, downloading it again") destination.parent.mkdir(parents=True, exist_ok=True) # written beside the destination and moved into place only once verified, so an - # interrupted download never leaves a broken workbook where the panel build looks. + # interrupted download never leaves a broken file where the later steps look. partial = destination.with_name(destination.name + ".part") try: - with client.stream("GET", settings.lbnl_workbook_url) as response: + with client.stream("GET", url) as response: response.raise_for_status() with partial.open("wb") as handle: for block in response.iter_bytes(DOWNLOAD_CHUNK_BYTES): handle.write(block) actual = sha256_of(partial) - if actual != settings.lbnl_workbook_sha256: + if actual != sha256: raise ValueError( - f"the downloaded workbook has SHA-256 {actual}, not the pinned " - f"{settings.lbnl_workbook_sha256}. Berkeley Lab may have replaced the file. Check " - "https://emp.lbl.gov/queues, then update lbnl_workbook_url and lbnl_workbook_sha256 " - "in src/config.py" + f"the downloaded {destination.name} has SHA-256 {actual}, not the pinned {sha256}. " + f"Berkeley Lab may have replaced the file. {if_replaced}" ) except BaseException: partial.unlink(missing_ok=True) @@ -67,6 +70,30 @@ def fetch_workbook(client: httpx.Client) -> Path: return destination +def fetch_workbook(client: httpx.Client) -> Path: + """Download the pinned workbook unless a verified copy is already on disk, and return its path.""" + return _fetch_pinned( + client, + settings.lbnl_workbook_url, + settings.lbnl_workbook_sha256, + settings.lbnl_workbook_path, + "Check https://emp.lbl.gov/queues, then update lbnl_workbook_url and lbnl_workbook_sha256 " + "in src/config.py", + ) + + +def fetch_lbnl_costs(client: httpx.Client) -> Path: + """As fetch_workbook, for Berkeley Lab's PJM cost data.""" + return _fetch_pinned( + client, + settings.lbnl_costs_url, + settings.lbnl_costs_sha256, + settings.lbnl_costs_path, + "Check https://emp.lbl.gov/interconnection_costs, then update lbnl_costs_url and " + "lbnl_costs_sha256 in src/config.py", + ) + + def main() -> None: argparse.ArgumentParser( description="Download Berkeley Lab's Queued Up workbook and check its checksum." diff --git a/tests/test_extract.py b/tests/test_extract.py index 9ba8a11..0382f95 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -2,6 +2,7 @@ import shutil from unittest.mock import MagicMock +import httpx import pandas as pd import pytest import tiktoken @@ -21,8 +22,6 @@ compute_cost_per_kw, extract_all, extract_for_project, - find_lbnl_workbook, - load_lbnl_reference, network_upgrade_total, preview_chunks, retrieve_chunks, @@ -31,7 +30,6 @@ ) from src.ingest_pdfs import open_store from src.ingest_queue import ( - LBNL_SHEET, build_projects_table, normalize_frame, query_projects, @@ -411,27 +409,51 @@ def test_rebuild_reprocesses_a_project_that_already_has_a_stored_extract( assert reprocessed["projects"] == 1 -def test_find_lbnl_workbook_returns_none_when_the_directory_is_empty(tmp_path, monkeypatch) -> None: - monkeypatch.setattr(settings, "data_dir", tmp_path) - settings.queue_raw_dir.mkdir(parents=True, exist_ok=True) - assert find_lbnl_workbook() is None +def _serve_lbnl_costs(monkeypatch, rows: list[tuple[str, float, float]]) -> None: + """Stand in for Berkeley Lab's PJM cost data, with its own sheet and column names.""" + frame = pd.DataFrame(rows, columns=["Project #", "Nameplate MW", "$2022 Network Cost/kW"]) + frame.insert(1, "Queue Date", pd.Timestamp("2020-09-30")) + frame.insert(2, "Study Type", "System Impact") + frame.insert(3, "Study Date", pd.Timestamp("2021-08-01")) + settings.lbnl_costs_path.parent.mkdir(parents=True, exist_ok=True) + with pd.ExcelWriter(settings.lbnl_costs_path, engine="openpyxl") as writer: + frame.to_excel(writer, sheet_name="data", index=False) + monkeypatch.setattr("src.extract.fetch_lbnl_costs", lambda client: settings.lbnl_costs_path) + +def test_validation_sets_each_extracted_cost_beside_berkeley_labs(panel, monkeypatch, capsys) -> None: + write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6)) + # no studied mw, so the cost is divided by the panel's 150 MW. + write_extract(StudyExtract(queue_id="ac2115", total_network_upgrade_cost_usd=15e6)) + _serve_lbnl_costs(monkeypatch, [("z002", 210.0, 410.0), ("z003", 50.0, 99.0)]) -def test_load_lbnl_reference_is_none_when_the_cost_column_is_absent(tmp_path) -> None: - path = tmp_path / "fake_lbnl.xlsx" - frame = pd.DataFrame({"q_id": ["AC2-115"], "project_name": ["Gray Solar"]}) - with pd.ExcelWriter(path, engine="openpyxl") as writer: - frame.to_excel(writer, sheet_name=LBNL_SHEET, index=False, startrow=1) - assert load_lbnl_reference(path) is None + run_validation() + out = capsys.readouterr().out + assert "1 of 2 projects with an extracted cost" in out + table = [line.split(maxsplit=6) for line in out.splitlines() if line.startswith("z0")] + assert table == [ + ["z002", "400.00", "410.00", "-10.00", "200.0", "210.0", "System Impact, August 2021"] + ] -def test_run_validation_prints_a_clear_message_when_no_workbook_is_present( - tmp_path, monkeypatch, capsys -) -> None: - monkeypatch.setattr(settings, "data_dir", tmp_path) - settings.queue_raw_dir.mkdir(parents=True, exist_ok=True) +def test_validation_with_no_extracted_costs_downloads_nothing(panel, monkeypatch, capsys) -> None: + def must_not_download(client): + raise AssertionError("nothing to compare, so nothing should be downloaded") + + monkeypatch.setattr("src.extract.fetch_lbnl_costs", must_not_download) + run_validation() + assert "no project has an extracted cost yet" in capsys.readouterr().out + + +def test_validation_says_so_when_the_cost_data_cannot_be_downloaded(panel, monkeypatch, capsys) -> None: + write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6)) + + def offline(client): + raise httpx.ConnectError("no network") + + monkeypatch.setattr("src.extract.fetch_lbnl_costs", offline) run_validation() - assert "skipping validation" in capsys.readouterr().out + assert "could not download Berkeley Lab's PJM cost data: no network" in capsys.readouterr().out def test_compute_cost_per_kw_falls_back_to_panel_capacity_when_the_study_omits_mw() -> None: diff --git a/tests/test_fetch_queue.py b/tests/test_fetch_queue.py index 1ccbb60..adce505 100644 --- a/tests/test_fetch_queue.py +++ b/tests/test_fetch_queue.py @@ -4,7 +4,7 @@ import pytest from src.config import settings -from src.fetch_queue import fetch_workbook, workbook_is_verified +from src.fetch_queue import fetch_lbnl_costs, fetch_workbook, workbook_is_verified WORKBOOK_BYTES = b"pretend workbook bytes" @@ -55,6 +55,17 @@ def test_a_copy_that_does_not_match_is_replaced(sandbox) -> None: assert sandbox.read_bytes() == WORKBOOK_BYTES +def test_the_cost_data_is_checked_against_its_own_pinned_checksum(tmp_path, monkeypatch) -> None: + monkeypatch.setattr(settings, "data_dir", tmp_path) + monkeypatch.setattr(settings, "lbnl_costs_sha256", hashlib.sha256(WORKBOOK_BYTES).hexdigest()) + with pytest.raises(ValueError, match="update lbnl_costs_url and lbnl_costs_sha256"): + fetch_lbnl_costs(_client_serving(b"a different release")) + assert not settings.lbnl_costs_path.exists() + path = fetch_lbnl_costs(_client_serving(WORKBOOK_BYTES)) + assert path == settings.lbnl_costs_path + assert path.read_bytes() == WORKBOOK_BYTES + + def test_a_failed_request_raises_and_leaves_nothing(sandbox) -> None: client = httpx.Client(transport=httpx.MockTransport(lambda request: httpx.Response(404))) with pytest.raises(httpx.HTTPStatusError): From 24d1d8a3715bab0464862a8df3ec836d4fbd161c Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:06:59 +0000 Subject: [PATCH 2/3] Say that the study-year dollars are Berkeley Lab's assumption The --validate note said the extracted cost is in the dollars of the study's own year. PJM's reports don't say so; Berkeley Lab assumes it for PJM's studies. The note now says the cost is probably in the study's year's dollars, as Berkeley Lab assumes. --- src/extract.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/extract.py b/src/extract.py index 06f4321..4243e2b 100644 --- a/src/extract.py +++ b/src/extract.py @@ -450,9 +450,10 @@ def run_validation() -> None: ) print( "Berkeley Lab counts every cost except attachment facilities, divides by nameplate capacity " - "and gives 2022 dollars. The extracted cost is the study's network upgrades in its own year's " - "dollars, divided by the MW used. So the two can differ even when both are read correctly, " - "and more so if Berkeley Lab read a different study from the report in data/raw/pdfs." + "and gives 2022 dollars. The extracted cost is the study's network upgrades, probably in " + "the dollars of the study's year, as Berkeley Lab assumes, divided by the MW used. So the " + "two can differ even when both are read correctly, and more so if Berkeley Lab read a " + "different study from the report in data/raw/pdfs." ) From d576e480579754a8a9e3fd5435d542866e7f40a7 Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:22:59 +0000 Subject: [PATCH 3/3] Test the megawatt fallback, and explain the gaps An independent review found that no test covered the megawatts --validate shows when a study omits them or gives zero, and that future work tied --validate to AC2-093, which Berkeley Lab doesn't cover. The validation test now covers both fallbacks. New tests check that a file with another checksum is reported, and that --validate without a panel says to build one rather than ending in a traceback. The output says which way the difference runs and whose megawatts are whose. The docs now say --validate has nothing to compare until the paid extraction runs, and explain the gaps it will show. Most of AF1-236's is Berkeley Lab's conversion to 2022 dollars, and for four default projects whose reports give no network upgrades, the gap is all of Berkeley Lab's figure. The sources link to the page that offers the file. --- README.md | 8 ++++---- docs/decisions.md | 12 ++++++----- docs/future_work.md | 6 +++--- src/config.py | 5 +++-- src/extract.py | 19 +++++++++++------ src/fetch_queue.py | 4 ++-- tests/test_extract.py | 48 +++++++++++++++++++++++++++++++++++++------ 7 files changed, 74 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 2b2213b..baa868b 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed `make eval DRY_RUN=false` puts six questions to the real agent. It prints each answer, the result of each check, and the tokens and cost. The checks test, for example, that the agent used the right tool, stated the right count, and didn't present one line of a report as a project's total. Four checks compare answers with the extracted costs. Until there are costs to compare with, the evaluation skips these checks and says so, rather than passing them. One of them is about AF1-236, whose report isn't in the default sample, so it stays skipped until you add that report and extract its costs (see the Quickstart). The wind question's check follows the panel too: until a wind project's extracted cost is above $300 per kW, it expects the answer to say there is none. I haven't run the evaluation yet, because it needs the paid steps first. -`python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's [PJM cost data](https://emp.lbl.gov/interconnection_costs), which its researchers read by hand from PJM's studies. It calls no model. The first time, it downloads Berkeley Lab's file and checks that it's the expected copy. The file covers 13 of the 25 default projects, and AF1-236. For each one, it prints the two costs, the difference, the megawatts each was divided by, and the study Berkeley Lab read. The two costs are defined differently (see [Limitations](#limitations)), so they can differ even when both are read correctly. For AF1-236, the cost I read from its report by hand comes to $391.35 per kW, and Berkeley Lab's to $418.46 ([more](docs/decisions.md#checking-the-extracted-costs-against-berkeley-labs)). +`python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's [PJM cost data](https://emp.lbl.gov/publications/interconnection-cost-analysis-pjm), which its researchers read by hand from PJM's studies. It calls no model. The file covers 13 of the 25 default projects, and AF1-236. For each of these with an extracted cost, it prints the two costs, the difference, the megawatts each was divided by, and the study Berkeley Lab read. The first time it has a cost to compare, it downloads Berkeley Lab's file and checks that it's the expected copy. Until the paid extraction runs, it has nothing to compare, and says so. The two costs are defined differently (see [Limitations](#limitations)), so they can differ even when both are read correctly. For AF1-236, the cost I read from its report by hand comes to $391.35 per kW, and Berkeley Lab's to $418.46. Most of that gap is Berkeley Lab's conversion to 2022 dollars ([more](docs/decisions.md#checking-the-extracted-costs-against-berkeley-labs)). ## Limitations @@ -122,7 +122,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed - **`make fetch` only looks for reports of projects in the AG1 window or an earlier one, and the default sample is narrow.** See [What the data holds now](#what-the-data-holds-now). - **The paid steps haven't run yet.** Embedding the reports, extracting their costs, asking the agent questions and the evaluation all call OpenAI's paid models, and I haven't run any of them. The agent and the extraction use `gpt-6-luna` ([why](docs/decisions.md#the-models-gpt-6-luna-with-reasoning-off)), and no request has gone to it yet. So I haven't confirmed that OpenAI accepts the settings the code sends, or that the costs the code reports match OpenAI's bill. Nor have I measured how accurately the model extracts costs, how well the agent answers, or what either costs. The offline tests use a stand-in for OpenAI, so they check what the code sends, not what OpenAI does with it. - **The model can misread a report.** It can miss or misread a figure, and its output can vary between runs, so check any cost that matters against its report. -- **My cost per kW is defined differently from Berkeley Lab's.** Berkeley Lab counts every cost except attachment facilities as network cost, divides by the plant's nameplate capacity (its rated maximum output) and converts to 2022 dollars. I use the report's own network upgrade total, or if it gives none, its total minus the cost of the physical connection. Either can leave out connection work that Berkeley Lab counts. I divide by the megawatts the study assessed, or by the panel's capacity if it gives none, and don't adjust for inflation. `--validate` shows both costs for each project Berkeley Lab covers. +- **My cost per kW is defined differently from Berkeley Lab's.** Berkeley Lab counts every cost except attachment facilities as network cost, divides by the plant's nameplate capacity (its rated maximum output) and converts to 2022 dollars. I use the report's own network upgrade total, or if it gives none, its total minus the cost of the physical connection. Either can leave out connection work that Berkeley Lab counts. I divide by the megawatts the study assessed, or by the panel's capacity if it gives none, and don't adjust for inflation. `--validate` shows both costs for each project Berkeley Lab covers, once its cost is extracted. - **Withdrawal risk is reasoning, not prediction.** The agent weighs a project's costs against four research findings, each with its source ([what it is told](docs/decisions.md#what-the-agent-is-told-about-withdrawals)), and describes the risk. It is told never to say a project will certainly withdraw. It isn't a statistical model trained on past withdrawals. ## Project layout @@ -130,7 +130,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed ``` src/ config.py every setting, path, model name and price - fetch_queue.py downloads Berkeley Lab's queue spreadsheet and PJM cost data + fetch_queue.py downloads Berkeley Lab's queue spreadsheet and its PJM cost data ingest_queue.py builds the panel, and runs the agent's SQL safely fetch_pdfs.py downloads PJM's study reports ingest_pdfs.py splits the reports into passages and embeds them @@ -156,7 +156,7 @@ Python 3.11 to 3.14, LangChain and LangGraph for the agent, and OpenAI's models: | Data | What I use it for | Licence and terms | |---|---|---| | [Berkeley Lab, Queued Up: 2026 Edition](https://emp.lbl.gov/publications/queued-2026-edition-characteristics) ([data file](https://eta-publications.lbl.gov/sites/default/files/2026-05/lbnl_ix_queue_data_file_thru2025.xlsx)) | The panel, and the national figures on completion and withdrawal | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), credited to Lawrence Berkeley National Laboratory and GridTracker. `make data` downloads it, and Git ignores it. | -| [Berkeley Lab, PJM interconnection cost data](https://emp.lbl.gov/interconnection_costs) ([data file](https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx)), by Seel and others, with Exeter Associates (January 2023) | The costs `--validate` compares with: network costs read by hand from PJM's studies of 1,127 projects | It states no open licence. Its copyright notice only covers the US government's right to publish it. `--validate` downloads it for your own use, and Git ignores it. | +| [Berkeley Lab, PJM interconnection cost data](https://emp.lbl.gov/publications/interconnection-cost-analysis-pjm) ([data file](https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx)), by Seel and others, with Exeter Associates (January 2023) | The costs `--validate` compares with: network costs read by hand from PJM's studies of 1,127 projects | It states no open licence. Its copyright notice only reserves a licence for the US government to publish or reproduce it. `--validate` downloads it for your own use, and Git ignores it. | | PJM study reports, such as [AC2-093's](https://www.pjm.com/pjmfiles/pub/planning/project-queues/impact_studies/ac2093_imp.pdf) | The passages the agent reads, and the costs | © PJM Interconnection, all rights reserved. `make fetch` downloads them for your own use, and Git ignores them. | | PJM's live queue, through [gridstatus](https://github.com/gridstatus/gridstatus) (optional) | An alternative to Berkeley Lab's data | PJM's terms apply (see its [legal page](https://www.pjm.com/about-pjm/legal.aspx)). The data stays on your computer. | diff --git a/docs/decisions.md b/docs/decisions.md index eb4953c..c41f3f9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -177,7 +177,7 @@ Tests check that each finding ends with its source, and that the findings keep t **Evidence.** A test rebuilds the panel after extracting three projects and checks that their costs come back unchanged, whether the study gives its megawatts, omits them or gives zero. -**Trade-off.** The ratio is written twice, once in Python and once in SQL. That test keeps the two in step. +**Trade-off.** The ratio is written twice, once in Python and once in SQL, and `--validate` repeats its choice of megawatts in SQL. Tests keep all three in step. ## Queue age ends when a project leaves the queue @@ -248,7 +248,7 @@ Tests check that each finding ends with its source, and that the findings keep t ## Checking the extracted costs against Berkeley Lab's -**Decision.** `python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's PJM cost data, which its researchers read by hand from PJM's studies of 1,127 projects. For each project in both, it prints the two costs, the difference, the megawatts each was divided by, and the study Berkeley Lab read. Like the Queued Up spreadsheet, the file is pinned by its address and SHA-256 checksum in `src/config.py` (`lbnl_costs_url` and `lbnl_costs_sha256`). It is downloaded into `data/raw/costs/` the first time it's needed. The command calls no model. +**Decision.** `python -m src.extract --validate` sets each extracted cost per kW beside the one in Berkeley Lab's PJM cost data, which its researchers read by hand from PJM's studies of 1,127 projects. For each project in both, it prints the two costs, the difference (the extracted cost minus Berkeley Lab's), the megawatts each was divided by, and the study Berkeley Lab read. Like the Queued Up spreadsheet, the file is pinned by its address and SHA-256 checksum in `src/config.py` (`lbnl_costs_url` and `lbnl_costs_sha256`). It is downloaded into `data/raw/costs/` the first time it's needed. The command calls no model. **Why.** - **An independent check on more projects.** The file covers 13 of the 25 default projects, and AF1-236. I read three reports by hand. @@ -257,14 +257,16 @@ Tests check that each finding ends with its source, and that the findings keep t **Alternatives.** - **Only the three projects I read by hand** (AC2-093, AF1-236 and AF2-353). That check stays, but three projects that I chose say little about the rest. -- **Converting both costs to one definition first,** for example mine to 2022 dollars. It would hide where the two differ, and it needs figures the extraction doesn't collect, such as each study's date. Settling the definition is [future work](future_work.md). +- **Converting both costs to one definition first,** for example mine to 2022 dollars. It would hide where the two differ. And Berkeley Lab says only that it converts with a GDP deflator, an index of prices across the economy, not what factor it applies to each study, so my conversion could differ from its own. Settling the definition is [future work](future_work.md). - **The Queued Up spreadsheet.** It holds no costs. - **Committing the file.** It states no open licence, so, like PJM's reports, it is downloaded for local use and kept out of Git. **Evidence.** -- On 30 November 2026 I ran `--validate` on a copy of the panel holding only the cost I read by hand from AF1-236's report. It downloaded the file, matched its checksum, and printed $391.35 per kW beside Berkeley Lab's $418.46, both divided by 1,210 MW. +- On 1 December 2026 I ran `--validate` on a copy of the panel holding only the cost I read by hand from AF1-236's report. It downloaded the file, matched its checksum, and printed $391.35 per kW beside Berkeley Lab's $418.46, a difference of −$27.11, both divided by 1,210 MW. - I set the first page of each of the 14 reports beside the study type and date Berkeley Lab gives. Seven of the default projects' reports are system impact studies, and six combine a feasibility study with a system impact study, which Berkeley Lab lists as system impact. AF1-236's is a system impact study. -- Tests check that only projects in both are compared, that the file's own sheet and column names are read, that nothing is downloaded when there are no extracted costs, that a failed download is reported, and that a file with another checksum is refused. +- Berkeley Lab's figures come back to the reports' own. For AF1-236, its $418.46 is the report's $473,529,878 of network upgrades plus $2,400,000 for two substation breakers, which the report counts as part of the physical connection, divided by 1,210 MW and raised by 6.4% to 2022 dollars. So of the gap of $27.11 per kW, $1.98 is the breakers and $25.13 the conversion. For the 2021 studies I checked, the rise is 2.1%. +- For four default projects, AG1-330, AG1-335, AG1-336 and AG1-337, the report's cost summary gives "Total System Network Upgrade Costs $0" and lists the substation and line work as part of the physical connection. Berkeley Lab counts most of that work as network cost: $405.43, $928.25, $1,638.58 and $575.47 per kW. So for these, a correct extraction will show all of Berkeley Lab's figure as the gap. +- Tests check that only projects in both are compared, that the megawatts shown follow the same rule as the cost, that the file's own sheet and column names are read, and that nothing is downloaded when there are no extracted costs. They also check that a failed download, or a file with another checksum, is reported rather than used, and that running it without a panel says to build one. **Trade-offs.** - A gap isn't by itself a mistake, because the definitions differ. The output says so. diff --git a/docs/future_work.md b/docs/future_work.md index 65345c8..c6ed878 100644 --- a/docs/future_work.md +++ b/docs/future_work.md @@ -4,13 +4,13 @@ Changes I plan or propose, starting with the most urgent. ## Next -- **Run the paid steps.** Embed the reports, extract their costs and run the evaluation. Then add the reports of AC2-093, AF1-236 and AF2-353, which aren't in the default sample, check their extracted costs against the figures I read from them by hand, and compare the 14 projects that Berkeley Lab covers with its costs (`python -m src.extract --validate`). This needs OpenAI credits. +- **Run the paid steps.** Embed the reports, extract their costs and run the evaluation. Then add the reports of AC2-093, AF1-236 and AF2-353, which aren't in the default sample, check their extracted costs against the figures I read from them by hand, and compare the 14 projects that Berkeley Lab covers (13 of the default 25, and AF1-236) with its costs (`python -m src.extract --validate`). This needs OpenAI credits. ## Method - **Choose a more varied sample of reports.** Of the default 25, 22 applied on the same day, and 12 are 5 MW or smaller. A better rule could set a minimum size, prefer system impact studies and spread the choice across queue windows. -- **Settle the cost definition.** Either match Berkeley Lab's (every cost except attachment facilities, divided by nameplate capacity, in 2022 dollars) or keep mine. `--validate` will show how far apart the two are once costs are extracted. -- **Check which megawatts the extraction copies.** AC2-093's report gives 675 MW of output, of which PJM counts 429.4 MW as capacity. Its cost per kW depends on which one the model takes. `--validate` shows the megawatts used beside Berkeley Lab's. +- **Settle the cost definition.** Either match Berkeley Lab's (every cost except attachment facilities, divided by nameplate capacity, in 2022 dollars) or keep mine. For four of the default projects, a correct extraction gives $0 per kW, where Berkeley Lab gives $405 to $1,639 ([why](decisions.md#checking-the-extracted-costs-against-berkeley-labs)). `--validate` will show how far apart the two are once costs are extracted. +- **Check which megawatts the extraction copies.** AF1-236's report gives 1,210 MW of output, of which PJM counts 459.8 MW as capacity, so its cost is $391.35 or $1,029.86 per kW, depending on which one the model takes. `--validate` shows the megawatts used beside Berkeley Lab's. - **Compare PDF readers.** On my laptop, PyMuPDF took about 140 seconds to read AG1-321's 65-page report with its tables added in Markdown, a simple text format, and gave 365,148 characters. Without the Markdown tables it took under half a second and gave 133,495. I haven't measured whether the tables help the extraction. ## Scope diff --git a/src/config.py b/src/config.py index aae18dd..5c88f4e 100644 --- a/src/config.py +++ b/src/config.py @@ -145,8 +145,9 @@ class Settings(BaseSettings): lbnl_data_end: date = date(2025, 12, 31) # the reference for --validate, Berkeley Lab's PJM cost data (January 2023, - # https://emp.lbl.gov/interconnection_costs), with costs read by hand from PJM's studies of - # 1,127 projects. it states no open licence, so it is downloaded for local use, never committed. + # https://emp.lbl.gov/publications/interconnection-cost-analysis-pjm), with costs read by hand + # from PJM's studies of 1,127 projects. it states no open licence, so it is downloaded for local + # use, never committed. lbnl_costs_url: str = ( "https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx" ) diff --git a/src/extract.py b/src/extract.py index 4243e2b..e0de48a 100644 --- a/src/extract.py +++ b/src/extract.py @@ -428,25 +428,29 @@ def run_validation() -> None: ) as client: path = fetch_lbnl_costs(client) except (httpx.HTTPError, ValueError) as error: - print(f"could not download Berkeley Lab's PJM cost data: {error}") + print(f"could not get Berkeley Lab's PJM cost data: {error}") return reference = load_lbnl_costs(path) rows = [(row, reference[row["queue_id"]]) for row in extracted if row["queue_id"] in reference] print( - f"{len(rows)} of {len(extracted)} projects with an extracted cost are in Berkeley Lab's " - "PJM cost data. Costs are in dollars per kW." + f"Projects with an extracted cost: {len(extracted)}. " + f"In Berkeley Lab's PJM cost data: {len(rows)}." ) if not rows: return + print( + "Costs are in dollars per kW. The difference is the extracted cost minus Berkeley Lab's, " + "and MW used is the megawatts the extracted cost was divided by." + ) print( f"{'queue_id':<12}{'extracted':>11}{'Berkeley Lab':>14}{'difference':>12}" - f"{'MW used':>10}{'nameplate MW':>14} Berkeley Lab's study" + f"{'MW used':>10}{'Berkeley Lab MW':>17} Berkeley Lab's study" ) for row, (lbnl_cost, nameplate_mw, study) in rows: print( f"{row['queue_id']:<12}{row['cost_per_kw']:>11.2f}{lbnl_cost:>14.2f}" f"{row['cost_per_kw'] - lbnl_cost:>12.2f}{row['divided_by_mw']:>10.1f}" - f"{nameplate_mw:>14.1f} {study}" + f"{nameplate_mw:>17.1f} {study}" ) print( "Berkeley Lab counts every cost except attachment facilities, divides by nameplate capacity " @@ -471,7 +475,10 @@ def main() -> None: ) args = parser.parse_args() if args.validate: - run_validation() + try: + run_validation() + except FileNotFoundError as error: + raise SystemExit(f"could not compare the costs: {error}") from error return require_key_for_paid_run() extract_all(rebuild=args.rebuild) diff --git a/src/fetch_queue.py b/src/fetch_queue.py index 5ea8001..df25e1f 100644 --- a/src/fetch_queue.py +++ b/src/fetch_queue.py @@ -89,8 +89,8 @@ def fetch_lbnl_costs(client: httpx.Client) -> Path: settings.lbnl_costs_url, settings.lbnl_costs_sha256, settings.lbnl_costs_path, - "Check https://emp.lbl.gov/interconnection_costs, then update lbnl_costs_url and " - "lbnl_costs_sha256 in src/config.py", + "Check https://emp.lbl.gov/publications/interconnection-cost-analysis-pjm, then update " + "lbnl_costs_url and lbnl_costs_sha256 in src/config.py", ) diff --git a/tests/test_extract.py b/tests/test_extract.py index 0382f95..e8744f0 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -22,6 +22,7 @@ compute_cost_per_kw, extract_all, extract_for_project, + main, network_upgrade_total, preview_chunks, retrieve_chunks, @@ -423,16 +424,30 @@ def _serve_lbnl_costs(monkeypatch, rows: list[tuple[str, float, float]]) -> None def test_validation_sets_each_extracted_cost_beside_berkeley_labs(panel, monkeypatch, capsys) -> None: write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6)) - # no studied mw, so the cost is divided by the panel's 150 MW. + # one study omits its megawatts and one gives zero, so those costs are divided by the panel's + # 150 MW and 50 MW. z004 isn't in berkeley lab's data, and z005 has no extracted cost. write_extract(StudyExtract(queue_id="ac2115", total_network_upgrade_cost_usd=15e6)) - _serve_lbnl_costs(monkeypatch, [("z002", 210.0, 410.0), ("z003", 50.0, 99.0)]) + write_extract(StudyExtract(queue_id="z003", studied_mw=0.0, total_network_upgrade_cost_usd=5e6)) + write_extract(StudyExtract(queue_id="z004", studied_mw=120, total_network_upgrade_cost_usd=12e6)) + _serve_lbnl_costs( + monkeypatch, + [ + ("ac2115", 160.0, 95.0), + ("z002", 210.0, 410.0), + ("z003", 60.0, 99.0), + ("z005", 300.0, 50.0), + ], + ) run_validation() out = capsys.readouterr().out - assert "1 of 2 projects with an extracted cost" in out - table = [line.split(maxsplit=6) for line in out.splitlines() if line.startswith("z0")] + assert "Projects with an extracted cost: 4. In Berkeley Lab's PJM cost data: 3." in out + table = [line.split(maxsplit=6) for line in out.splitlines() if line.startswith(("ac", "z0"))] + study = "System Impact, August 2021" assert table == [ - ["z002", "400.00", "410.00", "-10.00", "200.0", "210.0", "System Impact, August 2021"] + ["ac2115", "100.00", "95.00", "5.00", "150.0", "160.0", study], + ["z002", "400.00", "410.00", "-10.00", "200.0", "210.0", study], + ["z003", "100.00", "99.00", "1.00", "50.0", "60.0", study], ] @@ -453,7 +468,28 @@ def offline(client): monkeypatch.setattr("src.extract.fetch_lbnl_costs", offline) run_validation() - assert "could not download Berkeley Lab's PJM cost data: no network" in capsys.readouterr().out + assert "could not get Berkeley Lab's PJM cost data: no network" in capsys.readouterr().out + + +def test_validation_says_so_when_the_cost_data_fails_its_checksum(panel, monkeypatch, capsys) -> None: + write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6)) + served = httpx.Client( + transport=httpx.MockTransport(lambda request: httpx.Response(200, content=b"another file")) + ) + monkeypatch.setattr(httpx, "Client", lambda **kwargs: served) + + run_validation() + out = capsys.readouterr().out + assert "could not get Berkeley Lab's PJM cost data: the downloaded" in out + assert "not the pinned" in out + assert not settings.lbnl_costs_path.exists() + + +def test_validation_without_a_panel_says_to_build_one(tmp_path, monkeypatch) -> None: + monkeypatch.setattr(settings, "data_dir", tmp_path) + monkeypatch.setattr("sys.argv", ["extract", "--validate"]) + with pytest.raises(SystemExit, match="could not compare the costs: no panel at .*make panel"): + main() def test_compute_cost_per_kw_falls_back_to_panel_capacity_when_the_study_omits_mw() -> None: