-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlogging_utilities.py
More file actions
207 lines (180 loc) · 6.21 KB
/
logging_utilities.py
File metadata and controls
207 lines (180 loc) · 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import logging
import os
import warnings
from datetime import datetime
import json
import copy
import pickle
import time
import numpy as np
logging.EXP = logging.INFO - 1
logging.TEST = 25
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
try:
stage = printProgressBar.stage
except:
printProgressBar.stage = 0.
stage = printProgressBar.stage
ratio = iteration / float(total)
if total > 10 and ratio < stage - 1.0e-5:
return
printProgressBar.stage += 0.1
percent = ("{0:." + str(decimals) + "f}").format(100 * ratio)
print(prefix, percent + "% Complete" + suffix)
# Print New Line on Complete
if iteration == total:
print()
def log_init(log_prefix, level=logging.WARN):
"""
If level<=EXP, Initialze the log file with the current time as ID.
Otherwise only retrun ID
"""
log = logging.getLogger() # root logger
for hdlr in log.handlers[:]: # remove all old handlers
log.removeHandler(hdlr)
date = datetime.now()
id = log_prefix + "-" + date.strftime('%Y%m%d-%H%M%S')
if os.path.isfile("logging/" + id + '.log'):
warnings.warn("ID repeatition.")
id += "r"
if level == logging.EXP:
logging.basicConfig(filename="logging/" + id + '.log', level=level)
else:
logging.basicConfig(level=level)
logging.info("ID: " + id)
logging.info("Date: " + date.strftime('%Y-%m-%d %H:%M:%S') + "\n")
return id
def log_params(parameters):
paramstr = "Parameters:\n"
for name, value in parameters.items():
paramstr += name + " " + str(value) + "\n"
logging.info(paramstr)
def log_finish(id, parameters, remark=""):
"""
Save the parameters and
"""
parameters = copy.deepcopy(parameters)
parameters["ID"] = id
date = datetime.now()
parameters["finishing date"] = str(date.date())
parameters["finishing time"] = str(date.time())
parameters["remark"] = remark
if logging.getLogger().getEffectiveLevel() == logging.EXP:
logging.info("Saving parameters into record...")
with open("logging/logging_record.json", "a") as write_file:
try:
json.dump(parameters, write_file)
write_file.write("\n")
except Exception as err:
logging.exception(
"Failed to save heading data into the record.\n" +
str(parameters))
logging.info("Simulation finished.")
def save_data(id, data):
if logging.getLogger().getEffectiveLevel() != logging.EXP:
return
logging.info("Saving data...")
try:
data_address = "data/" + id + ".pickle"
outfile = open(data_address, 'wb')
pickle.dump(data, outfile)
outfile.close()
logging.info("Data saved at " + '"' + data_address + '"')
except Exception as err:
logging.exception("Failed to save data")
def load_data(id):
infile = open("data//" + id + ".pickle", "rb")
data = pickle.load(infile)
infile.close()
return data
def create_iter_kwargs(parameters):
from itertools import product
names = parameters.keys()
values = [value if isinstance(value, list) else [value]
for value in list(parameters.values())]
kwarg_list = []
for param_list in product(*values):
param_dict = {}
for i, key in enumerate(names):
value = param_list[i]
param_dict[key] = value
kwarg_list.append(param_dict)
return kwarg_list
def find_record_id(ID):
patterns = {"ID":ID}
result = find_record_patterns(patterns)
if not result:
return None
else:
return result
def find_record_patterns(patterns):
with open("logging/logging_record.json") as log:
record_list = log.readlines()
matched_records = []
if patterns is not None:
for record in record_list:
record = json.loads(record)
match = True
for key in patterns.keys():
try:
if record[key] != patterns[key]:
match = False
continue
except KeyError:
match = False
continue
if match:
matched_records.append(record)
for parameters in matched_records:
try:
parameters["protocol"] = tuple(parameters["protocol"])
except KeyError:
pass
if len(matched_records) == 1:
return matched_records[0]
else:
return matched_records
def mytimeit(func):
"""
Decorator for automatically calculate the elapsed time.
"""
def inner(*arg, **kwargs):
start_time = time.time()
result = func(*arg, **kwargs)
end_time = time.time()
print("Elapse time: {}\n".format(end_time - start_time))
return result
return inner
def clear_junk_data():
for filename in os.listdir("./logging"):
if filename.endswith(".log"):
id_end = filename.rfind('.')
ID = filename[:id_end]
result = find_record_id(ID)
if result is None:
try:
os.remove("./logging/" + ID + ".log")
except:
pass
for filename in os.listdir("./data"):
if filename.endswith(".pickle"):
id_end = filename.rfind('.')
ID = filename[:id_end]
result = find_record_id(ID)
if result is None:
try:
os.remove("./data/" + ID + ".pickle")
except:
pass