Skip to content

Commit 0255cca

Browse files
committed
Breakout ecm_prep shared methods and variable classes in separate modules.
1 parent cf69d2a commit 0255cca

File tree

6 files changed

+2137
-2143
lines changed

6 files changed

+2137
-2143
lines changed

scout/config.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99

1010

1111
class LogConfig:
12-
"""Configure the logger
13-
"""
12+
"""Configure the logger"""
1413

1514
@staticmethod
1615
def configure_logging():

scout/ecm_prep.py

Lines changed: 34 additions & 2087 deletions
Large diffs are not rendered by default.

scout/ecm_prep_vars.py

Lines changed: 1975 additions & 0 deletions
Large diffs are not rendered by default.

scout/run.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
import numpy_financial as npf
1414
from datetime import datetime
1515
from scout.plots import run_plot
16-
from scout.config import FilePaths as fp
17-
from scout.config import Config
16+
from scout.config import Config, FilePaths as fp
17+
from scout.utils import PrintFormat as fmt
1818
import warnings
1919

2020

@@ -5022,9 +5022,6 @@ def main(opts: argparse.NameSpace): # noqa: F821
50225022
of key results to an output JSON.
50235023
"""
50245024

5025-
# Set function that only prints message when in verbose mode
5026-
verboseprint = print if opts.verbose else lambda *a, **k: None
5027-
50285025
# Raise numpy errors as exceptions
50295026
numpy.seterr('raise')
50305027
# Initialize user opts variable (elements: S-S calculation method;
@@ -5268,7 +5265,7 @@ def main(opts: argparse.NameSpace): # noqa: F821
52685265
# Reset measure fuel split attribute to imported values
52695266
m.eff_fs_splt = meas_eff_fs_data
52705267
# Print data import message for each ECM if in verbose mode
5271-
verboseprint("Imported ECM '" + m.name + "' competition data")
5268+
fmt.verboseprint(opts.verbose, f"Imported ECM {m.name} competition data")
52725269

52735270
# Import total absolute heating and cooling energy use data, used in
52745271
# removing overlaps between supply-side and demand-side heating/cooling
@@ -5355,12 +5352,12 @@ def main(opts: argparse.NameSpace): # noqa: F821
53555352
try:
53565353
elec_carb = elec_cost_carb['CO2 intensity of electricity']['data']
53575354
elec_cost = elec_cost_carb['End-use electricity price']['data']
5358-
fmt = True # Boolean for indicating data key substructure
5355+
format_data = True # Boolean for indicating data key substructure
53595356
except KeyError:
53605357
# Data are structured as in the site_source_co2_conversions files
53615358
elec_carb = elec_cost_carb['electricity']['CO2 intensity']['data']
53625359
elec_cost = elec_cost_carb['electricity']['price']['data']
5363-
fmt = False
5360+
format_data = False
53645361

53655362
# Determine regions and building types used by active measures for
53665363
# aggregating onsite generation data
@@ -5401,7 +5398,7 @@ def variable_depth_dict(): return defaultdict(variable_depth_dict)
54015398
else:
54025399
bt_bin = 'commercial'
54035400
# Get CO2 intensity and electricity cost data and convert units
5404-
if fmt: # Data (and data structure) from emm_region files
5401+
if format_data: # Data (and data structure) from emm_region files
54055402
# Convert Mt/TWh to Mt/MMBtu
54065403
carbtmp = {k: elec_carb[cz].get(k, 0)/3.41214e6
54075404
for k in elec_carb[cz].keys()}

scout/utils.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import json
2+
import numpy
3+
from pathlib import Path, PurePath
4+
5+
6+
class JsonIO:
7+
@classmethod
8+
def load_json(cls, filepath: Path) -> dict:
9+
"""Loads data from a .json file
10+
11+
Args:
12+
filepath (pathlib.Path): filepath of .json file
13+
14+
Returns:
15+
dict: .json data as a dict
16+
"""
17+
with open(filepath, 'r') as handle:
18+
try:
19+
data = json.load(handle)
20+
except ValueError as e:
21+
raise ValueError(f"Error reading in '{filepath}': {str(e)}") from None
22+
return data
23+
24+
@classmethod
25+
def dump_json(cls, data, filepath: Path):
26+
"""Export data to .json file
27+
28+
Args:
29+
data: data to write to .json file
30+
filepath (pathlib.Path): filepath of .json file
31+
"""
32+
with open(filepath, "w") as handle:
33+
json.dump(data, handle, indent=2, cls=MyEncoder)
34+
35+
36+
class MyEncoder(json.JSONEncoder):
37+
"""Convert numpy arrays to list for JSON serializing."""
38+
39+
def default(self, obj):
40+
"""Modify 'default' method from JSONEncoder."""
41+
# Case where object to be serialized is numpy array
42+
if isinstance(obj, numpy.ndarray):
43+
return obj.tolist()
44+
if isinstance(obj, PurePath):
45+
return str(obj)
46+
# All other cases
47+
else:
48+
return super(MyEncoder, self).default(obj)
49+
50+
51+
class PrintFormat:
52+
"""Class for customizing print messages."""
53+
54+
@classmethod
55+
def custom_showwarning(cls, message, category, filename, lineno, file=None, line=None):
56+
"""Define a custom warning message format."""
57+
# Other message details suppressed because error location and type are not relevant
58+
print(message)
59+
60+
@classmethod
61+
def verboseprint(cls, verbose, msg):
62+
"""Print input message when the code is run in verbose mode.
63+
64+
Args:
65+
verbose (boolean): Indicator of verbose mode
66+
msg (string): Message to print to console when in verbose mode
67+
68+
Returns:
69+
Printed console message when code is run in verbose mode.
70+
"""
71+
print(msg) if verbose else lambda *a, **k: None
72+
73+
@classmethod
74+
def format_console_list(cls, list_to_format):
75+
return [f" {elem}\n" for elem in list_to_format]

0 commit comments

Comments
 (0)