-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFDC.imjoy.html
More file actions
275 lines (242 loc) · 9.35 KB
/
Copy pathBFDC.imjoy.html
File metadata and controls
275 lines (242 loc) · 9.35 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<docs lang="markdown">
You need to install Python Engine first https://github.com/oeway/ImJoy-Python
Then create a new plugin and paste this code to it.
The plugin will configure Python automatically with all dependencies.
Click on the BFDC to run the plugin.
You'll see the file dialog to select zstack, roi and movie.
Then the plugin will launch Python package to process the files and output the drift table.
It will also show the drift plot in the separate window.
</docs>
<config lang="json">
{
"name": "BFDC-test",
"mode": "pyworker",
"version": "0.1.0",
"api_version": "0.1.1",
"description": "A plugin for demonstrate python plugin.",
"tags": null,
"ui": "Ops for tracing, applying and batch processing bright field drift. Select your operation type and check the parameters.",
"inputs": null,
"outputs": null,
"flags": [],
"icon": null,
"env": "conda create -n imjoy python=3.7",
"requirements": ["git+https://github.com/imodpasteur/Brightfield-Drift-Correction-3D.git@v0.4.2"],
"dependencies": []
}
</config>
<script lang="python">
#"git+https://github.com/imodpasteur/Brightfield-Drift-Correction-3D.git@v0.3.0"
import numpy as np
import sys
import os
#sys.path.insert(0,'/Volumes/Imod-grenier/Andrey/Phase retrieve/drift-correction/BFDC/')
from bfdc import drift
import base64
import asyncio
import json
class PythonPlugin():
async def setup(self):
print(f'Running BFDC in Python {sys.version}.')
self.root = str(await api.getConfig('root'))
self.config_root()
self.config = {"trace":{'xypixel':110,
'zstep':100,
'zdirection':['approach','retract'],
'start':10,
'nframes':0,
'skip':10,
'minsignal':0,
'paths':['dictionary',
'roi',
'movie']},
"apply":{'smooth':0,
'zinvert':[0,1],
'maxbg':0,
'paths':['zola_table',
'drift_table']},
"batch":{'xypixel':110,
'zstep':100,
'zdirection':['approach','retract'],
'start':10,
'skip':10,
'fov_prefix': 'FOV',
'dict_folder_prefix': 'dict',
'dict_suffix': 'ome.tif',
'sr_folder_prefix': 'sr_',
'sr_movie_suffix': 'Pos0.ome.tif',
'zola_dc_filename':'ZOLA*BFDC*.csv',
'dc_table_filename': 'BFCC*.csv',
'zola_raw_filename': 'ZOLA_localization_table.csv',
'smooth': 50,
'filter_bg': 0,
'zinvert': 0,
'paths': ['batch_path']}
}
await self.revoke_config()
self.print_config()
self.plot_menus()
def plot_menus(self):
##bla
for action in self.config:
name = self.config[action]
ui = []
for param in self.config[action]:
value = self.config[action][param]
#print(f'{param}:{value}({type(value)})')
if param is not 'paths':
if isinstance(value,int):
line = {param: {"id": param,
"type": "number",
"min": 0,
"placeholder":value}
}
#print(str(line))
ui.append(line)
elif isinstance(value,str):
line = {param: {"id": param,
"type": "string",
"placeholder":value}
}
#print(str(line))
ui.append(line)
elif isinstance(value,list):
line = {param: {"id": param,
"type": "choose",
"options": value,
"placeholder": value[0]}
}
#print(str(line))
ui.append(line)
else:
raise('unknown entry, expected str, list or int')
#print(ui)
api.register({"name" : action,
"ui": ui})
async def run(self,my):
print(my.config)
arg_dict = my.config
action = arg_dict.pop('type').split('/')[-1]
if action in self.config:
self.update_config(action,arg_dict)
self.config_root()
titles = self.config[action]['paths']
print(titles)
try:
paths = await self.get_paths(titles)
except:
print('Canceled by user')
return
#paths = ['as','sdf']
print(paths)
args = [action]
args += paths
args += [f'--{key}={value}' for key,value in zip(arg_dict.keys(),arg_dict.values())]
print(args)
drift.main(argsv=args, callback=self.show_progress)
else:
#print("action")
#print("not supported")
api.alert('Select action from drop down menu BFDC')
def update_config(self, action,new_dict):
print('updating config')
self.config[action].update(new_dict)
self.dump_config()
#print('New config: ')
#print(json.dumps(self.config, indent=4))
async def get_paths(self, title_list):
if isinstance(title_list, list) or isinstance(title_list, tuple):
path_list = []
for title in title_list:
print('request ' + title)
path = await api.showFileDialog(title='Select ' + title, root=self.root)
print('selected: ' + path)
api.showSnackbar(f'Selected {path}')
self.save_root(path)
path_list.append(path)
return path_list
else:
raise IndexError(f'Expected list/tuple, got {type(title_list)}')
def show_config(self):
print(f'Root directory is set to : {self.root}')
api.showProgress(0)
def config_root(self):
print(f'found getConfig.root {self.root}')
api.showStatus(f'Found root path: {self.root}')
if self.root == "null" or not os.path.isdir(self.root):
api.showDialog({"name": "Configure start folder",
"ui": "Please type in the path to start with: {id:'path', type:'string', placeholder: '%s'}."%self.root}).then(self.set_root)
else:
#self.root = root
self.show_config()
def set_root(self,path):
api.showStatus(f'Received {path.path} from the dialog')
path = path.path
try:
os.path.isdir(path)
except:
path = r'%s'%path
if os.path.isdir(path):
self.root = path
api.setConfig('root', path)
self.show_config()
else:
api.alert('Suggested path is wrong, try again')
self.config_root()
return
def save_root(self,root):
if os.path.isfile(root):
root = os.path.dirname(root)
self.root = root
api.setConfig('root', root)
async def revoke_config(self):
conf = str(await api.getConfig('bfdc'))
print(conf)
print('Loaded conf from Imjoy bfdc key')
try:
print('Trying to serialize with json')
config = json.loads(conf)
except json.decoder.JSONDecodeError:
print('No configuration found in Imjoy')
return False
print('Loaded configuration from Imjoy')
if config.keys() == self.config.keys():
print('Keys are the same')
print('Updating current configuration from Imjoy')
for it in self.config:
for param in self.config[it]:
try:
if isinstance(self.config[it][param], int) and isinstance(config[it][param], int):
self.config[it][param] = config[it][param]
except KeyError:
pass
else:
print(f'Keys are different current vs remote: {self.config.keys()} vs {config.keys()}')
print('Keep the curent configuration')
return True
def dump_config(self):
print('Saving updated config to Imjoy')
conf = json.dumps(self.config)
api.setConfig('bfdc', conf)
def print_config(self):
print(json.dumps(self.config, sort_keys=False, indent=2))
def show_drift_plot(self, plot_path):
with open(plot_path, 'rb') as f:
data = f.read()
result = base64.b64encode(data).decode('ascii')
imgurl = 'data:image/png;base64,' + result
api.createWindow(name='Drift prediction', type = 'imjoy/image', w=5, h=5, data= {"src": imgurl})
def show_progress(self, msg):
assert isinstance(msg,dict)
#print(json.dumps(msg, indent=4))
if list(msg)[0] == 'Progress':
current, total, found = msg['Progress'].values()
api.showStatus(f'Processing {current}/{total}, found {found} BF frames')
api.showProgress(int(current / total * 100))
elif list(msg)[0] == 'Message':
api.showStatus(msg['Message'])
elif list(msg)[0] == 'Plot':
print('plot ',msg['Plot'])
self.show_drift_plot(msg['Plot'])
api.export(PythonPlugin())
</script>