PK!peakipy/__init__.pyPK!peakipy/__main__.py__all__ = ( 'main', ) def main(): """ execute main peakipy script """ import sys from peakipy.commandline.peakipy import main as _main _main(sys.argv) if __name__ == "__main__": main() PK!peakipy/commandline/__init__.pyPK!YH-)-)peakipy/commandline/check.py#!/usr/bin/env python3 """ Plot peakipy fits Usage: check [options] Options: --dims= Dimension order [default: 0,1,2] --clusters= Plot selected cluster based on clustid [default: None] eg. --clusters=1 or --clusters=2,4,6,7 --outname= Plot name [default: plots.pdf] --first Only plot first plane --show Invoke plt.show() for interactive plot --rcount= row count setting for wireplot [default: 50] --ccount= column count setting for wireplot [default: 50] --colors= plot colors [default: '#5e3c99','#e66101'] --help peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import json from sys import exit from pathlib import Path import pandas as pd import numpy as np import nmrglue as ng import matplotlib.pyplot as plt from docopt import docopt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.backends.backend_pdf import PdfPages from matplotlib.widgets import Button from peakipy.core import ( make_mask, pvoigt2d, pv_pv, pv_g, pv_l, gaussian_lorentzian, Pseudo3D, run_log, ) def main(argv): args = docopt(__doc__, argv=argv) fits = Path(args.get("")) fits = pd.read_csv(fits) # get dims from config file config_path = Path("peakipy.config") if config_path.exists(): config = json.load(open(config_path)) print(f"Using config file with --dims={config.get('--dims')}") dims = config.get("--dims", [0, 1, 2]) else: dims = args.get("--dims") dims = [int(i) for i in eval(dims)] data_path = args.get("") dic, data = ng.pipe.read(data_path) pseudo3D = Pseudo3D(dic, data, dims) outname = args.get("--outname") first_only = args.get("--first") show = args.get("--show") clusters = args.get("--clusters") ccount = eval(args.get("--ccount")) rcount = eval(args.get("--rcount")) colors = args.get("--colors").strip().split(",") if type(ccount) == int: ccount = ccount else: raise TypeError("ccount should be an integer") if type(rcount) == int: rcount = rcount else: raise TypeError("rcount should be an integer") if (type(colors) == list) and len(colors) == 2: data_color, fit_color = colors else: raise TypeError( "colors should be valid pair for matplotlib. i.e. g,b or green,blue" ) if clusters == "None": pass else: clusters = [int(i) for i in clusters.split(",")] # only use these clusters fits = fits[fits.clustid.isin(clusters)] groups = fits.groupby("clustid") # make plotting meshes x = np.arange(pseudo3D.f2_size) y = np.arange(pseudo3D.f1_size) XY = np.meshgrid(x, y) X, Y = XY with PdfPages(outname) as pdf: for ind, group in groups: mask = np.zeros((pseudo3D.f1_size, pseudo3D.f2_size), dtype=bool) # sim_data = np.zeros((pseudo3D.f1_size, pseudo3D.f2_size)) first_plane = group[group.plane == 0] x_radius = group.x_radius.max() y_radius = group.y_radius.max() max_x, min_x = ( int(np.ceil(max(group.center_x) + x_radius + 1)), int(np.floor(min(group.center_x) - x_radius)), ) max_y, min_y = ( int(np.ceil(max(group.center_y) + y_radius + 1)), int(np.floor(min(group.center_y) - y_radius)), ) #  deal with peaks on the edge of spectrum if min_y < 0: min_y = 0 if min_x < 0: min_x = 0 if max_y > pseudo3D.f1_size: max_y = pseudo3D.f1_size if max_x > pseudo3D.f2_size: max_x = pseudo3D.f2_size masks = [] # make masks for cx, cy, rx, ry, name in zip( first_plane.center_x, first_plane.center_y, first_plane.x_radius, first_plane.y_radius, first_plane.assignment, ): tmp_mask = make_mask(mask, cx, cy, rx, ry) mask += tmp_mask masks.append(tmp_mask) # generate simulated data for plane_id, plane in group.groupby("plane"): sim_data = np.zeros((pseudo3D.f1_size, pseudo3D.f2_size)) shape = sim_data.shape try: for amp, c_x, c_y, s_x, s_y, frac_x, frac_y, ls in zip( plane.amp, plane.center_x, plane.center_y, plane.sigma_x, plane.sigma_y, plane.fraction_x, plane.fraction_y, plane.lineshape, ): sim_data += pv_pv( XY, amp, c_x, c_y, s_x, s_y, frac_x, frac_y ).reshape(shape) except: for amp, c_x, c_y, s_x, s_y, frac, ls in zip( plane.amp, plane.center_x, plane.center_y, plane.sigma_x, plane.sigma_y, plane.fraction, plane.lineshape, ): # print(amp) if (ls == "G") or (ls == "L") or (ls == "PV"): sim_data += pvoigt2d( XY, amp, c_x, c_y, s_x, s_y, frac ).reshape(shape) elif ls == "PV_L": sim_data += pv_l(XY, amp, c_x, c_y, s_x, s_y, frac).reshape( shape ) elif ls == "PV_G": sim_data += pv_g(XY, amp, c_x, c_y, s_x, s_y, frac).reshape( shape ) elif ls == "G_L": sim_data += gaussian_lorentzian( XY, amp, c_x, c_y, s_x, s_y, frac ).reshape(shape) masked_data = pseudo3D.data[plane_id].copy() masked_sim_data = sim_data.copy() masked_data[~mask] = np.nan masked_sim_data[~mask] = np.nan fig = plt.figure() ax = fig.add_subplot(111, projection="3d") # slice out plot area x_plot = pseudo3D.uc_f2.ppm(X[min_y:max_y, min_x:max_x]) y_plot = pseudo3D.uc_f1.ppm(Y[min_y:max_y, min_x:max_x]) masked_data = masked_data[min_y:max_y, min_x:max_x] sim_plot = masked_sim_data[min_y:max_y, min_x:max_x] residual = masked_data - sim_plot cset = ax.contourf( x_plot, y_plot, residual, zdir="z", offset=np.nanmin(masked_data) * 1.1, alpha=0.5, cmap=cm.coolwarm, ) fig.colorbar(cset, ax=ax, shrink=0.5, format="%.2e") ax.plot_wireframe( x_plot, y_plot, sim_plot, # colors=[cm.coolwarm(i) for i in np.ravel(residual)], colors=fit_color, linestyle="--", label="fit", rcount=rcount, ccount=ccount, ) ax.plot_wireframe( x_plot, y_plot, masked_data, colors=data_color, linestyle="-", label="data", rcount=rcount, ccount=ccount, ) ax.set_ylabel(pseudo3D.f1_label) ax.set_xlabel(pseudo3D.f2_label) # axes will appear inverted ax.view_init(30,120) #names = ",".join(plane.assignment) title = f"Plane={plane_id},Cluster={plane.clustid.iloc[0]}" plt.title(title) print(f"Plotting: {title}") out_str = "Amplitudes\n----------------\n" # chi2s = [] for amp, name, peak_mask in zip(plane.amp, plane.assignment, masks): out_str += f"{name} = {amp:.3e}\n" ax.text2D( -0.15, 1.0, out_str, transform=ax.transAxes, fontsize=10, va="top" ) ax.legend() pdf.savefig() if show: def exit_program(event): exit() def next_plot(event): plt.close() axexit = plt.axes([0.81, 0.05, 0.1, 0.075]) bnexit = Button(axexit, "Exit") bnexit.on_clicked(exit_program) axnext = plt.axes([0.71, 0.05, 0.1, 0.075]) bnnext = Button(axnext, "Next") bnnext.on_clicked(next_plot) plt.show() plt.close() if first_only: break run_log() if __name__ == "__main__": argv = sys.argv[1:] main(argv) PK!#&$pffpeakipy/commandline/edit.py#!/usr/bin/env python3 """ Script for checking fits and editing fit params Usage: edit_fits_script.py [options] Arguments: peaklist output from read_peaklist.py (csv, tab or pkl) NMRPipe data Options: --dims= order of dimensions [default: 0,1,2] peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import shutil import json from pathlib import Path from subprocess import check_output from docopt import docopt from schema import Schema, And, SchemaError import pandas as pd import nmrglue as ng import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import magma, autumn from scipy import ndimage from skimage.filters import threshold_otsu from skimage.morphology import binary_closing, square, rectangle, disk from bokeh.events import ButtonClick, DoubleTap from bokeh.layouts import row, column, widgetbox from bokeh.models import ColumnDataSource from bokeh.models.tools import HoverTool from bokeh.models.widgets import ( Slider, Select, Button, DataTable, TableColumn, NumberFormatter, NumberEditor, IntEditor, SelectEditor, TextInput, RadioButtonGroup, CheckboxGroup, Div, Tabs, Panel, ) from bokeh.plotting import figure # from bokeh.io import curdoc from bokeh.server.server import Server from bokeh.palettes import PuBuGn9, Category20 from peakipy.core import Pseudo3D, run_log def bokeh_script(doc): # Temp files TEMP_PATH = Path("tmp") TEMP_PATH.mkdir(parents=True, exist_ok=True) TEMP_OUT_CSV = TEMP_PATH / Path("tmp_out.csv") TEMP_INPUT_CSV = TEMP_PATH / Path("tmp.csv") TEMP_OUT_PLOT = TEMP_PATH / Path("plots") TEMP_OUT_PLOT.mkdir(parents=True, exist_ok=True) def clusters(df, data, thres=None, struc_el="square", struc_size=(3,)): """ Find clusters of peaks :param thres: threshold for signals above which clusters are selected :type thres : float :param df: DataFrame containing peak list :type df: pandas.DataFrame :param data: NMR data :type data: numpy.array :param struc_el: :type struc_el: :param struc_size: :type struc_size: """ peaks = [[y, x] for y, x in zip(df.Y_AXIS, df.X_AXIS)] if thres == None: thresh = threshold_otsu(data[0]) else: thresh = thres thresh_data = np.bitwise_or(data[0] < (thresh * -1.0), data[0] > thresh) if struc_el == "disk": radius = struc_size[0] print(f"using disk with {radius}") closed_data = binary_closing(thresh_data, disk(int(radius))) # closed_data = binary_dilation(thresh_data, disk(radius), iterations=iterations) elif struc_el == "square": width = struc_size[0] print(f"using square with {width}") closed_data = binary_closing(thresh_data, square(int(width))) # closed_data = binary_dilation(thresh_data, square(width), iterations=iterations) elif struc_el == "rectangle": width, height = struc_size print(f"using rectangle with {width} and {height}") closed_data = binary_closing(thresh_data, rectangle(int(width), int(height))) # closed_data = binary_dilation(thresh_data, rectangle(width, height), iterations=iterations) else: closed_data = thresh_data print(f"Not using any closing function") labeled_array, num_features = ndimage.label(closed_data) # print(labeled_array, num_features) df.loc[:, "CLUSTID"] = [labeled_array[i[0], i[1]] for i in peaks] #  renumber "0" clusters max_clustid = df["CLUSTID"].max() n_of_zeros = len(df[df["CLUSTID"] == 0]["CLUSTID"]) df.loc[df[df["CLUSTID"] == 0].index, "CLUSTID"] = np.arange( max_clustid + 1, n_of_zeros + max_clustid + 1, dtype=int ) for ind, group in df.groupby("CLUSTID"): df.loc[group.index, "MEMCNT"] = len(group) df.loc[:, "color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1, ) source.data = {col: df[col] for col in df.columns} return df def recluster_peaks(event): struc_size = tuple([int(i) for i in struct_el_size.value.split(",")]) print(struc_size) clusters( df, data, thres=eval(contour_start.value), struc_el=struct_el.value, struc_size=struc_size, # iterations=int(iterations.value) ) # print("struct", struct_el.value) # print("struct size", struct_el_size.value ) # print(type(struct_el_size.value) ) # print(type(eval(struct_el_size.value)) ) # print(type([].extend(eval(struct_el_size.value))) def update_memcnt(df): for ind, group in df.groupby("CLUSTID"): df.loc[group.index, "MEMCNT"] = len(group) # set cluster colors (set to black if singlet peaks) df["color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1, ) # change color of excluded peaks include_no = df.include == "no" df.loc[include_no, "color"] = "ghostwhite" # update source data source.data = {col: df[col] for col in df.columns} return df def fit_selected(event): selectionIndex = source.selected.indices current = df.iloc[selectionIndex] df.loc[selectionIndex, "X_RADIUS_PPM"] = slider_X_RADIUS.value df.loc[selectionIndex, "Y_RADIUS_PPM"] = slider_Y_RADIUS.value df.loc[selectionIndex, "X_DIAMETER_PPM"] = current["X_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER_PPM"] = current["Y_RADIUS_PPM"] * 2.0 selected_df = df[df.CLUSTID.isin(list(current.CLUSTID))] selected_df.to_csv(TEMP_INPUT_CSV) lineshape = lineshapes[radio_button_group.active] if checkbox_group.active == []: print("Using LS = ", lineshape) fit_command = f"peakipy fit {TEMP_INPUT_CSV} {data_path} {TEMP_OUT_CSV} --plot={TEMP_OUT_PLOT} --show --lineshape={lineshape} --dims={_dims} --nomp" else: plane_index = select_plane.value print("Using LS = ", lineshape) fit_command = f"peakipy fit {TEMP_INPUT_CSV} {data_path} {TEMP_OUT_CSV} --plot={TEMP_OUT_PLOT} --show --lineshape={lineshape} --dims={_dims} --plane={plane_index} --nomp" print(fit_command) fit_reports.text += fit_command + "
" stdout = check_output(fit_command.split(" ")) fit_reports.text += stdout.decode() + "


" fit_reports.text = fit_reports.text.replace("\n", "
") def save_peaks(event): if savefilename.value: to_save = Path(savefilename.value) else: to_save = Path(savefilename.placeholder) if to_save.exists(): shutil.copy(f"{to_save}", f"{to_save}.bak") print(f"Making backup {to_save}.bak") print(f"Saving peaks to {to_save}") if to_save.suffix == ".csv": df.to_csv(to_save, float_format="%.4f", index=False) else: df.to_pickle(to_save) def select_callback(attrname, old, new): # print("Calling Select Callback") selectionIndex = source.selected.indices current = df.iloc[selectionIndex] # update memcnt update_memcnt(df) def peak_pick_callback(event): # global so that df is updated globally global df x_radius_ppm = 0.035 y_radius_ppm = 0.35 x_radius = x_radius_ppm * pt_per_ppm_f2 y_radius = y_radius_ppm * pt_per_ppm_f1 x_diameter_ppm = x_radius_ppm * 2.0 y_diameter_ppm = y_radius_ppm * 2.0 clustid = df.CLUSTID.max() + 1 index = df.INDEX.max() + 1 x_ppm = event.x y_ppm = event.y x_axis = uc_f2.f(x_ppm, "ppm") y_axis = uc_f1.f(y_ppm, "ppm") xw_hz = 20.0 yw_hz = 20.0 xw = xw_hz * pt_per_hz_f2 yw = yw_hz * pt_per_hz_f1 assignment = f"test_peak_{index}_{clustid}" height = data[0][int(y_axis), int(x_axis)] volume = height print(f"""Adding peak at {assignment}: {event.x:.3f},{event.y:.3f}""") new_peak = { "INDEX": index, "X_PPM": x_ppm, "Y_PPM": y_ppm, "HEIGHT": height, "VOL": volume, "XW_HZ": xw_hz, "YW_HZ": yw_hz, "X_AXIS": int(np.floor(x_axis)), # integers "Y_AXIS": int(np.floor(y_axis)), # integers "X_AXISf": x_axis, "Y_AXISf": y_axis, "XW": xw, "YW": yw, "ASS": assignment, "X_RADIUS_PPM": x_radius_ppm, "Y_RADIUS_PPM": y_radius_ppm, "X_RADIUS": x_radius, "Y_RADIUS": y_radius, "CLUSTID": clustid, "MEMCNT": 1, "X_DIAMETER_PPM": x_diameter_ppm, "Y_DIAMETER_PPM": y_diameter_ppm, "Edited": True, "include": "yes", "color": "black", } df = df.append(new_peak, ignore_index=True) update_memcnt(df) def slider_callback(attrname, old, new): selectionIndex = source.selected.indices current = df.iloc[selectionIndex] df.loc[selectionIndex, "X_RADIUS"] = slider_X_RADIUS.value * pt_per_ppm_f2 df.loc[selectionIndex, "Y_RADIUS"] = slider_Y_RADIUS.value * pt_per_ppm_f1 df.loc[selectionIndex, "X_RADIUS_PPM"] = slider_X_RADIUS.value df.loc[selectionIndex, "Y_RADIUS_PPM"] = slider_Y_RADIUS.value df.loc[selectionIndex, "X_DIAMETER_PPM"] = current["X_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER_PPM"] = current["Y_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "X_DIAMETER"] = current["X_RADIUS"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER"] = current["Y_RADIUS"] * 2.0 # set edited rows to True df.loc[selectionIndex, "Edited"] = True # selected_df = df[df.CLUSTID.isin(list(current.CLUSTID))] # print(list(selected_df)) source.data = {col: df[col] for col in df.columns} def get_contour_data(data, levels, **kwargs): cs = plt.contour(data, levels, **kwargs) xs = [] ys = [] xt = [] yt = [] col = [] text = [] isolevelid = 0 for isolevel in cs.collections: isocol = isolevel.get_color()[0] thecol = 3 * [None] theiso = str(cs.get_array()[isolevelid]) isolevelid += 1 for i in range(3): thecol[i] = int(255 * isocol[i]) thecol = "#%02x%02x%02x" % (thecol[0], thecol[1], thecol[2]) for path in isolevel.get_paths(): v = path.vertices x = v[:, 0] y = v[:, 1] xs.append(x.tolist()) ys.append(y.tolist()) indx = int(len(x) / 2) indy = int(len(y) / 2) xt.append(x[indx]) yt.append(y[indy]) text.append(theiso) col.append(thecol) source = ColumnDataSource( data={"xs": xs, "ys": ys, "line_color": col, "xt": xt, "yt": yt, "text": text} ) return source def update_contour(attrname, old, new): new_cs = eval(contour_start.value) cl = new_cs * contour_factor ** np.arange(contour_num) plane_index = select_planes_dic[select_plane.value] spec_source.data = get_contour_data(data[plane_index], cl, extent=extent).data # print("Value of checkbox",checkbox_group.active) def exit_edit_peaks(event): exit() #  Script starts here args = docopt(__doc__, argv=argv) args = check_input(args) path = Path(args.get("")) if path.suffix == ".csv": df = pd.read_csv(path) # , comment="#") elif path.suffix == ".tab": df = pd.read_csv(path, sep="\t") # comment="#") else: df = pd.read_pickle(path) # make diameter columns if "X_DIAMETER_PPM" in df.columns: pass else: df["X_DIAMETER_PPM"] = df["X_RADIUS_PPM"] * 2.0 df["Y_DIAMETER_PPM"] = df["Y_RADIUS_PPM"] * 2.0 #  make a column to track edited peaks if "Edited" in df.columns: pass else: df["Edited"] = np.zeros(len(df), dtype=bool) if "include" in df.columns: pass else: df["include"] = df.apply(lambda _: "yes", axis=1) # color clusters df["color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1 ) # get rid of unnamed columns unnamed_cols = [i for i in df.columns if "Unnamed:" in i] df = df.drop(columns=unnamed_cols) # make datasource source = ColumnDataSource(data=dict()) source.data = {col: df[col] for col in df.columns} #  read dims from config config_path = Path("peakipy.config") if config_path.exists(): config = json.load(open(config_path)) print(f"Using config file with --dims={config.get('--dims')}") dims = config.get("--dims", [0, 1, 2]) _dims = ",".join(str(i) for i in dims) else: # get dim numbers from commandline _dims = args.get("--dims") dims = [int(i) for i in _dims.split(",")] # read pipe data data_path = args.get("") dic, data = ng.pipe.read(data_path) pseudo3D = Pseudo3D(dic, data, dims) data = pseudo3D.data udic = pseudo3D.udic dims = pseudo3D.dims planes, f1, f2 = dims # size of f1 and f2 in points f2pts = pseudo3D.f2_size f1pts = pseudo3D.f1_size #  points per ppm pt_per_ppm_f1 = pseudo3D.pt_per_ppm_f1 pt_per_ppm_f2 = pseudo3D.pt_per_ppm_f2 # points per hz pt_per_hz_f1 = pseudo3D.pt_per_hz_f1 pt_per_hz_f2 = pseudo3D.pt_per_hz_f2 # get ppm limits for ppm scales uc_f1 = pseudo3D.uc_f1 ppm_f1 = uc_f1.ppm_scale() ppm_f1_0, ppm_f1_1 = uc_f1.ppm_limits() uc_f2 = pseudo3D.uc_f2 ppm_f2 = uc_f2.ppm_scale() ppm_f2_0, ppm_f2_1 = uc_f2.ppm_limits() f2_label = pseudo3D.f2_label f1_label = pseudo3D.f1_label #  make bokeh figure tools = [ # "redo", # "undo", "tap", "box_zoom", "lasso_select", "box_select", "wheel_zoom", "pan", "reset", ] p = figure( x_range=(ppm_f2_0, ppm_f2_1), y_range=(ppm_f1_0, ppm_f1_1), x_axis_label=f"{f2_label} - ppm", y_axis_label=f"{f1_label} - ppm", tools=tools, active_drag="pan", active_scroll="wheel_zoom", active_tap=None, ) thres = threshold_otsu(data[0]) contour_start = thres # contour level start value contour_num = 20 # number of contour levels contour_factor = 1.20 # scaling factor between contour levels cl = contour_start * contour_factor ** np.arange(contour_num) extent = (ppm_f2_0, ppm_f2_1, ppm_f1_0, ppm_f1_1) spec_source = get_contour_data(data[0], cl, extent=extent) #  negative contours spec_source_neg = get_contour_data(data[0] * -1.0, cl, extent=extent, cmap=autumn) p.multi_line(xs="xs", ys="ys", line_color="line_color", source=spec_source) p.multi_line(xs="xs", ys="ys", line_color="line_color", source=spec_source_neg) # contour_num = Slider(title="contour number", value=20, start=1, end=50,step=1) # contour_start = Slider(title="contour start", value=100000, start=1000, end=10000000,step=1000) contour_start = TextInput(value="%.2e" % thres, title="Contour level:", width=100) # contour_factor = Slider(title="contour factor", value=1.20, start=1., end=2.,step=0.05) contour_start.on_change("value", update_contour) # for w in [contour_num,contour_start,contour_factor]: # w.on_change("value",update_contour) #  plot mask outlines el = p.ellipse( x="X_PPM", y="Y_PPM", width="X_DIAMETER_PPM", height="Y_DIAMETER_PPM", source=source, fill_color="color", fill_alpha=0.1, line_dash="dotted", line_color="red", ) p.add_tools( HoverTool( tooltips=[ ("Index", "$index"), ("Assignment", "@ASS"), ("CLUSTID", "@CLUSTID"), ("RADII", "@X_RADIUS_PPM{0.000}, @Y_RADIUS_PPM{0.000}"), (f"{f2_label},{f1_label}", "$x{0.000} ppm, $y{0.000} ppm"), ], mode="mouse", # add renderers renderers=[el], ) ) # p.toolbar.active_scroll = "auto" p.circle(x="X_PPM", y="Y_PPM", source=source, color="color") # plot cluster numbers p.text( x="X_PPM", y="Y_PPM", text="CLUSTID", text_color="color", source=source, text_font_size="8pt", text_font_style="bold", ) p.on_event(DoubleTap, peak_pick_callback) # configure sliders slider_X_RADIUS = Slider( title="X_RADIUS - ppm", start=0.001, end=0.200, value=0.040, step=0.001, format="0[.]000", ) slider_Y_RADIUS = Slider( title="Y_RADIUS - ppm", start=0.010, end=2.000, value=0.400, step=0.001, format="0[.]000", ) slider_X_RADIUS.on_change( "value", lambda attr, old, new: slider_callback(attr, old, new) ) slider_Y_RADIUS.on_change( "value", lambda attr, old, new: slider_callback(attr, old, new) ) # save file savefilename = TextInput(title="Save file as (.csv)", placeholder="edited_peaks.csv") button = Button(label="Save", button_type="success") button.on_event(ButtonClick, save_peaks) # call fit_peaks fit_button = Button(label="Fit selected cluster", button_type="primary") # lineshape selection lineshapes = {0: "PV", 1: "G", 2: "L", 3: "PV_PV", 4: "PV_L", 5: "PV_G", 6: "G_L"} radio_button_group = RadioButtonGroup( labels=[lineshapes[i] for i in lineshapes.keys()], active=0 ) ls_div = Div( text="""Choose lineshape you wish to fit. This can be Pseudo-voigt (PV), Gaussian (G), Lorentzian (L), PV/G, PV/L, PV_PV, G/L. PV/G fits a PV lineshape to the direct dimension and a G lineshape to the indirect.""" ) clust_div = Div( text="""If you want to adjust how the peaks are automatically clustered then try changing the width/diameter/height (integer values) of the structuring element used during the binary dilation step (you can also remove it by selecting 'None'). Increasing the size of the structuring element will cause peaks to be more readily incorporated into clusters. Be sure to save your peak list before doing this as any manual edits will be lost.""" ) intro_div = Div( text="""

peakipy - interactive fit adjustment

""" ) doc_link = Div( text="

ℹ️ click here for documentation

" ) fit_reports = Div( text="", height=400, sizing_mode="scale_width", style={"overflow-y": "scroll"} ) # Plane selection select_planes_list = [f"{i+1}" for i in range(data.shape[planes])] select_plane = Select( title="Select plane:", value=select_planes_list[0], options=select_planes_list ) select_planes_dic = {f"{i+1}": i for i in range(data.shape[planes])} select_plane.on_change("value", update_contour) checkbox_group = CheckboxGroup(labels=["fit current plane only"], active=[]) #  not sure this is needed selected_df = df.copy() fit_button.on_event(ButtonClick, fit_selected) columns = [ TableColumn(field="ASS", title="Assignment"), TableColumn(field="CLUSTID", title="Cluster", editor=IntEditor()), TableColumn( field="X_PPM", title=f"{f2_label}", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="Y_PPM", title=f"{f1_label}", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="X_RADIUS_PPM", title=f"{f2_label} radius (ppm)", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="Y_RADIUS_PPM", title=f"{f1_label} radius (ppm)", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="XW_HZ", title=f"{f2_label} LW (Hz)", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00"), ), TableColumn( field="YW_HZ", title=f"{f1_label} LW (Hz)", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00"), ), TableColumn(field="VOL", title="Volume", formatter=NumberFormatter(format="0.0")), TableColumn( field="include", title="Include", editor=SelectEditor(options=["yes", "no"]) ), TableColumn(field="MEMCNT", title="MEMCNT", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True, fit_columns=True) # callback for adding # source.selected.on_change('indices', callback) source.selected.on_change("indices", select_callback) # Quit button exit_button = Button(label="Quit", button_type="warning") exit_button.on_event(ButtonClick, exit_edit_peaks) # Document layout fitting_controls = column( row(column(slider_X_RADIUS, slider_Y_RADIUS), column(contour_start, fit_button)), row( column(widgetbox(ls_div), radio_button_group), column(select_plane, widgetbox(checkbox_group)), ), ) # reclustering tab struct_el = Select( title="Structuring element:", value="disk", options=["square", "disk", "rectangle", "None"], width=100, ) struct_el_size = TextInput( value="3", title="Size(width/radius or width,height for rectangle):", width=100 ) recluster = Button(label="Re-cluster", button_type="warning") recluster.on_event(ButtonClick, recluster_peaks) # edit_fits tabs fitting_layout = fitting_controls log_layout = fit_reports recluster_layout = widgetbox( row(clust_div, column(contour_start, struct_el, struct_el_size, recluster)) ) save_layout = column(savefilename, button, exit_button) fitting_tab = Panel(child=fitting_layout, title="Peak fitting") log_tab = Panel(child=log_layout, title="Log") recluster_tab = Panel(child=recluster_layout, title="Re-cluster peaks") save_tab = Panel(child=save_layout, title="Save edited peaklist") tabs = Tabs(tabs=[fitting_tab, log_tab, recluster_tab, save_tab]) # for running fit_peaks from edit_fits # fit_all_layout = # fit_all_tab = Panel(child=fit_all_layout) # fit_all_result = Panel(child=fit_all_result_layout) # fit_all_tabs = Tabs(tabs=[fit_all_tab, fit_all_result]) #curdoc().add_root( # column( # intro_div, # row(column(p, doc_link), column(data_table, tabs)), # sizing_mode="stretch_both", # ) #) #curdoc().title = "peakipy: Edit Fits" doc.add_root( column( intro_div, row(column(p, doc_link), column(data_table, tabs)), sizing_mode="stretch_both", ) ) doc.title = "peakipy: Edit Fits" def check_input(args): """ validate commandline input """ schema = Schema( { "": And( os.path.exists, open, error=f"{args['']} should exist and be readable", ), "": And( os.path.exists, ng.pipe.read, error=f"{args['']} either does not exist or is not an NMRPipe format 2D or 3D", ), "--dims": And( lambda n: [int(i) for i in eval(n)], error="--dims should be list of integers e.g. --dims=0,1,2", ), } ) try: args = schema.validate(args) return args except SchemaError as e: exit(e) def main(args): global argv argv = args # docopt(__doc__, argv) run_log() server = Server({'/': bokeh_script}) server.start() print('Opening peakipy: Edit fits on http://localhost:5006/') server.io_loop.add_callback(server.show, "/") server.io_loop.start() if __name__ == "__main__": args = sys.argv[1:] main(args)PK!dHdH)peakipy/commandline/edit_fits_app/main.py#!/usr/bin/env python3 """ Script for checking fits and editing fit params Usage: edit_fits_script.py [options] Arguments: peaklist output from read_peaklist.py (csv, tab or pkl) NMRPipe data Options: --dims= order of dimensions [default: 0,1,2] peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import json from docopt import docopt from pathlib import Path import pandas as pd import nmrglue as ng import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import magma, autumn from scipy import ndimage # from scipy.ndimage.morphology import binary_dilation from skimage.filters import threshold_otsu from skimage.morphology import binary_closing, square, rectangle, disk from bokeh.events import ButtonClick, DoubleTap from bokeh.layouts import row, column, widgetbox from bokeh.models import ColumnDataSource from bokeh.models.tools import HoverTool from bokeh.models.widgets import ( Slider, Select, Button, DataTable, TableColumn, NumberFormatter, NumberEditor, IntEditor, StringEditor, StringFormatter, SelectEditor, TextInput, RadioButtonGroup, Div, ) from bokeh.plotting import figure from bokeh.io import curdoc from bokeh.palettes import PuBuGn9, Category20 from peakipy.core import Pseudo3D def clusters( df, data, thres=None, struc_el="square", struc_size=(3,), iterations=1, l_struc=None ): """ Find clusters of peaks Need to update these docs. thres : float threshold for signals above which clusters are selected ndil: int number of iterations of ndimage.binary_dilation function if set to 0 then function not used """ peaks = [[y, x] for y, x in zip(df.Y_AXIS, df.X_AXIS)] if thres == None: thresh = threshold_otsu(data[0]) else: thresh = thres thresh_data = np.bitwise_or(data[0] < (thresh * -1.0), data[0] > thresh) if struc_el == "disk": radius = struc_size[0] print(f"using disk with {radius}") closed_data = binary_closing(thresh_data, disk(int(radius))) # closed_data = binary_dilation(thresh_data, disk(radius), iterations=iterations) elif struc_el == "square": width = struc_size[0] print(f"using square with {width}") closed_data = binary_closing(thresh_data, square(int(width))) # closed_data = binary_dilation(thresh_data, square(width), iterations=iterations) elif struc_el == "rectangle": width, height = struc_size print(f"using rectangle with {width} and {height}") closed_data = binary_closing(thresh_data, rectangle(int(width), int(height))) # closed_data = binary_dilation(thresh_data, rectangle(width, height), iterations=iterations) else: closed_data = thresh_data print(f"Not using any closing function") labeled_array, num_features = ndimage.label(closed_data, l_struc) # print(labeled_array, num_features) df["CLUSTID"] = [labeled_array[i[0], i[1]] for i in peaks] #  renumber "0" clusters max_clustid = df["CLUSTID"].max() n_of_zeros = len(df[df["CLUSTID"] == 0]["CLUSTID"]) df.loc[df[df["CLUSTID"] == 0].index, "CLUSTID"] = np.arange( max_clustid + 1, n_of_zeros + max_clustid + 1, dtype=int ) for ind, group in df.groupby("CLUSTID"): df.loc[group.index, "MEMCNT"] = len(group) df["color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1, ) source.data = {col: df[col] for col in df.columns} return df def recluster_peaks(event): struc_size = tuple([int(i) for i in struct_el_size.value.split(",")]) print(struc_size) clusters( df, data, thres=eval(contour_start.value), struc_el=struct_el.value, struc_size=struc_size, # iterations=int(iterations.value) ) # print("struct", struct_el.value) # print("struct size", struct_el_size.value ) # print(type(struct_el_size.value) ) # print(type(eval(struct_el_size.value)) ) # print(type([].extend(eval(struct_el_size.value))) def update_memcnt(df): for ind, group in df.groupby("CLUSTID"): df.loc[group.index, "MEMCNT"] = len(group) # set cluster colors (set to black if singlet peaks) df["color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1, ) # update source data source.data = {col: df[col] for col in df.columns} return df def fit_selected(event): selectionIndex = source.selected.indices current = df.iloc[selectionIndex] df.loc[selectionIndex, "X_RADIUS_PPM"] = slider_X_RADIUS.value df.loc[selectionIndex, "Y_RADIUS_PPM"] = slider_Y_RADIUS.value df.loc[selectionIndex, "X_DIAMETER_PPM"] = current["X_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER_PPM"] = current["Y_RADIUS_PPM"] * 2.0 selected_df = df[df.CLUSTID.isin(list(current.CLUSTID))] selected_df.to_csv("~tmp.csv") lineshape = lineshapes[radio_button_group.active] print("Using LS = ", lineshape) print( f"fit_peaks ~tmp.csv {data_path} ~tmp_out.csv --plot=out --show --lineshape={lineshape} --dims={_dims}" ) os.system( f"fit_peaks ~tmp.csv {data_path} ~tmp_out.csv --plot=out --show --lineshape={lineshape} --dims={_dims}" ) def save_peaks(event): if savefilename.value: to_save = Path(savefilename.value) else: to_save = Path(savefilename.placeholder) if to_save.exists(): os.system(f"cp {to_save} {to_save}.bak") print(f"Making backup {to_save}.bak") print(f"Saving peaks to {to_save}") if to_save.suffix == ".csv": df.to_csv(to_save, float_format="%.4f", index=False) else: df.to_pickle(to_save) def select_callback(attrname, old, new): # print("Calling Select Callback") selectionIndex = source.selected.indices current = df.iloc[selectionIndex] # update memcnt update_memcnt(df) def peak_pick_callback(event): print(event.x, event.y) def slider_callback(attrname, old, new): selectionIndex = source.selected.indices current = df.iloc[selectionIndex] df.loc[selectionIndex, "X_RADIUS"] = slider_X_RADIUS.value * pt_per_ppm_f2 df.loc[selectionIndex, "Y_RADIUS"] = slider_Y_RADIUS.value * pt_per_ppm_f1 df.loc[selectionIndex, "X_RADIUS_PPM"] = slider_X_RADIUS.value df.loc[selectionIndex, "Y_RADIUS_PPM"] = slider_Y_RADIUS.value df.loc[selectionIndex, "X_DIAMETER_PPM"] = current["X_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER_PPM"] = current["Y_RADIUS_PPM"] * 2.0 df.loc[selectionIndex, "X_DIAMETER"] = current["X_RADIUS"] * 2.0 df.loc[selectionIndex, "Y_DIAMETER"] = current["Y_RADIUS"] * 2.0 # set edited rows to True df.loc[selectionIndex, "Edited"] = True # selected_df = df[df.CLUSTID.isin(list(current.CLUSTID))] # print(list(selected_df)) source.data = {col: df[col] for col in df.columns} def get_contour_data(data, levels, **kwargs): cs = plt.contour(data, levels, **kwargs) xs = [] ys = [] xt = [] yt = [] col = [] text = [] isolevelid = 0 for isolevel in cs.collections: isocol = isolevel.get_color()[0] thecol = 3 * [None] theiso = str(cs.get_array()[isolevelid]) isolevelid += 1 for i in range(3): thecol[i] = int(255 * isocol[i]) thecol = "#%02x%02x%02x" % (thecol[0], thecol[1], thecol[2]) for path in isolevel.get_paths(): v = path.vertices x = v[:, 0] y = v[:, 1] xs.append(x.tolist()) ys.append(y.tolist()) indx = int(len(x) / 2) indy = int(len(y) / 2) xt.append(x[indx]) yt.append(y[indy]) text.append(theiso) col.append(thecol) source = ColumnDataSource( data={"xs": xs, "ys": ys, "line_color": col, "xt": xt, "yt": yt, "text": text} ) return source def update_contour(attrname, old, new): new_cs = eval(contour_start.value) cl = new_cs * contour_factor ** np.arange(contour_num) spec_source.data = get_contour_data(data[0], cl, extent=extent).data def exit_edit_peaks(event): exit() #  Script starts here args = docopt(__doc__) path = Path(args.get("")) if path.suffix == ".csv": df = pd.read_csv(path) # , comment="#") elif path.suffix == ".tab": df = pd.read_csv(path, sep="\t") # comment="#") else: df = pd.read_pickle(path) # make diameter columns if "X_DIAMETER_PPM" in df.columns: pass else: df["X_DIAMETER_PPM"] = df["X_RADIUS_PPM"] * 2.0 df["Y_DIAMETER_PPM"] = df["Y_RADIUS_PPM"] * 2.0 #  make a column to track edited peaks if "Edited" in df.columns: pass else: df["Edited"] = np.zeros(len(df), dtype=bool) if "include" in df.columns: pass else: df["include"] = df.apply(lambda _: "yes", axis=1) # df["color"] = df.Edited.apply(lambda x: 'red' if x else 'black') # color clusters df["color"] = df.apply( lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1 ) # make datasource source = ColumnDataSource(data=dict()) source.data = {col: df[col] for col in df.columns} #  read dims from config config_path = Path("peakipy.config") if config_path.exists(): config = json.load(open(config_path)) print(f"Using config file with --dims={config.get('--dims')}") dims = config.get("--dims", [0, 1, 2]) _dims = ",".join(str(i) for i in dims) else: # get dim numbers from commandline _dims = args.get("--dims") dims = [int(i) for i in _dims.split(",")] # read pipe data data_path = args.get("") dic, data = ng.pipe.read(data_path) pseudo3D = Pseudo3D(dic, data, dims) data = pseudo3D.data udic = pseudo3D.udic dims = pseudo3D.dims planes, f1, f2 = dims # size of f1 and f2 in points f2pts = pseudo3D.f2_size f1pts = pseudo3D.f1_size #  points per ppm pt_per_ppm_f1 = pseudo3D.pt_per_ppm_f1 pt_per_ppm_f2 = pseudo3D.pt_per_ppm_f2 # get ppm limits for ppm scales uc_f1 = pseudo3D.uc_f1 ppm_f1 = uc_f1.ppm_scale() ppm_f1_0, ppm_f1_1 = uc_f1.ppm_limits() uc_f2 = pseudo3D.uc_f2 ppm_f2 = uc_f2.ppm_scale() ppm_f2_0, ppm_f2_1 = uc_f2.ppm_limits() f2_label = pseudo3D.f2_label f1_label = pseudo3D.f1_label #  make bokeh figure tools = [ "redo", "undo", "tap", "box_zoom", "lasso_select", "box_select", "wheel_zoom", "pan", "reset", ] p = figure( x_range=(ppm_f2_0, ppm_f2_1), y_range=(ppm_f1_0, ppm_f1_1), x_axis_label=f"{f2_label} - ppm", y_axis_label=f"{f1_label} - ppm", title="Check fits", tools=tools, active_drag="pan", active_scroll="wheel_zoom", active_tap=None, ) thres = threshold_otsu(data[0]) contour_start = thres # contour level start value contour_num = 20 # number of contour levels contour_factor = 1.20 # scaling factor between contour levels cl = contour_start * contour_factor ** np.arange(contour_num) extent = (ppm_f2_0, ppm_f2_1, ppm_f1_0, ppm_f1_1) spec_source = get_contour_data(data[0], cl, extent=extent) #  negative contours spec_source_neg = get_contour_data(data[0] * -1.0, cl, extent=extent, cmap=autumn) p.multi_line(xs="xs", ys="ys", line_color="line_color", source=spec_source) p.multi_line(xs="xs", ys="ys", line_color="line_color", source=spec_source_neg) # contour_num = Slider(title="contour number", value=20, start=1, end=50,step=1) # contour_start = Slider(title="contour start", value=100000, start=1000, end=10000000,step=1000) contour_start = TextInput(value="%.2e" % thres, title="Contour level:") # contour_factor = Slider(title="contour factor", value=1.20, start=1., end=2.,step=0.05) contour_start.on_change("value", update_contour) # for w in [contour_num,contour_start,contour_factor]: # w.on_change("value",update_contour) #  plot mask outlines el = p.ellipse( x="X_PPM", y="Y_PPM", width="X_DIAMETER_PPM", height="Y_DIAMETER_PPM", source=source, fill_color="color", fill_alpha=0.1, line_dash="dotted", line_color="red", ) p.add_tools( HoverTool( tooltips=[ ("Index", "$index"), ("Assignment", "@ASS"), ("CLUSTID", "@CLUSTID"), ("RADII", "@X_RADIUS_PPM{0.000}, @Y_RADIUS_PPM{0.000}"), (f"{f2_label},{f1_label}", "$x{0.000} ppm, $y{0.000} ppm"), ], mode="mouse", # add renderers renderers=[el], ) ) # p.toolbar.active_scroll = "auto" p.circle(x="X_PPM", y="Y_PPM", source=source, color="color") # plot cluster numbers p.text( x="X_PPM", y="Y_PPM", text="CLUSTID", text_color="color", source=source, text_font_size="8pt", text_font_style="bold", ) p.on_event(DoubleTap, peak_pick_callback) # configure sliders slider_X_RADIUS = Slider( title="X_RADIUS - ppm", start=0.001, end=0.200, value=0.040, step=0.001, format="0[.]000", ) slider_Y_RADIUS = Slider( title="Y_RADIUS - ppm", start=0.010, end=2.000, value=0.400, step=0.001, format="0[.]000", ) slider_X_RADIUS.on_change( "value", lambda attr, old, new: slider_callback(attr, old, new) ) slider_Y_RADIUS.on_change( "value", lambda attr, old, new: slider_callback(attr, old, new) ) # save file savefilename = TextInput( title="Save file as (.csv or .pkl)", placeholder="edited_peaks.csv" ) button = Button(label="Save", button_type="success") button.on_event(ButtonClick, save_peaks) # call fit_peaks fit_button = Button(label="Fit selected cluster", button_type="primary") radio_button_group = RadioButtonGroup( labels=["PV", "G", "L", "PV_L", "PV_G", "PV_PV", "G_L"], active=0 ) lineshapes = {0: "PV", 1: "G", 2: "L", 3: "PV_L", 4: "PV_G", 5: "PV_PV", 6: "G_L"} ls_div = Div( text="Choose lineshape you wish to fit. This can be Pseudo-voigt (PV), Gaussian (G), Lorentzian (L), PV/G, PV/L, PV_PV, G/L. PV/G fits a PV lineshape to the direct dimension and a G lineshape to the indirect." ) clust_div = Div( text="""If you want to adjust how the peaks are automatically clustered then try changing the width/diameter/height (integer values) of the structuring element used during the binary dilation step (you can also remove it by selecting 'None'). Increasing the size of the structuring element will cause peaks to be more readily incorporated into clusters.""" ) #  not sure this is needed selected_df = df.copy() fit_button.on_event(ButtonClick, fit_selected) # selected_columns = [ # "ASS", # "CLUSTID", # "X_PPM", # "Y_PPM", # "X_RADIUS_PPM", # "Y_RADIUS_PPM", # "XW_HZ", # "YW_HZ", # "VOL", # "include", # "MEMCNT", # ] # # columns = [TableColumn(field=field, title=field) for field in selected_columns] columns = [ TableColumn(field="ASS", title="Assignment"), TableColumn(field="CLUSTID", title="Cluster", editor=IntEditor()), TableColumn( field="X_PPM", title=f"{f2_label}", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="Y_PPM", title=f"{f1_label}", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="X_RADIUS_PPM", title=f"{f2_label} radius (ppm)", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="Y_RADIUS_PPM", title=f"{f1_label} radius (ppm)", editor=NumberEditor(step=0.0001), formatter=NumberFormatter(format="0.0000"), ), TableColumn( field="XW_HZ", title=f"{f2_label} LW (Hz)", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00"), ), TableColumn( field="YW_HZ", title=f"{f1_label} LW (Hz)", editor=NumberEditor(step=0.01), formatter=NumberFormatter(format="0.00"), ), TableColumn(field="VOL", title="Volume", formatter=NumberFormatter(format="0.0")), TableColumn( field="include", title="Include", editor=SelectEditor(options=["yes", "no"]) ), TableColumn(field="MEMCNT", title="MEMCNT", editor=IntEditor()), ] data_table = DataTable( source=source, columns=columns, editable=True, fit_columns=True, width=800 ) # callback for adding # source.selected.on_change('indices', callback) source.selected.on_change("indices", select_callback) # controls = column(slider, button) exit_button = Button(label="Quit", button_type="warning") exit_button.on_event(ButtonClick, exit_edit_peaks) controls = column( row(slider_X_RADIUS, slider_Y_RADIUS), row( column(contour_start, fit_button, widgetbox(ls_div), radio_button_group), column(savefilename, button, exit_button), ), ) # widgetbox(radio_button_group) struct_el = Select( title="Structuring element:", value="disk", options=["square", "disk", "rectangle", "None"], ) struct_el_size = TextInput( value="3", title="Size(width/radius or width,height for rectangle):" ) # iterations = TextInput(value="1", title="Number of iterations of binary dilation") recluster = Button(label="Re-cluster", button_type="warning") recluster.on_event(ButtonClick, recluster_peaks) # cluster_widget = widgetbox(struct_el, struct_el_size) # recluster) curdoc().add_root( row( column(p, widgetbox(clust_div), row(struct_el, struct_el_size), recluster), column(data_table, controls), ) ) curdoc().title = "peakipy: Edit Fits" # curdoc().theme = 'dark_minimal' # update() PK!]Kyww6peakipy/commandline/edit_fits_app/templates/index.html{% extends base %} {% block title %}Bokeh Crossfilter Example{% endblock %} {% block preamble %} {% endblock %} PK!ј?,peakipy/commandline/edit_fits_app/theme.yamlattrs: Figure: background_fill_color: 'white' border_fill_color: '#2F2F2F' outline_line_color: '#444444' Axis: axis_line_color: "white" axis_label_text_color: "white" major_label_text_color: "white" major_tick_line_color: "white" minor_tick_line_color: "white" minor_tick_line_color: "white" Grid: grid_line_dash: [6, 4] grid_line_alpha: .3 text_color: "white" PK!qbVVpeakipy/commandline/fit.py#!/usr/bin/env python3 """Fit and deconvolute NMR peaks Usage: fit [options] Arguments: peaklist output from read_peaklist.py 2D or pseudo3D NMRPipe data (single file) output peaklist ".csv" will output CSV format file, ".tab" will give a tab delimited output while ".pkl" results in Pandas pickle of DataFrame Options: -h --help Show this page -v --version Show version --dims= Dimension order [default: 0,1,2] --max_cluster_size= Maximum size of cluster to fit (i.e exclude large clusters) [default: 999] --lineshape= lineshape to fit [default: PV] --fix= Parameters to fix after initial fit on summed planes [default: fraction,sigma,center] --xy_bounds= Bound X and Y peak centers during fit [default: None] This can be set like so --xy_bounds=0.1,0.5 --vclist= Bruker style vclist [default: None] --plane= Specific plane(s) to fit [default: 0] eg. --plane=1 or --plane=1,4,5 --exclude_plane= Specific plane(s) to fit [default: 0] eg. --plane=1 or --plane=1,4,5 --nomp Do not use multiprocessing --plot= Whether to plot wireframe fits for each peak (saved into ) [default: None] --show Whether to show (using plt.show()) wireframe fits for each peak. Only works if --plot is also selected --verb Print what's going on ToDo: change outputs (print/log.txt) so that they do not attempt to write at the same time during multiprocess peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import sys import os import json from pathlib import Path from multiprocessing import cpu_count, Pool import nmrglue as ng import numpy as np import pandas as pd from docopt import docopt from skimage.filters import threshold_otsu from schema import Schema, And, Or, Use, SchemaError from peakipy.core import fix_params, get_params, fit_first_plane, Pseudo3D, run_log def check_xybounds(x): x = x.split(",") if len(x) == 2: xy_bounds = float(x[0]), float(x[1]) return xy_bounds else: print("🤔 xy_bounds must be pair of floats e.g. --xy_bounds=0.05,0.5") exit() def split_peaklist(peaklist, n_cpu): """ split peaklist into smaller files based on number of cpus""" tmp_path = Path("tmp") tmp_path.mkdir(exist_ok=True) clustids = peaklist.CLUSTID.unique() window = int(np.ceil(len(clustids) / n_cpu)) clustids = [clustids[i : i + window] for i in range(0, len(clustids), window)] for i in range(n_cpu): split_peaks = peaklist[peaklist.CLUSTID.isin(clustids[i])] split_peaks.to_csv(tmp_path / f"peaks_{i}.csv", index=False) return tmp_path class FitPeaksInput: def __init__(self, args, data): self.data = data self.args = args class FitPeaksResult: def __init__(self, df: pd.DataFrame, log: str): self.df = df self.log = log def fit_peaks(peaks, fit_input): # sum planes for initial fit summed_planes = fit_input.data.sum(axis=0) # for saving data, currently not using errs for center and sigma amps = [] amp_errs = [] center_xs = [] init_center_xs = [] # center_x_errs = [] center_ys = [] init_center_ys = [] # center_y_errs = [] sigma_ys = [] # sigma_y_errs = [] sigma_xs = [] # sigma_x_errs = [] names = [] assign = [] clustids = [] planes = [] x_radii = [] y_radii = [] x_radii_ppm = [] y_radii_ppm = [] lineshapes = [] if fit_input.args.get("lineshape") == "PV_PV": fractions_x = [] fractions_y = [] else: fractions = [] # group peaks based on CLUSTID groups = peaks.groupby("CLUSTID") to_fix = fit_input.args.get("to_fix") noise = fit_input.args.get("noise") verb = fit_input.args.get("verb") lineshape = fit_input.args.get("lineshape") xy_bounds = fit_input.args.get("xy_bounds") vclist = fit_input.args.get("vclist") uc_dics = fit_input.args.get("uc_dics") # iterate over groups of peaks out_str = "" for name, group in groups: #  max cluster size len_group = len(group) if len_group <= fit_input.args.get("max_cluster_size"): if len_group == 1: peak_str = "peak" else: peak_str = "peaks" out_str += f""" #################################### Fitting cluster of {len_group} {peak_str} #################################### """ # fits sum of all planes first fit_result = fit_first_plane( group, summed_planes, # norm(summed_planes), uc_dics, lineshape=lineshape, xy_bounds=xy_bounds, verbose=verb, noise=noise, ) fit_result.plot( plot_path=fit_input.args.get("plot"), show=fit_input.args.get("--show"), nomp=fit_input.args.get("--nomp") ) first = fit_result.out mask = fit_result.mask # log.write( out_str += fit_result.fit_str out_str += f""" ------------------------------------ Summed planes ------------------------------------ {first.fit_report()} """ # ) # fix sigma center and fraction parameters # could add an option to select params to fix if len(to_fix) == 0 or to_fix == "None": float_str = "Floating all parameters" if verb: print(float_str) pass else: to_fix = to_fix float_str = f"Fixing parameters: {to_fix}" if verb: print(float_str) fix_params(first.params, to_fix) out_str += float_str + "\n" for num, d in enumerate(fit_input.data): first.fit( data=d[mask], params=first.params, weights=1.0 / np.array([noise] * len(np.ravel(d[mask]))), ) fit_report = first.fit_report() # log.write( out_str += f""" ------------------------------------ Plane = {num+1} ------------------------------------ {fit_report} """ # ) if verb: print(fit_report) amp, amp_err, name = get_params(first.params, "amplitude") cen_x, cen_x_err, cx_name = get_params(first.params, "center_x") cen_y, cen_y_err, cy_name = get_params(first.params, "center_y") sig_x, sig_x_err, sx_name = get_params(first.params, "sigma_x") sig_y, sig_y_err, sy_name = get_params(first.params, "sigma_y") if lineshape == "PV_PV": frac_x, frac_err_x, name = get_params(first.params, "fraction_x") frac_y, frac_err_y, name = get_params(first.params, "fraction_y") fractions_x.extend(frac_x) fractions_y.extend(frac_y) else: frac, frac_err, name = get_params(first.params, "fraction") fractions.extend(frac) amps.extend(amp) amp_errs.extend(amp_err) center_xs.extend(cen_x) init_center_xs.extend(group.X_AXISf) # center_x_errs.extend(cen_x_err) center_ys.extend(cen_y) init_center_ys.extend(group.Y_AXISf) # center_y_errs.extend(cen_y_err) sigma_xs.extend(sig_x) # sigma_x_errs.extend(sig_x_err) sigma_ys.extend(sig_y) # sigma_y_errs.extend(sig_y_err) # add plane number, this should map to vclist planes.extend([num for _ in amp]) lineshapes.extend([lineshape for _ in amp]) #  get prefix for fit names.extend([i.replace("fraction", "") for i in name]) assign.extend(group["ASS"]) clustids.extend(group["CLUSTID"]) x_radii.extend(group["X_RADIUS"]) y_radii.extend(group["Y_RADIUS"]) x_radii_ppm.extend(group["X_RADIUS_PPM"]) y_radii_ppm.extend(group["Y_RADIUS_PPM"]) df_dic = { "fit_prefix": names, "assignment": assign, "amp": amps, "amp_err": amp_errs, "center_x": center_xs, "init_center_x": init_center_xs, # "center_x_err": center_x_errs, "center_y": center_ys, "init_center_y": init_center_ys, # "center_y_err": center_y_errs, "sigma_x": sigma_xs, # "sigma_x_err": sigma_x_errs, "sigma_y": sigma_ys, # "sigma_y_err": sigma_y_errs, "clustid": clustids, "plane": planes, "x_radius": x_radii, "y_radius": y_radii, "x_radius_ppm": x_radii_ppm, "y_radius_ppm": y_radii_ppm, "lineshape": lineshapes, } if lineshape == "PV_PV": df_dic["fraction_x"] = fractions_x df_dic["fraction_y"] = fractions_y else: df_dic["fraction"] = fractions #  make dataframe df = pd.DataFrame(df_dic) # Fill nan values df.fillna(value=np.nan, inplace=True) # vclist if vclist: vclist_data = fit_input.args.get("vclist_data") df["vclist"] = df.plane.apply(lambda x: vclist_data[x]) #  output data return FitPeaksResult(df=df, log=out_str) def main(argv): # number of CPUs n_cpu = cpu_count() args = docopt(__doc__, argv=argv) schema = Schema( { "": And( os.path.exists, open, error=f"🤔 {args['']} should exist and be readable", ), "": And( os.path.exists, Use( ng.pipe.read, error=f"🤔 {args['']} should be NMRPipe format 2D or 3D cube", ), error=f"🤔 {args['']} either does not exist or is not an NMRPipe format 2D or 3D", ), "": Use(str), "--max_cluster_size": And(Use(int), lambda n: 0 < n), "--lineshape": Or( "PV", "L", "G", "PV_PV", "PV_G", "PV_L", "G_L", error="🤔 --lineshape must be either PV, L, G, PV_PV, PV_G, PV_L, G_L", ), "--fix": Or( Use( lambda x: [ i for i in x.split(",") if (i == "fraction") or (i == "center") or (i == "sigma") ] ) ), "--dims": Use( lambda n: [int(i) for i in eval(n)], error="🤔 --dims should be list of integers e.g. --dims=0,1,2", ), "--vclist": Or( "None", And( os.path.exists, Use(np.genfromtxt, error=f"🤔 cannot open {args.get('--vclist')}"), ), ), "--plot": Or("None", Use(lambda f: Path(f))), "--xy_bounds": Or( "None", Use( check_xybounds, error="🤔 xy_bounds must be pair of floats e.g. --xy_bounds=0.05,0.5", ), ), "--plane": Or( 0, Use( lambda n: [int(i) for i in n.split(",")], error="🤔 plane(s) to fit should be an integer or list of integers e.g. --plane=1,2,3,4", ), ), "--exclude_plane": Or( 0, Use( lambda n: [int(i) for i in n.split(",")], error="🤔 plane(s) to exclude should be an integer or list of integers e.g. --exclude_plane=1,2,3,4", ), ), object: object, }, # ignore_extra_keys=True, ) try: args = schema.validate(args) except SchemaError as e: exit(e) config_path = Path("peakipy.config") if config_path.exists(): config = json.load(open(config_path)) print(f"Using config file with --dims={config.get('--dims')}") args["--dims"] = config.get("--dims", [0, 1, 2]) noise = config.get("noise") if noise: noise = float(noise) else: noise = False args["noise"] = noise lineshape = args.get("--lineshape") args["lineshape"] = lineshape # params to fix to_fix = args.get("--fix") args["to_fix"] = to_fix # print(to_fix) verb = args.get("--verb") if verb: print("Using ", args) args["verb"] = verb # path to peaklist peaklist = Path(args.get("")) # determine file type if peaklist.suffix == ".csv": peaks = pd.read_csv(peaklist) # , comment="#") else: # assume that file is a pickle peaks = pd.read_pickle(peaklist) # only include peaks with 'include' if "include" in peaks.columns: pass else: # for compatibility peaks["include"] = peaks.apply(lambda _: "yes", axis=1) if len(peaks[peaks.include != "yes"]) > 0: print(f"The following peaks have been exluded:\n{peaks[peaks.include != 'yes']}") peaks = peaks[peaks.include == "yes"] # filter list based on cluster size max_cluster_size = args.get("--max_cluster_size") if max_cluster_size == 999: max_cluster_size = peaks.MEMCNT.max() if peaks.MEMCNT.max() > 10: print( f""" ################################################################## You have some clusters of as many as {max_cluster_size} peaks. You may want to consider reducing the size of your clusters as the fits will struggle. Otherwise you can use the --max_cluster_size flag to exclude large clusters ################################################################## """ ) else: max_cluster_size = max_cluster_size args["max_cluster_size"] = max_cluster_size # read vclist vclist = args.get("--vclist") if type(vclist) == np.ndarray: vclist_data = vclist args["vclist_data"] = vclist_data vclist = True else: vclist = False args["vclist"] = vclist # plot results or not plot = args.get("--plot") if plot == "None": plot = None log_file = open("log.txt", "w") else: log_file = open("~log.txt", "w") plot.mkdir(parents=True, exist_ok=True) args["plot"] = plot # get dims from command line input dims = args.get("--dims") # read NMR data dic, data = args[""] pseudo3D = Pseudo3D(dic, data, dims) uc_f1 = pseudo3D.uc_f1 uc_f2 = pseudo3D.uc_f2 uc_dics = {"f1": uc_f1, "f2": uc_f2} args["uc_dics"] = uc_dics dims = pseudo3D.dims data = pseudo3D.data if len(dims) != len(data.shape): print(f"Dims are {dims} while data shape is {data.shape}?") exit() if args.get("--plane", [0]) != [0]: _inds = args.get("--plane") inds = [i - 1 for i in _inds] data_inds = [(i in inds) for i in range(data.shape[dims[0]])] data = data[data_inds] print(f"Using only planes {_inds} data now has the following shape", data.shape) if data.shape[dims[0]] == 0: print("You have excluded all the data!", data.shape) exit() if args.get("--exclude_plane", [0]) != [0]: _inds = args.get("--exclude_plane") inds = [i - 1 for i in _inds] data_inds = [(i not in inds) for i in range(data.shape[dims[0]])] data = data[data_inds] print(f"Excluding planes {_inds} data now has the following shape", data.shape) if data.shape[dims[0]] == 0: print("You have excluded all the data!", data.shape) exit() if not noise: noise = threshold_otsu(data) args["noise"] = noise # print(noise) # point per Hz pt_per_hz_f2 = pseudo3D.pt_per_hz_f2 pt_per_hz_f1 = pseudo3D.pt_per_hz_f1 # point per Hz hz_per_pt_f2 = 1.0 / pt_per_hz_f2 hz_per_pt_f1 = 1.0 / pt_per_hz_f1 # ppm per point ppm_per_pt_f2 = pseudo3D.ppm_per_pt_f2 ppm_per_pt_f1 = pseudo3D.ppm_per_pt_f1 # point per ppm pt_per_ppm_f2 = pseudo3D.pt_per_ppm_f2 pt_per_ppm_f1 = pseudo3D.pt_per_ppm_f1 xy_bounds = args.get("--xy_bounds") if xy_bounds == "None": xy_bounds = None else: # convert ppm to points xy_bounds[0] = xy_bounds[0] * pt_per_ppm_f2 xy_bounds[1] = xy_bounds[1] * pt_per_ppm_f1 args["xy_bounds"] = xy_bounds # convert linewidths from Hz to points in case they were adjusted when running run_check_fits.py peaks["XW"] = peaks.XW_HZ * pt_per_hz_f2 peaks["YW"] = peaks.YW_HZ * pt_per_hz_f1 # convert peak positions from ppm to points in case they were adjusted running run_check_fits.py peaks["X_AXIS"] = peaks.X_PPM.apply(lambda x: uc_f2(x, "PPM")) peaks["Y_AXIS"] = peaks.Y_PPM.apply(lambda x: uc_f1(x, "PPM")) peaks["X_AXISf"] = peaks.X_PPM.apply(lambda x: uc_f2.f(x, "PPM")) peaks["Y_AXISf"] = peaks.Y_PPM.apply(lambda x: uc_f1.f(x, "PPM")) if (peaks.CLUSTID.nunique() >= n_cpu) and not args.get("--nomp"): print("Using multiprocessing") # split peak lists tmp_dir = split_peaklist(peaks, n_cpu) peaklists = [pd.read_csv(tmp_dir / f"peaks_{i}.csv") for i in range(n_cpu)] args_list = [FitPeaksInput(args, data) for _ in range(n_cpu)] with Pool(processes=n_cpu) as pool: # result = pool.map(fit_peaks, peaklists) result = pool.starmap(fit_peaks, zip(peaklists, args_list)) df = pd.concat([i.df for i in result], ignore_index=True) for num, i in enumerate(result): i.df.to_csv(tmp_dir / f"peaks_{num}_fit.csv", index=False) log_file.write(i.log + "\n") else: print("Not using multiprocessing") result = fit_peaks(peaks, FitPeaksInput(args, data)) df = result.df log_file.write(result.log) # close log file log_file.close() output = Path(args[""]) suffix = output.suffix #  convert sigmas to fwhm df["fwhm_x"] = df.sigma_x.apply(lambda x: x * 2.0) df["fwhm_y"] = df.sigma_y.apply(lambda x: x * 2.0) #  convert values to ppm df["center_x_ppm"] = df.center_x.apply(lambda x: uc_f2.ppm(x)) df["center_y_ppm"] = df.center_y.apply(lambda x: uc_f1.ppm(x)) df["init_center_x_ppm"] = df.init_center_x.apply(lambda x: uc_f2.ppm(x)) df["init_center_y_ppm"] = df.init_center_y.apply(lambda x: uc_f1.ppm(x)) df["sigma_x_ppm"] = df.sigma_x.apply(lambda x: x * ppm_per_pt_f2) df["sigma_y_ppm"] = df.sigma_y.apply(lambda x: x * ppm_per_pt_f1) df["fwhm_x_ppm"] = df.fwhm_x.apply(lambda x: x * ppm_per_pt_f2) df["fwhm_y_ppm"] = df.fwhm_y.apply(lambda x: x * ppm_per_pt_f1) df["fwhm_x_hz"] = df.fwhm_x.apply(lambda x: x * hz_per_pt_f2) df["fwhm_y_hz"] = df.fwhm_y.apply(lambda x: x * hz_per_pt_f1) if suffix == ".csv": df.to_csv(output, float_format="%.4f", index=False) elif suffix == ".tab": df.to_csv(output, sep="\t", float_format="%.4f", index=False) else: df.to_pickle(output) print( """ 🍾 ✨ Finished! ✨ 🍾 """ ) run_log() if __name__ == "__main__": argv = sys.argv[1:] main(argv) PK!p [...] Options: -h, --help peakipy commands are: read Read peaklist and generate initial peak clusters edit Interactively edit fit parameters fit Fit peaks check Check individual fits and generate plots spec Plot spectra and make overlays See 'peakipy help ' for more information on a specific command. For help on specific type peakipy -h E.g. peakipy read -h """ from docopt import docopt def main(argv): args = docopt(__doc__, version='peakipy version 0.1.17', options_first=True, argv=argv[1:]) argv = args[''] if args[''] == 'read': import peakipy.commandline.read as read_peaklist read_peaklist.main(argv) elif args[''] == 'fit': import peakipy.commandline.fit as fit fit.main(argv) elif args[''] == 'edit': import peakipy.commandline.edit as edit edit.main(argv) elif args[''] == 'check': import peakipy.commandline.check as check check.main(argv) elif args[''] == 'spec': import peakipy.commandline.spec as spec spec.main(argv) elif args[''] == 'help': print(__doc__) exit() else: print(__doc__) exit("%r is not a peakipy command. See 'peakipy help'." % args['']) if __name__ == '__main__': main() PK!mNNpeakipy/commandline/read.py#!/usr/bin/env python3 """ Read NMRPipe/Analysis peaklist into pandas dataframe Usage: read (--a2|--sparky|--pipe) [options] Arguments: Analysis2/Sparky/NMRPipe peak list (see below) 2D or pseudo3D NMRPipe data --a2 Analysis peaklist as input (tab delimited) --sparky Sparky peaklist as input --pipe NMRPipe peaklist as input Options: -h --help Show this screen --version Show version --thres= Threshold for making binary mask that is used for peak clustering [default: None] If set to None then threshold_otsu from scikit-image is used to determine threshold --struc_el= Structuring element for binary_closing [default: disk] 'square'|'disk'|'rectangle' --struc_size= Size/dimensions of structuring element [default: 3,] For square and disk first element of tuple is used (for disk value corresponds to radius). For rectangle, tuple corresponds to (width,height). --f1radius= F1 radius in ppm for fit mask [default: 0.4] --f2radius= F2 radius in ppm for fit mask [default: 0.04] --dims= Order of dimensions [default: 0,1,2] --posF2= Name of column in Analysis2 peak list containing F2 (i.e. X_PPM) peak positions [default: "Position F1"] --posF1= Name of column in Analysis2 peak list containing F1 (i.e. Y_PPM) peak positions [default: "Position F2"] --outfmt= Format of output peaklist [default: csv] --show Show the clusters on the spectrum color coded using matplotlib --fuda Create a parameter file for running fuda (params.fuda) Examples: read_peaklist.py test.tab test.ft2 --pipe --dims0,1 read_peaklist.py test.a2 test.ft2 --a2 --thres=1e5 --dims=0,2,1 Description: NMRPipe column headers: INDEX X_AXIS Y_AXIS DX DY X_PPM Y_PPM X_HZ Y_HZ XW YW XW_HZ YW_HZ X1 X3 Y1 Y3 HEIGHT DHEIGHT VOL PCHI2 TYPE ASS CLUSTID MEMCNT Are mapped onto analysis peak list 'Number', '#', 'Position F1', 'Position F2', 'Sampled None', 'Assign F1', 'Assign F2', 'Assign F3', 'Height', 'Volume', 'Line Width F1 (Hz)', 'Line Width F2 (Hz)', 'Line Width F3 (Hz)', 'Merit', 'Details', 'Fit Method', 'Vol. Method' Or sparky peaklist Assignment w1 w2 Volume Data Height lw1 (hz) lw2 (hz) Clusters of peaks are selected peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import sys import os import json import textwrap from pathlib import Path import pandas as pd import numpy as np import nmrglue as ng from docopt import docopt from scipy import ndimage from skimage.morphology import square, binary_closing, disk, rectangle from skimage.filters import threshold_otsu from peakipy.core import make_mask, Pseudo3D, run_log analysis_to_pipe = { "#": "INDEX", # "": "X_AXIS", # "": "Y_AXIS", # "": "DX", # "": "DY", "Position F1": "X_PPM", "Position F2": "Y_PPM", # "": "X_HZ", # "": "Y_HZ", # "": "XW", # "": "YW", "Line Width F1 (Hz)": "XW_HZ", "Line Width F2 (Hz)": "YW_HZ", # "": "X1", # "": "X3", # "": "Y1", # "": "Y3", "Height": "HEIGHT", # "Height": "DHEIGHT", "Volume": "VOL", # "": "PCHI2", # "": "TYPE", # "": "ASS", # "": "CLUSTID", # "": "MEMCNT" } sparky_to_pipe = { "index": "INDEX", # "": "X_AXIS", # "": "Y_AXIS", # "": "DX", # "": "DY", "w1": "X_PPM", "w2": "Y_PPM", # "": "X_HZ", # "": "Y_HZ", # "": "XW", # "": "YW", "lw1 (hz)": "XW_HZ", "lw2 (hz)": "YW_HZ", # "": "X1", # "": "X3", # "": "Y1", # "": "Y3", "Height": "HEIGHT", # "Height": "DHEIGHT", "Volume": "VOL", # "": "PCHI2", # "": "TYPE", "Assignment": "ASS", # "": "CLUSTID", # "": "MEMCNT" } class Peaklist: """ Read analysis, sparky or NMRPipe peak list and convert to NMRPipe-ish format also find peak clusters Parameters ---------- path : path-like or str path to peaklist data : ndarray NMRPipe format data fmt : a2|sparky|pipe dims: [planes,y,x] radii: [x,y] Mask radii in ppm Methods ------- clusters : adaptive_clusters : Returns ------- df : pandas DataFrame dataframe containing peaklist """ def __init__(self, path, data_path, fmt="a2", dims=[0, 1, 2], radii=[0.04, 0.4]): self.fmt = fmt self.path = path self.data_path = data_path if self.fmt == "a2": self.df = self._read_analysis() elif self.fmt == "sparky": self.df = self._read_sparky() elif self.fmt == "pipe": self.df = self._read_pipe() else: raise (TypeError, "I don't know this format") #  read pipe data dic, self.data = ng.pipe.read(data_path) pseudo3D = Pseudo3D(dic, self.data, dims) self.data = pseudo3D.data uc_f1 = pseudo3D.uc_f1 uc_f2 = pseudo3D.uc_f2 self.dims = pseudo3D.dims self.data = pseudo3D.data self.pt_per_ppm_f1 = pseudo3D.pt_per_ppm_f1 self.pt_per_ppm_f2 = pseudo3D.pt_per_ppm_f2 pt_per_hz_f2dim = pseudo3D.pt_per_hz_f2 pt_per_hz_f1dim = pseudo3D.pt_per_hz_f1 print("Points per hz f1 = %.3f, f2 = %.3f" % (pt_per_hz_f1dim, pt_per_hz_f2dim)) # int point value self.df["X_AXIS"] = self.df.X_PPM.apply(lambda x: uc_f2(x, "ppm")) self.df["Y_AXIS"] = self.df.Y_PPM.apply(lambda x: uc_f1(x, "ppm")) # decimal point value self.df["X_AXISf"] = self.df.X_PPM.apply(lambda x: uc_f2.f(x, "ppm")) self.df["Y_AXISf"] = self.df.Y_PPM.apply(lambda x: uc_f1.f(x, "ppm")) # in case of missing values (should estimate though) self.df.XW_HZ.replace("None", "20.0", inplace=True) self.df.YW_HZ.replace("None", "20.0", inplace=True) self.df.XW_HZ.replace(np.NaN, "20.0", inplace=True) self.df.YW_HZ.replace(np.NaN, "20.0", inplace=True) # convert linewidths to float self.df["XW_HZ"] = self.df.XW_HZ.apply(lambda x: float(x)) self.df["YW_HZ"] = self.df.YW_HZ.apply(lambda x: float(x)) # convert Hz lw to points self.df["XW"] = self.df.XW_HZ.apply(lambda x: x * pt_per_hz_f2dim) self.df["YW"] = self.df.YW_HZ.apply(lambda x: x * pt_per_hz_f1dim) # makes an assignment column if self.fmt == "a2": self.df["ASS"] = self.df.apply( lambda i: "".join([i["Assign F1"], i["Assign F2"]]), axis=1 ) # check assignments for duplicates self.check_assignments() # make default values for X and Y radii for fit masks self.f2radius, self.f1radius = radii self.df["X_RADIUS_PPM"] = np.zeros(len(self.df)) + self.f2radius self.df["Y_RADIUS_PPM"] = np.zeros(len(self.df)) + self.f1radius self.df["X_RADIUS"] = self.df.X_RADIUS_PPM.apply( lambda x: x * self.pt_per_ppm_f2 ) self.df["Y_RADIUS"] = self.df.Y_RADIUS_PPM.apply( lambda x: x * self.pt_per_ppm_f1 ) # add include column self.df["include"] = self.df.apply(lambda x: "yes", axis=1) def _read_analysis(self): df = pd.read_csv(self.path, delimiter="\t") new_columns = [analysis_to_pipe.get(i, i) for i in df.columns] pipe_columns = dict(zip(df.columns, new_columns)) df = df.rename(index=str, columns=pipe_columns) return df def _read_sparky(self): df = pd.read_csv( self.path, skiprows=2, delim_whitespace=True, names=["ASS", "Y_PPM", "X_PPM", "VOLUME", "HEIGHT", "YW_HZ", "XW_HZ"], ) return df def _read_pipe(self): to_skip = 0 with open(self.path) as f: lines = f.readlines() for line in lines: if line.startswith("VARS"): columns = line.strip().split()[1:] elif line[:5].strip(" ").isdigit(): break else: to_skip += 1 df = pd.read_csv( self.path, skiprows=to_skip, names=columns, delim_whitespace=True ) return df def check_assignments(self): duplicates_bool = self.df.ASS.duplicated() duplicates = self.df.ASS[duplicates_bool] if len(duplicates) > 0: print( """ You have duplicated assignments in your list... Currently each peak needs a unique assignment. Sorry about that buddy... Here are the duplicates""" ) print(duplicates) print("Creating dummy assignments for duplicates") self.df.loc[duplicates_bool, "ASS"] = [ f"{i}_dummy_{num+1}" for num, i in enumerate(duplicates) ] print(self.df.ASS) def clusters(self, thres=None, struc_el="disk", struc_size=(3,), l_struc=None): """ Find clusters of peaks :param thres: threshold for positive signals above which clusters are selected. If None then threshold_otsu is used :type thres: float :param struc_el: 'square'|'disk'|'rectangle' structuring element for binary_closing of thresholded data can be square, disc or rectangle :type struc_el: str :param struc_size: size/dimensions of structuring element for square and disk first element of tuple is used (for disk value corresponds to radius) for rectangle, tuple corresponds to (width,height). :type struc_size: tuple """ peaks = [[y, x] for y, x in zip(self.df.Y_AXIS, self.df.X_AXIS)] if thres == None: self.thresh = threshold_otsu(self.data[0]) else: self.thresh = thres # get positive and negative thresh_data = np.bitwise_or( self.data[0] < (self.thresh * -1.0), self.data[0] > self.thresh ) if struc_el == "disk": radius = struc_size[0] print(f"using disk with {radius}") closed_data = binary_closing(thresh_data, disk(int(radius))) elif struc_el == "square": width = struc_size[0] print(f"using square with {width}") closed_data = binary_closing(thresh_data, square(int(width))) elif struc_el == "rectangle": width, height = struc_size print(f"using rectangle with {width} and {height}") closed_data = binary_closing( thresh_data, rectangle(int(width), int(height)) ) else: print(f"Not using any closing function") closed_data = self.data labeled_array, num_features = ndimage.label(closed_data, l_struc) # print(labeled_array, num_features) self.df["CLUSTID"] = [labeled_array[i[0], i[1]] for i in peaks] #  renumber "0" clusters max_clustid = self.df["CLUSTID"].max() n_of_zeros = len(self.df[self.df["CLUSTID"] == 0]["CLUSTID"]) self.df.loc[self.df[self.df["CLUSTID"] == 0].index, "CLUSTID"] = np.arange( max_clustid + 1, n_of_zeros + max_clustid + 1, dtype=int ) # count how many peaks per cluster self.df["MEMCNT"] = np.zeros(len(self.df), dtype=int) for ind, group in self.df.groupby("CLUSTID"): self.df.loc[group.index, "MEMCNT"] = len(group) # def adaptive_clusters(self, block_size, offset, l_struc=None): # self.thresh = threshold_otsu(self.data[0]) # peaks = [[y, x] for y, x in zip(self.df.Y_AXIS, self.df.X_AXIS)] # binary_adaptive = threshold_adaptive( # self.data[0], block_size=block_size, offset=offset # ) # labeled_array, num_features = ndimage.label(binary_adaptive, l_struc) # # print(labeled_array, num_features) # self.df["CLUSTID"] = [labeled_array[i[0], i[1]] for i in peaks] # #  renumber "0" clusters # max_clustid = self.df["CLUSTID"].max() # n_of_zeros = len(self.df[self.df["CLUSTID"] == 0]["CLUSTID"]) # self.df.loc[self.df[self.df["CLUSTID"] == 0].index, "CLUSTID"] = np.arange( # max_clustid + 1, n_of_zeros + max_clustid + 1, dtype=int # ) def mask_method(self, x_radius=0.04, y_radius=0.4, l_struc=None): self.thresh = threshold_otsu(self.data[0]) x_radius = self.pt_per_ppm_f2 * x_radius y_radius = self.pt_per_ppm_f1 * y_radius mask = np.zeros(self.data[0].shape, dtype=bool) for ind, peak in self.df.iterrows(): mask += make_mask( self.data[0], peak.X_AXISf, peak.Y_AXISf, x_radius, y_radius ) peaks = [[y, x] for y, x in zip(self.df.Y_AXIS, self.df.X_AXIS)] labeled_array, num_features = ndimage.label(mask, l_struc) self.df["CLUSTID"] = [labeled_array[i[0], i[1]] for i in peaks] #  renumber "0" clusters max_clustid = self.df["CLUSTID"].max() n_of_zeros = len(self.df[self.df["CLUSTID"] == 0]["CLUSTID"]) self.df.loc[self.df[self.df["CLUSTID"] == 0].index, "CLUSTID"] = np.arange( max_clustid + 1, n_of_zeros + max_clustid + 1, dtype=int ) import matplotlib.pyplot as plt plt.imshow(mask) plt.show() def get_df(self): return self.df def get_thres(self): return self.thresh def to_fuda(self, fname="params.fuda"): with open("peaks.fuda", "w") as peaks_fuda: for ass, f1_ppm, f2_ppm in zip(self.df.ASS, self.df.Y_PPM, self.df.X_PPM): peaks_fuda.write(f"{ass}\t{f1_ppm:.3f}\t{f2_ppm:.3f}\n") groups = self.df.groupby("CLUSTID") fuda_params = Path(fname) overlap_peaks = "" for ind, group in groups: if len(group) > 1: overlap_peaks_str = ";".join(group.ASS) overlap_peaks += f"OVERLAP_PEAKS=({overlap_peaks_str})\n" fuda_file = textwrap.dedent( f"""\ # Read peaklist and spectrum info PEAKLIST=peaks.fuda SPECFILE={self.data_path} PARAMETERFILE=(bruker;vclist) NOISE={self.get_thres()} # you'll need to adjust this BASELINE=N VERBOSELEVEL=5 PRINTDATA=Y LM=(MAXFEV=250;TOL=1e-5) #Specify the default values. All values are in ppm: DEF_LINEWIDTH_F1={self.f1radius} DEF_LINEWIDTH_F2={self.f2radius} DEF_RADIUS_F1={self.f1radius} DEF_RADIUS_F2={self.f2radius} SHAPE=GLORE # OVERLAP PEAKS {overlap_peaks}""" ) with open(fuda_params, "w") as f: f.write(fuda_file) print(overlap_peaks) def main(argv): args = docopt(__doc__, argv=argv) filename = Path(args[""]) # print(filename.stem) if args.get("--thres") == "None": args["--thres"] = None else: args["--thres"] = eval(args["--thres"]) thres = args.get("--thres") print("Using arguments:", args) f1radius = float(args.get("--f1radius")) f2radius = float(args.get("--f2radius")) clust_args = { "struc_el": args.get("--struc_el"), "struc_size": eval(args.get("--struc_size")), } dims = args.get("--dims") dims = [int(i) for i in dims.split(",")] pipe_ft_file = args.get("") if args.get("--a2"): # set X and Y ppm column names if not default (i.e. "Position F1" = "X_PPM" # "Position F2" = "Y_PPM" ) this is due to Analysis2 often having the #  dimension order flipped relative to convention analysis_to_pipe[args.get("--posF1")] = "Y_PPM" analysis_to_pipe[args.get("--posF2")] = "X_PPM" peaks = Peaklist( filename, pipe_ft_file, fmt="a2", dims=dims, radii=[f2radius, f1radius] ) # peaks.adaptive_clusters(block_size=151,offset=0) elif args.get("--sparky"): peaks = Peaklist( filename, pipe_ft_file, fmt="sparky", dims=dims, radii=[f2radius, f1radius] ) elif args.get("--pipe"): peaks = Peaklist( filename, pipe_ft_file, fmt="pipe", dims=dims, radii=[f2radius, f1radius] ) peaks.clusters(thres=thres, **clust_args, l_struc=None) data = peaks.get_df() thres = peaks.get_thres() if args.get("--fuda"): print("Creating fuda parameter file") peaks.to_fuda() print(data.head()) outfmt = args.get("--outfmt", "csv") outname = filename.stem if outfmt == "csv": outname = outname + ".csv" data.to_csv(outname, float_format="%.4f", index=False) else: outname = outname + ".pkl" data.to_pickle(outname) # write config file with open("peakipy.config", "w") as config: #  add dims config_dic = dict( [ ("--dims", dims), ("", pipe_ft_file), ("--thres", float(thres)), ("--f1radius", f1radius), ("--f2radius", f2radius), ] ) # write json config.write(json.dumps(config_dic, sort_keys=True, indent=4)) # json.dump(config_dic, fp=config, sort_keys=True, indent=4) run_log() yaml = f""" ########################################################################################################## # This first block is global parameters which can be overridden by adding the desired argument # # to your list of spectra. One exception is "colors" which if set in global params overrides the # # color option set for individual spectra as the colors will now cycle through the chosen matplotlib # # colormap # ########################################################################################################## cs: {thres} # contour start contour_num: 10 # number of contours contour_factor: 1.2 # contour factor colors: tab20 # must be matplotlib.cm colormap show_cs: True outname: ["clusters.pdf","clusters.png"] # either single value or list of output names ncol: 1 # tells matplotlib how many columns to give the figure legend - if not set defaults to 2 clusters: {outname} dims: {dims} # Here is where your list of spectra to plot goes spectra: - fname: {pipe_ft_file} label: "" contour_num: 20 linewidths: 0.1 """ if args.get("--show"): with open("show_clusters.yml", "w") as out: out.write(yaml) os.system("peakipy spec show_clusters.yml") if __name__ == "__main__": argv = sys.argv[1:] main(argv) PK!}#&&peakipy/commandline/spec.py#!/usr/bin/env python3 """ Usage: spec.py spec.py make Plot NMRPipe spectra overlays using nmrglue and matplotlib. This is my attempt to make a general script for plotting NMR data. Below is an example yaml file for input # This first block is global parameters which can be overridden by adding the desired argument # to your list of spectra. One exception is "colors" which if set in global params overrides the # color option set for individual spectra as the colors will now cycle through the chosen matplotlib # colormap cs: 10e5 # contour start contour_num: 10 # number of contours contour_factor: 1.2 # contour factor colors: Set1 # must be matplotlib.cm colormap outname: ["overlay.pdf","overlay.png"] # either single value or list of output names # Here is where your list of spectra to plot goes spectra: - fname: test.ft2 label: write legend here contour_num: 1 linewidths: 1 Options: -h --help -v --version Dependencies: -- python3 -- matplotlib, pyyaml, numpy, nmrglue, pandas and docopt peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import shutil import yaml import nmrglue as ng import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm from docopt import docopt yaml_file = """ ########################################################################################################## # This first block is global parameters which can be overridden by adding the desired argument # # to your list of spectra. One exception is "colors" which if set in global params overrides the # # color option set for individual spectra as the colors will now cycle through the chosen matplotlib # # colormap # ########################################################################################################## cs: 10e5 # contour start contour_num: 10 # number of contours contour_factor: 1.2 # contour factor colors: Set1 # must be matplotlib.cm colormap outname: ["overlay_wt_s95a.pdf","overlay_wt_s95a.png"] # either single value or list of output names ncol: 1 # tells matplotlib how many columns to give the figure legend - if not set defaults to 2 # Here is where your list of spectra to plot goes spectra: - fname: test.ft2 label: shHTL5(S95A) pH 6.5 - 30 degrees contour_num: 1 linewidths: 1 """ def make_yaml_file(name, yaml_file=yaml_file): if os.path.exists(name): print(f"Copying {name} to {name}.bak") shutil.copy(name,f"{name}.bak") print(f"Making yaml file ... {name}") with open(name, "w") as new_yaml_file: new_yaml_file.write(yaml_file) def onpick(event): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind points = tuple(zip(xdata[ind], ydata[ind])) print("onpick points:", points) def main(args): arguments = docopt(__doc__, argv=args) if arguments["make"]: make_yaml_file(name=arguments[""]) exit() params = yaml.load(open(arguments[""], "r"), Loader=yaml.FullLoader) fig = plt.figure() ax = fig.add_subplot(111) cs_g = float(params["cs"]) spectra = params["spectra"] contour_num_g = params.get("contour_num", 10) contour_factor_g = params.get("contour_factor", 1.2) nspec = len(spectra) notes = [] legends = 0 for num, spec in enumerate(spectra): # unpack spec specific parameters fname = spec["fname"] if params.get("colors"): # currently overrides color option color = np.linspace(0, 1, nspec)[num] colors = cm.get_cmap(params.get("colors"))(color) # print("Colors set to cycle though %s from Matplotlib"%params.get("colors")) # print(colors) colors = colors[:-1] else: colors = spec["colors"] neg_colors = spec.get("neg_colors") label = spec.get("label") cs = float(spec.get("cs", cs_g)) contour_num = spec.get("contour_num", contour_num_g) contour_factor = spec.get("contour_factor", contour_factor_g) #  append cs and colors to notes notes.append((cs, colors)) # read spectra dic, data = ng.pipe.read(fname) udic = ng.pipe.guess_udic(dic, data) ndim = udic["ndim"] if ndim == 1: uc_f1 = ng.pipe.make_uc(dic, data, dim=0) elif ndim == 2: f1, f2 = params.get("dims", [0, 1]) uc_f1 = ng.pipe.make_uc(dic, data, dim=f1) uc_f2 = ng.pipe.make_uc(dic, data, dim=f2) ppm_f1 = uc_f1.ppm_scale() ppm_f2 = uc_f2.ppm_scale() ppm_f1_0, ppm_f1_1 = uc_f1.ppm_limits() # max,min ppm_f2_0, ppm_f2_1 = uc_f2.ppm_limits() # max,min elif ndim == 3: dims = params.get("dims", [0, 1, 2]) f1, f2, f3 = dims uc_f1 = ng.pipe.make_uc(dic, data, dim=f1) uc_f2 = ng.pipe.make_uc(dic, data, dim=f2) uc_f3 = ng.pipe.make_uc(dic, data, dim=f3) #  need to make more robust ppm_f1 = uc_f2.ppm_scale() ppm_f2 = uc_f3.ppm_scale() ppm_f1_0, ppm_f1_1 = uc_f2.ppm_limits() # max,min ppm_f2_0, ppm_f2_1 = uc_f3.ppm_limits() # max,min # if f1 == 0: # data = data[f1] if dims != [1, 2, 3]: data = np.transpose(data, dims) data = data[0] # x and y are set to f2 and f1 f1, f2 = f2, f3 # elif f1 == 1: # data = data[:,0,:] # else: # data = data[:,:,0] # plot parameters contour_start = cs # contour level start value contour_num = contour_num # number of contour levels contour_factor = contour_factor # scaling factor between contour levels # calculate contour levels cl = contour_start * contour_factor ** np.arange(contour_num) ax.contour( data, cl, colors=[colors for _ in cl], linewidths=spec.get("linewidths", 0.5), extent=(ppm_f2_0, ppm_f2_1, ppm_f1_0, ppm_f1_1), ) if neg_colors: ax.contour( data * -1, cl, colors=[neg_colors for _ in cl], linewidths=spec.get("linewidths", 0.5), extent=(ppm_f2_0, ppm_f2_1, ppm_f1_0, ppm_f1_1), ) else: # if no neg color given then plot with 0.5 alpha ax.contour( data * -1, cl, colors=[colors for _ in cl], linewidths=spec.get("linewidths", 0.5), extent=(ppm_f2_0, ppm_f2_1, ppm_f1_0, ppm_f1_1), alpha=0.5, ) # make legend if label: legends += 1 # hack for legend ax.plot([], [], c=colors, label=label) # plt.xlim(ppm_f2_0, ppm_f2_1) ax.invert_xaxis() ax.set_xlabel(udic[f2]["label"] + " ppm") if params.get("xlim"): ax.set_xlim(*params.get("xlim")) # plt.ylim(ppm_f1_0, ppm_f1_1) ax.invert_yaxis() ax.set_ylabel(udic[f1]["label"] + " ppm") if legends > 0: plt.legend( loc="upper center", bbox_to_anchor=(0.5, 1.20), ncol=params.get("ncol", 2) ) plt.tight_layout() #  add a list of outfiles y = 0.025 # only write cs levels if show_cs: True in yaml file if params.get("show_cs"): for num, j in enumerate(notes): col = j[1] con_strt = j[0] ax.text(0.025, y, "cs=%.2e" % con_strt, color=col, transform=ax.transAxes) y += 0.05 if params.get("clusters"): peaklist = params.get("clusters") if os.path.splitext(peaklist)[-1] == ".csv": clusters = pd.read_csv(peaklist) else: clusters = pd.read_pickle(peaklist) groups = clusters.groupby("CLUSTID") for ind, group in groups: if len(group) == 1: ax.plot(group.X_PPM, group.Y_PPM, "ko", markersize=1) # , picker=5) else: ax.plot(group.X_PPM, group.Y_PPM, "o", markersize=1) # , picker=5) if params.get("outname") and (type(params.get("outname")) == list): for i in params.get("outname"): plt.savefig(i, bbox_inches="tight", dpi=300) else: plt.savefig(params.get("outname", "test.pdf"), bbox_inches="tight") # fig.canvas.mpl_connect("pick_event", onpick) # line, = ax.plot(np.random.rand(100), 'o', picker=5) # 5 points tolerance plt.show() if __name__ == "__main__": args = sys.argv[1:] arguments = docopt(__doc__, argv=args, version="Spec 0.1") main(arguments) PK!owwpeakipy/core.py""" peakipy - deconvolute overlapping NMR peaks Copyright (C) 2019 Jacob Peter Brady This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import sys from datetime import datetime from pathlib import Path import numpy as np import nmrglue as ng import matplotlib.pyplot as plt import pandas as pd from numpy import sqrt, log, pi, exp from lmfit import Model from lmfit.model import ModelResult from lmfit.models import LinearModel from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D from matplotlib.widgets import Button # constants log2 = log(2) π = pi def gaussian(x, center=0.0, sigma=1.0): """ 1-dimensional Gaussian function. gaussian(x, center, sigma) = (1/(s2pi*sigma)) * exp(-(1.0*x-center)**2 / (2*sigma**2)) :math:`\\frac{1}{ \sqrt{2\pi} } exp \left( \\frac{-(x-center)^2}{2 \sigma^2} \\right)` :param x: x :param center: center :param sigma: sigma :type x: numpy.array :type center: float :type sigma: float :return: 1-dimensional Gaussian :rtype: numpy.array """ return (1.0 / (sqrt(2 * π) * sigma)) * exp( -(1.0 * x - center) ** 2 / (2 * sigma ** 2) ) def lorentzian(x, center=0.0, sigma=1.0): """ 1-dimensional Lorentzian function. lorentzian(x, center, sigma) = (1/(1 + ((1.0*x-center)/sigma)**2)) / (pi*sigma) :math:`\\frac{1}{ 1+ \left( \\frac{x-center}{\sigma}\\right)^2} / (\pi\sigma)` :param x: x :param center: center :param sigma: sigma :type x: numpy.array :type center: float :type sigma: float :return: 1-dimensional Lorenztian :rtype: numpy.array """ return (1.0 / (1 + ((1.0 * x - center) / sigma) ** 2)) / (π * sigma) def pseudo_voigt(x, center=0.0, sigma=1.0, fraction=0.5): """ 1-dimensional Pseudo-voigt function Superposition of Gaussian and Lorentzian function :math:`(1-\phi) G(x,center,\sigma_g) + \phi L(x, center, \sigma)` Where :math:`\phi` is the fraction of Lorentzian lineshape and :math:`G` and :math:`L` are Gaussian and Lorentzian functions, respectively. :param x: data :type x: numpy.array :param center: center of peak :type center: float :param sigma: sigma of lineshape :type sigma: float :param fraction: fraction of lorentzian lineshape (between 0 and 1) :type fraction: float :return: pseudo-voigt function :rtype: numpy.array """ sigma_g = sigma / sqrt(2 * log2) pv = (1 - fraction) * gaussian(x, center, sigma_g) + fraction * lorentzian( x, center, sigma ) return pv def pvoigt2d( XY, amplitude=1.0, center_x=0.5, center_y=0.5, sigma_x=1.0, sigma_y=1.0, fraction=0.5, ): """ 2D pseudo-voigt model :math:`(1-fraction) G(x,center,\sigma_{gx}) + (fraction) L(x, center, \sigma_x) * (1-fraction) G(y,center,\sigma_{gy}) + (fraction) L(y, center, \sigma_y)` :param XY: meshgrid of X and Y coordinates [X,Y] each with shape Z :type XY: numpy.array :param center_x: center of peak in x :type center_x: float :param center_y: center of peak in x :type center_y: float :param sigma_x: sigma of lineshape in x :type sigma_x: float :param sigma_y: sigma of lineshape in y :type sigma_y: float :param fraction: fraction of lorentzian lineshape (between 0 and 1) :type fraction: float :return: flattened array of Z values (use Z.reshape(X.shape) for recovery) :rtype: numpy.array """ x, y = XY # sigma_gx = sigma_x / sqrt(2 * log2) # sigma_gy = sigma_y / sqrt(2 * log2) # fraction same for both dimensions # super position of gaussian and lorentzian # then convoluted for x y # pv_x = (1 - fraction) * gaussian(x, center_x, sigma_gx) + fraction * lorentzian( # x, center_x, sigma_x # ) pv_x = pseudo_voigt(x, center_x, sigma_x, fraction) pv_y = pseudo_voigt(y, center_y, sigma_y, fraction) # pv_y = (1 - fraction) * gaussian(y, center_y, sigma_gy) + fraction * lorentzian( # y, center_y, sigma_y # ) return amplitude * pv_x * pv_y def pv_l( XY, amplitude=1.0, center_x=0.5, center_y=0.5, sigma_x=1.0, sigma_y=1.0, fraction=0.5, ): """ 2D lineshape model with pseudo-voigt in x and lorentzian in y Arguments ========= -- XY: meshgrid of X and Y coordinates [X,Y] each with shape Z -- amplitude: peak amplitude (gaussian and lorentzian) -- center_x: position of peak in x -- center_y: position of peak in y -- sigma_x: linewidth in x -- sigma_y: linewidth in y -- fraction: fraction of lorentzian in fit Returns ======= -- flattened array of Z values (use Z.reshape(X.shape) for recovery) """ x, y = XY pv_x = pseudo_voigt(x, center_x, sigma_x, fraction) pv_y = pseudo_voigt(y, center_y, sigma_y, 1.0) # lorentzian return amplitude * pv_x * pv_y def pv_g( XY, amplitude=1.0, center_x=0.5, center_y=0.5, sigma_x=1.0, sigma_y=1.0, fraction=0.5, ): """ 2D lineshape model with pseudo-voigt in x and gaussian in y Arguments --------- -- XY: meshgrid of X and Y coordinates [X,Y] each with shape Z -- amplitude: peak amplitude (gaussian and lorentzian) -- center_x: position of peak in x -- center_y: position of peak in y -- sigma_x: linewidth in x -- sigma_y: linewidth in y -- fraction: fraction of lorentzian in fit Returns ------- -- flattened array of Z values (use Z.reshape(X.shape) for recovery) """ x, y = XY pv_x = pseudo_voigt(x, center_x, sigma_x, fraction) pv_y = pseudo_voigt(y, center_y, sigma_y, 0.0) # gaussian return amplitude * pv_x * pv_y def pv_pv( XY, amplitude=1.0, center_x=0.5, center_y=0.5, sigma_x=1.0, sigma_y=1.0, fraction_x=0.5, fraction_y=0.5, ): """ 2D lineshape model with pseudo-voigt in x and pseudo-voigt in y i.e. fraction_x and fraction_y params Arguments ========= -- XY: meshgrid of X and Y coordinates [X,Y] each with shape Z -- amplitude: peak amplitude (gaussian and lorentzian) -- center_x: position of peak in x -- center_y: position of peak in y -- sigma_x: linewidth in x -- sigma_y: linewidth in y -- fraction_x: fraction of lorentzian in x -- fraction_y: fraction of lorentzian in y Returns ======= -- flattened array of Z values (use Z.reshape(X.shape) for recovery) """ x, y = XY pv_x = pseudo_voigt(x, center_x, sigma_x, fraction_x) pv_y = pseudo_voigt(y, center_y, sigma_y, fraction_y) return amplitude * pv_x * pv_y def gaussian_lorentzian( XY, amplitude=1.0, center_x=0.5, center_y=0.5, sigma_x=1.0, sigma_y=1.0, fraction=0.5, ): """ 2D lineshape model with gaussian in x and lorentzian in y Arguments ========= -- XY: meshgrid of X and Y coordinates [X,Y] each with shape Z -- amplitude: peak amplitude (gaussian and lorentzian) -- center_x: position of peak in x -- center_y: position of peak in y -- sigma_x: linewidth in x -- sigma_y: linewidth in y -- fraction: fraction of lorentzian in fit Returns ======= -- flattened array of Z values (use Z.reshape(X.shape) for recovery) """ x, y = XY pv_x = pseudo_voigt(x, center_x, sigma_x, 0.0) # gaussian pv_y = pseudo_voigt(y, center_y, sigma_y, 1.0) # lorentzian return amplitude * pv_x * pv_y def make_mask(data, c_x, c_y, r_x, r_y): """ Create and elliptical mask Generate an elliptical boolean mask with center c_x/c_y in points with radii r_x and r_y. Used to generate fit mask :param data: 2D array :type data: np.array :param c_x: x center :type c_x: float :param c_y: y center :type c_y: float :param r_x: radius in x :type r_x: float :param r_y: radius in y :type r_y: float :return: boolean mask of data.shape :rtype: numpy.array """ a, b = c_y, c_x n_y, n_x = data.shape y, x = np.ogrid[-a : n_y - a, -b : n_x - b] mask = x ** 2.0 / r_x ** 2.0 + y ** 2.0 / r_y ** 2.0 <= 1.0 return mask def rmsd(residuals): return np.sqrt(np.sum(residuals ** 2.0) / len(residuals)) def fix_params(params, to_fix): """ Set parameters to fix :param params: lmfit parameters :type params: lmfit.Parameters :param to_fix: list of parameter name to fix :type to_fix: list :return: updated parameter object :rtype: lmfit.Parameters """ for k in params: for p in to_fix: if p in k: params[k].vary = False return params def get_params(params, name): ps = [] ps_err = [] names = [] for k in params: if name in k: ps.append(params[k].value) ps_err.append(params[k].stderr) names.append(k) return ps, ps_err, names def make_param_dict(peaks, data, lineshape="PV"): """ Make dict of parameter names using prefix """ param_dict = {} for index, peak in peaks.iterrows(): str_form = lambda x: "%s%s" % (to_prefix(peak.ASS), x) # using exact value of points (i.e decimal) param_dict[str_form("center_x")] = peak.X_AXISf param_dict[str_form("center_y")] = peak.Y_AXISf #  linewidth esimate param_dict[str_form("sigma_x")] = peak.XW / 2.0 param_dict[str_form("sigma_y")] = peak.YW / 2.0 # estimate peak volume amplitude_est = data[ int(peak.Y_AXIS) - int(peak.YW) : int(peak.Y_AXIS) + int(peak.YW) + 1, int(peak.X_AXIS) - int(peak.XW) : int(peak.X_AXIS) + int(peak.XW) + 1, ].sum() param_dict[str_form("amplitude")] = amplitude_est if lineshape == "G": param_dict[str_form("fraction")] = 0.0 elif lineshape == "L": param_dict[str_form("fraction")] = 1.0 elif lineshape == "PV_PV": param_dict[str_form("fraction_x")] = 0.5 param_dict[str_form("fraction_y")] = 0.5 else: param_dict[str_form("fraction")] = 0.5 return param_dict def to_prefix(x): """ Peak assignments with characters that are not compatible lmfit model naming are converted to lmfit "safe" names. :param x: Peak assignment to be used as prefix for lmfit model :type x: str :returns: lmfit model prefix (_Peak_assignment_) :rtype: str """ # must be string if type(x) != str: x = str(x) prefix = "_" + x to_replace = [ [".", "_"], [" ", ""], ["{", "_"], ["}", "_"], ["[", "_"], ["]", "_"], ["-", ""], ["/", "or"], ["?", "maybe"], ["\\", ""], ["(", "_"], [")", "_"], ] for p in to_replace: prefix = prefix.replace(*p) return prefix + "_" def make_models(model, peaks, data, lineshape="PV", xy_bounds=None): """ Make composite models for multiple peaks :param model: lineshape function :type model: function :param peaks: instance of pandas.df.groupby("CLUSTID") :type peaks: pandas.df.groupby("CLUSTID") :param data: NMR data :type data: numpy.array :param lineshape: lineshape to use for fit (PV/G/L/PV_PV) :type lineshape: str :param xy_bounds: bounds for peak centers (+/-x, +/-y) :type xy_bounds: tuple :return mod: Composite lmfit model containing all peaks :rtype mod: lmfit.CompositeModel :return p_guess: params for composite model with starting values :rtype p_guess: lmfit.Parameters """ if len(peaks) == 1: # make model for first peak mod = Model(model, prefix="%s" % to_prefix(peaks.ASS.iloc[0])) # add parameters param_dict = make_param_dict(peaks, data, lineshape=lineshape) p_guess = mod.make_params(**param_dict) elif len(peaks) > 1: # make model for first peak first_peak, *remaining_peaks = peaks.iterrows() mod = Model(model, prefix="%s" % to_prefix(first_peak[1].ASS)) for index, peak in remaining_peaks: mod += Model(model, prefix="%s" % to_prefix(peak.ASS)) param_dict = make_param_dict(peaks, data, lineshape=lineshape) p_guess = mod.make_params(**param_dict) # add Peak params to p_guess update_params(p_guess, param_dict, lineshape=lineshape, xy_bounds=xy_bounds) return mod, p_guess def update_params(params, param_dict, lineshape="PV", xy_bounds=None): """ Update lmfit parameters with values from Peak :param params: lmfit parameters :type params: lmfit.Parameters object :param param_dict: parameters corresponding to each peak in fit :type param_dict: dict :param lineshape: lineshape (PV, G, L, PV_PV etc.) :type lineshape: str :param xy_bounds: bounds on xy peak positions :type xy_bounds: tuple :returns: None :rtype: None ToDo: -- deal with boundaries -- currently positions in points """ for k, v in param_dict.items(): params[k].value = v # print("update", k, v) if "center" in k: if xy_bounds == None: # no bounds set pass else: if "center_x" in k: # set x bounds x_bound = xy_bounds[0] params[k].min = v - x_bound params[k].max = v + x_bound elif "center_y" in k: # set y bounds y_bound = xy_bounds[1] params[k].min = v - y_bound params[k].max = v + y_bound # pass print( "setting limit of %s, min = %.3e, max = %.3e" % (k, params[k].min, params[k].max) ) elif "sigma" in k: params[k].min = 0.0 params[k].max = 1e4 # print( # "setting limit of %s, min = %.3e, max = %.3e" # % (k, params[k].min, params[k].max) # ) elif "fraction" in k: # fix weighting between 0 and 1 params[k].min = 0.0 params[k].max = 1.0 if lineshape == "G": params[k].vary = False elif lineshape == "L": params[k].vary = False # return params def run_log(log_name="run_log.txt"): """ Write log file containing time script was run and with which arguments""" with open(log_name, "a") as log: sys_argv = sys.argv sys_argv[0] = Path(sys_argv[0]).name run_args = " ".join(sys_argv) time_stamp = datetime.now() time_stamp = time_stamp.strftime("%A %d %B %Y at %H:%M") log.write(f"# Script run on {time_stamp}:\n{run_args}\n") def fit_first_plane( group, data, uc_dics, lineshape="PV", xy_bounds=None, verbose=False, log=None, noise=1.0, ): """ Deconvolute group of peaks :param group: pandas data from containing group of peaks using groupby("CLUSTID") :type group: pandas.core.groupby.generic.DataFrameGroupBy :param data: NMR data :type data: numpy.array :param uc_dics: nmrglue unit conversion dics {"f1":uc_f1,"f2":uc_f2} :type uc_dics: dict :param lineshape: lineshape to fit (PV, G, L, G_L, PV_L, PV_G or PV_PV) :type lineshape: str :param xy_bounds: set bounds on x y positions. None or (x_bound, y_bound) :type xy_bounds: tuple :param plot: dir to save wireframe plots :type plot: str :param show: interactive matplotlib plot :type show: bool :param verbose: print what is happening to terminal :type verbose: bool :param log: file :type log: str :param noise: estimate of spectral noise for calculation of :math:`\chi^2` and :math:`\chi^2_{red}` :type noise: float :return: FitResult :rtype: FitResult """ shape = data.shape mask = np.zeros(shape, dtype=bool) if (lineshape == "PV") or (lineshape == "G") or (lineshape == "L"): mod, p_guess = make_models( pvoigt2d, group, data, lineshape=lineshape, xy_bounds=xy_bounds ) elif lineshape == "G_L": mod, p_guess = make_models( gaussian_lorentzian, group, data, lineshape="PV", xy_bounds=xy_bounds ) elif lineshape == "PV_G": mod, p_guess = make_models( pv_g, group, data, lineshape="PV", xy_bounds=xy_bounds ) elif lineshape == "PV_L": mod, p_guess = make_models( pv_l, group, data, lineshape="PV", xy_bounds=xy_bounds ) elif lineshape == "PV_PV": mod, p_guess = make_models( pv_pv, group, data, lineshape="PV_PV", xy_bounds=xy_bounds ) # get initial peak centers cen_x = [p_guess[k].value for k in p_guess if "center_x" in k] cen_y = [p_guess[k].value for k in p_guess if "center_y" in k] for index, peak in group.iterrows(): mask += make_mask( data, peak.X_AXISf, peak.Y_AXISf, peak.X_RADIUS, peak.Y_RADIUS ) x_radius = group.X_RADIUS.max() y_radius = group.Y_RADIUS.max() max_x, min_x = ( int(np.ceil(max(group.X_AXISf) + x_radius + 1)), int(np.floor(min(group.X_AXISf) - x_radius)), ) max_y, min_y = ( int(np.ceil(max(group.Y_AXISf) + y_radius + 1)), int(np.floor(min(group.Y_AXISf) - y_radius)), ) #  deal with peaks on the edge of spectrum if min_y < 0: min_y = 0 if min_x < 0: min_x = 0 if max_y > shape[-2]: max_y = shape[-2] if max_x > shape[-1]: max_x = shape[-1] peak_slices = data.copy()[mask] # must be a better way to make the meshgrid x = np.arange(shape[-1]) y = np.arange(shape[-2]) XY = np.meshgrid(x, y) X, Y = XY XY_slices = [X.copy()[mask], Y.copy()[mask]] weights = 1.0 / np.array([noise] * len(np.ravel(peak_slices))) out = mod.fit(peak_slices, XY=XY_slices, params=p_guess, weights=weights) if verbose: print(out.fit_report()) z_sim = mod.eval(XY=XY, params=out.params) z_sim[~mask] = np.nan z_plot = data.copy() z_plot[~mask] = np.nan #  also if peak position changed significantly from start then add warning _z_plot = z_plot[~np.isnan(z_plot)] _z_sim = z_sim[~np.isnan(z_sim)] linmod = LinearModel() linpars = linmod.guess(_z_sim, x=_z_plot) linfit = linmod.fit(_z_sim, x=_z_plot, params=linpars) slope = linfit.params["slope"].value #  number of peaks in cluster n_peaks = len(group) chi2 = out.chisqr redchi = out.redchi fit_str = f""" Cluster {peak.CLUSTID} containing {n_peaks} peaks - slope={slope:.3f} chi^2 = {chi2:.5f} redchi = {redchi:.5f} """ if (slope > 1.05) or (slope < 0.95): fit_str += """ 🧐 NEEDS CHECKING 🧐 """ print(fit_str) else: print(fit_str) if log != None: log.write("".join("#" for _ in range(60)) + "\n\n") log.write(fit_str + "\n\n") # pass else: pass return FitResult( out=out, mask=mask, fit_str=fit_str, log=log, group=group, uc_dics=uc_dics, min_x=min_x, min_y=min_y, max_x=max_x, max_y=max_y, X=X, Y=Y, Z=z_plot, Z_sim=z_sim, ) class FitResult: """ Data structure for storing fit results """ def __init__( self, out: ModelResult, mask: np.array, fit_str: str, log: str, group: pd.core.groupby.generic.DataFrameGroupBy, uc_dics: dict, min_x: float, min_y: float, max_x: float, max_y: float, X: np.array, Y: np.array, Z: np.array, Z_sim: np.array, ): """ Store output of fit_first_plane function """ self.out = out self.mask = mask self.fit_str = fit_str self.log = log self.group = group self.uc_dics = uc_dics self.min_x = min_x self.min_y = min_y self.max_x = max_x self.max_y = max_y self.X = X self.Y = Y self.Z = Z self.Z_sim = Z_sim def check_shifts(self): """ Calculate difference between initial peak positions and check whether they moved too much from original position """ pass def jackknife(self): """ perform jackknife sampling to estimate fitting errors """ pass def plot(self, plot_path=None, show=False, nomp=True): """ Matplotlib interactive plot of the fits """ if plot_path != None: plot_path = Path(plot_path) plot_path.mkdir(parents=True, exist_ok=True) # plotting fig = plt.figure() ax = fig.add_subplot(111, projection="3d") # slice out plot area x_plot = self.uc_dics["f2"].ppm( self.X[self.min_y : self.max_y, self.min_x : self.max_x] ) y_plot = self.uc_dics["f1"].ppm( self.Y[self.min_y : self.max_y, self.min_x : self.max_x] ) z_plot = self.Z[self.min_y : self.max_y, self.min_x : self.max_x] z_sim = self.Z_sim[self.min_y : self.max_y, self.min_x : self.max_x] ax.set_title( "$\chi^2$=" + f"{self.out.chisqr:.3f}, " + "$\chi_{red}^2$=" + f"{self.out.redchi:.4f}" ) residual = z_plot - z_sim cset = ax.contourf( x_plot, y_plot, residual, zdir="z", offset=np.nanmin(z_plot) * 1.1, alpha=0.5, cmap=cm.coolwarm, ) fig.colorbar(cset, ax=ax, shrink=0.5, format="%.2e") # plot raw data ax.plot_wireframe(x_plot, y_plot, z_plot, color="#03353E", label="data") ax.set_xlabel("F2 ppm") ax.set_ylabel("F1 ppm") ax.plot_wireframe( x_plot, y_plot, z_sim, color="#C1403D", linestyle="--", label="fit" ) # axes will appear inverted ax.view_init(30,120) # Annotate plots labs = [] Z_lab = [] Y_lab = [] X_lab = [] for k, v in self.out.params.valuesdict().items(): if "amplitude" in k: Z_lab.append(v) # get prefix labs.append(" ".join(k.split("_")[:-1])) elif "center_x" in k: X_lab.append(self.uc_dics["f2"].ppm(v)) elif "center_y" in k: Y_lab.append(self.uc_dics["f1"].ppm(v)) #  this is dumb as !£$@ Z_lab = [ self.Z[ int(round(self.uc_dics["f1"](y, "ppm"))), int(round(self.uc_dics["f2"](x, "ppm"))), ] for x, y in zip(X_lab, Y_lab) ] for l, x, y, z in zip(labs, X_lab, Y_lab, Z_lab): # print(l, x, y, z) ax.text(x, y, z * 1.2, l, None) # plt.colorbar(contf) plt.legend(bbox_to_anchor=(1.2, 1.1)) name = self.group.CLUSTID.iloc[0] if show and nomp: plt.savefig(plot_path / f"{name}.png", dpi=300) def exit_program(event): exit() def next_plot(event): plt.close() axexit = plt.axes([0.81, 0.05, 0.1, 0.075]) bnexit = Button(axexit, "Exit") bnexit.on_clicked(exit_program) axnext = plt.axes([0.71, 0.05, 0.1, 0.075]) bnnext = Button(axnext, "Next") bnnext.on_clicked(next_plot) plt.show() else: print( "Cannot use interactive matplotlib in multiprocess mode. Use --nomp flag." ) plt.savefig(plot_path / f"{name}.png", dpi=300) # print(p_guess) # close plot plt.close() else: pass class Pseudo3D: """Read dic, data from NMRGlue and dims from input to create a Pseudo3D dataset :param dic: from nmrglue.pipe.read :type dic: dict :param data: data from nmrglue.pipe.read :type data: numpy.array :param dims: dimension order i.e [0,1,2] where 0 = planes, 1 = f1, 2 = f2 :type dims: list """ def __init__(self, dic, data, dims): # check dimensions self._udic = ng.pipe.guess_udic(dic, data) self._ndim = self._udic["ndim"] if self._ndim == 1: err = f""" ########################################## NMR Data should be either 2D or 3D ########################################## """ raise TypeError(err) # check that spectrum has correct number of dims elif self._ndim != len(dims): err = f""" ################################################################# Your spectrum has {self._ndim} dimensions with shape {data.shape} but you have given a dimension order of {dims}... ################################################################# """ raise ValueError(err) elif (self._ndim == 2) and (len(dims) == 2): self._f1_dim, self._f2_dim = dims self._planes = 0 self._uc_f1 = ng.pipe.make_uc(dic, data, dim=self._f1_dim) self._uc_f2 = ng.pipe.make_uc(dic, data, dim=self._f2_dim) # make data pseudo3d self._data = data.reshape((1, data.shape[0], data.shape[1])) self._dims = [self._planes, self._f1_dim + 1, self._f2_dim + 1] else: self._planes, self._f1_dim, self._f2_dim = dims self._dims = dims self._data = data # make unit conversion dicts self._uc_f2 = ng.pipe.make_uc(dic, data, dim=self._f2_dim) self._uc_f1 = ng.pipe.make_uc(dic, data, dim=self._f1_dim) #  rearrange data if dims not in standard order if self._dims != [0, 1, 2]: # np.argsort returns indices of array for order 0,1,2 to transpose data correctly # self._dims = np.argsort(self._dims) self._data = np.transpose(data, self._dims) self._dic = dic self._f1_label = self._udic[self._f1_dim]["label"] self._f2_label = self._udic[self._f2_dim]["label"] @property def uc_f1(self): """ Return unit conversion dict for F1""" return self._uc_f1 @property def uc_f2(self): """ Return unit conversion dict for F2""" return self._uc_f2 @property def dims(self): """ Return dimension order """ return self._dims @property def data(self): """ Return array containing data """ return self._data @property def dic(self): return self._dic @property def udic(self): return self._udic @property def ndim(self): return self._ndim @property def f1_label(self): # dim label return self._f1_label @property def f2_label(self): # dim label return self._f2_label # size of f1 and f2 in points @property def f2_size(self): """ Return size of f2 dimension in points """ return self._udic[self._f2_dim]["size"] @property def f1_size(self): """ Return size of f1 dimension in points """ return self._udic[self._f1_dim]["size"] # points per ppm @property def pt_per_ppm_f1(self): return self.f1_size / ( self._udic[self._f1_dim]["sw"] / self._udic[self._f1_dim]["obs"] ) @property def pt_per_ppm_f2(self): return self.f2_size / ( self._udic[self._f2_dim]["sw"] / self._udic[self._f2_dim]["obs"] ) # points per hz @property def pt_per_hz_f1(self): return self.f1_size / self._udic[self._f1_dim]["sw"] @property def pt_per_hz_f2(self): return self.f2_size / self._udic[self._f2_dim]["sw"] # ppm per point @property def ppm_per_pt_f1(self): return 1.0 / self.pt_per_ppm_f1 @property def ppm_per_pt_f2(self): return 1.0 / self.pt_per_ppm_f2 # get ppm limits for ppm scales # uc_f1 = ng.pipe.make_uc(dic, data, dim=f1) # ppm_f1 = uc_f1.ppm_scale() # ppm_f1_0, ppm_f1_1 = uc_f1.ppm_limits() # # uc_f2 = ng.pipe.make_uc(dic, data, dim=f2) # ppm_f2 = uc_f2.ppm_scale() # ppm_f2_0, ppm_f2_1 = uc_f2.ppm_limits() PK!H૗+1)peakipy-0.1.19.dist-info/entry_points.txtN+I/N.,()*HM,z񹉙yV PK!a@2NN peakipy-0.1.19.dist-info/LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . PK!HڽTUpeakipy-0.1.19.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HJl!peakipy-0.1.19.dist-info/METADATAMO0 9ZIW:V VG ]Xӄ$E꿧iLJX9pJd?~ɂ;\+TX)7B7W6 k)4)๪UY;N;7%j-dJPcѪ=dSE+#pZ2)\-əU\(S3ӓ‡!W2o0܆M[Z<>C2@/ڷFXukm+yH]1{!Ŝ'PG=vʕv@4Q `|[j ؐDKJh(kٖնnXҍhVh{(W1.?C VPK!H7@7peakipy-0.1.19.dist-info/RECORD˒H}? X$@I@H$\,;jq[qOf(^Z*g6!+mWxrjEe-d @Nܸw\W3̏?PK!peakipy/__init__.pyPK!1peakipy/__main__.pyPK!5peakipy/commandline/__init__.pyPK!YH-)-)rpeakipy/commandline/check.pyPK!#&$pff*peakipy/commandline/edit.pyPK!dHdH)-peakipy/commandline/edit_fits_app/main.pyPK!]Kyww6peakipy/commandline/edit_fits_app/templates/index.htmlPK!ј?,peakipy/commandline/edit_fits_app/theme.yamlPK!qbVV큼peakipy/commandline/fit.pyPK!p