Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple program to auto generate a Micro-manager startup script from a Micro manager configuration file
#!/usr/bin/python
import sys
import csv
from string import Template
###############################################################################
# CMD Line Usage
###############################################################################
def print_usage():
sys.stdout.write("Usage:\n")
sys.stdout.write("python config_to_beanshell.py input_cfg output_bsh\n\n")
sys.stdout.write("Example:\n")
sys.stdout.write("python config_to_beanshell.py "
"'C:\Program Files\Micro-Manager-1.4\MMConfig_demo.cfg' "
"demo_startup.bsh")
###############################################################################
# Template Stubs
###############################################################################
def bsh_newline():
return "\n"
def bsh_comment(comment):
TEMPLATE = Template("""
/** ********** $comment ********** **/
""")
return TEMPLATE.substitute(comment=comment)
def bsh_autogen_header():
TEMPLATE = """
/**
*******************************************************************************
**************************** autogenerated ************************************
*******************************************************************************
**/
"""
return TEMPLATE
def bsh_autogen_footer():
return bsh_autogen_header()
def bsh_init_false():
TEMPLATE = """
/*** Reset **/
mmc.reset();
mmc.setProperty("Core", "Initialize", "0");
"""
return TEMPLATE
def bsh_new_load_device_map():
TEMPLATE = """
Hashtable deviceLoadMap = new Hashtable();
"""
return TEMPLATE
def bsh_load_device_map(device_label, init_state):
TEMPLATE = Template("""deviceLoadMap.put("$device_label", $state);\n""")
return TEMPLATE.substitute(
device_label=device_label,
state='true' if init_state else 'false')
def bsh_load_device(device_label, library, adapter):
TEMPLATE = Template("""
try {
// Loading device $device_label
mmc.loadDevice("$device_label", "$library", "$adapter");
deviceLoadMap.put("$device_label", true);
} catch (java.lang.Exception ex) {
deviceLoadMap.put("$device_label", false);
gui.logMessage("Exception loading '$device_label':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
};
""")
return TEMPLATE.substitute(
device_label=device_label,
library=library,
adapter=adapter)
def bsh_set_property(device_label, property_label, value):
TEMPLATE = Template("""
try {
// Setting property $property_label
if (deviceLoadMap.containsKey("$device_label") &&
deviceLoadMap.get("$device_label")) {
mmc.setProperty("$device_label", "$property_label", "$value");
} else {
gui.logMessage("Skipping setting property '$property_label' on device '$device_label'");
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting property: '$device_label' '$property_label':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
};
""")
return TEMPLATE.substitute(
device_label=device_label,
property_label=property_label,
value=value)
def bsh_set_parent(device_label, parent_label):
TEMPLATE = Template("""
try {
// Setting parent for $device_label
if (deviceLoadMap.containsKey("$device_label") &&
deviceLoadMap.get("$device_label")) {
mmc.setParentLabel("$device_label", "$parent_label");
} else {
gui.logMessage("Skipping setting parent '$parent_label' of device '$device_label'");
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting parent '$parent_label' of device '$device_label':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
};
""")
return TEMPLATE.substitute(
device_label=device_label,
parent_label=parent_label)
def bsh_new_init_device_map():
TEMPLATE = """
Hashtable deviceInitMap = new Hashtable();
"""
return TEMPLATE
def bsh_init_device_map(device_label, init_state):
TEMPLATE = Template("""deviceInitMap.put("$device_label", $state);\n""")
return TEMPLATE.substitute(
device_label=device_label,
state='true' if init_state else 'false')
def bsh_init_device(device_label):
TEMPLATE = Template("""
try {
// Initializing device $device_label
if (deviceLoadMap.containsKey("$device_label") &&
deviceLoadMap.get("$device_label")) {
mmc.initializeDevice("$device_label");
deviceInitMap.put("$device_label", true);
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception initializing device '$device_label'");
gui.logMessage(ex.getMessage());
gui.logMessage("Unloading device...");
try {
mmc.unloadDevice("$device_label");
deviceInitMap.put("$device_label", false);
} catch (java.lang.Exception ex2) {
gui.logMessage("Exception unloading device '$device_label'");
gui.logMessage(ex2.getMessage());
gui.logMessage("ignoring...");
}
}
""")
return TEMPLATE.substitute(
device_label=device_label)
def bsh_set_label(device_label, state, label):
TEMPLATE = Template("""
try {
// Setting state label for $device_label
if (deviceInitMap.containsKey("$device_label") &&
deviceInitMap.get("$device_label")) {
mmc.defineStateLabel("$device_label", $state, "$state_label");
} else {
gui.logMessage("Skipping setting state label '$state_label' of device '$device_label'");
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting state label '$state_label' of device '$device_label':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
};
""")
return TEMPLATE.substitute(
device_label=device_label,
state=int(state),
state_label=label)
def bsh_set_config_group(group_label, config_label, device_label, property_label, value):
TEMPLATE = Template("""
try {
// Setting config group $group_label : $config_label : $property_label
if (deviceInitMap.containsKey("$device_label") &&
deviceInitMap.get("$device_label")) {
mmc.defineConfig("$group_label", "$config_label",
"$device_label", "$property_label", "$value");
} else {
gui.logMessage("Skipping setting config group '$group_label':'$config_label' property '$property_label'");
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting config group '$group_label' property '$property_label':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
};
""")
return TEMPLATE.substitute(
group_label=group_label,
config_label=config_label,
device_label=device_label,
property_label=property_label,
value=value)
def bsh_set_pixel_size_config(res_id, device_label, property_label, value):
TEMPLATE = Template("""
try {
// Setting pixel config for $res_id
if (deviceInitMap.containsKey("$device_label") &&
deviceInitMap.get("$device_label")) {
mmc.definePixelSizeConfig("$res_id", "$device_label", "$property_label", "$value");
} else {
gui.logMessage("Skipping setting pixel size config '$res_id' for device '$device_label'");
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting pixel config '$res_id':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
}
""")
return TEMPLATE.substitute(
res_id=res_id,
device_label=device_label,
property_label=property_label,
value=value)
def bsh_set_pixel_size(res_id, pixel_size):
TEMPLATE = Template("""
try {
// set pixel size for pixel config $res_id
if (deviceInitMap.containsKey("$device_label") &&
deviceInitMap.get("$device_label")) {
mmc.setPixelSizeUm("$res_id", $pixel_size);
} else {
gui.logMessage("Skipping setting pixel size for config '$res_id');
}
} catch (java.lang.Exception ex) {
gui.logMessage("Exception setting pixel size for config '$res_id':");
gui.logMessage(ex.getMessage());
gui.logMessage("ignoring...");
}
""")
return TEMPLATE.substitute(
res_id=res_id,
pixel_size=pixel_size)
def bsh_wait_for_system():
TEMPLATE = """
/** ********** wait for system ********** **/
// try to set startup config
if (mmc.isConfigDefined("System", "Startup")) {
mmc.setConfig("System", "Startup");
}
mmc.waitForSystem();
mmc.updateCoreProperties();
mmc.updateSystemStateCache();
"""
return TEMPLATE
def bsh_update_gui():
TEMPLATE = """
/** ********** update gui ********** **/
gui.refreshGUIFromCache();
"""
return TEMPLATE
###############################################################################
# MAIN
###############################################################################
if __name__ == '__main__':
if len(sys.argv) != 3:
print_usage()
sys.exit(1)
try:
input_fh = open(sys.argv[1], 'r')
output_fh = open(sys.argv[2], 'wb')
except IOError as exp:
print >> sys.stderr, exp
sys.exit(1)
mm_devices = []
mm_properties = []
mm_parents = []
mm_labels = []
mm_config_groups = []
mm_config_pixel = []
mm_pixel_size = []
with input_fh, output_fh:
reader = csv.reader(input_fh)
try:
#---------------------------------
#--- parse micromanger config ----
#---------------------------------
for line, row in enumerate(reader):
if len(row) == 0:
# skip newlines
continue
if row[0].startswith("#"):
# skip comments
continue
if row[0] == "Device":
if len(row) != 4:
err = "Invalid Device -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_devices.append(tuple(row[1:]))
continue
if row[0] == "Property":
if len(row) != 4:
err = "Invalid Property -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
if row[1] == 'Core' and row[2] == 'Initialize':
# we will explicitly call this
continue
mm_properties.append(tuple(row[1:]))
continue
if row[0] == "Parent":
if len(row) != 3:
err = "Invalid Parent -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_parents.append(tuple(row[1:]))
continue
if row[0] == "Label":
if len(row) != 4:
err = "Invalid Label -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_labels.append(tuple(row[1:]))
continue
if row[0] == "ConfigGroup":
if len(row) != 6:
err = "Invalid ConfigGroup -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_config_groups.append(tuple(row[1:]))
continue
if row[0] == "ConfigPixelSize":
if len(row) != 5:
err = "Invalid ConfigPixelSize -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_config_pixel.append(tuple(row[1:]))
continue
if row[0] == "PixelSize_um":
if len(row) != 3:
err = "Invalid PixelSize_um -> line: {}".format(line + 1)
print >> sys.stderr, err
sys.exit(1)
mm_pixel_size.append(tuple(row[1:]))
continue
#----------------------------------
#--- generate beanshell script ---
#----------------------------------
# autogen header
output_fh.write(bsh_autogen_header())
# set initialized to false
output_fh.write(bsh_init_false());
# write out device load map
output_fh.write(bsh_comment("Device load map"))
output_fh.write(bsh_new_load_device_map());
for dev_params in mm_devices:
device_label = dev_params[0]
output_fh.write(bsh_load_device_map(device_label, False))
# load devices
output_fh.write(bsh_comment("Devices"))
for dev_params in mm_devices:
output_fh.write(bsh_load_device(*dev_params))
# set properties
output_fh.write(bsh_comment("Pre-init settings for devices"))
for prop_params in mm_properties:
output_fh.write(bsh_set_property(*prop_params))
# set parent references
output_fh.write(bsh_comment("Hub (parent) references"))
for parent_params in mm_parents:
output_fh.write(bsh_set_parent(*parent_params))
# write out device initialized map
output_fh.write(bsh_comment("Device init map"))
output_fh.write(bsh_new_init_device_map());
for dev_params in mm_devices:
device_label = dev_params[0]
output_fh.write(bsh_init_device_map(device_label, False))
# initialize devices
output_fh.write(bsh_comment("Initialize Devices"))
for dev_params in mm_devices:
device_label = dev_params[0]
output_fh.write(bsh_init_device(device_label))
# set labels
output_fh.write(bsh_comment("Labels"))
for label_params in mm_labels:
output_fh.write(bsh_set_label(*label_params))
# set config groups
output_fh.write(bsh_comment("Configuration presets"))
for config_params in mm_config_groups:
output_fh.write(bsh_set_config_group(*config_params))
# set pixel size config
output_fh.write(bsh_comment("Pixel Size Config"))
for config_params in mm_config_pixel:
output_fh.write(bsh_set_pixel_size_config(*config_params))
# set pixel size
output_fh.write(bsh_comment("Pixel Size UM"))
for pixel_params in mm_pixel_size:
output_fh.write(bsh_set_pixel_size(*pixel_params))
# update system system cache and refresh gui from cache
output_fh.write(bsh_wait_for_system())
output_fh.write(bsh_update_gui());
# write autogen footer
output_fh.write(bsh_autogen_footer());
except csv.Error as exp:
err = "Parse Error, file: {}, line: {}, err: {}".format(sys.argv[1], line + 1, exp)
print >> sys.stderr, err
sys.exit(1)
except IOError as exp:
err = "Write Error, file: {}, err: {}".format(sys.argv[1], exp)
print >> sys.stderr, err
sys.exit(1)
sys.stdout.write("Success!\n")
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment