Skip to content

Commit 11e3508

Browse files
fix(tools): type hints and API updates for python scripts
1 parent 6b1457f commit 11e3508

9 files changed

Lines changed: 40 additions & 35 deletions

tools/ashrae_140_test_harness.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,9 @@ def run_rust_tests(
128128
duration = (datetime.now() - start_time).total_seconds()
129129

130130
# Parse test output
131-
total, passed, failed, skipped = self._parse_cTest_output(result.stdout)
131+
total, passed, failed, skipped = self._parse_cargo_test_output(
132+
result.stdout
133+
)
132134

133135
suite_result = TestSuiteResult(
134136
suite_name=test_pattern,

tools/ep_oracle.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import subprocess
1818
import sys
1919
from pathlib import Path
20-
from typing import Dict, Optional
20+
from typing import Any, Dict, Optional
2121

2222

2323
class EnergyPlusOracle:
@@ -382,16 +382,16 @@ def run_energyplus(
382382
Returns:
383383
Dictionary with simulation results
384384
"""
385-
output_dir = Path(output_dir)
386-
output_dir.mkdir(parents=True, exist_ok=True)
385+
output_path = Path(output_dir)
386+
output_path.mkdir(parents=True, exist_ok=True)
387387

388388
# Build EnergyPlus command
389389
ep_cmd = [
390390
str(self.ep_path / "energyplus"),
391391
"-w",
392392
str(epw_path),
393393
"-d",
394-
str(output_dir),
394+
str(output_path),
395395
"-r", # Read variables
396396
idf_path,
397397
]
@@ -412,17 +412,17 @@ def run_energyplus(
412412
raise RuntimeError(f"EnergyPlus simulation failed: {result.returncode}")
413413

414414
# Parse SQL output
415-
sql_file = output_dir / "eplusout.sql"
415+
sql_file = output_path / "eplusout.sql"
416416
if sql_file.exists():
417417
return self._parse_sql_results(sql_file)
418418
else:
419419
raise RuntimeError("EnergyPlus SQL output file not found")
420420

421-
def _parse_sql_results(self, sql_file: Path) -> Dict:
421+
def _parse_sql_results(self, sql_file: Path) -> Dict[str, Any]:
422422
"""Parse EnergyPlus SQL output."""
423423
import sqlite3
424424

425-
results = {}
425+
results: Dict[str, Any] = {}
426426

427427
try:
428428
conn = sqlite3.connect(sql_file)
@@ -529,14 +529,14 @@ def compare_results(
529529
ep_results: Dict,
530530
tolerance_abs: float = 1.0,
531531
tolerance_rel: float = 0.05,
532-
) -> Dict:
532+
) -> Dict[str, Any]:
533533
"""
534534
Compare Fluxion and EnergyPlus results.
535535
536536
Returns:
537537
Comparison report with metrics
538538
"""
539-
report = {
539+
report: Dict[str, Any] = {
540540
"passed": True,
541541
"metrics": {},
542542
"details": {},

tools/geometry_extraction.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -959,7 +959,7 @@ def to_cta_tensors(self, geometry: BuildingGeometry) -> Dict[str, np.ndarray]:
959959
Returns:
960960
Dictionary of numpy arrays
961961
"""
962-
tensors = {}
962+
tensors: Dict[str, np.ndarray] = {}
963963

964964
# Zone coordinates tensor
965965
# Format: [x1, y1, x2, y2, ..., x8, y8, floor_height, ceiling_height, area, volume, perimeter, zone_id]

tools/integrate_ml_surrogate_pipeline.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -358,14 +358,13 @@ def forward(self, x):
358358
# Export to ONNX
359359
torch.onnx.export(
360360
model,
361-
dummy_input,
362-
output_path,
361+
(dummy_input,),
362+
str(output_path),
363363
input_names=["input"],
364364
output_names=["output"],
365365
dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}},
366366
opset_version=17,
367367
)
368-
369368
logger.info(f"✓ Model exported successfully to {output_path}")
370369
return True
371370

tools/physics_informed_loss.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ class PhysicsInformedLoss(nn.Module):
169169
Physics-informed loss function that combines MSE with physics constraints.
170170
"""
171171

172+
min_temp: torch.Tensor
173+
max_temp: torch.Tensor
174+
172175
def __init__(
173176
self,
174177
mse_weight: float = 1.0,

tools/tests/test_train_integration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
# Add project root to path
1010
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
1111

12-
from tools import train_surrogate
1312
from tools.data_gen import geometry, simulation
13+
from tools.train_ml_surrogate import train_surrogate
1414

1515

1616
class TestTrainIntegration(unittest.TestCase):

tools/train_ensemble_surrogates.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def __init__(
3939
torch.manual_seed(seed)
4040
np.random.seed(seed)
4141

42-
layers = []
42+
layers: List[nn.Module] = []
4343
prev_dim = input_dim
4444

4545
for hidden_dim in hidden_dims:
@@ -153,8 +153,8 @@ def export_onnx(model: nn.Module, sample_input: np.ndarray, output_path: Path):
153153

154154
torch.onnx.export(
155155
model,
156-
dummy_input,
157-
output_path,
156+
(dummy_input,),
157+
str(output_path),
158158
input_names=["input"],
159159
output_names=["output"],
160160
dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}},
@@ -253,20 +253,19 @@ def evaluate_ensemble(
253253
X_t = torch.from_numpy(X)
254254

255255
# Get predictions from all models
256-
all_predictions = []
256+
all_predictions_list = []
257257
with torch.no_grad():
258258
for model in models:
259259
pred = model(X_t).numpy()
260-
all_predictions.append(pred)
260+
all_predictions_list.append(pred)
261261

262-
all_predictions = np.array(
263-
all_predictions
262+
all_predictions_arr = np.array(
263+
all_predictions_list
264264
) # Shape: (num_models, num_samples, output_dim)
265265

266266
# Calculate ensemble statistics
267-
mean_pred = np.mean(all_predictions, axis=0)
268-
std_pred = np.std(all_predictions, axis=0)
269-
267+
mean_pred = np.mean(all_predictions_arr, axis=0)
268+
std_pred = np.std(all_predictions_arr, axis=0)
270269
# Calculate metrics
271270
mse = np.mean((y - mean_pred) ** 2)
272271
mae = np.mean(np.abs(y - mean_pred))

tools/train_ml_surrogate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ def train_surrogate(
370370
# Optimizer and loss
371371
optimizer = optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=1e-5)
372372
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
373-
optimizer, "min", patience=10, factor=0.5, verbose=True
373+
optimizer, "min", patience=10, factor=0.5
374374
)
375375
criterion = PhysicsLoss()
376376

tools/train_pinn.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
import time
3434
from dataclasses import dataclass, field
3535
from pathlib import Path
36-
from typing import Dict, List, Optional, Tuple
36+
from typing import Any, Dict, List, Optional, Tuple
3737

3838
import numpy as np
3939
import torch
@@ -126,7 +126,7 @@ def __init__(
126126
):
127127
super().__init__()
128128

129-
layers = []
129+
layers: List[nn.Module] = []
130130
prev_dim = input_dim
131131

132132
# First layer: input -> first hidden
@@ -477,13 +477,13 @@ def generate_training_data(
477477
Returns:
478478
Tuple of (inputs_dict, targets_array)
479479
"""
480-
X: Dict[str, List[float]] = {
480+
X: Dict[str, Any] = {
481481
"time": [],
482482
"t_outdoor": [],
483483
"q_solar": [],
484484
"q_internal": [],
485485
}
486-
y = []
486+
y: List[float] = []
487487

488488
for _ in range(n_samples):
489489
# Generate outdoor temperature profile (daily cycle with noise)
@@ -521,11 +521,12 @@ def generate_training_data(
521521
y.extend(t_indoor)
522522

523523
# Convert to arrays
524+
X_array: Dict[str, np.ndarray] = {}
524525
for key in X:
525-
X[key] = np.array(X[key], dtype=np.float32)
526-
y = np.array(y, dtype=np.float32).reshape(-1, 1)
526+
X_array[key] = np.array(X[key], dtype=np.float32)
527+
y_array = np.array(y, dtype=np.float32).reshape(-1, 1)
527528

528-
return X, y
529+
return X_array, y_array
529530

530531
def generate_collocation_points(
531532
self,
@@ -800,8 +801,8 @@ def export_onnx(
800801
model.eval()
801802
torch.onnx.export(
802803
model,
803-
sample_input,
804-
output_path,
804+
(sample_input,),
805+
str(output_path),
805806
input_names=["input"],
806807
output_names=["t_indoor"],
807808
dynamic_axes={
@@ -810,6 +811,7 @@ def export_onnx(
810811
},
811812
opset_version=17,
812813
)
814+
813815
logger.info("ONNX export successful")
814816

815817

0 commit comments

Comments
 (0)