Skip to content

Commit 9d40cb7

Browse files
Add effectiveUFactor, compliance, requirements, and report functions, update documentation and skills
1 parent 1a52303 commit 9d40cb7

10 files changed

Lines changed: 430 additions & 16 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,4 @@ site/
6161

6262
# Build artifacts
6363
dist/
64+
reports/

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# COMcheck API — Python Package
22

3-
A type-safe Python package for the [COMcheck Web](https://comcheck.energycode.pnl.gov) — PNNL's hosted service for commercial building energy-code (ASHRAE 90.1 / IECC) compliance. Use it to build COMcheck projects, run compliance simulations, and read results from Python over the live API. Requires a free Personal Access Token (see below). The package is maintained with `uv`.
3+
A type-safe Python package for the [COMcheck Web](https://comcheck.energycode.pnl.gov) — PNNL's hosted service for commercial building energy-code (ASHRAE 90.1 / IECC) compliance. Use it to build COMcheck projects, run compliance simulations, check compliance and requirements, generate PDF reports, and read results from Python over the live API. Requires a free Personal Access Token (see below). The package is maintained with `uv`.
44

55
**Requirements:**
66
- Python: `>=3.12`

‎comcheck_api/ai/skill/SKILL.md‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,9 +150,11 @@ print(result["performanceRating"])
150150
`COMcheckClient` user methods (`list_projects`, `get_project`,
151151
`update_project`, `start_run_simulation`, `get_simulation_status`,
152152
`get_simulation_result`, `set_api_key`) are fully supported and
153-
fine to use. If asked for an unsupported mutation area, tell the
154-
user it's not implemented and offer building-area / envelope /
155-
simulation instead. Confirm operation scope with
153+
fine to use. The compliance/report client methods
154+
(`check_compliance`, `check_requirements`, `generate_report`) are
155+
also fully supported. If asked for an unsupported mutation area,
156+
tell the user it's not implemented and offer building-area /
157+
envelope / simulation instead. Confirm operation scope with
156158
`comcheck_api.list_operations()` (only `building_area` and
157159
`envelope` groups exist).
158160

@@ -230,6 +232,38 @@ else:
230232
raise TimeoutError(f"Simulation {session_id} did not complete in 5 min")
231233
```
232234

235+
### Checking compliance/requirements and generating a report
236+
237+
These are synchronous (no polling). All three take a `ComBuilding`
238+
directly.
239+
240+
```python
241+
# Per-category compliance status
242+
compliance = client.check_compliance(project)
243+
if compliance["mandatoryRequirementsMet"]:
244+
...
245+
246+
# Applicable requirements
247+
requirements = client.check_requirements(project)
248+
249+
# PDF report — returns {url, expires, fileName}. The url is a short-lived
250+
# presigned S3 URL (expires within minutes); don't cache it.
251+
report = client.generate_report(project)
252+
253+
# Download the PDF (saves using the server fileName; default dir is ~/Downloads)
254+
report = client.generate_report(project, download=True)
255+
report = client.generate_report(project, download=True, download_dir="./out")
256+
257+
# Toggle report sections (all default to True)
258+
report = client.generate_report(
259+
project, envelope=True, intlighting=True, extlighting=False, mechanical=True
260+
)
261+
```
262+
263+
`generate_report` deliberately does **not** open a browser — it's a
264+
library, so it returns metadata and lets the caller decide
265+
(`webbrowser.open(report["url"])`).
266+
233267
## Gotchas
234268

235269
- **Field names are lowercase camelCase**, not PascalCase.
@@ -281,5 +315,7 @@ else:
281315
- For Pydantic model field-level details → read `reference/types.md`.
282316
- For the simulation start/poll/fetch flow → read
283317
`reference/simulation.md`.
318+
- For compliance checks, requirements, and PDF report generation →
319+
read `reference/compliance.md`.
284320
- To validate generated code against a mocked client → run
285321
`scripts/validate_code.py`.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Compliance, Requirements & Reports Reference
2+
3+
Three client methods evaluate a project without running the full
4+
async simulation flow. All three accept a `ComBuilding` and serialize
5+
it for you — pass the project model directly.
6+
7+
```python
8+
from comcheck_api import COMcheckClient
9+
client = COMcheckClient(api_key="...")
10+
```
11+
12+
| Method | Returns | Purpose |
13+
|---|---|---|
14+
| `client.check_compliance(project)` | `dict` | Per-category compliance status for the project. |
15+
| `client.check_requirements(project)` | `dict` | The applicable requirements for the project. |
16+
| `client.generate_report(project, ...)` | `dict` | Generate a PDF report; returns `{url, expires, fileName}`. |
17+
18+
## check_compliance
19+
20+
Returns a dict with a top-level `mandatoryRequirementsMet` flag and a
21+
status object for each category:
22+
23+
- `envelopeStatus`
24+
- `interiorLightingStatus`
25+
- `exteriorLightingStatus`
26+
- `renewableStatus`
27+
- `energyCreditStatus`
28+
29+
```python
30+
compliance = client.check_compliance(project)
31+
if compliance["mandatoryRequirementsMet"]:
32+
...
33+
```
34+
35+
## check_requirements
36+
37+
Returns the applicable requirements payload for the project. Like
38+
`check_compliance`, it's a single synchronous call — no polling.
39+
40+
```python
41+
requirements = client.check_requirements(project)
42+
```
43+
44+
## generate_report
45+
46+
Builds a PDF report. The PDF is stored in S3; the API returns a
47+
**short-lived presigned URL** (expires within a few minutes) plus the
48+
file name:
49+
50+
```python
51+
report = client.generate_report(project)
52+
# {"url": "...", "expires": "in 5 minutes", "fileName": "report...pdf"}
53+
```
54+
55+
### Signature
56+
57+
```python
58+
client.generate_report(
59+
project,
60+
envelope=True,
61+
extlighting=True,
62+
intlighting=True,
63+
mechanical=True,
64+
download=False,
65+
download_dir=None,
66+
)
67+
```
68+
69+
- The four section flags toggle which sections appear in the report
70+
(all default to `True`).
71+
- `download=True` fetches the PDF from the presigned URL and saves it
72+
using the server-provided `fileName`. `download_dir` defaults to the
73+
user's `~/Downloads` folder.
74+
75+
```python
76+
report = client.generate_report(project, download=True) # ~/Downloads
77+
report = client.generate_report(project, download=True, download_dir="./out")
78+
```
79+
80+
## Don't
81+
82+
- Don't try to open the report in a browser from library code — this
83+
method intentionally returns metadata only. If a browser is wanted,
84+
the caller does `webbrowser.open(report["url"])`.
85+
- Don't cache the presigned `url` — it expires within minutes.
86+
Re-call `generate_report` to get a fresh one.

‎comcheck_api/api/api_services.py‎

Lines changed: 80 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -187,19 +187,21 @@ def update_project(
187187
except Exception as error:
188188
self._handle_api_error(error)
189189

190-
def assemblies_uvalue(self, envelope_data: Dict[str, Any], energy_code) -> Dict[str, Any]:
190+
def assemblies_uvalue(
191+
self, envelope_data: Dict[str, Any], energy_code
192+
) -> Dict[str, Any]:
191193
"""get assemblies u values
192194
193-
Args:
194-
envelope_data: The envelope data to send in the request body
195-
energy_code: The energy code for the api end point path
195+
Args:
196+
envelope_data: The envelope data to send in the request body
197+
energy_code: The energy code for the api end point path
196198
197-
Returns:
198-
RunSimulationResponse with session information
199+
Returns:
200+
RunSimulationResponse with session information
199201
200-
Raises:
201-
COMCheckHTTPError: If the API returns an error status
202-
COMCheckConnectionError: If the request fails
202+
Raises:
203+
COMCheckHTTPError: If the API returns an error status
204+
COMCheckConnectionError: If the request fails
203205
"""
204206
try:
205207
client = self._get_client()
@@ -212,6 +214,75 @@ def assemblies_uvalue(self, envelope_data: Dict[str, Any], energy_code) -> Dict[
212214
except Exception as error:
213215
self._handle_api_error(error)
214216

217+
def check_compliance(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
218+
"""Check compliance for a project.
219+
220+
Args:
221+
project_data: The project data to send in the request body
222+
223+
Returns:
224+
API response data as dictionary
225+
226+
Raises:
227+
COMCheckHTTPError: If the API returns an error status
228+
COMCheckConnectionError: If the request fails
229+
"""
230+
try:
231+
client = self._get_client()
232+
response = client.post("/compliance", json=project_data)
233+
response.raise_for_status()
234+
return response.json()
235+
except Exception as error:
236+
self._handle_api_error(error)
237+
238+
def check_requirements(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
239+
"""Check requirements for a project.
240+
241+
Args:
242+
project_data: The project data to send in the request body
243+
244+
Returns:
245+
API response data as dictionary
246+
247+
Raises:
248+
COMCheckHTTPError: If the API returns an error status
249+
COMCheckConnectionError: If the request fails
250+
"""
251+
try:
252+
client = self._get_client()
253+
response = client.post("/requirements", json=project_data)
254+
response.raise_for_status()
255+
return response.json()
256+
except Exception as error:
257+
self._handle_api_error(error)
258+
259+
def generate_report(self, report_data: Dict[str, Any]) -> Dict[str, Any]:
260+
"""Generate a PDF report for a project.
261+
262+
The API stores the generated PDF in S3 and returns a presigned URL
263+
to download it.
264+
265+
Args:
266+
report_data: The report request body, containing ``building`` (the
267+
project data) and the ``envelope``, ``extlighting``,
268+
``intlighting``, and ``mechanical`` section flags.
269+
270+
Returns:
271+
API response as a dictionary with ``url`` (the presigned S3 URL),
272+
``expires``, and ``fileName``
273+
274+
Raises:
275+
COMCheckHTTPError: If the API returns an error status
276+
COMCheckConnectionError: If the request fails
277+
"""
278+
try:
279+
client = self._get_client()
280+
response = client.post("/report", json=report_data)
281+
response.raise_for_status()
282+
return response.json()
283+
except Exception as error:
284+
self._handle_api_error(error)
285+
215286
def start_run_simulation(
216287
self, project_data: Dict[str, Any]
217288
) -> RunSimulationResponse:

‎comcheck_api/client/comcheck_client.py‎

Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
and return either Pydantic models, primitives, or raw dicts depending on the operation."""
55

66
import logging
7+
import os
78
from typing import Any, Dict, List, Literal, Optional, Union, overload
89

10+
import httpx
11+
912
from comcheck_api.api import COMCheckApiService
1013
from comcheck_api.constants.building_area_constants import DEFAULT_BUILDING_AREA
1114
from comcheck_api.exceptions import (
@@ -271,11 +274,93 @@ def fill_empty_description(assemblies: list[dict]) -> list[dict]:
271274
"skylight": fill_empty_description(envelope_data["skylight"]),
272275
"window": fill_empty_description(envelope_data["window"]),
273276
"door": fill_empty_description(envelope_data["door"]),
274-
"floor": fill_empty_description(envelope_data["floor"])
277+
"floor": fill_empty_description(envelope_data["floor"]),
275278
}
276-
assemblie_uvalue = self._service.assemblies_uvalue(reformatted_envelope_data, energy_code)
279+
assemblie_uvalue = self._service.assemblies_uvalue(
280+
reformatted_envelope_data, energy_code
281+
)
277282
return assemblie_uvalue["data"]
278283

284+
def check_compliance(self, project: ComBuilding) -> Any:
285+
"""Check code compliance for a project.
286+
287+
Args:
288+
project: The project data to evaluate.
289+
290+
Returns:
291+
The compliance results payload returned by the API.
292+
"""
293+
project_data = project.model_dump(mode="json", exclude_unset=True)
294+
response = self._service.check_compliance(project_data)
295+
return response.get("data")
296+
297+
def check_requirements(self, project: ComBuilding) -> Any:
298+
"""Check the applicable requirements for a project.
299+
300+
Args:
301+
project: The project data to evaluate.
302+
303+
Returns:
304+
The requirements payload returned by the API.
305+
"""
306+
project_data = project.model_dump(mode="json", exclude_unset=True)
307+
response = self._service.check_requirements(project_data)
308+
return response.get("data")
309+
310+
def generate_report(
311+
self,
312+
project: ComBuilding,
313+
envelope: bool = True,
314+
extlighting: bool = True,
315+
intlighting: bool = True,
316+
mechanical: bool = True,
317+
download: bool = False,
318+
download_dir: Optional[str] = None,
319+
) -> Optional[Dict[str, Any]]:
320+
"""Generate a PDF report for a project.
321+
322+
The report PDF is stored in S3; the API returns a presigned URL to
323+
download it. The URL is short-lived (expires within a few minutes).
324+
325+
This method does not open the report in a browser — as a library it
326+
returns the report metadata and lets the caller decide what to do
327+
(e.g. ``webbrowser.open(report["url"])``, stream it onward, or save it
328+
via *download*).
329+
330+
Args:
331+
project: The project data to generate a report for.
332+
envelope: Whether to include the envelope section in the report.
333+
extlighting: Whether to include the exterior lighting section.
334+
intlighting: Whether to include the interior lighting section.
335+
mechanical: Whether to include the mechanical section.
336+
download: When ``True``, fetch the PDF from the presigned URL and
337+
save it using the server-provided ``fileName``.
338+
download_dir: Directory to save the PDF into when *download* is
339+
``True``. Defaults to the user's ``~/Downloads`` folder.
340+
341+
Returns:
342+
The report metadata dict with ``url`` (the presigned S3 URL),
343+
``expires``, and ``fileName``.
344+
"""
345+
report_data = {
346+
"building": project.model_dump(mode="json", exclude_unset=True),
347+
"envelope": envelope,
348+
"extlighting": extlighting,
349+
"intlighting": intlighting,
350+
"mechanical": mechanical,
351+
}
352+
response = self._service.generate_report(report_data)
353+
if response and download:
354+
if download_dir is None:
355+
download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
356+
os.makedirs(download_dir, exist_ok=True)
357+
pdf_response = httpx.get(response["url"], timeout=60.0)
358+
pdf_response.raise_for_status()
359+
output_path = os.path.join(download_dir, response["fileName"])
360+
with open(output_path, "wb") as f:
361+
f.write(pdf_response.content)
362+
return response
363+
279364
def start_run_simulation(
280365
self, project: ComBuilding, project_id: Optional[int] = None
281366
) -> str:
@@ -312,7 +397,7 @@ def start_run_simulation(
312397
for wall in ag_Walls:
313398
for uvalue in updated_assembly_uvalues.get("agWall", []):
314399
if wall.assemblyType == uvalue["description"]:
315-
wall.effectiveUFactor = float(uvalue["propUValue"])
400+
wall.effectiveUFactor = float(uvalue["effectiveUFactor"])
316401
wall.propUValue = float(uvalue["propUValue"])
317402
for roof in roofs:
318403
for uvalue in updated_assembly_uvalues.get("roof", []):

0 commit comments

Comments
 (0)