Last active
October 5, 2018 18:30
-
-
Save aaristov/28aa60182ad1eddd7dd9dc088332c194 to your computer and use it in GitHub Desktop.
BFDC-Imjoy plugin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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", | |
"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, | |
"icon": null, | |
"env": "conda create -n imjoy python=3.7", | |
"requirements": [], | |
"dependencies": [] | |
} | |
</config> | |
<script lang="python"> | |
#"git+https://github.com/imodpasteur/Brightfield-Drift-Correction-3D.git@dev" | |
import numpy as np | |
#from bfdc import drift | |
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}.') | |
root = await api.getConfig('root') | |
self.config_root(root) | |
#api.getConfig('root').then(self.config_root).catch(print) | |
self.config = {"trace":{'xypixel':100, | |
'zstep':100, | |
'start':0, | |
'nframes':0, | |
'skip':0, | |
'minsignal':0, | |
'paths':['dictionary', | |
'roi', | |
'movie']}, | |
"apply":{'smooth':0, | |
'paths':['zola_table', | |
'drift_table']}, | |
"batch":{} | |
} | |
self.revoke_config(await api.getConfig('bfdc')) | |
self.print_config() | |
self.plot_menus() | |
def plot_menus(self): | |
for action in self.config: | |
name = self.config[action] | |
ui = [] | |
for param in self.config[action]: | |
if isinstance(self.config[action][param],int): | |
line = {param: {"id": param, | |
"type": "number", | |
"min": 0, | |
"placeholder":self.config[action][param]} | |
} | |
#print(str(line)) | |
ui.append(line) | |
#print(ui) | |
api.register({"name" : action, | |
"ui": ui}) | |
async def run(self,my): | |
print(my.config) | |
action = my.config.type | |
arg_dict = my.config | |
_ = arg_dict.pop('type') | |
self.update_config(action,arg_dict) | |
if action in self.config: | |
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 = [] | |
args += [action] | |
args += paths | |
args += ['--%s=%d'%(key,value) for key,value in zip(arg_dict.keys(),arg_dict.values())] | |
print(args) | |
drift.main(argsv=args, callback=self.show_progress) | |
else: | |
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,args): | |
print(f'Root directory is set to : {self.root}') | |
api.showProgress(0) | |
def config_root(self,root): | |
print(f'found getConfig.root {root}') | |
api.showStatus(f'Found root path: {root}') | |
if root == "null" or not os.path.isdir(root): | |
api.showDialog({"name": "Configure start folder", | |
"ui": "Please type in the path to start with: {id:'path', type:'string', placeholder: '%s'}."%root}).then(self.set_root) | |
else: | |
self.root = root | |
self.show_config(root) | |
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(None) | |
else: | |
api.alert('Suggerted 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) | |
def revoke_config(self, conf): | |
print(f'Loaded {conf} from Imjoy bfdc key') | |
if conf: | |
print('Trying to serialize with json') | |
config = json.loads(conf) | |
else: | |
print('No configuration found in Imjoy') | |
return | |
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: | |
self.config[it].update(config[it]) | |
else: | |
print(f'Keys are different current vs remote: {self.config.keys()} vs {config.keys()}') | |
print('Keep the curent configuration') | |
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)) | |
''' | |
HIV_EDU_647_SR | |
HIV_EDU_647_SR.Pos0.ome.tif | |
HIV_EDU_647_WF | |
HIV_EDU_647_WF.Pos0.ome.tif | |
HIV_EDU_647_WF.Pos0_1.ome.tif | |
HIV_EDU_647.roi | |
HIV_EDU_647_BR | |
HIV_EDU_647_BR.ome.tif | |
HIV_EDU_647.roi | |
''' | |
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> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment