Skip to content
Snippets Groups Projects
Commit 14ed66bc authored by Niko Ehrenfeuchter's avatar Niko Ehrenfeuchter :keyboard:
Browse files

Blackenize code

parent f48501e6
No related branches found
No related tags found
No related merge requests found
...@@ -21,4 +21,4 @@ Biozentrum, University of Basel, Switzerland. ...@@ -21,4 +21,4 @@ Biozentrum, University of Basel, Switzerland.
[imagej]: https://imagej.net [imagej]: https://imagej.net
""" """
__version__ = '${project.version}' __version__ = "${project.version}"
...@@ -15,9 +15,10 @@ def show_status(msg): ...@@ -15,9 +15,10 @@ def show_status(msg):
def show_progress(cur, final): def show_progress(cur, final):
"""Wrapper to update the progress bar and issue a log message.""" """Wrapper to update the progress bar and issue a log message."""
# ij.IJ.showProgress is adding 1 to the value given as first parameter... # ij.IJ.showProgress is adding 1 to the value given as first parameter...
log.info("Progress: %s / %s (%s)", cur+1, final, (1.0+cur)/final) log.info("Progress: %s / %s (%s)", cur + 1, final, (1.0 + cur) / final)
IJ.showProgress(cur, final) IJ.showProgress(cur, final)
def error_exit(msg): def error_exit(msg):
"""Convenience wrapper to log an error and exit then.""" """Convenience wrapper to log an error and exit then."""
log.error(msg) log.error(msg)
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
from ij import Prefs # pylint: disable-msg=E0401 from ij import Prefs # pylint: disable-msg=E0401
def debug_mode(): def debug_mode():
"""Wrapper to check if 'imcf.debugging' is enabled. """Wrapper to check if 'imcf.debugging' is enabled.
......
...@@ -82,18 +82,21 @@ def create_and_save(imp, projections, path, filename, export_format): ...@@ -82,18 +82,21 @@ def create_and_save(imp, projections, path, filename, export_format):
return False return False
command = { command = {
'Average': 'avg', "Average": "avg",
'Maximum': 'max', "Maximum": "max",
'Sum': 'sum', "Sum": "sum",
} }
for projection in projections: for projection in projections:
log.debug("Creating '%s' projection...", projection) log.debug("Creating '%s' projection...", projection)
proj = ZProjector.run(imp, command[projection]) proj = ZProjector.run(imp, command[projection])
export_using_orig_name(proj, export_using_orig_name(
path, filename, proj,
"-%s" % command[projection], path,
export_format, filename,
overwrite=True) "-%s" % command[projection],
export_format,
overwrite=True,
)
proj.close() proj.close()
return True return True
...@@ -105,10 +105,10 @@ def correct_and_project(filename, path, model, proj, fmt): ...@@ -105,10 +105,10 @@ def correct_and_project(filename, path, model, proj, fmt):
imps = [imp] imps = [imp]
ret_corr = True ret_corr = True
if proj == 'None': if proj == "None":
projs = [] projs = []
elif proj == 'ALL': elif proj == "ALL":
projs = ['Average', 'Maximum'] projs = ["Average", "Maximum"]
else: else:
projs = [proj] projs = [proj]
for imp in imps: for imp in imps:
...@@ -159,8 +159,7 @@ def process_files(files, outpath, model_file, fmt): ...@@ -159,8 +159,7 @@ def process_files(files, outpath, model_file, fmt):
fmt : str fmt : str
The file format suffix for storing the results. The file format suffix for storing the results.
""" """
log.info("Running shading correction and projections on %s files...", log.info("Running shading correction and projections on %s files...", len(files))
len(files))
if model_file.upper() in ["-", "NONE"]: if model_file.upper() in ["-", "NONE"]:
model = None model = None
...@@ -177,7 +176,7 @@ def process_files(files, outpath, model_file, fmt): ...@@ -177,7 +176,7 @@ def process_files(files, outpath, model_file, fmt):
misc.error_exit("Opening shading model [%s] failed!" % model_file) misc.error_exit("Opening shading model [%s] failed!" % model_file)
for in_file in files: for in_file in files:
correct_and_project(in_file, outpath, model, 'ALL', fmt) correct_and_project(in_file, outpath, model, "ALL", fmt)
if model: if model:
model.close() model.close()
...@@ -6,6 +6,7 @@ from ij import IJ, ImagePlus # pylint: disable-msg=E0401 ...@@ -6,6 +6,7 @@ from ij import IJ, ImagePlus # pylint: disable-msg=E0401
from ij.io import FileSaver # pylint: disable-msg=E0401 from ij.io import FileSaver # pylint: disable-msg=E0401
from ij.plugin import ChannelSplitter # pylint: disable-msg=E0401 from ij.plugin import ChannelSplitter # pylint: disable-msg=E0401
def split_by_c_and_z(log, dname, imgf, skip_top, skip_bottom): def split_by_c_and_z(log, dname, imgf, skip_top, skip_bottom):
"""Helper function to open, split and save a file. """Helper function to open, split and save a file.
...@@ -36,7 +37,7 @@ def split_by_c_and_z(log, dname, imgf, skip_top, skip_bottom): ...@@ -36,7 +37,7 @@ def split_by_c_and_z(log, dname, imgf, skip_top, skip_bottom):
if not os.path.isdir(tgt_dir): if not os.path.isdir(tgt_dir):
os.mkdir(tgt_dir) os.mkdir(tgt_dir)
stack = channel.getStack() stack = channel.getStack()
for z in range(1+skip_top, stack.getSize()+1-skip_bottom): for z in range(1 + skip_top, stack.getSize() + 1 - skip_bottom):
proc = stack.getProcessor(z) proc = stack.getProcessor(z)
fout = "%s/%s-z%s%s" % (tgt_dir, fname[0], z, fname[1]) fout = "%s/%s-z%s%s" % (tgt_dir, fname[0], z, fname[1])
# fout = dname + "/" + c_name + "/" + fname[0] + "-z" + z + fname[1] # fout = dname + "/" + c_name + "/" + fname[0] + "-z" + z + fname[1]
......
...@@ -26,12 +26,12 @@ def process_fluoview_project(infile): ...@@ -26,12 +26,12 @@ def process_fluoview_project(infile):
micrometa.experiment.MosaicExperiment micrometa.experiment.MosaicExperiment
The mosaic object if parsing the project file has been successful. The mosaic object if parsing the project file has been successful.
""" """
if infile[-9:] == '.omp2info': if infile[-9:] == ".omp2info":
mosaicclass = micrometa.fluoview.FluoView3kMosaic mosaicclass = micrometa.fluoview.FluoView3kMosaic
elif infile[-4:] == '.log': elif infile[-4:] == ".log":
mosaicclass = micrometa.fluoview.FluoViewMosaic mosaicclass = micrometa.fluoview.FluoViewMosaic
else: else:
error_exit('Unsupported input file: %s' % infile) error_exit("Unsupported input file: %s" % infile)
log.info("Parsing project file: [%s]", infile) log.info("Parsing project file: [%s]", infile)
ij.IJ.showStatus("Parsing mosaics...") ij.IJ.showStatus("Parsing mosaics...")
...@@ -41,15 +41,15 @@ def process_fluoview_project(infile): ...@@ -41,15 +41,15 @@ def process_fluoview_project(infile):
ij.IJ.showProgress(0.0) ij.IJ.showProgress(0.0)
show_status("Parsed %s / %s mosaics" % (0, total)) show_status("Parsed %s / %s mosaics" % (0, total))
for i, subtree in enumerate(mosaics.mosaictrees): for i, subtree in enumerate(mosaics.mosaictrees):
log.info("Parsing mosaic %s...", i+1) log.info("Parsing mosaic %s...", i + 1)
try: try:
mosaics.add_mosaic(subtree, i) mosaics.add_mosaic(subtree, i)
except (ValueError, IOError) as err: except (ValueError, IOError) as err:
log.warn('Skipping mosaic %s: %s', i, err) log.warn("Skipping mosaic %s: %s", i, err)
except RuntimeError as err: except RuntimeError as err:
log.warn('Error parsing mosaic %s, SKIPPING: %s', i, err) log.warn("Error parsing mosaic %s, SKIPPING: %s", i, err)
show_progress(i, total) show_progress(i, total)
show_status("Parsed %s / %s mosaics" % (i+1, total)) show_status("Parsed %s / %s mosaics" % (i + 1, total))
show_progress(total, total) show_progress(total, total)
show_status("Parsed %i mosaics." % total) show_status("Parsed %i mosaics." % total)
...@@ -79,30 +79,30 @@ def gen_macro(mosaics, indir, outfile=None, opts=None): ...@@ -79,30 +79,30 @@ def gen_macro(mosaics, indir, outfile=None, opts=None):
list(str) list(str)
The generated macro code as a list of strings (one str per line). The generated macro code as a list of strings (one str per line).
""" """
templates = join(getProperty('fiji.dir'), 'jars', 'python-micrometa.jar') templates = join(getProperty("fiji.dir"), "jars", "python-micrometa.jar")
log.info("Using macro templates from [%s].", templates) log.info("Using macro templates from [%s].", templates)
log.info("Using [%s] as base directory.", indir) log.info("Using [%s] as base directory.", indir)
# set the default stitcher options # set the default stitcher options
stitcher_options = { stitcher_options = {
'export_format': '".ids"', "export_format": '".ids"',
'split_z_slices': 'false', "split_z_slices": "false",
'rotation_angle': 0, "rotation_angle": 0,
'stitch_regression': 0.3, "stitch_regression": 0.3,
'stitch_maxavg_ratio': 2.5, "stitch_maxavg_ratio": 2.5,
'stitch_abs_displace': 3.5, "stitch_abs_displace": 3.5,
'compute' : 'false', "compute": "false",
} }
# merge explicit options, overriding the defaults from above if applicable: # merge explicit options, overriding the defaults from above if applicable:
if opts: if opts:
stitcher_options.update(opts) stitcher_options.update(opts)
code = micrometa.imagej.gen_stitching_macro( code = micrometa.imagej.gen_stitching_macro(
name=mosaics.infile['dname'], name=mosaics.infile["dname"],
path=indir, path=indir,
tplpfx='templates/imagej-macro/stitching', tplpfx="templates/imagej-macro/stitching",
tplpath=templates, tplpath=templates,
opts=stitcher_options opts=stitcher_options,
) )
log.debug("============= begin of generated macro code =============") log.debug("============= begin of generated macro code =============")
...@@ -110,7 +110,7 @@ def gen_macro(mosaics, indir, outfile=None, opts=None): ...@@ -110,7 +110,7 @@ def gen_macro(mosaics, indir, outfile=None, opts=None):
log.debug("============= end of generated macro code =============") log.debug("============= end of generated macro code =============")
if outfile is not None: if outfile is not None:
log.info('Writing stitching macro.') log.info("Writing stitching macro.")
micrometa.imagej.write_stitching_macro(code, outfile) micrometa.imagej.write_stitching_macro(code, outfile)
return code return code
...@@ -7,7 +7,7 @@ from .log import LOG as log ...@@ -7,7 +7,7 @@ from .log import LOG as log
from .strtools import flatten from .strtools import flatten
def filehandle(fname, mode='r'): def filehandle(fname, mode="r"):
"""Make sure a variable is either a filehandle or create one from it. """Make sure a variable is either a filehandle or create one from it.
This function takes a variable and checks whether it is already a This function takes a variable and checks whether it is already a
...@@ -41,13 +41,13 @@ def filehandle(fname, mode='r'): ...@@ -41,13 +41,13 @@ def filehandle(fname, mode='r'):
<type 'file'> <type 'file'>
""" """
log.debug(type(fname)) log.debug(type(fname))
if type(fname).__name__ == 'str': if type(fname).__name__ == "str":
try: try:
return open(fname, mode) return open(fname, mode)
except IOError as err: except IOError as err:
message = "can't open '%s': %s" message = "can't open '%s': %s"
raise SystemExit(message % (fname, err)) raise SystemExit(message % (fname, err))
elif type(fname).__name__ == 'file': elif type(fname).__name__ == "file":
if fname.mode != mode: if fname.mode != mode:
message = "mode mismatch: %s != %s" message = "mode mismatch: %s != %s"
raise IOError(message % (fname.mode, mode)) raise IOError(message % (fname.mode, mode))
...@@ -57,7 +57,7 @@ def filehandle(fname, mode='r'): ...@@ -57,7 +57,7 @@ def filehandle(fname, mode='r'):
raise SystemExit(message % type(fname)) raise SystemExit(message % type(fname))
def readtxt(fname, path='', flat=False): def readtxt(fname, path="", flat=False):
"""Commodity function for reading text files plain or zipped. """Commodity function for reading text files plain or zipped.
Read a text file line by line either plainly from a directory or a .zip or Read a text file line by line either plainly from a directory or a .zip or
...@@ -90,13 +90,13 @@ def readtxt(fname, path='', flat=False): ...@@ -90,13 +90,13 @@ def readtxt(fname, path='', flat=False):
""" """
zipread = None zipread = None
suffix = splitext(path)[1].lower() suffix = splitext(path)[1].lower()
if ((suffix == '.zip') or (suffix == '.jar')): if (suffix == ".zip") or (suffix == ".jar"):
# ZipFile only works as a context manager from Python 2.7 on # ZipFile only works as a context manager from Python 2.7 on
# tag:python25 # tag:python25
zipread = zipfile.ZipFile(path, 'r') zipread = zipfile.ZipFile(path, "r")
fin = zipread.open(fname) fin = zipread.open(fname)
else: else:
fin = open(join(path, fname), 'r') fin = open(join(path, fname), "r")
txt = fin.readlines() # returns file as a list, one entry per line txt = fin.readlines() # returns file as a list, one entry per line
if flat: if flat:
txt = flatten(txt) txt = flatten(txt)
......
...@@ -38,7 +38,7 @@ def enable_console_logging(): ...@@ -38,7 +38,7 @@ def enable_console_logging():
return stream_handler return stream_handler
def enable_file_logging(fname, mode='a'): def enable_file_logging(fname, mode="a"):
"""Add a logging handler writing to a file. """Add a logging handler writing to a file.
Returns Returns
......
...@@ -53,13 +53,13 @@ def parse_path(path): ...@@ -53,13 +53,13 @@ def parse_path(path):
'' ''
""" """
parsed = {} parsed = {}
parsed['orig'] = path parsed["orig"] = path
path = path.replace('\\', sep) path = path.replace("\\", sep)
parsed['full'] = path parsed["full"] = path
parsed['path'] = os.path.dirname(path) + sep parsed["path"] = os.path.dirname(path) + sep
parsed['fname'] = os.path.basename(path) parsed["fname"] = os.path.basename(path)
parsed['dname'] = os.path.basename(os.path.dirname(parsed['path'])) parsed["dname"] = os.path.basename(os.path.dirname(parsed["path"]))
parsed['ext'] = os.path.splitext(parsed['fname'])[1] parsed["ext"] = os.path.splitext(parsed["fname"])[1]
return parsed return parsed
...@@ -130,7 +130,7 @@ def image_basename(orig_name): ...@@ -130,7 +130,7 @@ def image_basename(orig_name):
'FoObAr' 'FoObAr'
""" """
base = os.path.splitext(os.path.basename(orig_name))[0] base = os.path.splitext(os.path.basename(orig_name))[0]
if base.lower().endswith('.ome'): if base.lower().endswith(".ome"):
base = base[:-4] base = base[:-4]
return base return base
...@@ -190,10 +190,11 @@ def derive_out_dir(in_dir, out_dir): ...@@ -190,10 +190,11 @@ def derive_out_dir(in_dir, out_dir):
# pylint: disable-msg=C0103 # pylint: disable-msg=C0103
# we use the variable name 'exists' in its common spelling (lowercase), so # we use the variable name 'exists' in its common spelling (lowercase), so
# removing this workaround will be straightforward at a later point # removing this workaround will be straightforward at a later point
if platform.python_implementation() == 'Jython': if platform.python_implementation() == "Jython":
# pylint: disable-msg=F0401 # pylint: disable-msg=F0401
# java.lang is only importable within Jython, pylint would complain # java.lang is only importable within Jython, pylint would complain
import java.lang import java.lang
exists = jython_fiji_exists exists = jython_fiji_exists
else: else:
exists = os.path.exists exists = os.path.exists
...@@ -18,7 +18,7 @@ def _is_string_like(obj): ...@@ -18,7 +18,7 @@ def _is_string_like(obj):
False False
""" """
try: try:
obj + '' obj + ""
except (TypeError, ValueError): except (TypeError, ValueError):
return False return False
return True return True
...@@ -95,5 +95,5 @@ def strip_prefix(string, prefix): ...@@ -95,5 +95,5 @@ def strip_prefix(string, prefix):
string doesn't start with the prefix, it is returned unchanged. string doesn't start with the prefix, it is returned unchanged.
""" """
if string.startswith(prefix): if string.startswith(prefix):
string = string[len(prefix):] string = string[len(prefix) :]
return string return string
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment