From 8728b501ce38cb775cf38bc8ed21bae716270481 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 1 Oct 2023 10:21:46 +0200 Subject: [PATCH] Use f-strings where possible It's faster. --- examples/fitting_data/t1_measurements/pt.py | 2 +- examples/plotting/plot_2d/plot_boxes.py | 2 +- .../plot_sparky_savefile/plot_sparky.py | 2 +- nmrglue/analysis/linesh.py | 3 +- nmrglue/analysis/peakpick.py | 4 +- nmrglue/fileio/bruker.py | 48 +++++++++---------- nmrglue/fileio/convert.py | 2 +- nmrglue/fileio/glue.py | 2 +- nmrglue/fileio/jcampdx.py | 15 +++--- nmrglue/fileio/rnmrtk.py | 2 +- nmrglue/fileio/table.py | 4 +- nmrglue/fileio/varian.py | 26 +++++----- nmrglue/util/xcpy.py | 8 ++-- 13 files changed, 59 insertions(+), 61 deletions(-) diff --git a/examples/fitting_data/t1_measurements/pt.py b/examples/fitting_data/t1_measurements/pt.py index 21925300..fa2710c6 100755 --- a/examples/fitting_data/t1_measurements/pt.py +++ b/examples/fitting_data/t1_measurements/pt.py @@ -40,5 +40,5 @@ def fit_func(p, x): ax.set_title(peak) # save the figure - fig.savefig(peak + "_plot.png") + fig.savefig(f"{peak}_plot.png") plt.close() diff --git a/examples/plotting/plot_2d/plot_boxes.py b/examples/plotting/plot_2d/plot_boxes.py index d8ffe745..7c30606e 100755 --- a/examples/plotting/plot_2d/plot_boxes.py +++ b/examples/plotting/plot_2d/plot_boxes.py @@ -56,5 +56,5 @@ ax.set_title(name) # save the figure - fig.savefig(name + ".png") + fig.savefig(f"{name}.png") del(fig) diff --git a/examples/plotting/plot_sparky_savefile/plot_sparky.py b/examples/plotting/plot_sparky_savefile/plot_sparky.py index 584e7e84..55280c91 100644 --- a/examples/plotting/plot_sparky_savefile/plot_sparky.py +++ b/examples/plotting/plot_sparky_savefile/plot_sparky.py @@ -82,7 +82,7 @@ def plot(dic, data, outfile=None, xlims=[], ylims=[]): # save figure if outfile is None: outfile = "plot" - fig.savefig(outfile + ".png") + fig.savefig(f"{outfile}.png") return diff --git a/nmrglue/analysis/linesh.py b/nmrglue/analysis/linesh.py index ad4504b8..b13b7cf3 100644 --- a/nmrglue/analysis/linesh.py +++ b/nmrglue/analysis/linesh.py @@ -496,8 +496,7 @@ def fit_NDregion(region, lineshapes, params, amps, bounds=None, if wmask is None: # default is to include all points in region wmask = np.ones(shape, dtype='bool') if wmask.shape != shape: - err = "wmask has incorrect shape:" + str(wmask.shape) + \ - " should be " + str(shape) + err = f"wmask has incorrect shape: {wmask.shape} should be {shape}" raise ValueError(err) # DEBUGGING diff --git a/nmrglue/analysis/peakpick.py b/nmrglue/analysis/peakpick.py index 639d502a..8eeda0d3 100644 --- a/nmrglue/analysis/peakpick.py +++ b/nmrglue/analysis/peakpick.py @@ -326,13 +326,13 @@ def pack_table(locations, cluster_ids=None, scales=None, amps=None, ndim = len(locations[0]) anames = axis_names[-ndim:] - dt = [(a + "_AXIS", float) for a in anames] + dt = [(f"{a}_AXIS", float) for a in anames] rec = np.rec.array(locations, dtype=dt) if cluster_ids is not None: rec = table.append_column(rec, cluster_ids, 'cID', 'int') if scales is not None: - names = [a + "_LW" for a in anames] + names = [f"{a}_LW" for a in anames] for n, c in zip(names, np.array(scales).T): rec = table.append_column(rec, c, n, 'float') if amps is not None: diff --git a/nmrglue/fileio/bruker.py b/nmrglue/fileio/bruker.py index fe66717f..2bcc6963 100644 --- a/nmrglue/fileio/bruker.py +++ b/nmrglue/fileio/bruker.py @@ -111,8 +111,8 @@ def add_axis_to_udic(udic, dic, udim, strip_fake): """ # This could still use some work b_dim = udic['ndim'] - udim - 1 # last dim - acq_file = "acqu" + str(b_dim + 1) + "s" - pro_file = "proc" + str(b_dim + 1) + "s" + acq_file = f"acqu{b_dim + 1}s" + pro_file = f"proc{b_dim + 1}s" # Because they're inconsistent,.. if acq_file == "acqu1s": @@ -1546,7 +1546,7 @@ def read_binary(filename, shape=(1), cplex=True, big=True, isfloat=False): return dic, data.reshape(shape) except ValueError: - warn(str(data.shape) + "cannot be shaped into" + str(shape)) + warn(f"{data.shape} cannot be shaped into {shape}") return dic, data @@ -2169,9 +2169,9 @@ def read_jcamp(filename, encoding=locale.getpreferredencoding()): key, value = parse_jcamp_line(line, f) dic[key] = value except: - warn("Unable to correctly parse line:" + line) + warn(f"Unable to correctly parse line: {line}") else: - warn("Extraneous line:" + line) + warn(f"Extraneous line: {line}") return dic @@ -2192,7 +2192,7 @@ def parse_jcamp_line(line, f): if "<" in text: # string while ">" not in text: # grab additional text until ">" in string - text = text + "\n" + f.readline().rstrip() + text += "\n" + f.readline().rstrip() value = text[1:-1] # remove < and > elif "(" in text: # array @@ -2317,24 +2317,24 @@ def write_jcamp_pair(f, key, value): """ # the parameter name and such - line = "##$" + key + "= " + line = f"##${key}= " - # need to be type not isinstance since isinstance(bool, int) == True - if type(value) == float or type(value) == int: # simple numbers - line = line + repr(value) - - elif isinstance(value, str): # string - line = line + "<" + value + ">" - - elif type(value) == bool: # yes or no + # need to be checked first since isinstance(bool, int) == True + if isinstance(value, bool): # yes or no if value: - line = line + "yes" + line += "yes" else: - line = line + "no" + line += "no" + + elif isinstance(value, (float, int)): # simple numbers + line += repr(value) + + elif isinstance(value, str): # string + line += f"<{value}>" elif isinstance(value, list): # write out the current line - line = line + "(0.." + repr(len(value) - 1) + ")" + line += f"(0..{len(value) - 1!r})" f.write(line) f.write("\n") line = "" @@ -2349,7 +2349,7 @@ def write_jcamp_pair(f, key, value): line = "" if isinstance(v, str): - to_add = "<" + v + ">" + to_add = f"<{v}>" else: to_add = repr(v) @@ -2359,7 +2359,7 @@ def write_jcamp_pair(f, key, value): line = "" if line != "": - line = line + to_add + " " + line += to_add + " " else: line = to_add + " " @@ -2558,20 +2558,20 @@ def write_pprog(filename, dic, overwrite=False): # write our the variables for k, v in dic["var"].items(): - f.write("\"" + k + "=" + v + "\"\n") + f.write(f'"{k}={v}"\n') # write out each loop for i, steps in enumerate(dic["loop"]): # write our the increments for v in dic["incr"][i]: - f.write("d01 id" + str(v) + "\n") + f.write(f"d01 id{v}\n") # write out the phases for v, w in zip(dic["phase"][i], dic["ph_extra"][i]): - f.write("d01 ip" + str(v) + " " + str(w) + "\n") + f.write(f"d01 ip{v} {w}\n") - f.write("lo to 0 times " + str(steps) + "\n") + f.write(f"lo to 0 times {steps}\n") # close the file f.close() diff --git a/nmrglue/fileio/convert.py b/nmrglue/fileio/convert.py index 82dda43a..acd4f1d1 100644 --- a/nmrglue/fileio/convert.py +++ b/nmrglue/fileio/convert.py @@ -467,7 +467,7 @@ def to_csdm(self): label=value["label"], ) for key, value in list(self._udic.items()) - if type(key) == int and value["size"] != 1 + if type(key) is int and value["size"] != 1 ] return cp.CSDM( diff --git a/nmrglue/fileio/glue.py b/nmrglue/fileio/glue.py index 43f2c1d4..e2f24664 100644 --- a/nmrglue/fileio/glue.py +++ b/nmrglue/fileio/glue.py @@ -155,7 +155,7 @@ def put_dic(f, dic, dataset="spectrum"): for key, value in dic.items(): # axis dictionaries - if type(key) == int and type(value) == dict: + if type(key) is int and type(value) is dict: axis = key for axiskey, axisvalue in value.items(): fullkey = str(axis) + "_" + axiskey diff --git a/nmrglue/fileio/jcampdx.py b/nmrglue/fileio/jcampdx.py index 4b31ecfd..1d41e2b5 100644 --- a/nmrglue/fileio/jcampdx.py +++ b/nmrglue/fileio/jcampdx.py @@ -72,7 +72,7 @@ def _parsejcampdx(filename): # for multi-line data, linebreak must be restored if it has been # cut out with comments: if actual[-1] != "\n": - actual = actual + "\n" + actual += "\n" # encountered new key: if actual[:2] == "##": @@ -85,7 +85,7 @@ def _parsejcampdx(filename): key = _getkey(currentkey) value = "".join(currentvaluestrings) # collapse if not value.strip(): - warn("JCAMP-DX key without value:" + key) + warn(f"JCAMP-DX key without value: {key}") else: try: activeblock[key].append(value) @@ -121,7 +121,7 @@ def _parsejcampdx(filename): keystr = keysplit[0][2:] # remove "##" already here valuestr = keysplit[1] if not keystr: - warn("Empty key in JCAMP-DX line:" + line) + warn(f"Empty key in JCAMP-DX line: {line}") currentkey = None currentvaluestrings = [] continue @@ -134,7 +134,7 @@ def _parsejcampdx(filename): else: if activeblock: if currentkey is None: - warn("JCAMP-DX data line without associated key:" + line) + warn(f"JCAMP-DX data line without associated key: {line}") continue currentvaluestrings.append(commentsplit[0]) @@ -272,7 +272,7 @@ def _parse_affn_pac(datalines): try: value = float(base + (exp if exp is not None else "")) except ValueError: - warn("Data parsing failed at line:" + dataline) + warn(f"Data parsing failed at line: {dataline}") return None linedata.append(value) if len(linedata) > 1: @@ -375,8 +375,7 @@ def _parse_pseudo(datalines): valuechar = _DUP_DIGITS[char] newmode = 3 except KeyError: - warn("Unknown pseudo-digit: " + - char + " at line: " + dataline) + warn(f"Unknown pseudo-digit: {char} at line: {dataline}") return None # finish previous number @@ -399,7 +398,7 @@ def _parse_pseudo(datalines): value_to_append, data) if not success: - warn("Data parsing failed at line:" + dataline) + warn(f"Data parsing failed at line: {dataline}") return None # in DIF mode last of line is same than the first of next line diff --git a/nmrglue/fileio/rnmrtk.py b/nmrglue/fileio/rnmrtk.py index 1d0db6ed..48a7cdd1 100644 --- a/nmrglue/fileio/rnmrtk.py +++ b/nmrglue/fileio/rnmrtk.py @@ -738,7 +738,7 @@ def write_par(par_file, dic, overwrite): f = fileiobase.open_towrite(par_file, overwrite, mode='w') # write comment line - f.write('Comment \'' + dic['comment'] + '\'\n') + f.write("Comment '" + dic['comment'] + "'\n") # Dom line, set from layout l = "Dom " + " ".join(dic['layout'][1]) diff --git a/nmrglue/fileio/table.py b/nmrglue/fileio/table.py index fdedec64..16cb9ece 100644 --- a/nmrglue/fileio/table.py +++ b/nmrglue/fileio/table.py @@ -34,7 +34,7 @@ def pipe2glue(pcomments, pformat, rec): """ # add a "#" to the list of comments and we are done - comments = ["# " + c for c in pcomments] + comments = [f"# {c}" for c in pcomments] return comments, rec @@ -62,7 +62,7 @@ def glue2pipe(comments, rec): """ # add REMARK to each comment - pcomments = ["REMARK " + c for c in comments] + pcomments = [f"REMARK {c}" for c in comments] # guess the pipe format strings pformat = [guess_pformat(rec[t]) for t in rec.dtype.names] diff --git a/nmrglue/fileio/varian.py b/nmrglue/fileio/varian.py index 75be3672..ad45583e 100644 --- a/nmrglue/fileio/varian.py +++ b/nmrglue/fileio/varian.py @@ -504,8 +504,8 @@ def find_torder(dic, shape): warn("missing phase order, torder set to 'r'") return 'r' - warn("No trace ordering for" + str(ndim) + - "dimensional data, torder set to 'r'") + warn(f"No trace ordering for {ndim}dimensional data, " + f"torder set to 'r'") return 'r' @@ -523,7 +523,7 @@ def torder2i2t(torder): elif torder in ('regular', 'r'): return fileiobase.index2trace_reg else: - raise ValueError("unknown torder" + str(torder)) + raise ValueError(f"unknown torder {torder}") def torder2t2i(torder): @@ -539,7 +539,7 @@ def torder2t2i(torder): elif torder in ('regular', 'r'): return fileiobase.trace2index_reg else: - raise ValueError("unknown torder" + str(torder)) + raise ValueError(f"unknown torder {torder}") def reorder_data(data, shape, torder): @@ -571,7 +571,7 @@ def reorder_data(data, shape, torder): try: data = data.reshape(shape) except ValueError: - warn(str(data.shape) + "cannot be shaped into" + str(shape)) + warn(f"{data.shape} cannot be shaped into {shape}") return data # all other cases @@ -716,14 +716,14 @@ def read_fid(filename, shape=None, torder='flat', as_2d=False, try: return dic, reorder_data(data, shape, torder) except: - warn("data cannot be re-ordered, returning raw 2D data\n" + - "Provided shape: " + str(shape) + " torder: " + str(torder)) + warn(f"data cannot be re-ordered, returning raw 2D data\n" + + f"Provided shape: {shape} torder: {torder}") return dic, data try: data = data.reshape(shape) except ValueError: - warn(str(data.shape) + "cannot be shaped into" + str(shape)) + warn(f"{data.shape} cannot be shaped into {shape}") return dic, data return dic, data @@ -858,7 +858,7 @@ def read_fid_ntraces(filename, shape=None, torder='flat', as_2d=False, try: data = data.reshape(shape) except ValueError: - warn(str(data.shape) + "cannot be shaped into" + str(shape)) + warn(f"{data.shape} cannot be shaped into {shape}") return dic, data return dic, data @@ -942,7 +942,7 @@ def write_fid(filename, dic, data, torder='flat', repack=False, correct=True, else: # create a generic blockheader bh = dic2blockheader(make_blockheader(dic, 1)) for i in range(data.shape[0]): - bh[2] = int(i + 1) + bh[2] = i + 1 trace = np.array(interleave_data(data[i]), dtype=dt) put_block(f, trace, dic["nbheaders"], bh) @@ -1027,7 +1027,7 @@ def write_fid_lowmem(filename, dic, data, torder='f', repack=False, else: # create a generic blockheader bh = dic2blockheader(make_blockheader(dic, 1)) for ntrace in range(nblocks): - bh[2] = int(ntrace + 1) + bh[2] = ntrace + 1 tup = t2i(data.shape[:-1], ntrace) trace = np.array(interleave_data(data[tup]), dtype=dt) put_block(f, trace, dic["nbheaders"], bh) @@ -1949,7 +1949,7 @@ def write_procpar(filename, dic, overwrite=False): print(len(d["values"]), end=' ', file=f) # don't end the line for value in d["values"]: # now end the line (for each string) - print('"' + value + '"', file=f) + print(f'"{value}"', file=f) # print out the last line print(d["enumerable"], end=' ', file=f) @@ -1959,7 +1959,7 @@ def write_procpar(filename, dic, overwrite=False): if d["basictype"] == "1": # reals print(e, end=' ', file=f) elif d["basictype"] == "2": # strings - print('"' + e + '"', end=' ', file=f) + print(f'"{e}"', end=' ', file=f) print("", file=f) # end the enumerable line f.close() diff --git a/nmrglue/util/xcpy.py b/nmrglue/util/xcpy.py index 79f11123..f63b19b8 100644 --- a/nmrglue/util/xcpy.py +++ b/nmrglue/util/xcpy.py @@ -196,7 +196,7 @@ def write_cfg(outfile, infile=None): with open(outfile, "w") as f: config.write(f) - MSG("Written Configuration file at: " + outfile) + MSG(f"Written Configuration file at: {outfile}") def exists(filename, raise_error=False): @@ -273,7 +273,7 @@ def run(cpython, script, pass_current_folder=True, use_shell=None, dry=None): args = [cpython, script] + cd if dry: - MSG("The following command will be executed: \n" + " ".join(args)) + MSG("The following command will be executed:\n" + " ".join(args)) process = None else: @@ -336,7 +336,7 @@ def show_config(filename, printing=True): MSG(config) except FileNotFoundError: if printing: - MSG(filename + " not found") + MSG(f"{filename} not found") config = None return config @@ -442,7 +442,7 @@ def main(): # check for .py extension and append it if not given if not scriptname.endswith('.py'): - scriptname = scriptname + '.py' + scriptname += '.py' # run the script if it exists and then break from the for loop # and set the executed status to true