Skip to content

Commit

Permalink
Merge pull request #132 from oemof/fix/logger-usage
Browse files Browse the repository at this point in the history
Fix suboptimal usage of the logging module
  • Loading branch information
jnettels authored Oct 23, 2023
2 parents 63c2f75 + 8f5e74d commit c6aeaef
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 24 deletions.
20 changes: 11 additions & 9 deletions dhnx/gistools/connect_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

from . import geometry_operations as go

logger = logging.getLogger(__name__) # Create a logger for this module


def line_of_point(point, gdf_lines):
"""Gets index of geometry of a GeoDataFrame, a point is located next to,
Expand Down Expand Up @@ -209,7 +211,7 @@ def create_object_connections(points, lines, tol_distance=1):
if n_p in supply_line_points:
# case that nearest point is a line ending

logging.debug(
logger.debug(
'Connect buildings... id {}: '
'Connected to supply line ending (nearest point)'.format(index)
)
Expand All @@ -229,7 +231,7 @@ def create_object_connections(points, lines, tol_distance=1):
# line is split, no line ending is close to the nearest point
# this also means the original supply line needs to be deleted

logging.debug(
logger.debug(
'Connect buildings... id {}: Supply line split'.format(index))

con_line = LineString([n_p, house_geo])
Expand All @@ -251,7 +253,7 @@ def create_object_connections(points, lines, tol_distance=1):
else:
# case that one or both line endings are closer than tolerance
# thus, the next line ending is chosen
logging.debug(
logger.debug(
'Connect buildings... id {}: Connected to Supply line '
'ending due to tolerance'.format(index))

Expand All @@ -264,7 +266,7 @@ def create_object_connections(points, lines, tol_distance=1):
gpd.GeoDataFrame(geometry=[con_line], crs=lines.crs)],
ignore_index=True)

logging.info('Connection of buildings completed.')
logger.info('Connection of buildings completed.')

return conn_lines, lines

Expand Down Expand Up @@ -372,7 +374,7 @@ def run_point_method_boundary(
Updated connection lines from street to each producer point.
"""
logging.info('Run "boundary" method for finding the building connections')
logger.info('Run "boundary" method for finding the building connections')
# Cut the part off of each "line_consumer" that is within the building
# polygon. As a result, the heating grid will only reach to the wall of
# the building.
Expand Down Expand Up @@ -451,14 +453,14 @@ def check_duplicate_geometries(gdf):
idx = gdf.duplicated(subset="geometry")
try:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(dpi=200)
fig, ax = plt.subplots(dpi=400)
gdf.loc[~idx].plot(ax=ax, color='green')
gdf.loc[idx].plot(ax=ax, color='red')
plt.title("Red are duplicate geometries. Please fix!")
plt.show()
except ImportError:
logging.info("Install matplotlib to show a plot of the duplicate "
"geometries.")
logger.info("Install matplotlib to show a plot of the duplicate "
"geometries.")
raise ValueError("GeoDataFrame has {} duplicate geometries"
.format(len(gdf.loc[idx])))

Expand Down Expand Up @@ -599,7 +601,7 @@ def process_geometry(lines, consumers, producers,
lines_all = go.insert_node_ids(lines_all, points_all)

lines_all['length'] = lines_all.length
logging.info(
logger.info(
"Total line length is {:.0f} m".format(lines_all['length'].sum()))

# Convert all MultiLineStrings to LineStrings
Expand Down
13 changes: 8 additions & 5 deletions dhnx/gistools/geometry_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import matplotlib.pyplot as plt
import pandas as pd

logger = logging.getLogger(__name__) # Create a logger for this module


def create_forks(lines):
"""
Expand Down Expand Up @@ -173,17 +175,17 @@ def check_double_points(gdf, radius=0.001, id_column=None):
else:
print_name = c[id_column]

logging.info(
logger.info(
'Node {} has a near neighbour! '
'Distance {}'.format(print_name, point.distance(x2))
)

count += 1

if count > 0:
logging.info('Number of duplicated points: ', count)
logger.info('Number of duplicated points: ', count)
else:
logging.info(
logger.info(
'Check passed: No points with a distance closer than {}'.format(radius))

return l_ids
Expand Down Expand Up @@ -304,11 +306,12 @@ def weld_segments(gdf_line_net, gdf_line_gen, gdf_line_houses,
gdf_line_houses, debug_plotting)
# Now do all of this recursively
while len(gdf_line_net_new) < len(gdf_line_net_last):
logging.info('Welding lines... reduced from {} to {} lines'.format(
logger.info('Welding lines... reduced from {} to {} lines'.format(
len(gdf_line_net_last), len(gdf_line_net_new)))
gdf_line_net_last = gdf_line_net_new
gdf_line_net_new = _weld_segments(gdf_line_net_new, gdf_line_gen,
gdf_line_houses, debug_plotting)
logger.info('Welding lines... done')
return gdf_line_net_new


Expand Down Expand Up @@ -517,6 +520,6 @@ def check_crs(gdf, crs=4647):
"""
if gdf.crs.to_epsg() != crs:
gdf.to_crs(epsg=crs, inplace=True)
logging.info('CRS of GeoDataFrame converted to EPSG:{0}'.format(crs))
logger.info('CRS of GeoDataFrame converted to EPSG:{0}'.format(crs))

return gdf
18 changes: 10 additions & 8 deletions dhnx/optimization/optimization_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from dhnx.optimization.dhs_nodes import add_nodes_dhs
from dhnx.optimization.dhs_nodes import add_nodes_houses

logger = logging.getLogger(__name__) # Create a logger for this module


class OemofOperationOptimizationModel(OperationOptimizationModel):
r"""
Expand Down Expand Up @@ -341,31 +343,31 @@ def setup_oemof_es(self):
periods=self.settings['num_ts'],
freq=self.settings['frequence'])

logging.info('Initialize the energy system')
logger.info('Initialize the energy system')

self.es = solph.EnergySystem(
timeindex=date_time_index,
infer_last_interval=True,
)

logging.info('Create oemof objects')
logger.info('Create oemof objects')

# add houses and generation
for typ in ['consumers', 'producers']:
self.nodes, self.buses = add_nodes_houses(
self, self.nodes, self.buses, typ)

logging.info('Producers, Consumers Nodes appended.')
logger.info('Producers, Consumers Nodes appended.')

# add heating infrastructure
self.nodes, self.buses = add_nodes_dhs(self, self.settings, self.nodes,
self.buses)
logging.info('DHS Nodes appended.')
logger.info('DHS Nodes appended.')

# add nodes and flows to energy system
self.es.add(*self.nodes)

logging.info('Energysystem has been created')
logger.info('Energysystem has been created')

if self.settings['print_logging_info']:
print("*********************************************************")
Expand Down Expand Up @@ -401,15 +403,15 @@ def setup(self):
def solve(self):
"""Builds the oemof.solph.Model of the energysystem *es*."""

logging.info('Build the operational model')
logger.info('Build the operational model')
self.om = solph.Model(self.es)

if self.settings['solve_kw'] is None:
s_kw = {"tee": True}
else:
s_kw = self.settings['solve_kw']

logging.info('Solve the optimization problem')
logger.info('Solve the optimization problem')
self.om.solve(
solver=self.settings['solver'],
solve_kwargs=s_kw,
Expand All @@ -418,7 +420,7 @@ def solve(self):
if self.settings['write_lp_file']:
filename = os.path.join(
helpers.extend_basic_path('lp_files'), 'DHNx.lp')
logging.info('Store lp-file in %s', filename)
logger.info('Store lp-file in %s', filename)
self.om.write(filename, io_options={'symbolic_solver_labels': True})

self.es.results['main'] = solph.processing.results(self.om)
Expand Down
4 changes: 2 additions & 2 deletions dhnx/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from cartopy.io.img_tiles import Stamen

except ImportError:
logging.info("Cartopy is not installed. Background maps will not be drawn.")
logger.info("Cartopy is not installed. Background maps will not be drawn.")
cartopy_installed = False


Expand Down Expand Up @@ -227,7 +227,7 @@ def draw(self, bgcolor='w', no_axis=False, background_map=False,
"""
if background_map:
if not cartopy_installed:
logging.warning('To draw background map, cartopy must be installed.')
logger.warning('To draw background map, cartopy must be installed.')
background_map = False

if background_map:
Expand Down

0 comments on commit c6aeaef

Please sign in to comment.