Skip to content

Commit 95fc731

Browse files
committed
print -> logging
1 parent b8287e6 commit 95fc731

File tree

10 files changed

+6167
-6144
lines changed

10 files changed

+6167
-6144
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ transistordatabase/__pycache__/
44
gpgit/
55
*.pyc
66
*.pdf
7+
*.html
8+
*.scl
79
build/
810
dist/
911
transistordatabase.egg-info/
@@ -18,3 +20,5 @@ database/
1820
output/
1921
.vscode/
2022
.venv/
23+
docs/_build
24+
dictionary.dic

template_example/template_example.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# imports
33
import transistordatabase as tdb
44
import os
5+
import logging
6+
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
57

68

79
# Template to generate a transistor
@@ -254,8 +256,8 @@ def template_example(database):
254256
# transistor methods #
255257
# transistor.wp.switch_v_channel, transistor.wp.switch_r_channel = transistor.calc_lin_channel(175, 15, 40, 'switch')
256258
# linearization at 175 degree, 15V gatevoltage, 40A channel current
257-
# print(f"{transistor.wp.switch_v_channel = } V")
258-
# print(f"{transistor.wp.switch_r_channel = } Ohm")
259+
# print(f"{transistor.wp.switch_v_channel=} V")
260+
# print(f"{transistor.wp.switch_r_channel=} Ohm")
259261
# print(transistor.calc_v_eoss())
260262
# transistor.plot_v_eoss()
261263
# transistor.plot_v_qoss()
@@ -306,18 +308,18 @@ def template_example(database):
306308
####################################
307309

308310
# update the database
309-
# db.update_from_fileexchange(True)
311+
db.update_from_fileexchange(True)
310312

311313
# print ALL database content
312-
# db.print_tdb()
314+
db.print_tdb()
313315

314316
# print database content of housing and datasheet hyperlink
315-
# db.print_tdb(['housing_type','datasheet_hyperlink'])
317+
db.print_tdb(['housing_type', 'datasheet_hyperlink'])
316318

317319
# load transistor
318320
# optional argument: collection. If no collection is specified, it connects to local TDB
319-
# transistor_loaded = db.load_transistor('CREE_C3M0016120K')
320-
# print(transistor_loaded.switch.t_j_max)
321+
transistor_loaded = db.load_transistor('CREE_C3M0016120K')
322+
print(transistor_loaded.switch.t_j_max)
321323

322324
# export to json
323325
# optional argument: path. If no path is specified, saves exports to local folder

transistordatabase/checker_functions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from __future__ import annotations
44
from typing import List, Dict
55
import numpy as np
6+
import logging
7+
logger = logging.getLogger(__name__)
68

79
def check_realnum(float_to_check: float) -> bool:
810
"""
@@ -201,6 +203,6 @@ def check_duplicates(current_items: List[Dict], item_to_append: Dict) -> bool:
201203
count += 1
202204
if count == len(c_item):
203205
msg = "Duplicate object detected: already present at index {0} of {1} object" .format(index, type(current_items).__name__)
204-
print(msg)
206+
logger.info(msg)
205207
return False
206208
return True

transistordatabase/data_classes.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
from datetime import datetime
77
import numpy as np
88
import numpy.typing as npt
9+
import logging
910

1011
# Local libraries
1112
from transistordatabase.checker_functions import check_float
1213
from transistordatabase.helper_functions import isvalid_dict, get_img_raw_data
1314

15+
logger = logging.getLogger(__name__)
16+
1417
class GateChargeCurve:
1518
"""A class to hold gate charge characteristics of switch which is added as a optional attribute inside switch class."""
1619

@@ -609,7 +612,7 @@ def get_plots(self, buffer_req: bool = False):
609612
:return: Respective plots are displayed if available else None is returned
610613
"""
611614
if self.graph_t_rthjc is None:
612-
print('No Foster impedance information exists!')
615+
logger.info('No Foster impedance information exists!')
613616
return None
614617
fig = plt.figure()
615618
ax = fig.add_subplot(111)

transistordatabase/database_manager.py

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,16 @@
1010
import requests
1111
import deepdiff
1212
import glob # Can this be removed?
13+
import logging
1314

1415
# Local libraries
1516
from transistordatabase.transistor import Transistor
1617
from transistordatabase.mongodb_handling import connect_local_tdb
1718
from transistordatabase.helper_functions import get_copy_transistor_name, isvalid_transistor_name, read_data_file, html_to_pdf, get_xml_data, compare_list
1819
from transistordatabase.checker_functions import check_float
1920

21+
logger = logging.getLogger(__name__)
22+
2023
class OperationMode(Enum):
2124
"""Operation mode definitions."""
2225

@@ -77,18 +80,18 @@ def set_operation_mode_json(self, json_folder_path: str = os.path.join(os.path.d
7780
os.makedirs(json_folder_path)
7881
self.json_folder = json_folder_path
7982
index_response = requests.get(index_url)
80-
print(index_response)
83+
logger.info(index_response)
8184
if not index_response.ok:
8285
raise Exception(f"Index file was not found. URL: {index_url}")
8386
for transistor_url in index_response.iter_lines():
8487
transistor_response = requests.get(transistor_url)
85-
print(transistor_url)
88+
logger.info(transistor_url)
8689

8790
# filename = transistor_url.split('/')[-1].decode()
8891
filename = transistor_url.decode().split('/')[-1]
89-
print(filename)
92+
logger.info(filename)
9093
if not transistor_response.ok:
91-
print(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
94+
logger.info(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
9295
continue
9396
else:
9497
transistor = self.convert_dict_to_transistor_object(transistor_response.json())
@@ -132,7 +135,7 @@ def save_transistor(self, transistor: Transistor, overwrite: bool = None) -> Non
132135
transistor_path = os.path.join(self.json_folder, f"{transistor.name}.json")
133136
if str(transistor.name) in os.listdir(self.json_folder):
134137
if overwrite is None:
135-
print(f"A transistor object with name {transistor.name} already exists. \
138+
logger.info(f"A transistor object with name {transistor.name} already exists. \
136139
If you want to override it please set the override argument to true, if you want to create a copy with a \
137140
different id please set it to false")
138141
return
@@ -151,7 +154,7 @@ def save_transistor(self, transistor: Transistor, overwrite: bool = None) -> Non
151154
elif self.operation_mode == OperationMode.MONGODB:
152155
if self.mongodb_collection.find_one({"_id": transistor._id}) is not None:
153156
if overwrite is None:
154-
print(f"A transistor object with id {transistor._id} already exists in the database. \
157+
logger.info(f"A transistor object with id {transistor._id} already exists in the database. \
155158
If you want to override it please set the override argument to true, if you want to create a copy with a \
156159
different id please set it to false")
157160
return
@@ -180,12 +183,12 @@ def delete_transistor(self, transistor_name: str) -> None:
180183
if file.endswith(".json") and file[:-5] == transistor_name and isvalid_transistor_name(file[:-5]):
181184
os.remove(os.path.join(self.json_folder, file))
182185
else:
183-
print(f"Can not find transistor with name {transistor_name} in the database. Therefore it cannot be deleted.")
186+
logger.info(f"Can not find transistor with name {transistor_name} in the database. Therefore it cannot be deleted.")
184187
elif self.operation_mode == OperationMode.MONGODB:
185188
if self.mongodb_collection.find_one({"name": transistor_name}) is not None:
186189
self.mongodb_collection.delete_one({"name": transistor_name})
187190
else:
188-
print(f"Can not find transistor with name {transistor_name} in the database. Therefore it cannot be deleted.")
191+
logger.info(f"Can not find transistor with name {transistor_name} in the database. Therefore it cannot be deleted.")
189192

190193
def load_transistor(self, transistor_name: str) -> Transistor:
191194
"""
@@ -205,7 +208,7 @@ def load_transistor(self, transistor_name: str) -> Transistor:
205208
if file_name.endswith(".json") and file_name.startswith(str(transistor_name)) and isvalid_transistor_name(file_name[:-5]):
206209
with open(os.path.join(self.json_folder, file_name), "r") as fd:
207210
return self.convert_dict_to_transistor_object(json.load(fd))
208-
print(f"Transitor with name {transistor_name} not found.")
211+
logger.info(f"Transitor with name {transistor_name} not found.")
209212
elif self.operation_mode == OperationMode.MONGODB:
210213
return self.convert_dict_to_transistor_object(self.mongodb_collection.find_one({"name": transistor_name}))
211214

@@ -271,15 +274,15 @@ def print_tdb(self, filters: List[str] = None) -> List[str]:
271274
for tran in returned_cursor:
272275
transistor = self.convert_dict_to_transistor_object(tran)
273276
transistor_list.append(transistor)
274-
print(transistor_list)
277+
logger.info(transistor_list)
275278
return transistor_list
276279
elif self.operation_mode == OperationMode.JSON:
277280
all_transistor_names = self.get_transistor_names_list()
278281
transistor_list = []
279282
for transistor_name in all_transistor_names:
280283
transistor = self.load_transistor(transistor_name)
281284
transistor_list.append(transistor)
282-
print(transistor_list)
285+
logger.info(transistor_list)
283286
return transistor_list
284287

285288
def update_from_fileexchange(self, overwrite: bool = True,
@@ -303,9 +306,9 @@ def update_from_fileexchange(self, overwrite: bool = True,
303306
:param housing_types_url: URL to the housing type file
304307
:type housing_types_url: str
305308
"""
306-
print("Note: Please make sure that you have installed the latest version of the transistor database, "
307-
"especially if the update_from_fileexchange()-method ends in an error. "
308-
"Find the latest version here: https://pypi.org/project/transistordatabase/")
309+
logger.info("Note: Please make sure that you have installed the latest version of the transistor database, "
310+
"especially if the update_from_fileexchange()-method ends in an error. "
311+
"Find the latest version here: https://pypi.org/project/transistordatabase/")
309312
# Read links from index_url
310313
index_response = requests.get(index_url)
311314
if not index_response.ok:
@@ -314,13 +317,13 @@ def update_from_fileexchange(self, overwrite: bool = True,
314317
for transistor_url in index_response.iter_lines():
315318
transistor_response = requests.get(transistor_url)
316319
if not transistor_response.ok:
317-
print(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
320+
logger.info(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
318321
continue
319322

320323
transistor = self.convert_dict_to_transistor_object(transistor_response.json())
321324
self.save_transistor(transistor, overwrite)
322325

323-
# Get module manufactuers and housing types if URLs are given
326+
# Get module manufacturers and housing types if URLs are given
324327
# Then overwrite local files and update lists
325328
if module_manufacturers_url is not None:
326329
module_manufacturers_response = requests.get(module_manufacturers_url)
@@ -331,7 +334,7 @@ def update_from_fileexchange(self, overwrite: bool = True,
331334
fd.write(module_manufacturers_response.text)
332335

333336
self.module_manufacturers = read_data_file(self.module_manufacturers_file_path)
334-
print("Updated module manufacturers.")
337+
logger.info("Updated module manufacturers.")
335338

336339
if housing_types_url is not None:
337340
housing_types_response = requests.get(housing_types_url)
@@ -342,7 +345,7 @@ def update_from_fileexchange(self, overwrite: bool = True,
342345
fd.write(housing_types_response.text)
343346

344347
self.housing_types = read_data_file(self.housing_types_file_path)
345-
print("Updated housing types.")
348+
logger.info("Updated housing types.")
346349

347350
def compare_with_fileexchange(self, index_url: str, output_file: str):
348351
"""
@@ -366,7 +369,7 @@ def compare_with_fileexchange(self, index_url: str, output_file: str):
366369
for transistor_url in index_response.iter_lines():
367370
transistor_response = requests.get(transistor_url)
368371
if not transistor_response.ok:
369-
print(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
372+
logger.info(f"Transistor with URL {transistor_url} couldn't be downloaded. Transistor was skipped.")
370373
continue
371374

372375
downloaded_transistor_dict = transistor_response.json()
@@ -389,9 +392,9 @@ def compare_with_fileexchange(self, index_url: str, output_file: str):
389392
diff_dict[not_found_transistor] = "Transistor exists in local database but is not on the given fileexchange."
390393

391394
if not diff_dict:
392-
print("The local database is equal to the given fileexchange database.")
395+
logger.info("The local database is equal to the given fileexchange database.")
393396
else:
394-
print("There are differences found between the local database and the given fileexchange database. Please have a look at the output file.")
397+
logger.info("There are differences found between the local database and the given fileexchange database. Please have a look at the output file.")
395398
with open(output_file, "w") as fd:
396399
json.dump(diff_dict, fd, indent=2)
397400

@@ -410,7 +413,7 @@ def export_all_datasheets(self, filter_list: list = None):
410413
if filter_list is not None:
411414
for item in filter_list:
412415
if item not in transistor_list:
413-
print("{0} transistor is not present in database".format(item))
416+
logger.info("{0} transistor is not present in database".format(item))
414417
else:
415418
filtered_list.append(item)
416419
else:
@@ -423,7 +426,7 @@ def export_all_datasheets(self, filter_list: list = None):
423426
paths_list.append(os.path.join(os.getcwd(), transistor.name + ".pdf"))
424427
html_to_pdf(html_list, pdf_name_list, paths_list)
425428
else:
426-
print("Nothing to export, please recheck inputs")
429+
logger.info("Nothing to export, please recheck inputs")
427430

428431
def convert_dict_to_transistor_object(self, transistor_dict: dict) -> Transistor:
429432
"""
@@ -693,7 +696,7 @@ def import_xml_data(files: Dict) -> Transistor:
693696
'r_th_switch_cs': 0}
694697
return Transistor(transistor_args, switch_args, diode_args)
695698
except ImportError as e:
696-
print(e.args[0])
699+
logger.info(e.args[0])
697700

698701
@staticmethod
699702
def export_single_transistor_to_json(transistor: Transistor, file_path: Optional[str] = None):
@@ -709,7 +712,7 @@ def export_single_transistor_to_json(transistor: Transistor, file_path: Optional
709712
file_path = os.getcwd()
710713
if os.path.isdir(file_path):
711714
file_path = os.path.join(file_path, f"{transistor.name}.json")
712-
print(file_path)
715+
logger.info(file_path)
713716
with open(file_path, "w") as fd:
714717
json.dump(transistor.convert_to_dict(), fd, indent=2)
715718

@@ -826,7 +829,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
826829
position_v_supply_off_start = csv_files[csv_count].rfind("_", 0, position_v_supply_off)
827830
v_supply_off.append(csv_files[csv_count][position_v_supply_off_start + 1:position_v_supply_off])
828831
csv_count += 1
829-
print('v_supply_off=', v_supply_off)
832+
logger.info('v_supply_off=', v_supply_off)
830833
if not compare_list(v_supply_off):
831834
raise ValueError
832835
i = 0
@@ -837,7 +840,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
837840
position_v_g_off_start = csv_files[i].rfind("_", 0, position_v_g_off)
838841
v_g_off.append(csv_files[i][position_v_g_off_start + 1:position_v_g_off])
839842
i += 1
840-
print('vg_off=', v_g_off)
843+
logger.info('vg_off=', v_g_off)
841844
if not compare_list(v_g_off):
842845
raise ValueError
843846
j = 0
@@ -848,7 +851,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
848851
position_r_g_off_start = csv_files[j].rfind("_", 0, position_r_g_off)
849852
r_g_off.append(csv_files[j][position_r_g_off_start + 1:position_r_g_off])
850853
j += 1
851-
print('Rg_off=', r_g_off)
854+
logger.info('Rg_off=', r_g_off)
852855
if not compare_list(r_g_off):
853856
raise ValueError
854857
k = 0
@@ -859,7 +862,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
859862
position_t_j_off_start = csv_files[k].rfind("_", 0, position_t_j_off)
860863
t_j_off.append(csv_files[k][position_t_j_off_start + 1:position_t_j_off])
861864
k += 1
862-
print('t_j_off=', t_j_off)
865+
logger.info('t_j_off=', t_j_off)
863866
if not compare_list(t_j_off):
864867
raise ValueError
865868

@@ -1064,7 +1067,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
10641067
position_v_g_start = csv_files[i].rfind("_", 0, position_v_g)
10651068
v_g.append(csv_files[i][position_v_g_start + 1:position_v_g])
10661069
i += 1
1067-
print('vg=', v_g)
1070+
logger.info('vg=', v_g)
10681071
if not compare_list(v_g):
10691072
raise ValueError
10701073
j = 0
@@ -1075,7 +1078,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
10751078
position_r_g_start = csv_files[j].rfind("_", 0, position_r_g)
10761079
r_g.append(csv_files[j][position_r_g_start + 1:position_r_g])
10771080
j += 1
1078-
print('Rg=', r_g)
1081+
logger.info('Rg=', r_g)
10791082
if not compare_list(r_g):
10801083
raise ValueError
10811084
k = 0
@@ -1086,7 +1089,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
10861089
position_t_j_start = csv_files[k].rfind("_", 0, position_t_j)
10871090
t_j.append(csv_files[k][position_t_j_start + 1:position_t_j])
10881091
k += 1
1089-
print('t_j=', t_j)
1092+
logger.info('t_j=', t_j)
10901093
if not compare_list(t_j):
10911094
raise ValueError
10921095
csv_count = 0
@@ -1097,7 +1100,7 @@ def dpt_save_data(measurement_dict: Dict) -> Dict:
10971100
position_v_supply_on_start = csv_files[csv_count].rfind("_", 0, position_v_supply_on)
10981101
v_supply_on.append(csv_files[csv_count][position_v_supply_on_start + 1:position_v_supply_on])
10991102
csv_count += 1
1100-
print('v_supply=', v_supply_on)
1103+
logger.info('v_supply=', v_supply_on)
11011104
if not compare_list(v_supply_on):
11021105
raise ValueError
11031106
##############################

0 commit comments

Comments
 (0)