diff --git a/src/imcflibs/__init__.py b/src/imcflibs/__init__.py index 16c39bca9f7cd1f32daeb8fb645cde0308d186c9..3b59a6fd781f93d8605357a582adeaeb04ad9dd1 100644 --- a/src/imcflibs/__init__.py +++ b/src/imcflibs/__init__.py @@ -21,4 +21,4 @@ Biozentrum, University of Basel, Switzerland. [imagej]: https://imagej.net """ -__version__ = '${project.version}' +__version__ = "${project.version}" diff --git a/src/imcflibs/imagej/misc.py b/src/imcflibs/imagej/misc.py index 2d0e33e3ab23dbbc6128d7faa5f3040e03f5491f..17620077ff1f479647d380a1cf2c44a913c51629 100644 --- a/src/imcflibs/imagej/misc.py +++ b/src/imcflibs/imagej/misc.py @@ -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) diff --git a/src/imcflibs/imagej/prefs.py b/src/imcflibs/imagej/prefs.py index 54e51f45e28466f68822325b625039b83f0d49dc..179907c5d4830c8558fe4fb435f6ae0500fb047a 100644 --- a/src/imcflibs/imagej/prefs.py +++ b/src/imcflibs/imagej/prefs.py @@ -2,6 +2,7 @@ from ij import Prefs # pylint: disable-msg=E0401 + def debug_mode(): """Wrapper to check if 'imcf.debugging' is enabled. diff --git a/src/imcflibs/imagej/projections.py b/src/imcflibs/imagej/projections.py index 6313875f3011a5b1066bd8b2c8b15ba7d76a31f1..1a6d0501f8edd77d909f0d624dc258e3566097c2 100644 --- a/src/imcflibs/imagej/projections.py +++ b/src/imcflibs/imagej/projections.py @@ -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 diff --git a/src/imcflibs/imagej/shading.py b/src/imcflibs/imagej/shading.py index c0a20a3ece44c5f1ea51557380cde8bbcbc65412..ab59777fb3572485eea81e2214b2f1b08129f992 100644 --- a/src/imcflibs/imagej/shading.py +++ b/src/imcflibs/imagej/shading.py @@ -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() diff --git a/src/imcflibs/imagej/split.py b/src/imcflibs/imagej/split.py index 8aa15b0b54e801181c549c842137b9f98c7bad99..5184e91b8234f5535e35495548dd1d7dcc61d126 100644 --- a/src/imcflibs/imagej/split.py +++ b/src/imcflibs/imagej/split.py @@ -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] diff --git a/src/imcflibs/imagej/stitching.py b/src/imcflibs/imagej/stitching.py index 29fd30b4194a0e320d15163e5e9e79189baec505..a82a66d228566c455871d6a11eb02d1d5b3d91d8 100644 --- a/src/imcflibs/imagej/stitching.py +++ b/src/imcflibs/imagej/stitching.py @@ -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 diff --git a/src/imcflibs/iotools.py b/src/imcflibs/iotools.py index 6c5a955ff95f327f1d6a3ef9dcdf679ae7d6403a..9d0d44c483b4e822631796905b3ff76b2ae4ab54 100644 --- a/src/imcflibs/iotools.py +++ b/src/imcflibs/iotools.py @@ -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) diff --git a/src/imcflibs/log.py b/src/imcflibs/log.py index 2d9682014d28c2de0ab209e0c88b132962b73d89..4b0b967df2da5da350943dc271860a7fff232c81 100644 --- a/src/imcflibs/log.py +++ b/src/imcflibs/log.py @@ -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 diff --git a/src/imcflibs/pathtools.py b/src/imcflibs/pathtools.py index da45be71e1f80cd6b34fafeead1a7d6a1f2314f2..7007fbb1eabd05948cd92a787000cbb85281893b 100644 --- a/src/imcflibs/pathtools.py +++ b/src/imcflibs/pathtools.py @@ -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 diff --git a/src/imcflibs/strtools.py b/src/imcflibs/strtools.py index 2f1c6269ab20d4f050c9e9f960116e085b658328..ecbb79048258c98261f70dc1fc8837481753f83c 100644 --- a/src/imcflibs/strtools.py +++ b/src/imcflibs/strtools.py @@ -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