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.
[imagej]: https://imagej.net
"""
__version__ = '${project.version}'
__version__ = "${project.version}"
......@@ -15,9 +15,10 @@ def show_status(msg):
def show_progress(cur, final):
"""Wrapper to update the progress bar and issue a log message."""
# 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)
def error_exit(msg):
"""Convenience wrapper to log an error and exit then."""
log.error(msg)
......
......@@ -2,6 +2,7 @@
from ij import Prefs # pylint: disable-msg=E0401
def debug_mode():
"""Wrapper to check if 'imcf.debugging' is enabled.
......
......@@ -82,18 +82,21 @@ def create_and_save(imp, projections, path, filename, export_format):
return False
command = {
'Average': 'avg',
'Maximum': 'max',
'Sum': 'sum',
"Average": "avg",
"Maximum": "max",
"Sum": "sum",
}
for projection in projections:
log.debug("Creating '%s' projection...", projection)
proj = ZProjector.run(imp, command[projection])
export_using_orig_name(proj,
path, filename,
"-%s" % command[projection],
export_format,
overwrite=True)
export_using_orig_name(
proj,
path,
filename,
"-%s" % command[projection],
export_format,
overwrite=True,
)
proj.close()
return True
......@@ -105,10 +105,10 @@ def correct_and_project(filename, path, model, proj, fmt):
imps = [imp]
ret_corr = True
if proj == 'None':
if proj == "None":
projs = []
elif proj == 'ALL':
projs = ['Average', 'Maximum']
elif proj == "ALL":
projs = ["Average", "Maximum"]
else:
projs = [proj]
for imp in imps:
......@@ -159,8 +159,7 @@ def process_files(files, outpath, model_file, fmt):
fmt : str
The file format suffix for storing the results.
"""
log.info("Running shading correction and projections on %s files...",
len(files))
log.info("Running shading correction and projections on %s files...", len(files))
if model_file.upper() in ["-", "NONE"]:
model = None
......@@ -177,7 +176,7 @@ def process_files(files, outpath, model_file, fmt):
misc.error_exit("Opening shading model [%s] failed!" % model_file)
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:
model.close()
......@@ -6,6 +6,7 @@ from ij import IJ, ImagePlus # pylint: disable-msg=E0401
from ij.io import FileSaver # 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):
"""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):
if not os.path.isdir(tgt_dir):
os.mkdir(tgt_dir)
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)
fout = "%s/%s-z%s%s" % (tgt_dir, fname[0], z, fname[1])
# fout = dname + "/" + c_name + "/" + fname[0] + "-z" + z + fname[1]
......
......@@ -26,12 +26,12 @@ def process_fluoview_project(infile):
micrometa.experiment.MosaicExperiment
The mosaic object if parsing the project file has been successful.
"""
if infile[-9:] == '.omp2info':
if infile[-9:] == ".omp2info":
mosaicclass = micrometa.fluoview.FluoView3kMosaic
elif infile[-4:] == '.log':
elif infile[-4:] == ".log":
mosaicclass = micrometa.fluoview.FluoViewMosaic
else:
error_exit('Unsupported input file: %s' % infile)
error_exit("Unsupported input file: %s" % infile)
log.info("Parsing project file: [%s]", infile)
ij.IJ.showStatus("Parsing mosaics...")
......@@ -41,15 +41,15 @@ def process_fluoview_project(infile):
ij.IJ.showProgress(0.0)
show_status("Parsed %s / %s mosaics" % (0, total))
for i, subtree in enumerate(mosaics.mosaictrees):
log.info("Parsing mosaic %s...", i+1)
log.info("Parsing mosaic %s...", i + 1)
try:
mosaics.add_mosaic(subtree, i)
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:
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_status("Parsed %s / %s mosaics" % (i+1, total))
show_status("Parsed %s / %s mosaics" % (i + 1, total))
show_progress(total, total)
show_status("Parsed %i mosaics." % total)
......@@ -79,30 +79,30 @@ def gen_macro(mosaics, indir, outfile=None, opts=None):
list(str)
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 [%s] as base directory.", indir)
# set the default stitcher options
stitcher_options = {
'export_format': '".ids"',
'split_z_slices': 'false',
'rotation_angle': 0,
'stitch_regression': 0.3,
'stitch_maxavg_ratio': 2.5,
'stitch_abs_displace': 3.5,
'compute' : 'false',
"export_format": '".ids"',
"split_z_slices": "false",
"rotation_angle": 0,
"stitch_regression": 0.3,
"stitch_maxavg_ratio": 2.5,
"stitch_abs_displace": 3.5,
"compute": "false",
}
# merge explicit options, overriding the defaults from above if applicable:
if opts:
stitcher_options.update(opts)
code = micrometa.imagej.gen_stitching_macro(
name=mosaics.infile['dname'],
name=mosaics.infile["dname"],
path=indir,
tplpfx='templates/imagej-macro/stitching',
tplpfx="templates/imagej-macro/stitching",
tplpath=templates,
opts=stitcher_options
opts=stitcher_options,
)
log.debug("============= begin of generated macro code =============")
......@@ -110,7 +110,7 @@ def gen_macro(mosaics, indir, outfile=None, opts=None):
log.debug("============= end of generated macro code =============")
if outfile is not None:
log.info('Writing stitching macro.')
log.info("Writing stitching macro.")
micrometa.imagej.write_stitching_macro(code, outfile)
return code
......@@ -7,7 +7,7 @@ from .log import LOG as log
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.
This function takes a variable and checks whether it is already a
......@@ -41,13 +41,13 @@ def filehandle(fname, mode='r'):
<type 'file'>
"""
log.debug(type(fname))
if type(fname).__name__ == 'str':
if type(fname).__name__ == "str":
try:
return open(fname, mode)
except IOError as err:
message = "can't open '%s': %s"
raise SystemExit(message % (fname, err))
elif type(fname).__name__ == 'file':
elif type(fname).__name__ == "file":
if fname.mode != mode:
message = "mode mismatch: %s != %s"
raise IOError(message % (fname.mode, mode))
......@@ -57,7 +57,7 @@ def filehandle(fname, mode='r'):
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.
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):
"""
zipread = None
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
# tag:python25
zipread = zipfile.ZipFile(path, 'r')
zipread = zipfile.ZipFile(path, "r")
fin = zipread.open(fname)
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
if flat:
txt = flatten(txt)
......
......@@ -38,7 +38,7 @@ def enable_console_logging():
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.
Returns
......
......@@ -53,13 +53,13 @@ def parse_path(path):
''
"""
parsed = {}
parsed['orig'] = path
path = path.replace('\\', sep)
parsed['full'] = path
parsed['path'] = os.path.dirname(path) + sep
parsed['fname'] = os.path.basename(path)
parsed['dname'] = os.path.basename(os.path.dirname(parsed['path']))
parsed['ext'] = os.path.splitext(parsed['fname'])[1]
parsed["orig"] = path
path = path.replace("\\", sep)
parsed["full"] = path
parsed["path"] = os.path.dirname(path) + sep
parsed["fname"] = os.path.basename(path)
parsed["dname"] = os.path.basename(os.path.dirname(parsed["path"]))
parsed["ext"] = os.path.splitext(parsed["fname"])[1]
return parsed
......@@ -130,7 +130,7 @@ def image_basename(orig_name):
'FoObAr'
"""
base = os.path.splitext(os.path.basename(orig_name))[0]
if base.lower().endswith('.ome'):
if base.lower().endswith(".ome"):
base = base[:-4]
return base
......@@ -190,10 +190,11 @@ def derive_out_dir(in_dir, out_dir):
# pylint: disable-msg=C0103
# we use the variable name 'exists' in its common spelling (lowercase), so
# removing this workaround will be straightforward at a later point
if platform.python_implementation() == 'Jython':
if platform.python_implementation() == "Jython":
# pylint: disable-msg=F0401
# java.lang is only importable within Jython, pylint would complain
import java.lang
exists = jython_fiji_exists
else:
exists = os.path.exists
......@@ -18,7 +18,7 @@ def _is_string_like(obj):
False
"""
try:
obj + ''
obj + ""
except (TypeError, ValueError):
return False
return True
......@@ -95,5 +95,5 @@ def strip_prefix(string, prefix):
string doesn't start with the prefix, it is returned unchanged.
"""
if string.startswith(prefix):
string = string[len(prefix):]
string = string[len(prefix) :]
return string
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment