Skip to content

Commit 366d3da

Browse files
authored
Updated recipe
1 parent 0b64e82 commit 366d3da

File tree

2 files changed

+104
-53
lines changed

2 files changed

+104
-53
lines changed

Recipes/Others/ExtractDeepLearningInfoInLogFile.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def search_activation_path():
1212
return ''
1313

1414
activate_path = search_activation_path()
15+
1516
if os.path.exists(activate_path):
1617
exec(open(activate_path).read(), {'__file__': activate_path})
1718
print(f'Aivia virtual environment activated\nUsing python: {activate_path}')
@@ -61,7 +62,7 @@ def run(params):
6162
print("Running")
6263
# Setting colors for chart
6364
col1 = 'royalblue'
64-
col2 = 'r'
65+
col2 = 'r' # red
6566

6667
# GUI to select a log file
6768
print('Starting wxPython app')
@@ -74,7 +75,7 @@ def run(params):
7475
if logfile.endswith('Worklog.log'):
7576
is_local = False
7677

77-
file = open(logfile, "r+")
78+
file = open(logfile, "r")
7879
all_lines = file.read()
7980
list_n_epoch, list_i_epoch = [], []
8081
if is_local:
@@ -99,23 +100,19 @@ def run(params):
99100
print('-- Found {} DL training blocks --'.format(len(list_n_epoch)))
100101

101102
# Init chart
102-
fig = plt.figure(figsize=plt.figaspect(0.4))
103-
ax1 = fig.add_subplot(111)
104-
ax1.set_xlabel('epochs')
105-
ax1.set_ylabel('loss', color=col1)
106-
ax1.tick_params(axis='y', labelcolor=col1)
103+
# fig = plt.figure(figsize=plt.figaspect(0.4))
104+
# ax1 = fig.add_subplot(111)
105+
fig, ax1 = plt.subplots(figsize=plt.figaspect(0.4))
107106

108107
# Create second axis
109-
ax2 = ax1.twinx()
110-
ax2.set_ylabel('validation_loss', color=col2)
111-
ax2.tick_params(axis='y', labelcolor=col2)
108+
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
112109

113110
# Create buttons to switch to another DL run
114111
# sub-plot for radio button with
115112
# left, bottom, width, height values
116113
plt.subplots_adjust(right=0.7)
117114
rax = plt.axes([0.8, 0.1, 0.16, 0.8])
118-
radio_button = RadioButtons(rax, tuple(['DL training no {}'.format(x) for x in range(1, len(list_n_epoch) + 1)]),
115+
radio_button = RadioButtons(rax, tuple(['DL training [{}]'.format(x) for x in range(1, len(list_n_epoch) + 1)]),
119116
active=len(list_n_epoch) - 1)
120117

121118
def get_values(run_index):
@@ -145,8 +142,16 @@ def change_DL_run(label):
145142
print('Selected DL run: {}'.format(run_no))
146143

147144
# Clear values
148-
ax1.cla()
149-
ax2.cla()
145+
ax1.clear()
146+
ax2.clear()
147+
148+
# Create the axes titles
149+
ax1.set_xlabel('epochs')
150+
ax1.set_ylabel('loss', color=col1)
151+
ax1.tick_params(axis='y', labelcolor=col1)
152+
153+
ax2.set_ylabel('validation_loss', color=col2)
154+
ax2.tick_params(axis='y', labelcolor=col2)
150155

151156
# Plot values
152157
ax1.plot(n_epoch, all_v1_nonsci, color=col1, linewidth=1)
@@ -264,3 +269,4 @@ def Mbox(title, text, style):
264269
# Changelog:
265270
# v1.10: - Bug fixed with wxPython app not being run in v1.00
266271
# v1.20: - New virtual env code for auto-activation
272+
# v1.21: - Correcting the mistake of opening the log file as 'r+'. Also fixing some display missing (axis title)

Recipes/Others/Read_WorkFlowFile.py

Lines changed: 85 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -28,72 +28,116 @@ def search_activation_path():
2828
import textwrap
2929
import re
3030

31+
32+
test_file = ''
33+
sep = ' | ' # separator for recipe parameters
3134
max_char_len = 150
3235

3336

37+
# Table with WxPython
38+
class WxTable:
39+
def __init__(self, t_title, t_width, t_height):
40+
self.app = wx.App()
41+
self.frame = wx.Frame(parent=None, title=t_title, size=(t_width, t_height))
42+
43+
self.table = wx.ListCtrl(self.frame, size=(-1, 100), style=wx.LC_REPORT)
44+
self.table.InsertColumn(0, 'Info', width=200)
45+
self.table.InsertColumn(1, 'Value', width=1600)
46+
47+
self.row = 0 # Table row number
48+
49+
def add_line(self, title, text):
50+
self.table.InsertItem(self.row, str(title))
51+
self.table.SetItem(self.row, 1, str(text))
52+
self.row += 1
53+
54+
def add_line_with_sep(self, title):
55+
self.table.InsertItem(self.row, '----- ' + str(title) + ' -----')
56+
self.table.SetItem(self.row, 1, '---------------------------------')
57+
self.row += 1
58+
59+
def add_block_with_header(self, action_name, block_dict, block_tags):
60+
self.add_line('Action', action_name)
61+
for t in block_tags:
62+
self.add_line(t, block_dict[t])
63+
64+
3465
# [INPUT Name:inputImagePath Type:string DisplayName:'Any channel']
3566
# [OUTPUT Name:resultPath Type:string DisplayName:'Dummy to delete']
3667
def run(params):
3768
# Choose file
38-
file_path = pick_file('')
69+
file_path = test_file if test_file else pick_file('')
3970

4071
# Read the file
4172
raw_text = open(file_path, 'r+').read()
73+
cleaned_text = replace_all(raw_text, {'null': '""', 'true': 'True', 'false': 'False'})
4274

43-
# Split description from processing steps
44-
main_parts = raw_text.split('"Entities":[')
45-
46-
# Split processing steps
47-
block_end_pattern = re.compile(r'},{\"[^(RecipeName|Name)]')
48-
step_blocks = re.split(block_end_pattern, main_parts[1])
75+
# Attempt to create dict from file string
76+
try:
77+
wkfl_dict = eval(cleaned_text)
4978

50-
# Prepare displayed table
51-
app = wx.App()
52-
frame = wx.Frame(parent=None, title='TIF tags', size=(1000, 1000))
79+
except BaseException as e:
80+
sys.exit(f'Error trying to convert workflow file as dict:\n{e}')
5381

54-
table = wx.ListCtrl(frame, size=(-1, 100), style=wx.LC_REPORT)
55-
table.InsertColumn(0, 'Info', width=200)
56-
table.InsertColumn(1, 'Value', width=1600)
82+
# Init wx table
83+
wx_table = WxTable('Aivia workflow file reader', 1000, 1000)
5784

5885
# Write first part
59-
r = 0
60-
table.InsertItem(r, 'Description')
61-
table.SetItem(r, 1, main_parts[0].replace(',', ',\n'))
62-
r += 1
86+
main_tags = ['Name', 'Description', 'CreationUser', 'CreationDateUTC']
87+
for t in main_tags:
88+
wx_table.add_line(t, wkfl_dict[t])
6389

64-
# Split values in each block
65-
for i in range(len(step_blocks)):
90+
# Process sub-parts in 'Entities' = workflow steps
91+
steps_dicts = wkfl_dict['Entities']
92+
93+
# Define tags to retrieve
94+
calib_tags = ['XYCalibration', 'ZCalibration', 'TCalibration']
95+
pxclass_tags = ['PixelClassifierName', 'InputChannels', 'BackupPath'] # InputChannels needs to be created
96+
recipe_tags = ['RecipeName', 'InputChannels', 'RecipeSettings', 'BackupPath']
97+
# RecipeName, InputChannels, RecipeSettings need to be created
98+
99+
for i in range(len(steps_dicts)):
66100
# Writing a line to separate blocks
67-
table.InsertItem(r, '----- Step ' + str(i) + ' ---')
68-
table.SetItem(r, 1, '---------------------------------')
69-
r += 1
101+
wx_table.add_line_with_sep('Step ' + str(i))
102+
103+
step_dict = steps_dicts[i]
70104

71-
lines = step_blocks[i].split(',')
105+
# Specific processing if first step is calibration of the image
106+
if 'DoCalibration' in step_dict.keys():
107+
wx_table.add_block_with_header('Image calibration', step_dict, calib_tags)
72108

73-
for l in lines:
74-
split_line = l.split(':')
109+
else:
110+
# Pixel Classifier step
111+
if 'PixelClassifierID' in step_dict.keys():
112+
# Creating / Processing some tags
113+
step_dict['InputChannels'] = ', '.join([f'Channel {ind}' for ind in step_dict['InputIndices']])
75114

76-
# Repair some broken text
77-
filtered_tag = split_line[0].replace('ackupPath"',
78-
'"BackupPath"').replace('ixelClassifierID"',
79-
'"PixelClassifierID"')
115+
wx_table.add_block_with_header('Pixel Classifier', step_dict, pxclass_tags)
80116

81-
# Insert tag name
82-
table.InsertItem(r, filtered_tag)
117+
elif 'RecipeApplyState' in step_dict.keys():
118+
# Creating / Processing some tags
119+
recipe_settings = step_dict['RecipeApplyState']['RecipeSettings']
120+
step_dict['RecipeName'] = recipe_settings['RecipeName']
121+
step_dict['InputChannels'] = ', '.join([f'Channel {ind}' for ind in step_dict['InputIndices']])
83122

84-
# Set value because some can be very long
85-
final_val = str(split_line[1:])
123+
# Gathering recipe parameters (ParameterSetStates = parameters group, Parameters = actual parameters)
124+
step_dict['RecipeSettings'] = ''
125+
for p_group in recipe_settings['ParameterSetStates']:
126+
recipe_params = p_group['Parameters']
127+
step_dict['RecipeSettings'] += p_group['ParameterSetName'] + sep
128+
step_dict['RecipeSettings'] += sep.join([f"{str(p['Name'])} = {str(p['Value'])}" for p in recipe_params])
129+
step_dict['RecipeSettings'] += sep
86130

87-
# Removing some characters from value
88-
filtered_value = re.sub('[}\[\]\"\']', '', final_val)
131+
wx_table.add_block_with_header('Recipe', step_dict, recipe_tags)
89132

90-
# Insert value
91-
table.SetItem(r, 1, filtered_value)
133+
wx_table.frame.Show()
134+
wx_table.app.MainLoop()
92135

93-
r += 1
94136

95-
frame.Show()
96-
app.MainLoop()
137+
def replace_all(text, dic):
138+
for i, j in dic.items():
139+
text = text.replace(i, j)
140+
return text
97141

98142

99143
def wrap(string, length):
@@ -123,3 +167,4 @@ def pick_file(default_dir):
123167
# CHANGELOG
124168
# v1.00: - First version
125169
# v1.01: - New virtual env code for auto-activation
170+
# v1.02: - Now using conversion of workflow to a dictionary. Tested on one workflow only. Text replacements are needed.

0 commit comments

Comments
 (0)