Skip to content

Commit

Permalink
Fixed logging formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
mrvisscher committed Aug 8, 2024
1 parent 4aa4ed7 commit 91afaca
Show file tree
Hide file tree
Showing 16 changed files with 40 additions and 56 deletions.
2 changes: 1 addition & 1 deletion activity_browser/bwutils/calculations.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def do_LCA_calculations(data: dict):
QApplication.restoreOverrideCursor()
raise CriticalCalculationError
else:
log.error("Calculation type must be: simple or scenario. Given:", cs_name)
log.error(f"Calculation type must be: simple or scenario. Given: {cs_name}")
raise ValueError

mlca.calculate()
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/bwutils/commontasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def cleanup_deleted_bw_projects() -> None:
NOTE: This cannot be done from within the AB.
"""
n_dir = bd.projects.purge_deleted_directories()
log.info("Deleted {} unused project directories!".format(n_dir))
log.info(f"Deleted {n_dir} unused project directories!")


# Database
Expand Down
12 changes: 5 additions & 7 deletions activity_browser/bwutils/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,13 @@ def add_metadata(self, db_names_list: list) -> None:
dfs = list()
dfs.append(self.dataframe)
log.debug(
"Current shape and databases in the MetaDataStore:",
self.dataframe.shape,
self.databases,
f"Current shape and databases in the MetaDataStore: {self.dataframe.shape} {self.databases}"
)
for db_name in new:
if db_name not in bd.databases:
raise ValueError("This database does not exist:", db_name)

log.debug("Adding:", db_name)
log.debug(f"Adding: {db_name}")
self.databases.add(db_name)

# make a temporary DataFrame and index it by ('database', 'code') (like all brightway activities)
Expand Down Expand Up @@ -130,7 +128,7 @@ def update_metadata(self, key: tuple) -> None:
) # if this does not work, it has been deleted (see except:).
except (UnknownObject, ActivityDataset.DoesNotExist):
# Situation 1: activity has been deleted (metadata needs to be deleted)
log.debug("Deleting activity from metadata:", key)
log.debug(f"Deleting activity from metadata: {key}")
self.dataframe.drop(key, inplace=True, errors="ignore")
# print('Dimensions of the Metadata:', self.dataframe.shape)
return
Expand All @@ -143,7 +141,7 @@ def update_metadata(self, key: tuple) -> None:
if (
key in self.dataframe.index
): # Situation 2: activity has been modified (metadata needs to be updated)
log.debug("Updating activity in metadata: ", act, key)
log.debug(f"Updating activity in metadata: {key}")
for col in self.dataframe.columns:
if col in self.CLASSIFICATION_SYSTEMS:
# update classification data
Expand All @@ -156,7 +154,7 @@ def update_metadata(self, key: tuple) -> None:
self.dataframe.at[key, 'key'] = act.key

else: # Situation 3: Activity has been added to database (metadata needs to be generated)
log.debug('Adding activity to metadata:', act, key)
log.debug(f'Adding activity to metadata: {key}')
df_new = pd.DataFrame([act.as_dict()], index=pd.MultiIndex.from_tuples([act.key]))
df_new['key'] = [act.key]
if act.get('classifications', False): # add classification data if present
Expand Down
15 changes: 5 additions & 10 deletions activity_browser/bwutils/montecarlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,8 @@ def calculate(self, iterations=10, seed: int = None, **kwargs):
self.results[iteration, row, col] = self.lca.score

log.info(
"Monte Carlo LCA: finished {} iterations for {} reference flows and {} methods in {} seconds.".format(
iterations,
len(self.func_units),
len(self.methods),
np.round(time() - start, 2),
)
f"Monte Carlo LCA: finished {iterations} iterations for {len(self.func_units)} reference flows and "
f"{len(self.methods)} methods in {np.round(time() - start, 2)} seconds."
)

@property
Expand All @@ -272,10 +268,10 @@ def get_results_by(self, act_key=None, method=None):

if act_key:
act_index = self.activity_index.get(act_key)
log.info("Activity key provided:", act_key, act_index)
log.info(f"Activity key provided: {act_key} {act_index}")
if method:
method_index = self.method_index.get(method)
log.info("Method provided", method, method_index)
log.info(f"Method provided: {method} {method_index}")

if not act_key and not method:
return self.results
Expand All @@ -284,7 +280,6 @@ def get_results_by(self, act_key=None, method=None):
elif method and not act_key:
return np.squeeze(self.results[:, :, method_index])
elif method and act_key:
log.info(act_index, method_index)
return np.squeeze(self.results[:, act_index, method_index])

def get_results_dataframe(self, act_key=None, method=None, labelled=True):
Expand Down Expand Up @@ -335,7 +330,7 @@ def get_labels(
def perform_MonteCarlo_LCA(project="default", cs_name=None, iterations=10):
"""Performs Monte Carlo LCA based on a calculation setup and returns the
Monte Carlo LCA object."""
log.info("-- Monte Carlo LCA --\n Project:", project, "CS:", cs_name)
log.info(f"-- Monte Carlo LCA --\n Project: {project} CS: {cs_name}")
bd.projects.set_current(project)

# perform Monte Carlo simulation
Expand Down
14 changes: 4 additions & 10 deletions activity_browser/bwutils/sensitivity_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_lca(fu, method):
lca = bc.LCA(fu, method=method)
lca.lci()
lca.lcia()
log.info("Non-stochastic LCA score:", lca.score)
log.info(f"Non-stochastic LCA score: {lca.score}")

# add reverse dictionaries
lca.activity_dict_rev, lca.product_dict_rev, lca.biosphere_dict_rev = (
Expand Down Expand Up @@ -230,7 +230,7 @@ def get_parameters_DF(mc):
if bool(mc.parameter_data): # returns False if dict is empty
dfp = pd.DataFrame(mc.parameter_data).T
dfp["GSA name"] = "P: " + dfp["name"]
log.info("PARAMETERS:", len(dfp))
log.info(f"PARAMETERS: {len(dfp)}")
return dfp
else:
log.info("PARAMETERS: None included.")
Expand Down Expand Up @@ -334,14 +334,8 @@ def perform_GSA(
return None

log.info(
"-- GSA --\n Project:",
bd.projects.current,
"CS:",
self.mc.cs_name,
"Activity:",
self.activity,
"Method:",
self.method,
f"-- GSA --\n Project: {bd.projects.current} CS: {self.mc.cs_name} "
f"Activity: {self.activity} Method: {self.method}",
)

# get non-stochastic LCA object with reverse dictionaries
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/bwutils/superstructure/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def _time_it_(func):
def wrapper(*args):
now = time.time()
result = func(*args)
log.info(f"{func} -- " + str(time.time() - now))
log.info(f"{func} -- {time.time() - now}")
return result

return wrapper
4 changes: 2 additions & 2 deletions activity_browser/layouts/panels/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def show_tab(self, tab_name):
"""Makes existing tab visible."""
if tab_name in self.tabs:
tab = self.tabs[tab_name]
log.info("+showing tab:", tab_name)
log.info(f"+showing tab: {tab_name}")
tab.setVisible(True)
self.addTab(tab, tab_name)
self.select_tab(tab)
Expand All @@ -72,7 +72,7 @@ def get_tab_name(self, obj):
if len(tab_names) == 1:
return tab_names[0]
else:
log.warning("found", len(tab_names), "occurences of this object.")
log.warning(f"found {len(tab_names)} occurrences of this object.")

def get_tab_name_from_index(self, index):
"""Return the name of a tab based on its index."""
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/layouts/panels/right.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def show_tab(self, tab_name):
"""
if tab_name in self.tabs:
tab = self.tabs[tab_name]
log.info("+showing tab:", tab_name)
log.info(f"+showing tab: {tab_name}")
tab.setVisible(True)
self.insertTab(self.tab_order[tab_name], tab, tab_name)
self.select_tab(tab)
Expand Down
10 changes: 5 additions & 5 deletions activity_browser/layouts/tabs/LCA_results_tabs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1326,12 +1326,12 @@ def calculate_mc_lca(self):
iterations = int(self.iterations.text())
seed = None
if self.seed.text():
log.info("SEED: ", self.seed.text())
log.info(f"SEED: {self.seed.text()}")
try:
seed = int(self.seed.text())
except ValueError as e:
log.error(
"Seed value must be an integer number or left empty.", error=e
"Seed value must be an integer number or left empty.", exc_info=e
)
QMessageBox.warning(
self,
Expand All @@ -1356,7 +1356,7 @@ def calculate_mc_lca(self):
InvalidParamsError
) as e: # This can occur if uncertainty data is missing or otherwise broken
# print(e)
log.error(error=e)
log.error(e)
QMessageBox.warning(
self, "Could not perform Monte Carlo simulation", str(e)
)
Expand Down Expand Up @@ -1630,7 +1630,7 @@ def calculate_gsa(self):
)
# self.update_mc()
except Exception as e: # Catch any error...
log.error(error=e)
log.error(e)
message = str(e)
message_addition = ""
if message == "singular matrix":
Expand Down Expand Up @@ -1709,7 +1709,7 @@ def set_mc(self, mc, iterations=20):
self.iterations = iterations

def run(self):
log.info("Starting new Worker Thread. Iterations:", self.iterations)
log.info(f"Starting new Worker Thread. Iterations: {self.iterations}")
self.mc.calculate(iterations=self.iterations)
# res = bw.GraphTraversal().calculate(self.demand, self.method, self.cutoff, self.max_calc)
log.info("in thread {}".format(QtCore.QThread.currentThread()))
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/ui/tables/models/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def create_row(self, exchange) -> dict:
return row
except DoesNotExist as e:
# The input activity does not exist. remove the exchange.
log.warning(f"Broken exchange: {e}, removing.")
log.warning(f"Broken exchange: {exchange}, removing.")
actions.ExchangeDelete.run([exchange])

def get_exchange(self, proxy: QModelIndex) -> ExchangeProxyBase:
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/ui/tables/models/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def sync(self, db_name: str, df: pd.DataFrame = None, query=None) -> None:

if df is not None:
# skip the rest of the sync here if a dataframe is directly supplied
log.debug("Pandas Dataframe passed to sync.", df.shape)
log.debug("Pandas Dataframe passed to sync.")
self._dataframe = df
self.updated.emit()
return
Expand Down
2 changes: 1 addition & 1 deletion activity_browser/ui/tables/models/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ def build_exchanges(cls, act_param, parent: TreeItem) -> None:
parent.appendChild(item)
except DoesNotExist as e:
# The exchange is coming from a deleted database, remove it
log.warning(f"Broken exchange: {e}, removing.")
log.warning(f"Broken exchange: {exc}, removing.")
actions.ExchangeDelete.run([exc])


Expand Down
2 changes: 1 addition & 1 deletion activity_browser/ui/web/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def node_clicked(self, click_text: str):
click_dict["database"],
click_dict["id"],
) # since JSON does not know tuples
log.info("Click information: ", click_dict) # TODO click_dict needs correcting
log.info(f"Click information: {click_dict}") # TODO click_dict needs correcting
self.update_graph.emit(click_dict)

@Slot(str, name="download_triggered")
Expand Down
11 changes: 5 additions & 6 deletions activity_browser/ui/web/navigator.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,12 @@ def is_expansion_mode(self) -> bool:
def toggle_navigation_mode(self):
mode = next(self.navigation_label)
self.button_navigation_mode.setText(mode)
log.info("Switched to:", mode)
log.info(f"Switched to: {mode}")
self.checkbox_remove_orphaned_nodes.setVisible(self.is_expansion_mode)
self.checkbox_direct_only.setVisible(self.is_expansion_mode)

def new_graph(self, key: tuple) -> None:
log.info("New Graph for key: ", key)
log.info(f"New Graph for key: {key}")
self.graph.new_graph(key)
self.send_json()

Expand Down Expand Up @@ -206,10 +206,10 @@ def update_graph(self, click_dict: dict) -> None:
self.new_graph(key)
else:
if keyboard["alt"]: # delete node
log.info("Deleting node: ", key)
log.info(f"Deleting node: {key}")
self.graph.reduce_graph(key)
else: # expansion mode
log.info("Expanding graph: ", key)
log.info(f"Expanding graph: {key}")
if keyboard["shift"]: # downstream expansion
log.info("Adding downstream nodes.")
self.graph.expand_graph(key, down=True)
Expand Down Expand Up @@ -402,9 +402,8 @@ def format_as_weighted_edges(exchanges, activity_objects=False):
count = 1
for count, key in enumerate(orphaned_node_ids, 1):
act = get_activity(key)
log.info(act["name"], act["location"])
self.nodes.remove(act)
log.info("\nRemoved ORPHANED nodes:", count)
log.info(f"Removed ORPHANED nodes: {count}")

# update edges again to remove those that link to nodes that have been deleted
self.remove_outside_exchanges()
Expand Down
9 changes: 4 additions & 5 deletions activity_browser/ui/wizards/db_import_wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ def run(self):
try:
login_success, error_message = self.downloader.login()
except Exception as e:
log.error(str(e), exc_info=True)
log.error(e)
import_signals.login_success.emit(False)
msg = str(e)
cs = ei.CachedStorage()
Expand Down Expand Up @@ -1339,7 +1339,7 @@ def _efficient_write_many_data(self, *args, **kwargs):

def _efficient_write_dataset(self, *args, **kwargs):
if import_signals.cancel_sentinel:
log.info(f"\nWriting canceled at position {self._ab_current_index}!")
log.info(f"Writing canceled at position {self._ab_current_index}")
raise errors.ImportCanceledError
self._ab_current_index += 1
import_signals.db_progress.emit(self._ab_current_index, self._ab_total)
Expand Down Expand Up @@ -1450,9 +1450,8 @@ def login(self) -> (bool, typing.Optional[typing.Tuple[str, str]]):
error_message = None
if e.response.status_code != 401:
log.error(
"Unexpected status code (%d) received when trying to list ecoinvent_versions, response: %s",
e.response.status_code,
e.response.text,
f"Unexpected status code {e.response.status_code} received when trying to list ecoinvent_versions, "
f"response: {e.response.text}",
)
error_message = (
"Unexpected Problem",
Expand Down
5 changes: 2 additions & 3 deletions activity_browser/ui/wizards/settings_wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ def save_settings(self):
if field and field != current_bw_dir:
ab_settings.custom_bw_dir = field
ab_settings.current_bw_dir = field
log.info("Saved startup brightway directory as: ", field)
log.info(f"Saved startup brightway directory as: {field}")

# project
field_project = self.field("startup_project")
current_startup_project = ab_settings.startup_project
if field_project and field_project != current_startup_project:
new_startup_project = field_project
ab_settings.startup_project = new_startup_project
log.info("Saved startup project as: ", new_startup_project)
log.info(f"Saved startup project as: {new_startup_project}")

ab_settings.write_settings()
projects.switch_dir(field)
Expand Down Expand Up @@ -234,7 +234,6 @@ def update_project_combo(self, initialization: bool = True, path: str = None):
self.startup_project_combobox.addItems(self.project_names)
else:
log.warning("No projects found in this directory.")
# return
if ab_settings.startup_project in self.project_names:
self.startup_project_combobox.setCurrentText(ab_settings.startup_project)
else:
Expand Down

0 comments on commit 91afaca

Please sign in to comment.