diff --git a/pycorrfit/PyCorrFit.py b/pycorrfit/PyCorrFit.py index d8985c60..d0bd9c90 100644 --- a/pycorrfit/PyCorrFit.py +++ b/pycorrfit/PyCorrFit.py @@ -1,11 +1,10 @@ +from pycorrfit.gui import main """PyCorrFit loader""" from os.path import dirname, abspath, split import sys sys.path = [split(abspath(dirname(__file__)))[0]] + sys.path -from pycorrfit.gui import main - if __name__ == "__main__": main.Main() diff --git a/pycorrfit/correlation.py b/pycorrfit/correlation.py index 3b54efd8..de582806 100644 --- a/pycorrfit/correlation.py +++ b/pycorrfit/correlation.py @@ -12,6 +12,7 @@ class Correlation(object): """ unifies correlation curve handling """ + def __init__(self, backgrounds=[], correlation=None, corr_type="AC", filename=None, fit_algorithm="Lev-Mar", fit_model=6000, fit_ival=(0, 0), @@ -93,7 +94,7 @@ def __repr__(self): else: c = "CC" text = "{} correlation '{}' with {} traces".format( - c, self.title, len(self._traces)) + c, self.title, len(self._traces)) return text def background_replace(self, channel, background): @@ -144,7 +145,8 @@ def backgrounds(self, value): elif isinstance(v, Trace): backgrounds.append(v) else: - raise ValueError("Each background must be instance of Trace or ndarray") + raise ValueError( + "Each background must be instance of Trace or ndarray") self._backgrounds = backgrounds @property @@ -321,12 +323,13 @@ def fit_model(self, value): else: raise NotImplementedError("Unknown model identifier") - if newmodel != self._fit_model : + if newmodel != self._fit_model: self._fit_model = newmodel # overwrite fitting parameters self._fit_parameters = self._fit_model.default_values self._fit_parameters_variables = self._fit_model.default_variables - self._fit_parameters_range = np.zeros((len(self._fit_parameters), 2)) + self._fit_parameters_range = np.zeros( + (len(self._fit_parameters), 2)) self.normparm = None @property @@ -390,8 +393,8 @@ def fit_parameters_range(self, value): expect_shape = (self.fit_parameters.shape[0], 2) if value.shape != expect_shape: msg = "Expected shape of fit parameters: {} (vs {})".format( - expect_shape, value.shape - ) + expect_shape, value.shape + ) raise ValueError(msg) self._fit_parameters_range = value @@ -399,7 +402,8 @@ def fit_parameters_range(self, value): def fit_parameters_variable(self): """which parameters are variable during fitting""" if self._fit_parameters_variable is None: - self._fit_parameters_variable = np.array(self.fit_model.default_variables, dtype=bool) + self._fit_parameters_variable = np.array( + self.fit_model.default_variables, dtype=bool) return self._fit_parameters_variable @fit_parameters_variable.setter @@ -408,7 +412,7 @@ def fit_parameters_variable(self, value): expect_size = self.fit_parameters.shape[0] if value.shape[0] != expect_size: msg = "Fit parameter variables must have size {}!".format( - expect_size) + expect_size) raise ValueError(msg) self._fit_parameters_variable = value @@ -416,17 +420,18 @@ def fit_parameters_variable(self, value): def lag_time(self): """logarithmic lag time axis""" if self.correlation is not None: - return self._correlation[:,0].copy() + return self._correlation[:, 0].copy() elif self._lag_time is not None: return self._lag_time else: # some default lag time - return 10**np.linspace(-6,8,1001) + return 10**np.linspace(-6, 8, 1001) @lag_time.setter def lag_time(self, value): if self.correlation is not None: - warnings.warn("Setting lag time not possible, because of existing correlation") + warnings.warn( + "Setting lag time not possible, because of existing correlation") else: self._lag_time = value @@ -441,8 +446,8 @@ def modeled(self): # perform parameter normalization lag = self.lag_time modeled = np.zeros((lag.shape[0], 2)) - modeled[:,0] = lag - modeled[:,1] = self.fit_model(self.fit_parameters, lag) + modeled[:, 0] = lag + modeled[:, 1] = self.fit_model(self.fit_parameters, lag) return modeled.copy() @property @@ -455,7 +460,7 @@ def modeled_fit(self): def modeled_plot(self): """fitted data values, same shape as self.correlation_fit""" toplot = self.modeled_fit - toplot[:,1] *= self.normalize_factor + toplot[:, 1] *= self.normalize_factor return toplot @property @@ -479,14 +484,14 @@ def residuals(self): if self.correlation is None: raise ValueError("Cannot compute residuals; No correlation given!") residuals = self.correlation.copy() - residuals[:,1] -= self.modeled[:,1] + residuals[:, 1] -= self.modeled[:, 1] return residuals @property def residuals_fit(self): """fit residuals, same shape as self.correlation_fit""" residuals_fit = self.correlation_fit.copy() - residuals_fit[:,1] -= self.modeled_fit[:,1] + residuals_fit[:, 1] -= self.modeled_fit[:, 1] return residuals_fit @property @@ -495,7 +500,7 @@ def residuals_plot(self): cp = self.correlation_plot if cp is not None: residuals_plot = self.correlation_plot.copy() - residuals_plot[:,1] -= self.modeled_plot[:,1] + residuals_plot[:, 1] -= self.modeled_plot[:, 1] return residuals_plot def set_weights(self, type_name, data): @@ -532,7 +537,8 @@ def traces(self, value): elif isinstance(v, Trace): traces.append(v) else: - raise ValueError("Each trace must be instance of Trace or ndarray") + raise ValueError( + "Each trace must be instance of Trace or ndarray") self._traces = traces if len(self._traces) == 2: diff --git a/pycorrfit/fit.py b/pycorrfit/fit.py index 412d5fee..5286b4e5 100644 --- a/pycorrfit/fit.py +++ b/pycorrfit/fit.py @@ -10,6 +10,7 @@ class Constraint(object): """ Class to translate fit constraints to lmfit syntax. """ + def __init__(self, constraint, fit_bool, fit_bounds, fit_values): """ Parameters @@ -45,7 +46,7 @@ def parameters(self): """ Returns list of dict for each parameter. """ - parms = [ it for it in self.constraint if isinstance(it, int)] + parms = [it for it in self.constraint if isinstance(it, int)] id2 = self.constraint.index(parms[1]) p1 = {"id": parms[0], @@ -56,7 +57,7 @@ def parameters(self): p2 = {"id": parms[1], "bool": self.fit_bool[parms[1]], - "sign": ( +1 if id2==2 else -1), + "sign": (+1 if id2 == 2 else -1), "value": self.fit_values[parms[1]] } @@ -64,7 +65,7 @@ def parameters(self): @property def operator(self): - strval = [ it for it in self.constraint if not isinstance(it, int)] + strval = [it for it in self.constraint if not isinstance(it, int)] return strval[0] @property @@ -153,46 +154,51 @@ def get_lmfit_parameter_kwargs(self): if p1["bool"] and p2["bool"]: if op == "<": - #p1 < (-)p2 + 1.2 - #-> p1 = (-)p2 - d12 + 1.2 - #-> d12 = (-)p2 - p1 + 1.2 - #-> d12 > 0 + # p1 < (-)p2 + 1.2 + # -> p1 = (-)p2 - d12 + 1.2 + # -> d12 = (-)p2 - p1 + 1.2 + # -> d12 > 0 deltaname = "delta_{}_{}".format(p1["id"], p2["id"]) kwdelt = {} kwdelt["name"] = deltaname - kwdelt["value"] = p2["bool"]*self.fit_values[p2["id"]] - self.fit_values[p1["id"]] + kwdelt["value"] = p2["bool"] * \ + self.fit_values[p2["id"]] - self.fit_values[p1["id"]] kwdelt["vary"] = True - kwdelt["min"] = 0 # note: enforces "<=" (not "<") + kwdelt["min"] = 0 # note: enforces "<=" (not "<") kwdelt["max"] = np.inf kwp1 = {} kwp1["name"] = "parm{:04d}".format(p1["id"]) # this condition deals with negative numbers kwp1["expr"] = "{MIN} if {COMP} < {MIN} else {MAX} if {COMP} > {MAX} else {COMP}".format( - COMP="{}*parm{:04d}-{}+{:.14f}".format(p2["sign"], p2["id"], deltaname, ofs), - MIN=self.fit_bounds[p1["id"]][0], - MAX=self.fit_bounds[p1["id"]][1]) + COMP="{}*parm{:04d}-{}+{:.14f}".format( + p2["sign"], p2["id"], deltaname, ofs), + MIN=self.fit_bounds[p1["id"]][0], + MAX=self.fit_bounds[p1["id"]][1]) kwargs = [kwdelt, kwp1] elif op == ">": - #p1 > (-)p2 + 1.2 - #-> p1 = (-)p2 + d12 + 1.2 - #-> d12 = p1 - (-)p2 - 1.2 - #-> d12 > 0 + # p1 > (-)p2 + 1.2 + # -> p1 = (-)p2 + d12 + 1.2 + # -> d12 = p1 - (-)p2 - 1.2 + # -> d12 > 0 deltaname = "delta_{}_{}".format(p1["id"], p2["id"]) kwdelt = {} kwdelt["name"] = deltaname - kwdelt["value"] = self.fit_values[p1["id"]] - p2["bool"]*self.fit_values[p2["id"]] + kwdelt["value"] = self.fit_values[p1["id"]] - \ + p2["bool"]*self.fit_values[p2["id"]] kwdelt["vary"] = True - kwdelt["min"] = 0 # note: enforces ">=" (not ">") - kwdelt["max"] = np.inf #self.fit_bounds[p1["id"]][1] + max(-p2["sign"]*self.fit_bounds[p2["id"]]) - ofs + kwdelt["min"] = 0 # note: enforces ">=" (not ">") + # self.fit_bounds[p1["id"]][1] + max(-p2["sign"]*self.fit_bounds[p2["id"]]) - ofs + kwdelt["max"] = np.inf kwp1 = {} kwp1["name"] = "parm{:04d}".format(p1["id"]) # this condition deals with negative numbers kwp1["expr"] = "{MIN} if {COMP} < {MIN} else {MAX} if {COMP} > {MAX} else {COMP}".format( - COMP="{}*parm{:04d}+{}+{:.14f}".format(p2["sign"], p2["id"], deltaname, ofs), - MIN=self.fit_bounds[p1["id"]][0], - MAX=self.fit_bounds[p1["id"]][1]) + COMP="{}*parm{:04d}+{}+{:.14f}".format( + p2["sign"], p2["id"], deltaname, ofs), + MIN=self.fit_bounds[p1["id"]][0], + MAX=self.fit_bounds[p1["id"]][1]) kwargs = [kwdelt, kwp1] @@ -202,10 +208,10 @@ def get_lmfit_parameter_kwargs(self): return kwargs - class Fit(object): """ Used for fitting FCS data to models. """ + def __init__(self, correlations=[], global_fit=False, global_fit_variables=[], uselatex=False, verbose=0): @@ -250,16 +256,16 @@ def __init__(self, correlations=[], global_fit=False, # Set fitting options self.fit_algorithm = corr.fit_algorithm # Get the data required for fitting - self.x = corr.correlation_fit[:,0] - self.y = corr.correlation_fit[:,1] + self.x = corr.correlation_fit[:, 0] + self.y = corr.correlation_fit[:, 1] # fit_bool: True for variable self.fit_bool = corr.fit_parameters_variable.copy() self.fit_parm = corr.fit_parameters.copy() self.fit_bound = copy.copy(corr.fit_parameters_range) self.is_weighted_fit = corr.is_weighted_fit self.fit_weights = Fit.compute_weights(corr, - verbose=verbose, - uselatex=uselatex) + verbose=verbose, + uselatex=uselatex) self.fit_parm_names = corr.fit_model.parameters[0] self.func = corr.fit_model.function self.check_parms = corr.check_parms @@ -290,8 +296,8 @@ def __init__(self, correlations=[], global_fit=False, varbound = [] # list of fitting boundaries self.is_weighted_fit = None for corr in self.correlations: - xtemp.append(corr.correlation_fit[:,0]) - ytemp.append(corr.correlation_fit[:,1]) + xtemp.append(corr.correlation_fit[:, 0]) + ytemp.append(corr.correlation_fit[:, 1]) weights.append(Fit.compute_weights(corr)) ids.append(len(xtemp[-1])+ids[-1]) cmodels.append(corr.fit_model) @@ -320,12 +326,12 @@ def __init__(self, correlations=[], global_fit=False, self.fit_parm_names = varin self.fit_bound = varbound self.constraints = [] - warnings.warn("Constraints are not supported yet for global fitting.") - + warnings.warn( + "Constraints are not supported yet for global fitting.") def parameters_global_to_local(parameters, iicorr, varin=varin, - initpar=initpar, - correlations=correlations): + initpar=initpar, + correlations=correlations): """ With global `parameters` and an id `iicorr` pointing at the correlation in `self.correlations`, return the @@ -337,7 +343,8 @@ def parameters_global_to_local(parameters, iicorr, varin=varin, for kk, pn in enumerate(mod.parameters[0]): if pn in varin: # edit that parameter - fit_parm[kk] = parameters[np.where(np.array(varin)==pn)[0]] + fit_parm[kk] = parameters[np.where( + np.array(varin) == pn)[0]] return fit_parm def parameters_local_to_global(parameters, iicorr, fit_parm, @@ -351,7 +358,8 @@ def parameters_local_to_global(parameters, iicorr, fit_parm, for kk, pn in enumerate(mod.parameters[0]): if pn in varin: # edit that parameter - parameters[np.where(np.array(varin)==pn)[0]] = fit_parm[kk] + parameters[np.where(np.array(varin) == pn)[ + 0]] = fit_parm[kk] return parameters # Create function for fitting using ids @@ -394,7 +402,6 @@ def global_check_parms(parameters, # save fit data in correlation class corr.fit_results = self.get_fit_results(corr) - def get_fit_results(self, correlation): """ Return a dictionary with all information about the performed fit. @@ -403,14 +410,14 @@ def get_fit_results(self, correlation): """ c = correlation d = { - "chi2" : self.chi_squared, - "chi2 type" : self.chi_squared_type, - "weighted fit" : c.is_weighted_fit, - "fit algorithm" : c.fit_algorithm, - "fit result" : 1*c.fit_parameters, - "fit parameters" : 1*np.where(c.fit_parameters_variable)[0], - "fit weights" : 1*self.compute_weights(c) - } + "chi2": self.chi_squared, + "chi2 type": self.chi_squared_type, + "weighted fit": c.is_weighted_fit, + "fit algorithm": c.fit_algorithm, + "fit result": 1*c.fit_parameters, + "fit parameters": 1*np.where(c.fit_parameters_variable)[0], + "fit weights": 1*self.compute_weights(c) + } if c.is_weighted_fit: d["weighted fit type"] = c.fit_weight_type @@ -422,7 +429,6 @@ def get_fit_results(self, correlation): return d - @property def chi_squared(self): """ Calculate displayed ChiĀ² @@ -445,12 +451,11 @@ def chi_squared(self): variance = self.fit_weights**2 chi2 = np.sum((self.y-fitted)**2/variance) / dof else: - chi2 = self.fit_function_scalar(self.fit_parm, self.x, self.y, self.fit_weights) - + chi2 = self.fit_function_scalar( + self.fit_parm, self.x, self.y, self.fit_weights) return chi2 - @property def chi_squared_type(self): """ The type of ChiĀ² that currently applies. @@ -470,7 +475,6 @@ def chi_squared_type(self): else: raise ValueError("Unknown weight type!") - @staticmethod def compute_weights(correlation, verbose=0, uselatex=False): """ computes and returns weights of the same length as @@ -492,9 +496,9 @@ def compute_weights(correlation, verbose=0, uselatex=False): if cdat is None: raise ValueError("Cannot compute weights; No correlation given!") cdatfit = corr.correlation_fit - x_full = cdat[:,0] - y_full = cdat[:,1] - x_fit = cdatfit[:,0] + x_full = cdat[:, 0] + y_full = cdat[:, 1] + x_fit = cdatfit[:, 0] #y_fit = cdatfit[:,1] dataweights = np.ones_like(x_fit) @@ -503,7 +507,8 @@ def compute_weights(correlation, verbose=0, uselatex=False): weight_spread = int(weight_data) except: if verbose > 1: - warnings.warn("Could not get weight spread for spline. Setting it to 3.") + warnings.warn( + "Could not get weight spread for spline. Setting it to 3.") weight_spread = 3 if weight_type[:6] == "spline": @@ -541,13 +546,13 @@ def compute_weights(correlation, verbose=0, uselatex=False): ys = spintp.splev(xs, tck, der=0) except: if verbose > 0: - raise ValueError("Could not find spline fit with "+\ + raise ValueError("Could not find spline fit with " + "{} knots.".format(knotnumber)) return if verbose > 0: - ## If plotting module is available: + # If plotting module is available: #name = "spline fit: "+str(knotnumber)+" knots" - #plotting.savePlotSingle(name, 1*x, 1*y, 1*ys, + # plotting.savePlotSingle(name, 1*x, 1*y, 1*ys, # dirname=".", # uselatex=uselatex) # use matplotlib.pylab @@ -560,7 +565,7 @@ def compute_weights(correlation, verbose=0, uselatex=False): # Tell the user to install matplotlib print("Couldn't import pylab! - not Plotting") - ## Calculation of variance + # Calculation of variance # In some cases, the actual cropping interval from ival[0] # to ival[1] is chosen, such that the dataweights must be # calculated from unknown datapoints. @@ -571,7 +576,7 @@ def compute_weights(correlation, verbose=0, uselatex=False): # Define start and end positions of the sections from # where we wish to calculate the dataweights. # Offset at beginning: - if i + ival[0] < weight_spread: + if i + ival[0] < weight_spread: # The offset that occurs offsetstart = weight_spread - i - ival[0] offsetcrop = 0 @@ -596,7 +601,7 @@ def compute_weights(correlation, verbose=0, uselatex=False): dataweights[i] *= reference/dividor # Do not substitute len(y[start:end]) with end-start! # It is not the same! - backset = 2*weight_spread + 1 - len(y[start:end]) - offsetstart + backset = 2*weight_spread + 1 - len(y[start:end]) - offsetstart if backset != 0: reference = 2*weight_spread + 1 dividor = reference - backset @@ -607,7 +612,7 @@ def compute_weights(correlation, verbose=0, uselatex=False): pmin = ival[0] else: pmin = weight_spread - if x_full.shape[0] - ival[1] < weight_spread: + if x_full.shape[0] - ival[1] < weight_spread: pmax = x_full.shape[0] - ival[1] else: pmax = weight_spread @@ -618,7 +623,7 @@ def compute_weights(correlation, verbose=0, uselatex=False): # Define start and end positions of the sections from # where we wish to calculate the dataweights. # Offset at beginning: - if i + ival[0] < weight_spread: + if i + ival[0] < weight_spread: # The offset that occurs offsetstart = weight_spread - i - ival[0] offsetcrop = 0 @@ -646,7 +651,8 @@ def compute_weights(correlation, verbose=0, uselatex=False): dataweights[i] *= reference/dividor # Do not substitute len(diff[start:end]) with end-start! # It is not the same! - backset = 2*weight_spread + 1 - len(diff[start:end]) - offsetstart + backset = 2*weight_spread + 1 - \ + len(diff[start:end]) - offsetstart if backset != 0: reference = 2*weight_spread + 1 dividor = reference - backset @@ -673,7 +679,6 @@ def compute_weights(correlation, verbose=0, uselatex=False): return dataweights - def fit_function(self, params, x, y, weights=1): """ objective function that returns the residual (difference between @@ -684,9 +689,9 @@ def fit_function(self, params, x, y, weights=1): # Check dataweights for zeros and don't use these # values for the least squares method. with np.errstate(divide='ignore'): - tominimize = np.where(weights!=0, + tominimize = np.where(weights != 0, tominimize/weights, 0) - ## There might be NaN values because of zero weights: + # There might be NaN values because of zero weights: #tominimize = tominimize[~np.isinf(tominimize)] return tominimize @@ -716,14 +721,14 @@ def get_lmfitparm(self): for pp in range(len(self.fit_parm)): if not self.fit_bool[pp]: if self.fit_bound[pp][0] == self.fit_bound[pp][1]: - self.fit_bound[pp]=[-np.inf, np.inf] + self.fit_bound[pp] = [-np.inf, np.inf] params.add(lmfit.Parameter(name="parm{:04d}".format(pp), value=self.fit_parm[pp], vary=self.fit_bool[pp], min=self.fit_bound[pp][0], max=self.fit_bound[pp][1], - ) ) + ) # Second, summarize the constraints in a dictionary, where # keys are the parameter indexes of varied parameters. @@ -743,7 +748,7 @@ def get_lmfitparm(self): # [1, 0, "<", "2.3"]] -> parm1 + parm0 < 2.3 for pp in range(len(self.fit_parm)): if self.fit_bool[pp]: - inconstr = len([ cc for cc in self.constraints if pp in cc]) + inconstr = len([cc for cc in self.constraints if pp in cc]) kwarglist = [] if inconstr: @@ -760,10 +765,10 @@ def get_lmfitparm(self): if len(kwarglist) == 0: # normal parameter kwarglist += [{"name": "parm{:04d}".format(pp), - "value": self.fit_parm[pp], - "vary": True, - "min": self.fit_bound[pp][0], - "max": self.fit_bound[pp][1], + "value": self.fit_parm[pp], + "vary": True, + "min": self.fit_bound[pp][0], + "max": self.fit_bound[pp][1], }] for kw in kwarglist: params.add(lmfit.Parameter(**kw)) @@ -833,9 +838,9 @@ def minimize(self): result = lmfit.minimize(fcn=self.fit_function, params=params, method=method, - kws={"x":self.x, - "y":self.y, - "weights":self.fit_weights}, + kws={"x": self.x, + "y": self.y, + "weights": self.fit_weights}, **methodkwargs ) params = result.params @@ -851,16 +856,16 @@ def minimize(self): # the parameters that are varied during fitting parmsbool = Fit.lmfitparm2array(params, attribute="vary") # The parameters that are stuck - parmstuck = parmsbool * (parmsinit==parmsres) + parmstuck = parmsbool * (parmsinit == parmsres) parmsres[parmstuck] *= multby # write changes self.fit_parm = parmsres params = self.get_lmfitparm() - warnings.warn(u"PyCorrFit detected problems in fitting, "+\ - u"detected a stuck parameter, multiplied "+\ - u"it by {}, and fitted again. ".format(multby)+\ + warnings.warn(u"PyCorrFit detected problems in fitting, " + + u"detected a stuck parameter, multiplied " + + u"it by {}, and fitted again. ".format(multby) + u"The stuck parameters are: {}".format( - np.array(self.fit_parm_names)[parmstuck])) + np.array(self.fit_parm_names)[parmstuck])) elif diff < 1e-8: # Experience tells us this is good enough. break @@ -876,24 +881,23 @@ def minimize(self): # - lmfit <= 0.9.10: result.covar is None # - lmfit >= 0.9.11: result.covar is not set and hasattr(result, "covar") - and result.covar is not None): + and result.covar is not None): # This is the standard way to minimize the data. Therefore, # we are a little bit more verbose. covar = result.covar try: self.parmoptim_error = np.diag(covar) except: - warnings.warn("PyCorrFit Warning: Error estimate not "+\ - "possible, because we could not "+\ - "calculate covariance matrix. Please "+\ - "try reducing the number of fitting "+\ + warnings.warn("PyCorrFit Warning: Error estimate not " + + "possible, because we could not " + + "calculate covariance matrix. Please " + + "try reducing the number of fitting " + "parameters.") self.parmoptim_error = None else: self.parmoptim_error = None - def GetAlgorithmStringList(): """ Get supported fitting algorithms as strings. @@ -920,10 +924,10 @@ def GetAlgorithmStringList(): # the original one is the least squares fit "leastsq" Algorithms["Lev-Mar"] = ["leastsq", "Levenberg-Marquardt", - {"ftol" : 1.49012e-08, - "xtol" : 1.49012e-08, + {"ftol": 1.49012e-08, + "xtol": 1.49012e-08, } - ] + ] # simplex Algorithms["Nelder-Mead"] = ["nelder", diff --git a/pycorrfit/gui/doc.py b/pycorrfit/gui/doc.py index b18ff329..75376fc4 100755 --- a/pycorrfit/gui/doc.py +++ b/pycorrfit/gui/doc.py @@ -90,19 +90,19 @@ def licence(): def SoftwareUsed(): """Return some Information about the software used for this program""" - text = "Python "+sys.version+\ - "\n\nModules:"+\ - "\n - cython "+\ - "\n - lmfit "+lmfit.__version__+\ - "\n - matplotlib "+matplotlib.__version__+\ - "\n - NumPy "+numpy.__version__+\ + text = "Python "+sys.version +\ + "\n\nModules:" +\ + "\n - cython " +\ + "\n - lmfit "+lmfit.__version__ +\ + "\n - matplotlib "+matplotlib.__version__ +\ + "\n - NumPy "+numpy.__version__ +\ "\n - PyYAML "+yaml.__version__ +\ - "\n - SciPy "+scipy.__version__+\ - "\n - simplejson "+simplejson.__version__+\ + "\n - SciPy "+scipy.__version__ +\ + "\n - simplejson "+simplejson.__version__ +\ "\n - sympy "+sympy.__version__ +\ "\n - wxPython "+wx.__version__ # Other software - text += "\n\nOther software:"+\ + text += "\n\nOther software:" +\ "\n - FCS_point_correlator ({})".format(read_pt3_scripts.version) +\ "\n PicoQuant file format for Python by Dominic Waithe" if hasattr(sys, 'frozen'): diff --git a/pycorrfit/gui/edclasses.py b/pycorrfit/gui/edclasses.py index a0129646..57bb503f 100644 --- a/pycorrfit/gui/edclasses.py +++ b/pycorrfit/gui/edclasses.py @@ -7,15 +7,16 @@ import warnings import matplotlib -import wx +import wx # We do catch warnings about performing this before matplotlib.backends stuff -#matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets +# matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets with warnings.catch_warnings(): warnings.simplefilter("ignore") try: - matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs + # Tells matplotlib to use WxWidgets for dialogs + matplotlib.use('WXAgg') except: pass @@ -24,10 +25,10 @@ class ChoicesDialog(wx.Dialog): def __init__(self, parent, dropdownlist, title, text): # parent is main frame self.parent = parent - #super(ChoicesDialog, self).__init__(parent=parent, + # super(ChoicesDialog, self).__init__(parent=parent, # title=title) wx.Dialog.__init__(self, parent, -1, title) - ## Controls + # Controls panel = wx.Panel(self) # text1 textopen = wx.StaticText(panel, label=text) @@ -35,7 +36,7 @@ def __init__(self, parent, dropdownlist, title, text): btnabort = wx.Button(panel, wx.ID_CANCEL) # Dropdown self.dropdown = wx.ComboBox(panel, -1, "", (15, 30), - wx.DefaultSize, dropdownlist, wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, dropdownlist, wx.CB_DROPDOWN | wx.CB_READONLY) self.dropdown.SetSelection(0) # Bindings self.Bind(wx.EVT_BUTTON, self.OnOK, btnok) @@ -50,19 +51,17 @@ def __init__(self, parent, dropdownlist, title, text): topSizer.Add(btnSizer) panel.SetSizer(topSizer) topSizer.Fit(self) - #self.Show(True) + # self.Show(True) self.SetFocus() def OnOK(self, event=None): self.SelcetedID = self.dropdown.GetSelection() self.EndModal(wx.ID_OK) - def OnAbort(self, event=None): self.EndModal(wx.ID_CANCEL) - def save_figure(self, evt=None): """ A substitude function for save in: @@ -70,8 +69,8 @@ def save_figure(self, evt=None): We want to be able to give parameters such as dirname and filename. """ try: - parent=self.canvas.HACK_parent - fig=self.canvas.HACK_fig + parent = self.canvas.HACK_parent + fig = self.canvas.HACK_fig Page = self.canvas.HACK_Page add = self.canvas.HACK_append dirname = parent.dirname @@ -89,8 +88,8 @@ def save_figure(self, evt=None): fieltypestring += formats[key]+"(*."+key+")|*."+key+"|" # remove last | fieltypestring = fieltypestring[:-1] - dlg = wx.FileDialog(parent, "Save figure", dirname, filename, - fieltypestring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) + dlg = wx.FileDialog(parent, "Save figure", dirname, filename, + fieltypestring, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) # png is default dlg.SetFilterIndex(keys.index("png")) # user cannot do anything until he clicks "OK" @@ -104,7 +103,7 @@ def save_figure(self, evt=None): savename = filename try: self.canvas.figure.savefig(savename) - except: # RuntimeError: + except: # RuntimeError: # The file does not seem to be what it seems to be. info = sys.exc_info() errstr = "Could not latex output:\n" @@ -113,8 +112,8 @@ def save_figure(self, evt=None): errstr += str(info[1])+"\n" for tb_item in traceback.format_tb(info[2]): errstr += tb_item - wx.MessageDialog(parent, errstr, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + wx.MessageDialog(parent, errstr, "Error", + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) else: dirname = dlg.GetDirectory() try: @@ -127,37 +126,39 @@ class MyScrolledDialog(wx.Dialog): def __init__(self, parent, overtext, readtext, title): wx.Dialog.__init__(self, parent, title=title) overtext = wx.StaticText(self, label=overtext) - text = wx.TextCtrl(self, -1, readtext, size=(500,400), + text = wx.TextCtrl(self, -1, readtext, size=(500, 400), style=wx.TE_MULTILINE | wx.TE_READONLY) - sizer = wx.BoxSizer(wx.VERTICAL ) + sizer = wx.BoxSizer(wx.VERTICAL) btnsizer = wx.BoxSizer() - btn = wx.Button(self, wx.ID_OK)#, "OK ") + btn = wx.Button(self, wx.ID_OK) # , "OK ") btnsizer.Add(btn, 0, wx.ALL, 5) - btnsizer.Add((5,-1), 0, wx.ALL, 5) - btn = wx.Button(self, wx.ID_CANCEL)#, "Abort ") + btnsizer.Add((5, -1), 0, wx.ALL, 5) + btn = wx.Button(self, wx.ID_CANCEL) # , "Abort ") btnsizer.Add(btn, 0, wx.ALL, 5) - sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5) - sizer.Add(text, 0, wx.EXPAND|wx.ALL, 5) - sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) + sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5) + sizer.Add(text, 0, wx.EXPAND | wx.ALL, 5) + sizer.Add(btnsizer, 0, wx.EXPAND | + wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.SetSizerAndFit(sizer) - - + + class MyOKAbortDialog(wx.Dialog): def __init__(self, parent, text, title): wx.Dialog.__init__(self, parent, title=title) overtext = wx.StaticText(self, label=text) - sizer = wx.BoxSizer(wx.VERTICAL ) + sizer = wx.BoxSizer(wx.VERTICAL) btnsizer = wx.BoxSizer() - btn = wx.Button(self, wx.ID_OK)#, "OK ") + btn = wx.Button(self, wx.ID_OK) # , "OK ") btnsizer.Add(btn, 0, wx.ALL, 5) - btnsizer.Add((5,-1), 0, wx.ALL, 5) - btn = wx.Button(self, wx.ID_CANCEL)#, "Abort ") + btnsizer.Add((5, -1), 0, wx.ALL, 5) + btn = wx.Button(self, wx.ID_CANCEL) # , "Abort ") btnsizer.Add(btn, 0, wx.ALL, 5) - sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5) - sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) + sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5) + sizer.Add(btnsizer, 0, wx.EXPAND | + wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.SetSizerAndFit(sizer) - - + + class MyYesNoAbortDialog(wx.Dialog): def __init__(self, parent, text, title): wx.Dialog.__init__(self, parent, title=title) @@ -167,18 +168,19 @@ def __init__(self, parent, text, title): btn1 = wx.Button(self, wx.ID_YES) #btn1.Bind(wx.EVT_BTN, self.YES) btnsizer.Add(btn1, 0, wx.ALL, 5) - btnsizer.Add((1,-1), 0, wx.ALL, 5) + btnsizer.Add((1, -1), 0, wx.ALL, 5) btn2 = wx.Button(self, wx.ID_NO) btnsizer.Add(btn2, 0, wx.ALL, 5) - btnsizer.Add((1,-1), 0, wx.ALL, 5) + btnsizer.Add((1, -1), 0, wx.ALL, 5) btn3 = wx.Button(self, wx.ID_CANCEL) btnsizer.Add(btn3, 0, wx.ALL, 5) - sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5) - sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) + sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5) + sizer.Add(btnsizer, 0, wx.EXPAND | + wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.SetSizerAndFit(sizer) self.SetFocus() self.Show() - + def YES(self, e): self.EndModal(wx.ID_YES) diff --git a/pycorrfit/gui/frontend.py b/pycorrfit/gui/frontend.py index 5036a508..90ad8dc4 100644 --- a/pycorrfit/gui/frontend.py +++ b/pycorrfit/gui/frontend.py @@ -37,10 +37,11 @@ ######################################################################## class ExceptionDialog(wx.MessageDialog): """""" + def __init__(self, msg): """Constructor""" wx.MessageDialog.__init__(self, None, msg, "Error", - wx.OK|wx.ICON_ERROR) + wx.OK | wx.ICON_ERROR) ######################################################################## @@ -48,17 +49,18 @@ class FlatNotebook(fnb.FlatNotebook): """ Flatnotebook class """ + def __init__(self, parent): """Constructor""" - style = fnb.FNB_SMART_TABS|fnb.FNB_NO_NAV_BUTTONS|\ - fnb.FNB_DROPDOWN_TABS_LIST|fnb.FNB_NODRAG|\ - fnb.FNB_TABS_BORDER_SIMPLE|\ - fnb.FNB_X_ON_TAB|fnb.FNB_NO_X_BUTTON + style = fnb.FNB_SMART_TABS | fnb.FNB_NO_NAV_BUTTONS |\ + fnb.FNB_DROPDOWN_TABS_LIST | fnb.FNB_NODRAG |\ + fnb.FNB_TABS_BORDER_SIMPLE |\ + fnb.FNB_X_ON_TAB | fnb.FNB_NO_X_BUTTON # Bugfix for Mac if platform.system().lower() in ["windows", "linux"]: - style = style|fnb.FNB_HIDE_ON_SINGLE_TAB + style = style | fnb.FNB_HIDE_ON_SINGLE_TAB self.fnb = fnb.FlatNotebook.__init__(self, parent, wx.ID_ANY, - agwStyle=style) + agwStyle=style) class MyApp(wx.App): @@ -68,7 +70,7 @@ def __init__(self, args): # http://anonscm.debian.org/cgit/collab-maint/wx-migration-tools.git/tree/README#n30 self.SetAssertMode(wx.APP_ASSERT_SUPPRESS) - def MacOpenFile(self,filename): + def MacOpenFile(self, filename): """ """ if filename.endswith(".pcfs"): @@ -85,17 +87,18 @@ def MacOpenFile(self,filename): class MyFrame(wx.Frame): def __init__(self, parent, anid, version): sys.excepthook = MyExceptionHook - ## Set initial variables that make sense + # Set initial variables that make sense self.version = version - ## Init of the superClass - super(MyFrame, self).__init__(parent, anid, "PyCorrFit " + self.version) + # Init of the superClass + super(MyFrame, self).__init__( + parent, anid, "PyCorrFit " + self.version) - self.CreateStatusBar() # A Statusbar in the bottom of the window - self.StatusBar.SetStatusText("Find help and updates online:"+ + self.CreateStatusBar() # A Statusbar in the bottom of the window + self.StatusBar.SetStatusText("Find help and updates online:" + " 'Help > Update'") - ## Properties of the Frame - initial_size = (768,700) + # Properties of the Frame + initial_size = (768, 700) self.SetSize(initial_size) self.SetMinSize(initial_size) @@ -108,7 +111,7 @@ def __init__(self, parent, anid, version): self.SessionComment = "This is a session comment. It will be saved" +\ " as the session is saved." - ## Set variables + # Set variables # The model module that can be changed by importing user defined # functions. # These are only for compatibility. @@ -136,7 +139,7 @@ def __init__(self, parent, anid, version): # New as of 0.7.9 self.RangeSelector = None - ## Setting up the menus. + # Setting up the menus. # models, modeldict, modeltypes only for compatibility! # I should use mdls for anything, since it's globally imported # and modified by this program (e.g. adding new function) @@ -147,16 +150,16 @@ def __init__(self, parent, anid, version): self.modelmenudict = dict() self.MakeMenu() - ## Create the Flatnotebook (Tabs Tabs Tabs!) + # Create the Flatnotebook (Tabs Tabs Tabs!) panel = wx.Panel(self) self.panel = panel self.notebook = FlatNotebook(panel) self.notebook.SetRightClickMenu(self.curmenu) - #self.notebook.SetAGWWindowStyleFlag(FNB_X_ON_TAB) + # self.notebook.SetAGWWindowStyleFlag(FNB_X_ON_TAB) sizer = wx.BoxSizer(wx.VERTICAL) - sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5) + sizer.Add(self.notebook, 1, wx.ALL | wx.EXPAND, 5) panel.SetSizer(sizer) self.Layout() @@ -188,7 +191,6 @@ def __init__(self, parent, anid, version): if hasattr(sys, "frozen"): self.OnSupport() - def add_fitting_tab(self, event=None, modelid=None, counter=None, select=False): """ This function creates a new page inside the notebook. @@ -222,14 +224,14 @@ def add_fitting_tab(self, event=None, modelid=None, counter=None, model = mdls.modeldict[modelid][1] # Create New Tab Newtab = page.FittingPanel(self, counter, modelid, active_parms) - #self.Freeze() + # self.Freeze() self.notebook.AddPage(Newtab, counter+model, select=select) if select: # A hack to have the last page displayed in the tab menu: Npag = self.notebook.GetPageCount() self.notebook.SetSelection(Npag-1) - #self.Thaw() + # self.Thaw() self.tabcounter = self.tabcounter + 1 # Enable the "Current" Menu self.EnableToolCurrent(True) @@ -243,7 +245,7 @@ def add_fitting_tab(self, event=None, modelid=None, counter=None, # Find Tool Statistics # Get open tools #toolkeys = self.ToolsOpen.keys() - #for key in toolkeys: + # for key in toolkeys: # tool = self.ToolsOpen[key] # try: # if tool.MyName=="STATISTICS": @@ -253,7 +255,6 @@ def add_fitting_tab(self, event=None, modelid=None, counter=None, # pass return Newtab - def EnableToolCurrent(self, enabled): """ Independent on order of menus, enable or disable tools and current menu. @@ -264,7 +265,6 @@ def EnableToolCurrent(self, enabled): cid = self.menuBar.FindMenu("Current &Page") self.menuBar.EnableTop(cid, enabled) - def MakeMenu(self): self.filemenu = wx.Menu() # toolmenu and curmenu are public, because they need to be enabled/ @@ -279,44 +279,44 @@ def MakeMenu(self): # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets. # self.filemenu menuAddModel = self.filemenu.Append(wx.ID_ANY, - "&Import model", "Add a user defined model.") + "&Import model", "Add a user defined model.") menuLoadBatch = self.filemenu.Append(wx.ID_ANY, - "&Load data\tCtrl+O", "Loads one or multiple data files") + "&Load data\tCtrl+O", "Loads one or multiple data files") menuOpen = self.filemenu.Append(wx.ID_OPEN, "&Open session\tCtrl+Shift+O", - "Restore a previously saved session") + "Restore a previously saved session") self.filemenu.AppendSeparator() self.menuComm = self.filemenu.Append(wx.ID_ANY, "Co&mment session", - "Add a comment to this session", kind=wx.ITEM_CHECK) + "Add a comment to this session", kind=wx.ITEM_CHECK) self.filemenu.Check(self.menuComm.GetId(), False) menuClear = self.filemenu.Append(wx.ID_ANY, "&Clear session\tAlt+C", - "Remove all pages but keep imported model functions.") + "Remove all pages but keep imported model functions.") menuSave = self.filemenu.Append(wx.ID_SAVE, "&Save session\tCtrl+S", - "Save entire Session") + "Save entire Session") self.filemenu.AppendSeparator() - menuExit = self.filemenu.Append(wx.ID_EXIT,"E&xit\tCtrl+Q", - "Terminate the program") + menuExit = self.filemenu.Append(wx.ID_EXIT, "E&xit\tCtrl+Q", + "Terminate the program") # prefmenu self.MenuUseLatex = prefmenu.Append(wx.ID_ANY, "Use Latex", - "Enables/Disables usage of Latex for image saving.", - kind=wx.ITEM_CHECK) + "Enables/Disables usage of Latex for image saving.", + kind=wx.ITEM_CHECK) self.MenuVerbose = prefmenu.Append(wx.ID_ANY, "Verbose mode", - "Enables/Disables output of additional information.", - kind=wx.ITEM_CHECK) + "Enables/Disables output of additional information.", + kind=wx.ITEM_CHECK) self.MenuShowWeights = prefmenu.Append(wx.ID_ANY, "Show weights", - "Enables/Disables displaying weights of fit.", - kind=wx.ITEM_CHECK) + "Enables/Disables displaying weights of fit.", + kind=wx.ITEM_CHECK) self.MenuShowWeights.Check() self.MenuAutocloseTools = prefmenu.Append(wx.ID_ANY, "Autoclose tools", - "Automatically close tools after usage.", - kind=wx.ITEM_CHECK) + "Automatically close tools after usage.", + kind=wx.ITEM_CHECK) # toolmenu toolkeys = list(tools.ToolDict.keys()) toolkeys.sort() for ttype in toolkeys: for tool in np.arange(len(tools.ToolDict[ttype])): menu = self.toolmenu.Append(wx.ID_ANY, - tools.ToolName[ttype][tool][0], - tools.ToolName[ttype][tool][1], kind=wx.ITEM_CHECK) + tools.ToolName[ttype][tool][0], + tools.ToolName[ttype][tool][1], kind=wx.ITEM_CHECK) self.toolmenu.Check(menu.GetId(), False) # Append tool to list of tools with menu ID self.Tools[menu.GetId()] = tools.ToolDict[ttype][tool] @@ -333,12 +333,12 @@ def MakeMenu(self): "Save data (comma separated values)") menuSavePlotCorr = self.curmenu.Append(wx.ID_ANY, - "&Save correlation as image", - "Export current plot as image.") + "&Save correlation as image", + "Export current plot as image.") menuSavePlotTrace = self.curmenu.Append(wx.ID_ANY, - "&Save trace as image", - "Export current trace as image.") + "&Save trace as image", + "Export current trace as image.") self.curmenu.AppendSeparator() menuClPa = self.curmenu.Append(wx.ID_ANY, "&Close Page", "Close Current Page") @@ -358,25 +358,25 @@ def MakeMenu(self): model = mdls.modeldict[modelid] if platform.system().lower() == "darwin" and hasattr(sys, 'frozen'): ### - ### Work-around for freezed mac version + # Work-around for freezed mac version ### - ### (strange UTF-8 decoding error, - ### would work with misc.removewrongUTF8) + # (strange UTF-8 decoding error, + # would work with misc.removewrongUTF8) b = model[1].split("(")[0].strip() c = misc.removewrongUTF8(model[2]) - menuentry = submenu.Append(model[0],b,c) + menuentry = submenu.Append(model[0], b, c) else: menuentry = submenu.Append(model[0], model[1], model[2]) self.Bind(wx.EVT_MENU, self.add_fitting_tab, menuentry) # help menu menuSupport = helpmenu.Append(wx.ID_ANY, "&Support", - "How to (get) support (for) PyCorrFit") + "How to (get) support (for) PyCorrFit") menuDocu = helpmenu.Append(wx.ID_ANY, "&Documentation", - "PyCorrFit documentation") + "PyCorrFit documentation") menuWiki = helpmenu.Append(wx.ID_ANY, "&Wiki", - "PyCorrFit wiki pages by users for users (online)") + "PyCorrFit wiki pages by users for users (online)") menuUpdate = helpmenu.Append(wx.ID_ANY, "&Update", - "Check for new version"+ + "Check for new version" + " (Web access required)") helpmenu.AppendSeparator() menuShell = helpmenu.Append(wx.ID_ANY, "S&hell", @@ -389,16 +389,17 @@ def MakeMenu(self): # Create the menubar. self.menuBar = wx.MenuBar() # Adding all the menus to the MenuBar - self.menuBar.Append(self.filemenu,"&File") - self.menuBar.Append(self.toolmenu,"&Tools") - self.menuBar.Append(self.curmenu,"Current &Page") - self.menuBar.Append(modelmenu,"&Model") - self.menuBar.Append(prefmenu,"&Preferences") - self.menuBar.Append(helpmenu,"&Help") - self.SetMenuBar(self.menuBar) # Adding the MenuBar to the Frame content. + self.menuBar.Append(self.filemenu, "&File") + self.menuBar.Append(self.toolmenu, "&Tools") + self.menuBar.Append(self.curmenu, "Current &Page") + self.menuBar.Append(modelmenu, "&Model") + self.menuBar.Append(prefmenu, "&Preferences") + self.menuBar.Append(helpmenu, "&Help") + # Adding the MenuBar to the Frame content. + self.SetMenuBar(self.menuBar) self.EnableToolCurrent(False) - ## Set events - #File + # Set events + # File #self.Bind(wx.EVT_MENU, self.OnLoadSingle, menuLoadSingle) self.Bind(wx.EVT_MENU, self.OnLoadBatch, menuLoadBatch) self.Bind(wx.EVT_MENU, self.OnAddModel, menuAddModel) @@ -427,26 +428,38 @@ def MakeMenu(self): # Add the shortcuts # # For Tools first. toolsitems = self.toolmenu.GetMenuItems() - avg = filter(lambda x: x.GetItemLabelText() == 'Average data', toolsitems).__next__() + avg = filter(lambda x: x.GetItemLabelText() == + 'Average data', toolsitems).__next__() avg.SetItemLabel("{}\tAlt+A".format(avg.GetItemLabel())) - bat = filter(lambda x: x.GetItemLabelText() == 'Batch control', toolsitems).__next__() + bat = filter(lambda x: x.GetItemLabelText() == + 'Batch control', toolsitems).__next__() bat.SetItemLabel("{}\tAlt+B".format(bat.GetItemLabel())) - stat = filter(lambda x: x.GetItemLabelText() == 'Statistics view', toolsitems).__next__() + stat = filter(lambda x: x.GetItemLabelText() == + 'Statistics view', toolsitems).__next__() stat.SetItemLabel("{}\tAlt+S".format(stat.GetItemLabel())) - view = filter(lambda x: x.GetItemLabelText() == 'Trace view', toolsitems).__next__() + view = filter(lambda x: x.GetItemLabelText() == + 'Trace view', toolsitems).__next__() view.SetItemLabel("{}\tAlt+V".format(view.GetItemLabel())) self.accel_tbl = wx.AcceleratorTable([ - (wx.ACCEL_ALT, ord('A'), avg.GetId()), - (wx.ACCEL_ALT, ord('B'), bat.GetId()), - (wx.ACCEL_ALT, ord('V'), view.GetId()), - (wx.ACCEL_ALT, ord('S'), stat.GetId()), - (wx.ACCEL_CTRL, ord('O'), menuLoadBatch.GetId()), - (wx.ACCEL_CTRL | wx.ACCEL_SHIFT, ord('O'), menuOpen.GetId()), - (wx.ACCEL_CTRL, ord('S'), menuSave.GetId()), - (wx.ACCEL_ALT, ord('C'), menuClear.GetId()), - (wx.ACCEL_CTRL, ord('Q'), menuExit.GetId()) - ]) + (wx.ACCEL_ALT, ord('A'), avg.GetId()), + (wx.ACCEL_ALT, ord( + 'B'), bat.GetId()), + (wx.ACCEL_ALT, ord( + 'V'), view.GetId()), + (wx.ACCEL_ALT, ord( + 'S'), stat.GetId()), + (wx.ACCEL_CTRL, ord('O'), + menuLoadBatch.GetId()), + (wx.ACCEL_CTRL | wx.ACCEL_SHIFT, ord( + 'O'), menuOpen.GetId()), + (wx.ACCEL_CTRL, ord('S'), + menuSave.GetId()), + (wx.ACCEL_ALT, ord('C'), + menuClear.GetId()), + (wx.ACCEL_CTRL, ord( + 'Q'), menuExit.GetId()) + ]) self.SetAcceleratorTable(self.accel_tbl) def OnAbout(self, event=None): @@ -494,19 +507,19 @@ def OnAddModel(self, event=None, modfile=None): NewModel = usermodel.UserModel(self) try: - NewModel.GetCode( os.path.join(dirname, filename) ) + NewModel.GetCode(os.path.join(dirname, filename)) except NameError: # sympy is probably not installed # Warn the user - text = ("SymPy not found.\n"+ - "In order to import user defined model\n"+ - "functions, please install Sympy\n"+ + text = ("SymPy not found.\n" + + "In order to import user defined model\n" + + "functions, please install Sympy\n" + "version 0.7.2 or higher.\nhttp://sympy.org/") if platform.system().lower() == 'linux': - text += ("\nSymPy is included in the package:\n"+ + text += ("\nSymPy is included in the package:\n" + " 'python-sympy'") dlg = wx.MessageDialog(None, text, 'SymPy not found', - wx.OK | wx.ICON_EXCLAMATION) + wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() return except: @@ -519,7 +532,7 @@ def OnAddModel(self, event=None, modfile=None): for tb_item in traceback.format_tb(info[2]): errstr += tb_item dlg = wx.MessageDialog(self, errstr, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) dlg.ShowModal() return # Test the code for sympy compatibility. @@ -530,14 +543,14 @@ def OnAddModel(self, event=None, modfile=None): except: # This means that the imported model file could be # contaminated. Ask the user how to proceed. - text = "The model parsing check raised an Error.\n"+\ - "This could be the result of a wrong Syntax\n"+\ - "or an error of the parser.\n"+\ - "This might be dangerous. Procceed\n"+\ - "only, if you trust the source of the file.\n"+\ + text = "The model parsing check raised an Error.\n" +\ + "This could be the result of a wrong Syntax\n" +\ + "or an error of the parser.\n" +\ + "This might be dangerous. Procceed\n" +\ + "only, if you trust the source of the file.\n" +\ "Try and import offensive file: "+filename+"?" dlg2 = wx.MessageDialog(self, text, "Unsafe Operation", - style=wx.ICON_EXCLAMATION|wx.YES_NO|wx.STAY_ON_TOP) + style=wx.ICON_EXCLAMATION | wx.YES_NO | wx.STAY_ON_TOP) if dlg2.ShowModal() == wx.ID_YES: NewModel.ImportModel() else: @@ -546,10 +559,8 @@ def OnAddModel(self, event=None, modfile=None): # The model was loaded correctly NewModel.ImportModel() - self.dirname = dirname - def OnClearSession(self, e=None, clearmodels=False): """ Clear the entire session @@ -563,9 +574,9 @@ def OnClearSession(self, e=None, clearmodels=False): # Ask, if user wants to save current session. if numtabs > 0: dial = wx.MessageDialog(self, - 'Do you wish to save this session first?', - 'Save current session?', - wx.ICON_QUESTION | wx.CANCEL | wx.YES_NO | wx.NO_DEFAULT ) + 'Do you wish to save this session first?', + 'Save current session?', + wx.ICON_QUESTION | wx.CANCEL | wx.YES_NO | wx.NO_DEFAULT) # dial = edclasses.MyYesNoAbortDialog(self, # 'Do you wish to save this session first?', # 'Save current session?') @@ -589,7 +600,7 @@ def OnClearSession(self, e=None, clearmodels=False): self.SetTitleFCS(None) self.SessionComment = "You may enter some information here." self.Background = list() - ## Do we want to keep user defined models after session clearing? + # Do we want to keep user defined models after session clearing? if clearmodels == True: # Also reset user defined models for modelid in mdls.modeltypes["User"]: @@ -599,13 +610,12 @@ def OnClearSession(self, e=None, clearmodels=False): del mdls.modeldict[modelid] mdls.modeltypes["User"] = list() # Model Menu - menu=self.modelmenudict["User"] - for item in menu.GetMenuItems(): + menu = self.modelmenudict["User"] + for item in menu.GetMenuItems(): menu.RemoveItem(item) return "clear" - - def OnCommSession(self,e=None): + def OnCommSession(self, e=None): """ Dialog for commenting on session. """ try: self.EditCommentDlg.IsEnabled() @@ -638,7 +648,6 @@ def OnDeletePage(self, event=None): if self.notebook.GetPageCount() == 0: self.OnFNBPageChanged() - def OnDocumentation(self, e=None): """ Get the documentation and view it with browser""" path = doc.GetLocationOfDocumentation() @@ -659,8 +668,7 @@ def OnDocumentation(self, e=None): cmd = 'xdg-open "{}" &'.format(path) os.system(cmd) - - def OnExit(self,e=None): + def OnExit(self, e=None): """ Kindly asks the user if he wants to save the session and then exit the program. @@ -669,13 +677,13 @@ def OnExit(self,e=None): # Ask, if user wants to save current session. if numtabs > 0: dial = wx.MessageDialog(self, - 'Do you wish to save this session first?', - 'Save current session?', - wx.ICON_QUESTION | wx.CANCEL | wx.YES_NO | wx.NO_DEFAULT ) + 'Do you wish to save this session first?', + 'Save current session?', + wx.ICON_QUESTION | wx.CANCEL | wx.YES_NO | wx.NO_DEFAULT) result = dial.ShowModal() dial.Destroy() if result == wx.ID_CANCEL: - return # stop this function - do nothing. + return # stop this function - do nothing. elif result == wx.ID_YES: filename = self.OnSaveSession() if filename is None: @@ -685,15 +693,12 @@ def OnExit(self,e=None): # Exit the Program self.Destroy() - - def OnFNBClosedPage(self,e=None): + def OnFNBClosedPage(self, e=None): """ Called, when a page has been closed """ if self.notebook.GetPageCount() == 0: # Grey out tools self.EnableToolCurrent(False) - - def OnFNBPageChanged(self, e=None, Page=None, trigger=None): """ Called, when - Page focus switches to another Page @@ -705,8 +710,8 @@ def OnFNBPageChanged(self, e=None, Page=None, trigger=None): """ if (e is not None and - e.GetEventType()==fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED.typeId - and trigger is None): + e.GetEventType() == fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED.typeId + and trigger is None): trigger = "tab_browse" # Get the Page if Page is None: @@ -729,9 +734,7 @@ def OnFNBPageChanged(self, e=None, Page=None, trigger=None): else: self.notebook.Show() - - - def OnImportData(self,e=None): + def OnImportData(self, e=None): """Import experimental data from all filetypes specified in *readfiles.filetypes_dict*. Is called by the curmenu and applies to currently opened model. @@ -750,7 +753,7 @@ def OnImportData(self,e=None): # This is wx widgets stuff. filters = filters+"|" dlg = wx.FileDialog(self, "Open data file", - self.dirname, "", filters, wx.FD_OPEN) + self.dirname, "", filters, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: # The filename the page will get path = dlg.GetPath() # Workaround since 0.7.5 @@ -769,7 +772,7 @@ def OnImportData(self,e=None): for tb_item in traceback.format_tb(info[2]): errstr += tb_item wx.MessageDialog(self, errstr, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) return else: dataexp = Stuff["Correlation"] @@ -839,18 +842,18 @@ def OnImportData(self,e=None): # pages title. num = len(curvelist) # Show a nice progress dialog: - style = wx.PD_REMAINING_TIME|wx.PD_SMOOTH|wx.PD_AUTO_HIDE|\ - wx.PD_CAN_ABORT + style = wx.PD_REMAINING_TIME | wx.PD_SMOOTH | wx.PD_AUTO_HIDE |\ + wx.PD_CAN_ABORT dlg = wx.ProgressDialog("Import", "Loading pages...", - maximum = num, parent=self, style=style) + maximum=num, parent=self, style=style) # Get current page and populate CurPage = self.notebook.GetCurrentPage() for i in np.arange(num): # Fill Page with data self.ImportData(CurPage, dataexp[i], trace[i], - curvetype=curvelist[i], filename=filename[i], - weights=Weight[i], weight_type=WeightName[i], - curveid=i) + curvetype=curvelist[i], filename=filename[i], + weights=Weight[i], weight_type=WeightName[i], + curveid=i) # Let the user abort, if he wants to: # We want to do this here before an empty page is added # to the notebok. @@ -861,8 +864,8 @@ def OnImportData(self,e=None): # Create new page. # (Add n-1 pages while importing.) CurPage = self.add_fitting_tab(event=None, - modelid=CurPage.corr.fit_model.id, - counter=None) + modelid=CurPage.corr.fit_model.id, + counter=None) # We are finished here: dlg.Destroy() return @@ -872,7 +875,6 @@ def OnImportData(self,e=None): dlg.Destroy() return - def OnMyLeftUp(self, event): """ Wrapper for LeftUp: @@ -907,7 +909,6 @@ def OnMyLeftUp(self, event): # Call what should have been called. pc.OnLeftUp(event) - def ImportData(self, Page, dataexp, trace, curvetype="", filename="", curveid="", run="0", weights=None, weight_type=None, trigger=None): @@ -932,7 +933,7 @@ def ImportData(self, Page, dataexp, trace, curvetype="", # It might be possible, that we want the channels to be # fixed to some interval. This is the case if the # checkbox on the "Channel selection" dialog is checked. - #self.OnFNBPageChanged() + # self.OnFNBPageChanged() # Enable Fitting Button CurPage.Fit_enable_fitting() # Set new tabtitle value and strip leading or trailing @@ -960,10 +961,9 @@ def ImportData(self, Page, dataexp, trace, curvetype="", # Call this function to allow the "Channel Selection" window that # might be open to update itself. # We are aware of the fact, that we just did that - #self.OnFNBPageChanged() - + # self.OnFNBPageChanged() - def OnLatexCheck(self,e): + def OnLatexCheck(self, e): """ Checks if we can use latex. If not, create a pop-up window stating so. """ @@ -971,42 +971,41 @@ def OnLatexCheck(self,e): if uselatex == False: # do nothing return - ## Check if we can use latex for plotting: + # Check if we can use latex for plotting: r1 = meta.find_program("latex")[0] r2 = meta.find_program("dvipng")[0] # Ghostscript r31 = meta.find_program("gs")[0] - r32 = meta.find_program("mgs")[0] # from miktex - r3 = max(r31,r32) + r32 = meta.find_program("mgs")[0] # from miktex + r3 = max(r31, r32) if r1+r2+r3 < 3: # Warn the user if platform.system().lower() == 'windows': - text = ("Latex plotting features will not work.\n"+ - "Please install MiKTeX.\n"+ + text = ("Latex plotting features will not work.\n" + + "Please install MiKTeX.\n" + "http://miktex.org/") elif platform.system().lower() == 'darwin': - text = ("Latex plotting features will not work.\n"+ - "Please install MacTeX.\n"+ + text = ("Latex plotting features will not work.\n" + + "Please install MacTeX.\n" + "http://tug.org/mactex/") else: - text = ("Latex plotting features will not work.\n"+ - "Make sure you have these packages installed:\n"+ - " - dvipng\n"+ - " - ghostscript\n"+ - " - texlive-latex-base\n"+ + text = ("Latex plotting features will not work.\n" + + "Make sure you have these packages installed:\n" + + " - dvipng\n" + + " - ghostscript\n" + + " - texlive-latex-base\n" + " - texlive-science\n") dlg = wx.MessageDialog(None, text, 'Latex not found', - wx.OK | wx.ICON_EXCLAMATION) + wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() - def OnLoadBatch(self, e=None, dataname=None): """ Open multiple data files and apply a single model to them We will create a new window where the user may decide which model to use. """ if dataname is None: - ## Browse the file system + # Browse the file system SupFiletypes = list(readfiles.filetypes_dict.keys()) # Sort them so we have "All suported filetypes" up front SupFiletypes.sort() @@ -1018,7 +1017,7 @@ def OnLoadBatch(self, e=None, dataname=None): # Add a separator if item is not last item filters = filters+"|" dlg = wx.FileDialog(self, "Open data files", - self.dirname, "", filters, wx.FD_OPEN|wx.FD_MULTIPLE) + self.dirname, "", filters, wx.FD_OPEN | wx.FD_MULTIPLE) if dlg.ShowModal() == wx.ID_OK: Datafiles = dlg.GetFilenames() # We rely on sorted filenames @@ -1044,8 +1043,8 @@ def OnLoadBatch(self, e=None, dataname=None): self.dirname = os.path.split(dataname)[0] Datafiles.sort() - ## Get information from the data files and let the user choose - ## which type of curves to load and the corresponding model. + # Get information from the data files and let the user choose + # which type of curves to load and the corresponding model. # List of filenames that could not be opened BadFiles = list() Exceptions = list() @@ -1054,19 +1053,19 @@ def OnLoadBatch(self, e=None, dataname=None): Trace = list() Type = list() Filename = list() # there might be zipfiles with additional name info - #Run = list() # Run number connecting AC1 AC2 CC12 CC21 + # Run = list() # Run number connecting AC1 AC2 CC12 CC21 Curveid = list() # Curve ID of each curve in a file Weight = list() WeightName = list() # Display a progress dialog for file import N = len(Datafiles) - style = wx.PD_REMAINING_TIME|wx.PD_SMOOTH|wx.PD_AUTO_HIDE|\ - wx.PD_CAN_ABORT + style = wx.PD_REMAINING_TIME | wx.PD_SMOOTH | wx.PD_AUTO_HIDE |\ + wx.PD_CAN_ABORT dlgi = wx.ProgressDialog("Import", "Loading data...", - maximum = N, parent=self, style=style) + maximum=N, parent=self, style=style) for j in np.arange(N): - afile=Datafiles[j] + afile = Datafiles[j] # Let the user abort, if he wants to: if dlgi.Update(j, "Loading data: "+afile)[0] == False: dlgi.Destroy() @@ -1081,8 +1080,8 @@ def OnLoadBatch(self, e=None, dataname=None): # Print exception trb = traceback.format_exc(excpt) trb = "..." + trb.replace("\n", "\n...") - warnings.warn("Problem processing a file."+\ - " Reason:\n{}".format(trb)) + warnings.warn("Problem processing a file." + + " Reason:\n{}".format(trb)) else: for i in np.arange(len(Stuff["Type"])): Correlation.append(Stuff["Correlation"][i]) @@ -1095,7 +1094,7 @@ def OnLoadBatch(self, e=None, dataname=None): else: Weight.append(None) WeightName.append(None) - #Curveid.append(str(i+1)) + # Curveid.append(str(i+1)) dlgi.Destroy() # Add number of the curve within a file. @@ -1119,7 +1118,7 @@ def OnLoadBatch(self, e=None, dataname=None): trb = " " + trb.replace("\n", "\n ") errstr += " " + item + "\n" + trb dlg = wx.MessageDialog(self, errstr, "Error", - style=wx.ICON_WARNING|wx.OK|wx.CANCEL|wx.STAY_ON_TOP) + style=wx.ICON_WARNING | wx.OK | wx.CANCEL | wx.STAY_ON_TOP) if dlg.ShowModal() == wx.ID_CANCEL: return # Abort, if there are no curves left @@ -1182,7 +1181,7 @@ def OnLoadBatch(self, e=None, dataname=None): # to import. keys = curvetypes.keys() # Start the dialog for choosing types and model functions - labels=list() + labels = list() for i in np.arange(len(Filename)): if Run[i] != "": labels.append("{} r{:03d}-{}".format(Filename[i], @@ -1236,22 +1235,22 @@ def OnLoadBatch(self, e=None, dataname=None): else: return Chosen.Destroy() - ## Import the data into new pages + # Import the data into new pages # curvelist is a list of numbers or labels that correspond # to each item in dataexp or trace. Each curvelist/filename # item will be converted to a string and then added to the # pages title. num = len(Type) # Show a nice progress dialog: - style = wx.PD_REMAINING_TIME|wx.PD_SMOOTH|wx.PD_AUTO_HIDE|\ - wx.PD_CAN_ABORT - dlg = wx.ProgressDialog("Import", "Loading pages..." - , maximum = num, parent=self, style=style) + style = wx.PD_REMAINING_TIME | wx.PD_SMOOTH | wx.PD_AUTO_HIDE |\ + wx.PD_CAN_ABORT + dlg = wx.ProgressDialog( + "Import", "Loading pages...", maximum=num, parent=self, style=style) for i in np.arange(num): # create a new page CurPage = self.add_fitting_tab(event=None, - modelid=modelList[i], - counter=None) + modelid=modelList[i], + counter=None) # Fill Page with data self.ImportData(CurPage, Correlation[i], Trace[i], curvetype=Type[i], filename=Filename[i], @@ -1268,7 +1267,6 @@ def OnLoadBatch(self, e=None, dataname=None): # the dialog. dlg.Destroy() - def OnOpenSession(self, e=None, sessionfile=None): """ Displays a dialog for opening PyCorrFit sessions @@ -1288,8 +1286,8 @@ def OnOpenSession(self, e=None, sessionfile=None): # the session. Therefore, we cannot open a new session. return "abort" - ## Create user dialog - wc = [ "*{}".format(w) for w in opf.session_wildcards ] + # Create user dialog + wc = ["*{}".format(w) for w in opf.session_wildcards] wcstring = "PyCorrFit session (*.pcfs)|{}".format(";".join(wc)) if sessionfile is None: dlg = wx.FileDialog(self, "Open session file", @@ -1298,7 +1296,7 @@ def OnOpenSession(self, e=None, sessionfile=None): if dlg.ShowModal() == wx.ID_OK: sessionfile = dlg.GetPath() (self.dirname, self.filename) = os.path.split( - sessionfile) + sessionfile) else: # User did not press OK # stop this function @@ -1307,17 +1305,17 @@ def OnOpenSession(self, e=None, sessionfile=None): dlg.Destroy() Infodict = opf.LoadSessionData(sessionfile) - ## Check for correct version + # Check for correct version try: arcv = LooseVersion(Infodict["Version"]) thisv = LooseVersion(self.version.strip()) if arcv > thisv: - errstring = "Your version of Pycorrfit ("+str(thisv)+\ - ") is too old to open this session ("+\ - str(arcv).strip()+").\n"+\ - "Please download the lates version of "+\ - " PyCorrFit from \n"+doc.HomePage+".\n"+\ - "Continue opening this session?" + errstring = "Your version of Pycorrfit ("+str(thisv) +\ + ") is too old to open this session (" +\ + str(arcv).strip()+").\n" +\ + "Please download the lates version of " +\ + " PyCorrFit from \n"+doc.HomePage+".\n" +\ + "Continue opening this session?" dlg = edclasses.MyOKAbortDialog(self, errstring, "Warning") returns = dlg.ShowModal() if returns == wx.ID_OK: @@ -1329,14 +1327,14 @@ def OnOpenSession(self, e=None, sessionfile=None): pass self.SetTitleFCS(self.filename) - ## Background traces + # Background traces try: self.Background = Infodict["Backgrounds"] except: pass - ## Preferences - ## if Preferences is Not None: - ## add them! + # Preferences + # if Preferences is Not None: + # add them! # External functions for key in Infodict["External Functions"].keys(): NewModel = usermodel.UserModel(self) @@ -1351,10 +1349,10 @@ def OnOpenSession(self, e=None, sessionfile=None): # Reset tabcounter self.tabcounter = 1 # Show a nice progress dialog: - style = wx.PD_REMAINING_TIME|wx.PD_SMOOTH|wx.PD_AUTO_HIDE|\ - wx.PD_CAN_ABORT + style = wx.PD_REMAINING_TIME | wx.PD_SMOOTH | wx.PD_AUTO_HIDE |\ + wx.PD_CAN_ABORT dlg = wx.ProgressDialog("Import", "Loading pages...", - maximum = N, parent=self, style=style) + maximum=N, parent=self, style=style) for i in np.arange(N): # Let the user abort, if he wants to: if dlg.Update(i+1, "Loading pages...")[0] == False: @@ -1381,7 +1379,8 @@ def OnOpenSession(self, e=None, sessionfile=None): # As of 0.7.3: Add external weights to page try: for key in Infodict["External Weights"][pageid].keys(): - Newtab.corr.set_weights(key, Infodict["External Weights"][pageid][key]) + Newtab.corr.set_weights( + key, Infodict["External Weights"][pageid][key]) except KeyError: pass @@ -1410,7 +1409,7 @@ def OnOpenSession(self, e=None, sessionfile=None): try: Newtab.tabtitle.SetValue(Infodict["Comments"][pageid]) except: - pass # no page title + pass # no page title # Parameters self.UnpackParameters(Infodict["Parameters"][i], Newtab, @@ -1438,7 +1437,8 @@ def OnOpenSession(self, e=None, sessionfile=None): except: pass # also set fit parameters - fit_results["fit parameters"] = np.where(Infodict["Parameters"][i][3])[0] + fit_results["fit parameters"] = np.where( + Infodict["Parameters"][i][3])[0] # set fit weights for plotting if fit_results["weighted fit"]: # these were already imported: @@ -1480,8 +1480,7 @@ def OnOpenSession(self, e=None, sessionfile=None): # Disable some menus and close some dialogs self.EnableToolCurrent(False) - - def OnSaveData(self,e=None): + def OnSaveData(self, e=None): """ Opens a dialog for saving correlation data of a Page Also saves the parameters that are accessible in the Info @@ -1493,9 +1492,9 @@ def OnSaveData(self,e=None): filename = "#{:04d}_{}".format(int(Page.counter.strip(":# ")), Page.title.strip()) dlg = wx.FileDialog(self, "Save curve", self.dirname, filename, - "Correlation with trace (*.csv)|*.csv;*.*"+\ - "|Correlation only (*.csv)|*.csv;*.*", - wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) + "Correlation with trace (*.csv)|*.csv;*.*" + + "|Correlation only (*.csv)|*.csv;*.*", + wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) # user cannot do anything until he clicks "OK" if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() # Workaround since 0.7.5 @@ -1503,7 +1502,6 @@ def OnSaveData(self,e=None): path += ".csv" (self.dirname, self.filename) = os.path.split(path) - if dlg.GetFilterIndex() == 0: savetrace = True else: @@ -1516,7 +1514,6 @@ def OnSaveData(self,e=None): dlg.Destroy() - def OnSavePlotCorr(self, e=None): """ make some output """ # Saving dialog box. @@ -1526,13 +1523,12 @@ def OnSavePlotCorr(self, e=None): Page = self.notebook.GetCurrentPage() try: plotting.savePlotCorrelation(self, self.dirname, Page, uselatex, - verbose, show_weights) + verbose, show_weights) except NameError as excpt: trb = traceback.format_exc(excpt) trb = " " + trb.replace("\n", "\n ") raise NameError("Please make sure matplotlib is installed:\n"+trb) - def OnSavePlotTrace(self, e=None): """ make some output """ # Saving dialog box. @@ -1546,8 +1542,7 @@ def OnSavePlotTrace(self, e=None): trb = " " + trb.replace("\n", "\n ") raise NameError("Please make sure matplotlib is installed:\n"+trb) - - def OnSaveSession(self,e=None): + def OnSaveSession(self, e=None): """ Displays a dialog for saving PyCorrFit sessions @@ -1563,15 +1558,17 @@ def OnSaveSession(self,e=None): """ # Parameters are all in one dictionary: Infodict = dict() - Infodict["Backgrounds"] = self.Background # Background list - Infodict["Comments"] = dict() # Session comment "Session" and Pages int - Infodict["Correlations"] = dict() # all correlation curves - Infodict["External Functions"] = dict() # external model functions - Infodict["External Weights"] = dict() # additional weights for the pages - Infodict["Parameters"] = dict() # all parameters of all pages - Infodict["Preferences"] = dict() # not used - Infodict["Supplements"] = dict() # error estimates for fitting - Infodict["Traces"] = dict() # all traces + Infodict["Backgrounds"] = self.Background # Background list + # Session comment "Session" and Pages int + Infodict["Comments"] = dict() + Infodict["Correlations"] = dict() # all correlation curves + Infodict["External Functions"] = dict() # external model functions + # additional weights for the pages + Infodict["External Weights"] = dict() + Infodict["Parameters"] = dict() # all parameters of all pages + Infodict["Preferences"] = dict() # not used + Infodict["Supplements"] = dict() # error estimates for fitting + Infodict["Traces"] = dict() # all traces # Save each Page N = self.notebook.GetPageCount() # External functions @@ -1579,7 +1576,7 @@ def OnSaveSession(self,e=None): # Those models belong to external user functions. doc = mdls.modeldict[usermodelid][-1].__doc__ doc = doc.splitlines() - docnew="" + docnew = "" for line in doc: docnew = docnew+line.strip()+"\r\n" Infodict["External Functions"][usermodelid] = docnew @@ -1596,7 +1593,8 @@ def OnSaveSession(self,e=None): if hasattr(corr, "fit_results"): Infodict["Supplements"][counter] = dict() if "chi2" in corr.fit_results: - Infodict["Supplements"][counter]["Chi sq"] = float(corr.fit_results["chi2"]) + Infodict["Supplements"][counter]["Chi sq"] = float( + corr.fit_results["chi2"]) else: Infodict["Supplements"][counter]["Chi sq"] = 0 PageList = list() @@ -1606,21 +1604,24 @@ def OnSaveSession(self,e=None): # optimization error Alist = list() - if (# there is an error key + if ( # there is an error key "fit error estimation" in corr.fit_results and # the errors were computed len(corr.fit_results["fit error estimation"]) != 0 and # len(errors) matches len(fit parameters) - len(corr.fit_results["fit error estimation"]) == len(corr.fit_results["fit parameters"]) - ): + len(corr.fit_results["fit error estimation"]) == len( + corr.fit_results["fit parameters"]) + ): for ii, fitpid in enumerate(corr.fit_results["fit parameters"]): Alist.append([int(fitpid), - float(corr.fit_results["fit error estimation"][ii]) - ]) + float( + corr.fit_results["fit error estimation"][ii]) + ]) Infodict["Supplements"][counter]["FitErr"] = Alist # Set exp data - Infodict["Correlations"][counter] = [corr.lag_time, corr.correlation] + Infodict["Correlations"][counter] = [ + corr.lag_time, corr.correlation] # Also save the trace Infodict["Traces"][counter] = corr.traces # Append title to Comments @@ -1651,7 +1652,7 @@ def OnSaveSession(self,e=None): # File dialog dlg = wx.FileDialog(self, "Save session file", self.dirname, "", "PyCorrFit session (*.pcfs)|*.pcfs|All files (*.*)|*.*", - wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) + wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: # Save everything path = dlg.GetPath() # Workaround since 0.7.5 @@ -1662,35 +1663,31 @@ def OnSaveSession(self,e=None): self.filename = None # Set title of our window if (self.filename is not None and - not self.filename.endswith(".pcfs")): + not self.filename.endswith(".pcfs")): self.filename += ".pcfs" dlg.Destroy() self.SetTitleFCS(self.filename) return self.filename - def OnShell(self, e=None): Shell = wx.py.shell.ShellFrame(self, title="PyCorrFit Shell", - style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT, - locals=locals()) + style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT, + locals=locals()) # Set window icon if self.MainIcon is not None: wx.Frame.SetIcon(Shell, self.MainIcon) Shell.Show(True) - def OnSoftware(self, event=None): # Show About Information text = doc.SoftwareUsed() wx.MessageBox(text, 'Software', wx.OK | wx.ICON_INFORMATION) - def OnSupport(self, event=None): # Show About Information text = doc.support wx.MessageBox(text, 'Support PyCorrFit', wx.OK | wx.ICON_INFORMATION) - def OnTool(self, event): eid = event.GetId() try: @@ -1707,16 +1704,13 @@ def OnTool(self, event): # We close it then self.ToolsOpen[eid].OnClose() - def OnUpdate(self, event): update.update(self) - def OnWiki(self, e=None): """ Go to the GitHub Wiki page""" webbrowser.open(doc.GitWiki) - def PackParameters(self, Page): """ Gets all parameters from a page and returns a list object, that can be used to save as e.g. a safe YAML file @@ -1734,7 +1728,7 @@ def PackParameters(self, Page): # Additional parameters as of v.0.2.0 # Splines and model function: # Additional parameters as of v.6.4.0 - #self.Fitbox=[ fitbox, weightedfitdrop, fittext, fittext2, + # self.Fitbox=[ fitbox, weightedfitdrop, fittext, fittext2, # fittextvar, fitspin, buttonfit ] # Some fits like Spline have a number of knots of the spline # that is important for fitting. If there is a number in the @@ -1764,7 +1758,6 @@ def PackParameters(self, Page): Parms.append(Page.corr.fit_parameters_range) return Parms - def UnpackParameters(self, Parms, Page, init=False): """ Apply the given parameters to the Page in question. This function contains several *len(Parms) >= X* statements. @@ -1804,7 +1797,7 @@ def UnpackParameters(self, Parms, Page, init=False): NA = active_values[lindex+1] sigma = 0.21*lamb/NA active_values[lindex] = sigma - active_values = np.delete(active_values,lindex+1) + active_values = np.delete(active_values, lindex+1) active_fitting = np.delete(active_fitting, lindex+1) # Cropping: What part of the correlation should be displayed. Page.corr.fit_ival = Parms[4] @@ -1871,13 +1864,11 @@ def UnpackParameters(self, Parms, Page, init=False): Page.OnAmplitudeCheck("init") if len(Parms) >= 10: Page.corr.fit_parameters_range = np.array(Parms[9]) - ## If we want to add more stuff, we should do something like: - ## if len(Parms) >= 11: + # If we want to add more stuff, we should do something like: + # if len(Parms) >= 11: ## nextvalue = Parms[10] - ## Such that we are compatible to earlier versions of - ## PyCorrFit sessions. - - + # Such that we are compatible to earlier versions of + # PyCorrFit sessions. def SetTitleFCS(self, title): if title is not None and len(title) != 0: diff --git a/pycorrfit/gui/icon.py b/pycorrfit/gui/icon.py index bfdf8e42..c35e8b43 100644 --- a/pycorrfit/gui/icon.py +++ b/pycorrfit/gui/icon.py @@ -1,4 +1,4 @@ -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # This file was generated by /usr/bin/img2py # from wx.lib.embeddedimage import PyEmbeddedImage diff --git a/pycorrfit/gui/main.py b/pycorrfit/gui/main.py index abb4ad12..86b73749 100755 --- a/pycorrfit/gui/main.py +++ b/pycorrfit/gui/main.py @@ -1,3 +1,9 @@ +from . import frontend as gui # The actual program +from . import doc +import yaml +import scipy +import numpy as np # NumPy +import warnings """Main execution script""" from distutils.version import LooseVersion import os @@ -7,6 +13,7 @@ class Fake(object): """ Fake module. """ + def __init__(self): self.__version__ = "0.0 unknown" self.version = "0.0 unknown" @@ -20,13 +27,10 @@ def __init__(self): except ImportError: matplotlib = Fake() # We do catch warnings about performing this before matplotlib.backends stuff -#matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets -import warnings +# matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets with warnings.catch_warnings(): warnings.simplefilter("ignore") - matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs -import numpy as np # NumPy -import scipy + matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs # Sympy is optional: @@ -41,14 +45,10 @@ def __init__(self): # We must not import wx here. frontend/gui does that. If we do import wx here, # somehow unicode characters will not be displayed correctly on windows. # import wx -import yaml -## Continue with the import: +# Continue with the import: sys.path.append(os.path.abspath(os.path.dirname(__file__))) -from . import doc -from . import frontend as gui # The actual program - def CheckVersion(given, required, name): """ For a given set of versions str *required* and str *given*, @@ -62,22 +62,22 @@ def CheckVersion(given, required, name): print(" WARNING: Could not verify version of "+name+".") return if req > giv: - print(" WARNING: You are using "+name+" v. "+given+\ - " | Required: "+name+" "+ required) + print(" WARNING: You are using "+name+" v. "+given + + " | Required: "+name+" " + required) else: print(" OK: "+name+" v. "+given+" | "+required+" required") -## Start gui +# Start gui def Main(): - ## VERSION + # VERSION version = doc.__version__ __version__ = version print(gui.doc.info(version)) - ## Check important module versions + # Check important module versions print("\n\nChecking module versions...") CheckVersion(matplotlib.__version__, "2.2.2", "matplotlib") CheckVersion(np.__version__, "1.14.2", "NumPy") @@ -86,7 +86,7 @@ def Main(): CheckVersion(sympy.__version__, "1.1.1", "sympy") CheckVersion(gui.wx.__version__, "4.0.1", "wxPython") - ## Start gui + # Start gui app = gui.MyApp(False) frame = gui.MyFrame(None, -1, version) diff --git a/pycorrfit/gui/misc.py b/pycorrfit/gui/misc.py index 53402466..5b31e778 100644 --- a/pycorrfit/gui/misc.py +++ b/pycorrfit/gui/misc.py @@ -31,12 +31,12 @@ def parseString2Pagenum(parent, string, nodialog=False): return PageNumbers except: if nodialog is False: - errstring = "Invalid syntax in page selection: "+string+\ - ". Please use a comma separated list with"+\ + errstring = "Invalid syntax in page selection: "+string +\ + ". Please use a comma separated list with" +\ " optional dashes, e.g. '1-3,6,8'." try: wx.MessageDialog(parent, errstring, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) except: raise ValueError(errstring) else: @@ -110,4 +110,3 @@ def getMainIcon(pxlength=32): iconBMP = wx.Bitmap(image) iconICO = wx.Icon(iconBMP) return iconICO - diff --git a/pycorrfit/gui/page.py b/pycorrfit/gui/page.py index 7c9156db..b5c87e8a 100644 --- a/pycorrfit/gui/page.py +++ b/pycorrfit/gui/page.py @@ -19,11 +19,11 @@ from . import wxutils - class FittingPanel(wx.Panel): """ Those are the Panels that show the fitting dialogs with the Plots. """ + def __init__(self, parent, counter, modelid, active_parms, tau=None): """ Initialize with given parameters. """ wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) @@ -42,11 +42,10 @@ def __init__(self, parent, counter, modelid, active_parms, tau=None): self._bgselected = None self._bg2selected = None - self.FitKnots = 5 # number of knots for spline fit or similiars - - self.weighted_fittype_id = 0 # integer (drop down item) - self.weighted_nuvar = 3 # bins for std-dev. (left and rigth) + self.FitKnots = 5 # number of knots for spline fit or similiars + self.weighted_fittype_id = 0 # integer (drop down item) + self.weighted_nuvar = 3 # bins for std-dev. (left and rigth) # The weights that are plotted in the page # This is set by the PlotAll function @@ -66,7 +65,7 @@ def __init__(self, parent, counter, modelid, active_parms, tau=None): # Tool statistics uses this list: self.StatisticsCheckboxes = None - ### Splitter window + # Splitter window # Sizes size = parent.notebook.GetSize() tabsize = 33 @@ -78,11 +77,11 @@ def __init__(self, parent, counter, modelid, active_parms, tau=None): self.sp = wx.SplitterWindow(self, size=size, style=wx.SP_3DSASH) # This is necessary to prevent "Unsplit" of the SplitterWindow: self.sp.SetMinimumPaneSize(1) - ## Settings Section (left side) + # Settings Section (left side) #self.panelsettings = wx.Panel(self.sp, size=sizepanel) self.panelsettings = scrolled.ScrolledPanel(self.sp, size=sizepanel) self.panelsettings.SetupScrolling(scroll_x=False) - ## Setting up Plot (correlation + chi**2) + # Setting up Plot (correlation + chi**2) self.spcanvas = wx.SplitterWindow(self.sp, size=sizecanvas, style=wx.SP_3DSASH) # This is necessary to prevent "Unsplit" of the SplitterWindow: @@ -164,7 +163,7 @@ def bgselected(self): @bgselected.setter def bgselected(self, value): if value is None: - self.corr.backgrounds=[] + self.corr.backgrounds = [] return # check paren.Background and get id background = self.parent.Background[value] @@ -179,7 +178,7 @@ def bg2selected(self): def bg2selected(self, value): if value is None: if self.corr.is_cc: - self.corr.backgrounds=[] + self.corr.backgrounds = [] return # check paren.Background and get id background = self.parent.Background[value] @@ -207,7 +206,7 @@ def apply_parameters(self, event=None): # Here: Convert human readable units to program internal # units parmsconv = mdls.GetInternalFromHumanReadableParm( - modelid, np.array(parameters))[1] + modelid, np.array(parameters))[1] self.corr.fit_parameters = parmsconv # Fitting parameters @@ -239,7 +238,7 @@ def apply_parameters(self, event=None): elif self.weighted_fittype_id == 2: fit_weight_type = "model function" fit_weight_data = self.weighted_nuvar - else: # fitbox_selection > 2: + else: # fitbox_selection > 2: fit_weight_type = fitbox_value self.corr.fit_weight_type = fitbox_value fit_weight_data = self.corr.fit_weight_data @@ -256,7 +255,6 @@ def apply_parameters(self, event=None): # function, write them back. self.apply_parameters_reverse() - def apply_parameters_reverse(self, event=None): """ Read the values from the pages parameters and write it to the GUI form. @@ -270,7 +268,7 @@ def apply_parameters_reverse(self, event=None): # Here: Convert program internal units to # human readable units parameters = mdls.GetHumanReadableParms(modelid, - self.corr.fit_parameters)[1] + self.corr.fit_parameters)[1] parameters_variable = self.corr.fit_parameters_variable # Write parameters to the form on the Page for i in np.arange(len(self.active_parms[1])): @@ -295,17 +293,15 @@ def apply_parameters_reverse(self, event=None): self.AlgorithmDropdown.SetSelection(idalg) self.updateChi2() - def calculate_corr(self): """ Calculate model correlation function """ return self.corr.modeled - def Fit_enable_fitting(self): """ Enable the fitting button and the weighted fit control""" - #self.Fitbox = [ fitbox, weightedfitdrop, fittext, fittext2, + # self.Fitbox = [ fitbox, weightedfitdrop, fittext, fittext2, # fittextvar, fitspin, buttonfit, textalg, # self.AlgorithmDropdown] self.Fitbox[0].Enable() @@ -314,7 +310,6 @@ def Fit_enable_fitting(self): self.Fitbox[7].Enable() self.Fitbox[8].Enable() - def Fit_function(self, event=None, noplots=False, trigger=None): """ Calls the fit function. @@ -327,7 +322,6 @@ def Fit_function(self, event=None, noplots=False, trigger=None): """ tools.batchcontrol.FitProgressDlg(self, self) - def Fit_finalize(self, trigger): """ Things that need be done after fitting """ @@ -350,12 +344,11 @@ def Fit_finalize(self, trigger): # update displayed chi2 self.updateChi2() - def Fit_WeightedFitCheck(self, event=None): """ Enable Or disable variance calculation, dependent on "Weighted Fit" checkbox """ - #self.Fitbox=[ fitbox, weightedfitdrop, fittext, fittext2, fittextvar, + # self.Fitbox=[ fitbox, weightedfitdrop, fittext, fittext2, fittextvar, # fitspin, buttonfit ] weighted = (self.Fitbox[1].GetSelection() != 0) # In the case of "Average" we do not enable the @@ -371,7 +364,6 @@ def Fit_WeightedFitCheck(self, event=None): self.Fitbox[4].Disable() self.Fitbox[5].Disable() - def MakeStaticBoxSizer(self, boxlabel): """ Create a Box with check boxes (fit yes/no) and possibilities to change initial values for fitting. @@ -410,26 +402,25 @@ def MakeStaticBoxSizer(self, boxlabel): sizer.Add(sizerh) return sizer, check, spin - def OnAmplitudeCheck(self, event=None): """ Enable/Disable BG rate text line. New feature introduced in 0.7.8 """ modelid = self.corr.fit_model.id - ## Normalization to a certain parameter in plots + # Normalization to a certain parameter in plots # Find all parameters that start with an "N" # ? and "C" ? # Create List normlist = list() normlist.append("None") - ## Add parameters + # Add parameters parameterlist = list() for i in np.arange(len(self.active_parms[0])): label = self.active_parms[0][i] if label[0].lower() == "n": normlist.append("*"+label) parameterlist.append(i) - ## Add supplementary parameters + # Add supplementary parameters # Get them from models supplement = mdls.GetMoreInfo(modelid, self) if supplement is not None: @@ -457,9 +448,9 @@ def OnAmplitudeCheck(self, event=None): # Set dropdown values self.AmplitudeInfo[2].SetItems(normlist) self.AmplitudeInfo[2].SetSelection(normsel) - ## Plot intensities + # Plot intensities # Quick reminder: - #self.AmplitudeInfo = [ [intlabel1, intlabel2], + # self.AmplitudeInfo = [ [intlabel1, intlabel2], # [bgspin1, bgspin2], # normtoNDropdown, textnor] # Signal @@ -473,20 +464,20 @@ def OnAmplitudeCheck(self, event=None): else: self.AmplitudeInfo[0][1].Disable() # Background - ## self.parent.Background[self.bgselected][i] - ## [0] average signal [kHz] - ## [1] signal name (edited by user) - ## [2] signal trace (tuple) ([ms], [kHz]) + # self.parent.Background[self.bgselected][i] + # [0] average signal [kHz] + # [1] signal name (edited by user) + # [2] signal trace (tuple) ([ms], [kHz]) if len(self.corr.backgrounds) >= 1: self.AmplitudeInfo[1][0].SetValue( - self.corr.backgrounds[0].countrate) + self.corr.backgrounds[0].countrate) else: self.AmplitudeInfo[1][0].SetValue(0) self.AmplitudeInfo[1][1].SetValue(0) if len(self.corr.backgrounds) == 2: self.AmplitudeInfo[1][1].SetValue( - self.corr.backgrounds[1].countrate) + self.corr.backgrounds[1].countrate) else: self.AmplitudeInfo[1][1].SetValue(0) # Disable the second line in amplitude correction, if we have @@ -495,13 +486,12 @@ def OnAmplitudeCheck(self, event=None): for item in self.WXAmplitudeCCOnlyStuff: item.Enable(boolval) - def OnBGSpinChanged(self, e): """ Calls tools.background.ApplyAutomaticBackground to update background information """ # Quick reminder: - #self.AmplitudeInfo = [ [intlabel1, intlabel2], + # self.AmplitudeInfo = [ [intlabel1, intlabel2], # [bgspin1, bgspin2], # normtoNDropdown, textnor] if self.corr.is_cc: @@ -509,7 +499,7 @@ def OnBGSpinChanged(self, e): bg = [float(self.AmplitudeInfo[1][0].GetValue()), float(self.AmplitudeInfo[1][1].GetValue())] sig = [float(self.AmplitudeInfo[0][0].GetValue()), - float(self.AmplitudeInfo[0][1].GetValue())] + float(self.AmplitudeInfo[0][1].GetValue())] # Make sure bg < sig for ii in range(len(bg)): if sig[ii] != 0: @@ -529,7 +519,6 @@ def OnBGSpinChanged(self, e): self.parent) e.Skip() - def OnTitleChanged(self, e): modelid = self.corr.fit_model.id pid = self.parent.notebook.GetPageIndex(self) @@ -539,7 +528,7 @@ def OnTitleChanged(self, e): # How many characters of the the page title should be displayed # in the tab? We choose 9: AC1-012 plus 2 whitespaces text = self.counter + self.tabtitle.GetValue()[-9:] - self.parent.notebook.SetPageText(pid,text) + self.parent.notebook.SetPageText(pid, text) def OnSetRange(self, e): """ Open a new Frame where the parameter range can be set. @@ -563,7 +552,6 @@ def OnSetRange(self, e): pass self.parent.RangeSelector = None - def OnSize(self, event): """ Resize the fitting Panel, when Window is resized. """ size = self.parent.notebook.GetSize() @@ -571,7 +559,6 @@ def OnSize(self, event): size[1] = size[1] - tabsize self.sp.SetSize(size) - def PlotAll(self, event=None, trigger=None): """ This function plots the whole correlation and residuals canvas. @@ -598,18 +585,18 @@ def PlotAll(self, event=None, trigger=None): return else: self.InitialPlot = True - ## Enable/Disable, set values frontend normalization + # Enable/Disable, set values frontend normalization self.OnAmplitudeCheck() - ## Apply parameters + # Apply parameters self.apply_parameters() # Calculate correlation function from parameters - ## Drawing of correlation plot + # Drawing of correlation plot # Plots corr.correlation_fit and the calcualted correlation function # self.datacorr into the upper canvas. # Create a line @ y=zero: zerostart = self.corr.lag_time_fit[0] zeroend = self.corr.lag_time_fit[-1] - datazero = [[zerostart, 0], [zeroend,0]] + datazero = [[zerostart, 0], [zeroend, 0]] # Set plot colors width = 1 colexp = "grey" @@ -633,14 +620,15 @@ def PlotAll(self, event=None, trigger=None): # if weights are from average or other, make sure that the # dimensions are correct if weights.shape[0] == self.corr.correlation.shape[0]: - weights = weights[self.corr.fit_ival[0]:self.corr.fit_ival[1]] + weights = weights[self.corr.fit_ival[0] :self.corr.fit_ival[1]] # perform some checks if np.allclose(weights, np.ones_like(weights)): weights = 0 elif weights.shape[0] != self.corr.modeled_fit.shape[0]: # non-matching weigths - warnings.warn("Unmatching weights found. Probably from previous data set.") + warnings.warn( + "Unmatching weights found. Probably from previous data set.") weights = 0 # Add the weights to the graph. @@ -653,24 +641,25 @@ def PlotAll(self, event=None, trigger=None): w2[:, 1] = w[:, 1] - weights # crop w1 and w2 if corr.correlation_fit does not include all # data points. - if np.all(w[:,0] == self.corr.correlation_fit[:,0]): + if np.all(w[:, 0] == self.corr.correlation_fit[:, 0]): pass else: - raise ValueError("This should not have happened: size of weights is wrong.") - ## Normalization with self.normfactor - w1[:,1] *= self.corr.normalize_factor - w2[:,1] *= self.corr.normalize_factor - self.weights_plot_fill_area = [w1,w2] + raise ValueError( + "This should not have happened: size of weights is wrong.") + # Normalization with self.normfactor + w1[:, 1] *= self.corr.normalize_factor + w2[:, 1] *= self.corr.normalize_factor + self.weights_plot_fill_area = [w1, w2] lineweight1 = plot.PolyLine(w1, legend='', - colour=colweight, width=width) + colour=colweight, width=width) lines.append(lineweight1) lineweight2 = plot.PolyLine(w2, legend='', - colour=colweight, width=width) + colour=colweight, width=width) lines.append(lineweight2) else: self.weights_plot_fill_area = None - ## Plot Correlation curves + # Plot Correlation curves # Plot both, experimental and calculated data # Normalization with self.normfactor, new feature in 0.7.8 datacorr_norm = self.corr.modeled_plot @@ -683,10 +672,10 @@ def PlotAll(self, event=None, trigger=None): lines.append(lineexp) lines.append(linecorr) PlotCorr = plot.PlotGraphics(lines, - xLabel=u'lag time Ļ [ms]', yLabel=u'G(Ļ)') + xLabel=u'lag time Ļ [ms]', yLabel=u'G(Ļ)') self.canvascorr.Draw(PlotCorr) - ## Calculate residuals + # Calculate residuals resid_norm = self.corr.residuals_plot lineres = plot.PolyLine(resid_norm, legend='', colour=colfit, width=width) @@ -697,8 +686,8 @@ def PlotAll(self, event=None, trigger=None): else: yLabelRes = "residuals" PlotRes = plot.PlotGraphics([linezero, lineres], - xLabel=u'lag time Ļ [ms]', - yLabel=yLabelRes) + xLabel=u'lag time Ļ [ms]', + yLabel=yLabelRes) self.canvaserr.Draw(PlotRes) else: # Amplitude normalization, new feature in 0.7.8 @@ -706,12 +695,11 @@ def PlotAll(self, event=None, trigger=None): linecorr = plot.PolyLine(datacorr_norm, legend='', colour='blue', width=1) PlotCorr = plot.PlotGraphics([linezero, linecorr], - xLabel=u'Lag time Ļ [ms]', yLabel=u'G(Ļ)') + xLabel=u'Lag time Ļ [ms]', yLabel=u'G(Ļ)') self.canvascorr.Draw(PlotCorr) self.Refresh() self.parent.OnFNBPageChanged(trigger=trigger) - def settings(self): """ Here we define, what should be displayed at the left side of the fitting page/tab. @@ -724,7 +712,7 @@ def settings(self): mddat = mdls.modeldict[modelid] modelshort = mdls.GetModelType(modelid) titlelabel = u"Data set {} ({} {})".format( - self.counter.strip(" :"), modelshort, mddat[1]) + self.counter.strip(" :"), modelshort, mddat[1]) boxti = wx.StaticBox(self.panelsettings, label=titlelabel) sizerti = wx.StaticBoxSizer(boxti, wx.VERTICAL) sizerti.SetMinSize((horizontalsize, -1)) @@ -743,7 +731,7 @@ def settings(self): # in the Page info tool. # labels, parameters = mdls.GetHumanReadableParms(modelid, - self.active_parms[1]) + self.active_parms[1]) parameterstofit = self.active_parms[2] # Set initial values given by user/programmer for Diffusion Model for i in np.arange(len(labels)): @@ -769,17 +757,18 @@ def settings(self): box1.Add(horzs) # Set horizontal size box1.SetMinSize((horizontalsize, -1)) - ## More info - normbox = wx.StaticBox(self.panelsettings, label="Amplitude corrections") + # More info + normbox = wx.StaticBox( + self.panelsettings, label="Amplitude corrections") miscsizer = wx.StaticBoxSizer(normbox, wx.VERTICAL) miscsizer.SetMinSize((horizontalsize, -1)) # Intensities and Background sizeint = wx.FlexGridSizer(rows=3, cols=3, vgap=5, hgap=5) sizeint.Add(wx.StaticText(self.panelsettings, label="[kHz]")) sizeint.Add(wx.StaticText(self.panelsettings, - label="Intensity")) + label="Intensity")) sizeint.Add(wx.StaticText(self.panelsettings, - label="Background")) + label="Background")) sizeint.Add(wx.StaticText(self.panelsettings, label="Ch1")) intlabel1 = wx.TextCtrl(self.panelsettings) bgspin1 = wxutils.PCFFloatTextCtrl(self.panelsettings) @@ -797,18 +786,18 @@ def settings(self): sizeint.Add(intlabel2) sizeint.Add(bgspin2) miscsizer.Add(sizeint) - ## Normalize to n? + # Normalize to n? textnor = wx.StaticText(self.panelsettings, label="Plot normalization") miscsizer.Add(textnor) normtoNDropdown = wx.ComboBox(self.panelsettings) self.Bind(wx.EVT_COMBOBOX, self.PlotAll, normtoNDropdown) miscsizer.Add(normtoNDropdown) - self.AmplitudeInfo = [ [intlabel1, intlabel2], - [bgspin1, bgspin2], - normtoNDropdown, textnor] + self.AmplitudeInfo = [[intlabel1, intlabel2], + [bgspin1, bgspin2], + normtoNDropdown, textnor] self.WXAmplitudeCCOnlyStuff = [chtext2, intlabel2, bgspin2] self.panelsettings.sizer.Add(miscsizer, 0, wx.EXPAND, 0) - ## Add fitting Box + # Add fitting Box fitbox = wx.StaticBox(self.panelsettings, label="Fitting options") fitsizer = wx.StaticBoxSizer(fitbox, wx.VERTICAL) fitsizer.SetMinSize((horizontalsize, -1)) @@ -834,7 +823,8 @@ def settings(self): fitsizer.Add(fittext2) fitsizerspin = wx.BoxSizer(wx.HORIZONTAL) fittextvar = wx.StaticText(self.panelsettings, label="j = ") - fitspin = wx.SpinCtrl(self.panelsettings, -1, initial=3, min=1, max=100) + fitspin = wx.SpinCtrl(self.panelsettings, -1, + initial=3, min=1, max=100) fitsizerspin.Add(fittextvar) fitsizerspin.Add(fitspin) fitsizer.Add(fitsizerspin) @@ -854,8 +844,9 @@ def settings(self): self.Bind(wx.EVT_BUTTON, self.Fit_function, buttonfit) fitbuttonsizer.Add(buttonfit) - ## add shortcut - acctbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), buttonfit.GetId())]) + # add shortcut + acctbl = wx.AcceleratorTable( + [(wx.ACCEL_CTRL, ord('F'), buttonfit.GetId())]) self.SetAcceleratorTable(acctbl) ## @@ -870,16 +861,15 @@ def settings(self): self.panelsettings.Layout() self.panelsettings.Show() # Make all the stuff available for everyone - self.Fitbox = [ fitbox, weightedfitdrop, fittext, fittext2, - fittextvar, fitspin, buttonfit, textalg, - self.AlgorithmDropdown] + self.Fitbox = [fitbox, weightedfitdrop, fittext, fittext2, + fittextvar, fitspin, buttonfit, textalg, + self.AlgorithmDropdown] # Disable Fitting since no data has been loaded yet for element in self.Fitbox: element.Disable() self.panelsettings.sizer.Fit(self.panelsettings) self.parent.Layout() - def updateChi2(self): """ updates the self.WXTextChi2 text control @@ -892,5 +882,5 @@ def updateChi2(self): chi2str = wxutils.nice_string(chi2str) label = u" ĻĀ²={}".format(chi2str) # This does not work with wxPython 2.8.12: - #self.WXTextChi2.SetLabelMarkup(u"{}".format(label)) + # self.WXTextChi2.SetLabelMarkup(u"{}".format(label)) self.WXTextChi2.SetLabel(u"{}".format(label)) diff --git a/pycorrfit/gui/plotting.py b/pycorrfit/gui/plotting.py index 22b095be..e832facc 100644 --- a/pycorrfit/gui/plotting.py +++ b/pycorrfit/gui/plotting.py @@ -1,3 +1,9 @@ +from pycorrfit import models as mdls +from pycorrfit.meta import find_program +import unicodedata +from matplotlib import rcParams +import matplotlib.pyplot as plt +import matplotlib.gridspec as gridspec """Module plotting Everything about plotting with matplotlib is located here. @@ -13,15 +19,9 @@ with warnings.catch_warnings(): warnings.simplefilter("ignore") matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs -import matplotlib.gridspec as gridspec -import matplotlib.pyplot as plt # Text rendering with matplotlib -from matplotlib import rcParams -import unicodedata # For finding latex tools -from pycorrfit.meta import find_program -from pycorrfit import models as mdls def greek2tex(char): @@ -103,7 +103,7 @@ def latexmath(string): else: anew += char # lower case - lcitems = anew.split("_",1) + lcitems = anew.split("_", 1) if len(lcitems) > 1: anew = lcitems[0]+"_{\\text{"+lcitems[1]+"}}" return anew + r" \hspace{0.3em} \mathrm{"+b+r"}" @@ -154,7 +154,7 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, weights = Page.weights_plot_fill_area tabtitle = Page.tabtitle.GetValue() - #fitlabel = ur"Fit model: "+str(mdls.modeldict[Page.modelid][0]) + # fitlabel = ur"Fit model: "+str(mdls.modeldict[Page.modelid][0]) fitlabel = Page.corr.fit_model.name labelweights = r"Weights of fit" labels, parms = mdls.GetHumanReadableParms(Page.modelid, @@ -168,22 +168,23 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, if tabtitle.strip() == "": tabtitle = "page"+str(Page.counter).strip().strip(":") if Page.corr.normparm is not None: - fitlabel += r", normalized to "+Page.corr.fit_model.parameters[0][Page.corr.normparm] + fitlabel += r", normalized to " + \ + Page.corr.fit_model.parameters[0][Page.corr.normparm] - ## Check if we can use latex for plotting: + # Check if we can use latex for plotting: r1 = find_program("latex")[0] r2 = find_program("dvipng")[0] # Ghostscript r31 = find_program("gs")[0] - r32 = find_program("mgs")[0] # from miktex - r3 = max(r31,r32) + r32 = find_program("mgs")[0] # from miktex + r3 = max(r31, r32) if r1+r2+r3 < 3: uselatex = False if uselatex == True: rcParams['text.usetex'] = True rcParams['text.latex.unicode'] = True rcParams['font.family'] = 'serif' - rcParams['text.latex.preamble']=[r"""\usepackage{amsmath} + rcParams['text.latex.preamble'] = [r"""\usepackage{amsmath} \usepackage[utf8x]{inputenc} \usepackage{amssymb} \usepackage{siunitx}"""] @@ -191,31 +192,31 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, tabtitle = r"{\normalsize "+escapechars(tabtitle)+r"}" labelweights = r"{\normalsize "+escapechars(labelweights)+r"}" else: - rcParams['text.usetex']=False + rcParams['text.usetex'] = False # create plot # plt.plot(x, y, '.', label = 'original data', markersize=5) - fig=plt.figure() + fig = plt.figure() wtit = "Correlation #{:04d}_{}".format(int(Page.counter.strip(":# ")), - Page.title.strip()) + Page.title.strip()) fig.canvas.set_window_title(wtit) if resid is not None: - gs = gridspec.GridSpec(2, 1, height_ratios=[5,1]) + gs = gridspec.GridSpec(2, 1, height_ratios=[5, 1]) ax = plt.subplot(gs[0]) else: ax = plt.subplot(111) # ax = plt.axes() ax.semilogx() # plot fit first - plt.plot(fit[:,0], fit[:,1], '-', label=fitlabel, lw=1.5, + plt.plot(fit[:, 0], fit[:, 1], '-', label=fitlabel, lw=1.5, color="blue") if dataexp is not None: - plt.plot(dataexp[:,0], dataexp[:,1], '-', color="black", + plt.plot(dataexp[:, 0], dataexp[:, 1], '-', color="black", alpha=.7, label=tabtitle, lw=1) else: plt.xlabel(r'lag time $\tau$ [ms]') if weights is not None and show_weights is True: - plt.fill_between(weights[0][:,0],weights[0][:,1],weights[1][:,1], + plt.fill_between(weights[0][:, 0], weights[0][:, 1], weights[1][:, 1], color='cyan') # fake legend: p = plt.Rectangle((0, 0), 0, 0, color='cyan', @@ -223,16 +224,16 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, ax.add_patch(p) plt.ylabel('correlation') if dataexp is not None: - mind = np.min([ dataexp[:,1], fit[:,1]]) - maxd = np.max([ dataexp[:,1], fit[:,1]]) + mind = np.min([dataexp[:, 1], fit[:, 1]]) + maxd = np.max([dataexp[:, 1], fit[:, 1]]) else: - mind = np.min(fit[:,1]) - maxd = np.max(fit[:,1]) + mind = np.min(fit[:, 1]) + maxd = np.max(fit[:, 1]) ymin = mind - (maxd - mind)/20. ymax = maxd + (maxd - mind)/20. ax.set_ylim(bottom=ymin, top=ymax) - xmin = np.min(fit[:,0]) - xmax = np.max(fit[:,0]) + xmin = np.min(fit[:, 0]) + xmax = np.max(fit[:, 0]) ax.set_xlim(xmin, xmax) # Add some nice text: if uselatex == True and len(parms) != 0: @@ -240,8 +241,8 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, text += r'\[' text += r'\begin{split}' text += genLatexText(parms, labels) - ## According to issue #54, we remove fitting errors from plots - #if errparms is not None: + # According to issue #54, we remove fitting errors from plots + # if errparms is not None: # keys = errparms.keys() # keys.sort() # for key in keys: @@ -252,21 +253,19 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, text = r"" for i in np.arange(len(parms)): text += u"{} = {:.3g}\n".format(labels[i], parms[i]) - ## According to issue #54, we remove fitting errors from plots - #if errparms is not None: + # According to issue #54, we remove fitting errors from plots + # if errparms is not None: # keys = errparms.keys() # keys.sort() # for key in keys: # text += "Err "+key+" = " + str(errparms[key]) +"\n" - - logmax = np.log10(xmax) logmin = np.log10(xmin) logtext = 0.6*(logmax-logmin)+logmin xt = 10**(logtext) yt = 0.3*ymax - plt.text(xt,yt,text, size=12) + plt.text(xt, yt, text, size=12) if resid is not None: ax2 = plt.subplot(gs[1]) #ax2 = plt.axes() @@ -276,15 +275,15 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, lb = r"\newline \indent " else: lb = "\n" - yLabelRes = "weighted "+ lb +"residuals" + yLabelRes = "weighted " + lb + "residuals" else: yLabelRes = "residuals" - minx = np.min(resid[:,0]) - maxx = np.max(resid[:,0]) - miny = np.min(resid[:,1]) - maxy = np.max(resid[:,1]) + minx = np.min(resid[:, 0]) + maxx = np.max(resid[:, 0]) + miny = np.min(resid[:, 1]) + maxy = np.max(resid[:, 1]) plt.hlines(0, minx, maxx, colors="orange") - plt.plot(resid[:,0], resid[:,1], '-', color="black", + plt.plot(resid[:, 0], resid[:, 1], '-', color="black", alpha=.85, label=yLabelRes, lw=1) plt.xlabel(r'lag time $\tau$ [ms]') plt.ylabel(yLabelRes, multialignment='center') @@ -294,14 +293,13 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, ax2.set_ylim(-maxy, maxy) ticks = ax2.get_yticks() ax2.set_yticks([ticks[0], ticks[-1], 0]) - ## Hack + # Hack # We need this for hacking. See edclasses. fig.canvas.HACK_parent = parent fig.canvas.HACK_fig = fig fig.canvas.HACK_Page = Page fig.canvas.HACK_append = ".png" - # Legend outside of plot # Decrease size of plot to fit legend box = ax.get_position() @@ -312,11 +310,10 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False, if resid is not None: box2 = ax2.get_position() ax2.set_position([box2.x0, box2.y0 + box.height * 0.2, - box2.width, box2.height]) + box2.width, box2.height]) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.55), - prop={'size':9}) - + prop={'size': 9}) if verbose == True: plt.show() @@ -364,44 +361,44 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False): for ii, tr in enumerate(traces): labels.append("Channel {}: {}".format(ii+1, tr.name)) - ## Check if we can use latex for plotting: + # Check if we can use latex for plotting: r1 = find_program("latex")[0] r2 = find_program("dvipng")[0] # Ghostscript r31 = find_program("gs")[0] r32 = find_program("mgs")[0] - r3 = max(r31,r32) + r3 = max(r31, r32) if r1+r2+r3 < 3: uselatex = False if uselatex == True: - rcParams['text.usetex']=True - rcParams['text.latex.unicode']=True - rcParams['font.family']='serif' - rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"] + rcParams['text.usetex'] = True + rcParams['text.latex.unicode'] = True + rcParams['font.family'] = 'serif' + rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"] for i in np.arange(len(labels)): labels[i] = r"{\normalsize "+escapechars(labels[i])+r"}" else: - rcParams['text.usetex']=False + rcParams['text.usetex'] = False # create plot # plt.plot(x, y, '.', label = 'original data', markersize=5) - fig=plt.figure(figsize=(10,3)) + fig = plt.figure(figsize=(10, 3)) wtit = "Trace #{:04d}_{}".format(int(Page.counter.strip(":# ")), Page.title.strip()) fig.canvas.set_window_title(wtit) ax = plt.subplot(111) for i in np.arange(len(traces)): # Columns - time = traces[i][:,0]*timefactor - intensity = traces[i][:,1] + time = traces[i][:, 0]*timefactor + intensity = traces[i][:, 1] plt.plot(time, intensity, '-', - label = labels[i], + label=labels[i], lw=1) # set plot boundaries maxy = -np.infty miny = np.infty for tr in traces: - maxy = max(np.max(tr[:,1]), maxy) - miny = min(np.min(tr[:,1]), miny) + maxy = max(np.max(tr[:, 1]), maxy) + miny = min(np.min(tr[:, 1]), miny) ax.set_ylim(miny, maxy) plt.ylabel('count rate [kHz]') @@ -414,17 +411,17 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False): box.width, box.height * 0.9]) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35), - prop={'size':9}, + prop={'size': 9}, ) - ## Hack + # Hack # We need this for hacking. See edclasses. fig.canvas.HACK_parent = parent fig.canvas.HACK_fig = fig fig.canvas.HACK_Page = Page fig.canvas.HACK_append = "_trace.png" - plt.tight_layout(rect=(.001,.34,.999,1.0)) + plt.tight_layout(rect=(.001, .34, .999, 1.0)) if verbose == True: plt.show() @@ -441,5 +438,6 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False): except: pass + # set dpi to 300 matplotlib.rcParams['savefig.dpi'] = 300 diff --git a/pycorrfit/gui/threaded_progress.py b/pycorrfit/gui/threaded_progress.py index b78a9894..1d5029f3 100644 --- a/pycorrfit/gui/threaded_progress.py +++ b/pycorrfit/gui/threaded_progress.py @@ -20,6 +20,7 @@ class KThread(threading.Thread): thread will not actually be killed until the next Python statement is executed. """ + def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False @@ -53,9 +54,9 @@ def kill(self): self.killed = True - class WorkerThread(KThread): """Worker Thread Class.""" + def __init__(self, target, args, kwargs): """Init Worker Thread Class.""" KThread.__init__(self) @@ -134,21 +135,20 @@ def __init__(self, parent, targets, args=None, kwargs={}, elif isinstance(args, list): # convenience-convert args to tuples if not isinstance(args[0], tuple): - args = [ (t,) for t in args ] + args = [(t,) for t in args] if isinstance(kwargs, dict): kwargs = [kwargs]*nums if not messages: - messages = [ "item {} of {}".format(a+1, nums) for a in range(nums) ] - + messages = ["item {} of {}".format(a+1, nums) for a in range(nums)] time1 = time.time() - sty = wx.PD_SMOOTH|wx.PD_AUTO_HIDE|wx.PD_CAN_ABORT + sty = wx.PD_SMOOTH | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT if len(targets) > 1: - sty = sty|wx.PD_REMAINING_TIME + sty = sty | wx.PD_REMAINING_TIME dlgargs = [title, "initializing..."] - dlgkwargs = {"maximum":nums, "parent":parent, "style":sty } + dlgkwargs = {"maximum": nums, "parent": parent, "style": sty} dlg = None self.aborted = False @@ -166,7 +166,7 @@ def __init__(self, parent, targets, args=None, kwargs={}, dlg = wx.ProgressDialog(*dlgargs, **dlgkwargs) wx.EndBusyCursor() - init=False + init = False time.sleep(.01) if dlg: if len(targets) == 1: @@ -207,25 +207,25 @@ def finalize(self): pass - if __name__ == "__main__": # GUI Frame class that spins off the worker thread class MainFrame(wx.Frame): """Class MainFrame.""" + def __init__(self, parent, aid): """Create the MainFrame.""" wx.Frame.__init__(self, parent, aid, 'Thread Test') # Dumb sample frame with two buttons - but = wx.Button(self, wx.ID_ANY, 'Start Progress', pos=(0,0)) - + but = wx.Button(self, wx.ID_ANY, 'Start Progress', pos=(0, 0)) self.Bind(wx.EVT_BUTTON, self.OnStart, but) def OnStart(self, event): """Start Computation.""" # Trigger the worker thread unless it's already busy - arguments = [ test_class(a) for a in range(10) ] + arguments = [test_class(a) for a in range(10)] + def method(x): x.arg *= 1.1 time.sleep(1) @@ -233,9 +233,9 @@ def method(x): print(tp.index_aborted) print([a.arg for a in arguments]) - class MainApp(wx.App): """Class Main App.""" + def OnInit(self): """Init Main App.""" self.frame = MainFrame(None, -1) @@ -247,6 +247,5 @@ class test_class(object): def __init__(self, arg): self.arg = arg - app = MainApp(0) - app.MainLoop() \ No newline at end of file + app.MainLoop() diff --git a/pycorrfit/gui/tools/__init__.py b/pycorrfit/gui/tools/__init__.py index 4d9e68ea..4e48d82f 100644 --- a/pycorrfit/gui/tools/__init__.py +++ b/pycorrfit/gui/tools/__init__.py @@ -1,3 +1,7 @@ +from .parmrange import RangeSelector +from .comment import EditComment +from .chooseimport import ChooseImportTypesModel +from .chooseimport import ChooseImportTypes """PyCorrFit - module "tools" This file contains tools, such as dialog boxes and other stuff, @@ -38,42 +42,40 @@ # Load all of the classes # This also defines the order of the tools in the menu ImpA = [ - ["datarange", "SelectChannels"], - ["overlaycurves", "Wrapper_Tools"], - ["batchcontrol", "BatchCtrl"], - ["globalfit", "GlobalFit"], - ["average", "Average"], - ["background", "BackgroundCorrection"] - ] + ["datarange", "SelectChannels"], + ["overlaycurves", "Wrapper_Tools"], + ["batchcontrol", "BatchCtrl"], + ["globalfit", "GlobalFit"], + ["average", "Average"], + ["background", "BackgroundCorrection"] +] ImpB = [ - ["trace", "ShowTrace"], - ["statistics", "Stat"], - ["info", "ShowInfo"], - ["simulation", "Slide"] - ] + ["trace", "ShowTrace"], + ["statistics", "Stat"], + ["info", "ShowInfo"], + ["simulation", "Slide"] +] ModuleActive = list() ToolsActive = list() for i in np.arange(len(ImpA)): # We have to add "tools." because this is a relative import - ModuleActive.append(__import__(ImpA[i][0], globals(), locals(), [ImpA[i][1]], 1)) + ModuleActive.append(__import__( + ImpA[i][0], globals(), locals(), [ImpA[i][1]], 1)) ToolsActive.append(getattr(ModuleActive[i], ImpA[i][1])) ModulePassive = list() ToolsPassive = list() for i in np.arange(len(ImpB)): - ModulePassive.append(__import__(ImpB[i][0], globals(), locals(), [ImpB[i][1]], 1)) + ModulePassive.append(__import__( + ImpB[i][0], globals(), locals(), [ImpB[i][1]], 1)) ToolsPassive.append(getattr(ModulePassive[i], ImpB[i][1])) - #ModulePassive.append(importlib.import_module("tools."+ImpB[i][0])) + # ModulePassive.append(importlib.import_module("tools."+ImpB[i][0])) #ToolsPassive.append(getattr(ModulePassive[i], ImpB[i][1])) # This is in the file menu and not needed in the dictionaries below. -from .chooseimport import ChooseImportTypes -from .chooseimport import ChooseImportTypesModel -from .comment import EditComment # the "special" tool RangeSelector -from .parmrange import RangeSelector ToolDict = dict() ToolDict["A"] = ToolsActive @@ -93,4 +95,3 @@ ToolName = dict() ToolName["A"] = NameActive ToolName["P"] = NamePassive - diff --git a/pycorrfit/gui/tools/average.py b/pycorrfit/gui/tools/average.py index 348202c2..9af1777d 100644 --- a/pycorrfit/gui/tools/average.py +++ b/pycorrfit/gui/tools/average.py @@ -10,51 +10,52 @@ # Menu entry name MENUINFO = ["&Average data", "Create an average curve from whole session."] + class Average(wx.Frame): # This tool is derived from a wx.frame. def __init__(self, parent): # Define a unique name that identifies this tool # Do not change this value. It is important for the Overlay tool # (selectcurves.py, *Wrapper_Tools*). - self.MyName="AVERAGE" + self.MyName = "AVERAGE" # parent is the main frame of PyCorrFit self.parent = parent # Get the window positioning correctly pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Average curves", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) self.topSizer = wx.BoxSizer(wx.VERTICAL) textinit = wx.StaticText(self.panel, - label="Create an average from the following pages:") + label="Create an average from the following pages:") self.topSizer.Add(textinit) - ## Page selection + # Page selection self.WXTextPages = wx.TextCtrl(self.panel, value="", - size=(textinit.GetSize()[0],-1)) + size=(textinit.GetSize()[0], -1)) self.topSizer.Add(self.WXTextPages) - ## Chechbox asking for Mono-Model + # Chechbox asking for Mono-Model self.WXCheckMono = wx.CheckBox(self.panel, - label="Only use pages with the same model as the first page.") + label="Only use pages with the same model as the first page.") self.WXCheckMono.SetValue(True) self.topSizer.Add(self.WXCheckMono) - ## Model selection Dropdown + # Model selection Dropdown textinit2 = wx.StaticText(self.panel, - label="Select a model for the average:") + label="Select a model for the average:") self.topSizer.Add(textinit2) - self.WXDropSelMod = wx.ComboBox(self.panel, -1, "", (15,30), - wx.DefaultSize, [], wx.CB_DROPDOWN|wx.CB_READONLY) + self.WXDropSelMod = wx.ComboBox(self.panel, -1, "", (15, 30), + wx.DefaultSize, [], wx.CB_DROPDOWN | wx.CB_READONLY) self.topSizer.Add(self.WXDropSelMod) textinit3 = wx.StaticText(self.panel, - label="This tool averages only over pages with the same type"+\ - "\n(auto- or cross-correlation). Intensity data are"+\ - "\nappended sequentially.") + label="This tool averages only over pages with the same type" + + "\n(auto- or cross-correlation). Intensity data are" + + "\nappended sequentially.") self.topSizer.Add(textinit3) # Set all values of Text and Strin self.SetValues() @@ -65,13 +66,12 @@ def __init__(self, parent): self.panel.SetSizer(self.topSizer) self.topSizer.Fit(self) self.SetMinSize(self.topSizer.GetMinSize()) - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) self.OnPageChanged(self.Page) - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. @@ -79,7 +79,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnPageChanged(self, page, trigger=None): """ This function is called, when something in the panel @@ -102,12 +101,11 @@ def OnPageChanged(self, page, trigger=None): #idsel = self.WXDropSelMod.GetSelection() self.SetValues() # Set back user selection: - #self.WXDropSelMod.SetSelection(idsel) + # self.WXDropSelMod.SetSelection(idsel) self.panel.Enable() self.Page = page - def OnAverage(self, evt=None): strFull = self.WXTextPages.GetValue() PageNumbers = misc.parseString2Pagenum(self, strFull) @@ -128,8 +126,8 @@ def OnAverage(self, evt=None): if referencePage is None: # If that did not work, we have to raise an error. - raise IndexError("PyCorrFit could not find the first"+ - " page for averaging.") + raise IndexError("PyCorrFit could not find the first" + + " page for averaging.") return for i in np.arange(self.parent.notebook.GetPageCount()): @@ -141,8 +139,8 @@ def OnAverage(self, evt=None): # Get all pages with the same model? if self.WXCheckMono.GetValue() == True: if (model.id == referencePage.corr.fit_model.id and - corr.is_cc == referencePage.corr.is_cc): - ## Check if the page has experimental data: + corr.is_cc == referencePage.corr.is_cc): + # Check if the page has experimental data: # If there is an empty page somewhere, don't bother if corr.correlation is not None: pages.append(Page) @@ -155,14 +153,14 @@ def OnAverage(self, evt=None): UsedPagenumbers.append(int(j)) # If there are no pages in the list, exit gracefully if len(pages) <= 0: - texterr_a = "At least one page with experimental data is\n"+\ - "required for averaging. Please check the pages\n"+\ + texterr_a = "At least one page with experimental data is\n" +\ + "required for averaging. Please check the pages\n" +\ "that you selected for averaging." if self.WXCheckMono.GetValue() == True: - texterr_a += " Note: You selected\n"+\ - "to only use pages with same model as the first page." + texterr_a += " Note: You selected\n" +\ + "to only use pages with same model as the first page." wx.MessageDialog(self, texterr_a, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) return # Now get all the experimental data explist = list() @@ -170,7 +168,7 @@ def OnAverage(self, evt=None): tracetime = [np.array([]), np.array([])] tracerate = [np.array([]), np.array([])] TraceNumber = 0 - TraceAvailable = False # turns True, if pages contain traces + TraceAvailable = False # turns True, if pages contain traces for page in pages: corr = page.corr # experimental correlation curve @@ -191,35 +189,35 @@ def OnAverage(self, evt=None): # we assume that the first two points in a # trace are equidistant and we will use their # difference as an offset - offset = trace[j][:,0][1] - 2*trace[j][:,0][0] - newtracetime = 1.*trace[j][:,0] + offset + offset = trace[j][:, 0][1] - 2*trace[j][:, 0][0] + newtracetime = 1.*trace[j][:, 0] + offset newtracetime = newtracetime + oldend tracetime[j] = np.append(tracetime[j], newtracetime) del newtracetime - tracerate[j] = np.append(tracerate[j], trace[j][:,1]) + tracerate[j] = np.append(tracerate[j], trace[j][:, 1]) else: # Initiate the trace - tracetime[j] = 1.*trace[j][:,0] - tracerate[j] = 1.*trace[j][:,1] + tracetime[j] = 1.*trace[j][:, 0] + tracerate[j] = 1.*trace[j][:, 1] # Now check if the length of the correlation arrays are the same: len0 = len(explist[0]) for item in explist[1:]: if len(item) != len0: # print an error message wx.MessageDialog(self, - "Averaging over curves with different lengths is not"+\ - "\nsupported. When measuring, please make sure that"+\ - "\nthe measurement time for all curves is the same.", - "Error", style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + "Averaging over curves with different lengths is not" + + "\nsupported. When measuring, please make sure that" + + "\nthe measurement time for all curves is the same.", + "Error", style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) return # Now shorten the trace, because we want as little memory usage as # possible. I used this algorithm in read_FCS_Confocor3.py as well. newtraces = list() if TraceAvailable: for j in np.arange(TraceNumber): - tracej = np.zeros((len(tracetime[j]),2)) - tracej[:,0] = tracetime[j] - tracej[:,1] = tracerate[j] + tracej = np.zeros((len(tracetime[j]), 2)) + tracej[:, 0] = tracetime[j] + tracej[:, 1] = tracerate[j] if len(tracej) >= 500: # We want about 500 bins # We need to sum over intervals of length *teiler* @@ -229,43 +227,43 @@ def OnAverage(self, evt=None): # Simultaneously sum over all intervals for k in np.arange(teiler): newsignal = \ - newsignal+tracej[k:newlength*teiler:teiler][:,1] - newsignal = 1.* newsignal / teiler - newtimes = tracej[teiler-1:newlength*teiler:teiler][:,0] - if len(tracej)%teiler != 0: + newsignal+tracej[k:newlength*teiler:teiler][:, 1] + newsignal = 1. * newsignal / teiler + newtimes = tracej[teiler-1:newlength*teiler:teiler][:, 0] + if len(tracej) % teiler != 0: # We have a rest signal # We average it and add it to the trace - rest = tracej[newlength*teiler:][:,1] + rest = tracej[newlength*teiler:][:, 1] lrest = len(rest) rest = np.array([sum(rest)/lrest]) newsignal = np.concatenate((newsignal, rest), axis=0) timerest = np.array([tracej[-1][0]]) newtimes = np.concatenate((newtimes, timerest), axis=0) - newtrace=np.zeros((len(newtimes),2)) - newtrace[:,0] = newtimes - newtrace[:,1] = newsignal + newtrace = np.zeros((len(newtimes), 2)) + newtrace[:, 0] = newtimes + newtrace[:, 1] = newsignal else: # Declare newtrace - # otherwise we have a problem down three lines ;) newtrace = tracej newtraces.append(newtrace) else: - newtraces=[None,None] + newtraces = [None, None] # Everything is cleared for averaging exparray = np.array(explist) - averagedata = exparray.sum(axis=0)[:,1]/len(exparray) + averagedata = exparray.sum(axis=0)[:, 1]/len(exparray) # Create a copy from the first page average = 1*exparray[0] # Set average data - average[:,1] = averagedata + average[:, 1] = averagedata # create new page self.IsCrossCorrelation = self.Page.corr.is_cc interval = self.Page.corr.fit_ival # Obtain the model ID from the dropdown selection. idsel = self.WXDropSelMod.GetSelection() modelid = self.DropdownIndex[idsel] - self.AvgPage = self.parent.add_fitting_tab(modelid = modelid, - select = True) + self.AvgPage = self.parent.add_fitting_tab(modelid=modelid, + select=True) self.AvgPage.corr.fit_ival = interval self.AvgPage.corr.correlation = average if self.IsCrossCorrelation is False: @@ -287,12 +285,13 @@ def OnAverage(self, evt=None): newtabti = referencePage.tabtitle.GetValue() else: # Create a new tab title - newtabti = "Average ["+misc.parsePagenum2String(UsedPagenumbers)+"]" + newtabti = "Average [" + \ + misc.parsePagenum2String(UsedPagenumbers)+"]" self.AvgPage.tabtitle.SetValue(newtabti) # Set the addition information about the variance from averaging Listname = "Average" listname = Listname.lower() - standarddev = exparray.std(axis=0)[:,1] + standarddev = exparray.std(axis=0)[:, 1] if np.sum(np.abs(standarddev)) == 0: # The average sd is zero. We probably made an average # from only one page. In this case we do not enable @@ -310,7 +309,7 @@ def OnAverage(self, evt=None): # TODO: # find a cleaner solution extTypes.remove("none") - extTypes.sort() # sorting + extTypes.sort() # sorting for key in extTypes: try: WeightKinds.remove(key) @@ -339,8 +338,9 @@ def SetValues(self, e=None): pagenumlist = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) - pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + pagenumlist.append( + int("".join(filter(lambda x: x.isdigit(), Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) # Dropdown modelkeys = list(mdls.modeltypes.keys()) @@ -351,7 +351,7 @@ def SetValues(self, e=None): current_model = -1 i = 0 DropdownList = list() - self.DropdownIndex = list() # Contains model ids with same index + self.DropdownIndex = list() # Contains model ids with same index current_index = 0 for modeltype in modelkeys: for modelid in mdls.modeltypes[modeltype]: @@ -359,6 +359,6 @@ def SetValues(self, e=None): self.DropdownIndex.append(str(modelid)) if str(current_model) == str(modelid): current_index = i - i+=1 + i += 1 self.WXDropSelMod.SetItems(DropdownList) self.WXDropSelMod.SetSelection(current_index) diff --git a/pycorrfit/gui/tools/background.py b/pycorrfit/gui/tools/background.py index ca10b969..e8709545 100644 --- a/pycorrfit/gui/tools/background.py +++ b/pycorrfit/gui/tools/background.py @@ -16,17 +16,18 @@ # Menu entry name MENUINFO = ["&Background correction", "Open a file for background correction."] + class BackgroundCorrection(wx.Frame): def __init__(self, parent): - self.MyName="BACKGROUND" + self.MyName = "BACKGROUND" # Parent is main frame self.parent = parent # Get the window positioning correctly pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=parent, title="Background correction", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Current trace we are looking at @@ -37,65 +38,66 @@ def __init__(self, parent): self.oldtrace = None self.oldfilename = None self.average = None - ## Start drawing + # Start drawing # Splitter Window self.sp = wx.SplitterWindow(self, style=wx.SP_NOBORDER) - ## Controls + # Controls panel = wx.Panel(self.sp) # text1 backgroundinit = ( - "Correct the amplitude for non-correlated background.\n"+ - "The background intensity can be either imported\n"+ + "Correct the amplitude for non-correlated background.\n" + + "The background intensity can be either imported\n" + "from a blank measurement or set manually.") textinit = wx.StaticText(panel, label=backgroundinit) # Radio buttons self.rbtnfile = wx.RadioButton(panel, -1, 'Blank measurement: ', - style = wx.RB_GROUP) + style=wx.RB_GROUP) self.rbtnfile.SetValue(True) self.btnbrowse = wx.Button(panel, wx.ID_ANY, 'Browse ...') - self.rbtnhand = wx.RadioButton (panel, -1, 'Manual, [kHz]: ') + self.rbtnhand = wx.RadioButton(panel, -1, 'Manual, [kHz]: ') # Spincontrol self.spinctrl = floatspin.FloatSpin(panel, digits=4, min_val=0, increment=.01) self.spinctrl.Enable(False) # Verbose text self.textfile = wx.StaticText(panel, - label="No blank measurement file selected.") + label="No blank measurement file selected.") textmeanavg = wx.StaticText(panel, label="Average background signal [kHz]: ") self.textmean = wx.StaticText(panel, label="") # name textname = wx.StaticText(panel, label="User defined background name: ") sizeTextn = textname.GetSize()[0] - self.bgname = wx.TextCtrl(panel, value="", size=(sizeTextn,-1)) + self.bgname = wx.TextCtrl(panel, value="", size=(sizeTextn, -1)) self.bgname.Enable(False) self.btnimport = wx.Button(panel, wx.ID_ANY, 'Import into session') self.btnimport.Enable(False) # Dropdown - self.BGlist = ["File/User"] # updated by self.UpdateDropdown() + self.BGlist = ["File/User"] # updated by self.UpdateDropdown() textdropdown = wx.StaticText(panel, label="Show background: ") self.dropdown = wx.ComboBox(panel, -1, "File/User", (15, -1), - wx.DefaultSize, self.BGlist, wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, self.BGlist, wx.CB_DROPDOWN | wx.CB_READONLY) self.UpdateDropdown() # Radio buttons Channel1 and 2 - self.rbtnCh1 = wx.RadioButton (panel, -1, 'Ch1 ', - style = wx.RB_GROUP) + self.rbtnCh1 = wx.RadioButton(panel, -1, 'Ch1 ', + style=wx.RB_GROUP) self.rbtnCh1.SetValue(True) - self.rbtnCh2 = wx.RadioButton (panel, -1, 'Ch2') + self.rbtnCh2 = wx.RadioButton(panel, -1, 'Ch2') # Apply buttons self.btnapply = wx.Button(panel, wx.ID_ANY, 'Apply') textor = wx.StaticText(panel, label=" or ") self.btnrem = wx.Button(panel, wx.ID_ANY, 'Dismiss') - textpages = wx.StaticText(panel, label=" correction for pages: ") + textpages = wx.StaticText(panel, label=" correction for pages: ") self.WXTextPages = wx.TextCtrl(panel, value="") # Initial value for WXTextPages pagenumlist = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) - pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + pagenumlist.append( + int("".join(filter(lambda x: x.isdigit(), Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) - textyma = wx.StaticText(panel, label="Shortcut - ") + textyma = wx.StaticText(panel, label="Shortcut - ") self.btnapplyall = wx.Button(panel, wx.ID_ANY, 'Apply to all pages') textor2 = wx.StaticText(panel, label=" or ") self.btnremyall = wx.Button(panel, wx.ID_ANY, 'Dismiss from all pages') @@ -126,7 +128,7 @@ def __init__(self, parent): droprightsizer = wx.BoxSizer(wx.VERTICAL) dropsizer.Add(droprightsizer) droprightsizer.Add(self.dropdown) - #droprightsizer.Add(self.textafterdropdown) + # droprightsizer.Add(self.textafterdropdown) applysizer = wx.BoxSizer(wx.HORIZONTAL) applysizer.Add(self.btnapply) applysizer.Add(textor) @@ -156,11 +158,11 @@ def __init__(self, parent): topSizer.Fit(self) self.SetMinSize(topSizer.GetMinSize()) self.Show(True) - ## Canvas + # Canvas self.canvas = plot.PlotCanvas(self.sp) # Sizes psize = panel.GetBestSize() - initial_size = (psize[0],psize[1]+200) + initial_size = (psize[0], psize[1]+200) self.SetSize(initial_size) sashsize = psize[1]+3 # This is also necessary to prevent unsplitting @@ -168,11 +170,10 @@ def __init__(self, parent): self.sp.SplitHorizontally(panel, self.canvas, sashsize) # If there is no page, disable ourselves: self.OnPageChanged(self.parent.notebook.GetCurrentPage()) - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) - def Apply(self, Page, backgroundid): if self.rbtnCh1.GetValue() == True: Page.bgselected = backgroundid @@ -182,7 +183,6 @@ def Apply(self, Page, backgroundid): # Autocorrelation only has one background! Page.bg2selected = None - def OnApply(self, event): strFull = self.WXTextPages.GetValue() PageNumbers = misc.parseString2Pagenum(self, strFull) @@ -203,7 +203,6 @@ def OnApply(self, event): # Clean up unused backgrounds CleanupAutomaticBackground(self.parent) - def OnApplyAll(self, event): self.btnrem.Enable(True) self.btnremyall.Enable(True) @@ -217,23 +216,21 @@ def OnApplyAll(self, event): Page.OnAmplitudeCheck("init") Page.PlotAll() except OverflowError: - errstr = "Could not apply background to Page "+Page.counter+\ - ". \n Check the value of the trace average and the background." + errstr = "Could not apply background to Page "+Page.counter +\ + ". \n Check the value of the trace average and the background." dlg = wx.MessageDialog(self, errstr, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) dlg.ShowModal() Page.bgselected = None Page.bg2selected = None # Clean up unused backgrounds CleanupAutomaticBackground(self.parent) - def OnClose(self, event=None): self.parent.toolmenu.Check(self.MyID, False) self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnBrowse(self, event): # filetypes_bg_dict is a dictionary with filetypes that have some # trace signal information. @@ -247,7 +244,7 @@ def OnBrowse(self, event): # Add a separator filters = filters+"|" dlg = wx.FileDialog(self, "Choose a data file", - self.parent.dirname, "", filters, wx.FD_OPEN) + self.parent.dirname, "", filters, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: # Workaround since 0.7.5 (dirname, filename) = os.path.split(dlg.GetPath()) @@ -268,7 +265,7 @@ def OnBrowse(self, event): for tb_item in traceback.format_tb(info[2]): errstr += tb_item wx.MessageDialog(self, errstr, "Error", - style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP) + style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP) return # Usually we will get a bunch of traces. Let the user select which # one to take. @@ -288,12 +285,12 @@ def OnBrowse(self, event): # If we accidentally recorded a cross correlation curve # as the background, let the user choose which trace he wants: channelindex = None - if ( len(stuff["Type"][selindex]) >= 2 and - stuff["Type"][selindex][0:2] == "CC" ): + if (len(stuff["Type"][selindex]) >= 2 and + stuff["Type"][selindex][0:2] == "CC"): choices = ["Channel 1", "Channel 2"] label = "From which channel do you want to use the trace?" dlg = wx.SingleChoiceDialog(self, label, - "Curve selection", choices=choices) + "Curve selection", choices=choices) if dlg.ShowModal() == wx.ID_OK: channelindex = dlg.GetSelection() trace = stuff["Trace"][selindex][channelindex] @@ -306,15 +303,15 @@ def OnBrowse(self, event): return # Display filename and some of the directory self.textfile.SetLabel("File: ..."+dirname[-10:]+"/"+filename) - name = str(selindex)+". "+stuff["Filename"][selindex]+" "+\ - stuff["Type"][selindex] + name = str(selindex)+". "+stuff["Filename"][selindex]+" " +\ + stuff["Type"][selindex] if channelindex is not None: name += " "+str(channelindex+1) self.bgname.SetValue(name) self.trace = trace # Calculate average - self.average = self.trace[:,1].mean() + self.average = self.trace[:, 1].mean() # Display average self.textmean.SetLabel(str(self.average)+" kHz") self.spinctrl.SetValue(self.average) @@ -340,9 +337,9 @@ def OnDraw(self, event=None): # Draw the trace that was just imported if self.trace and self.trace.all(): # It is enougth to check that you have an array # Calculate average - self.average = self.trace[:,1].mean() + self.average = self.trace[:, 1].mean() self.activetrace = self.trace - #self.textafterdropdown.SetLabel(" Avg: "+str(self.average)+ + # self.textafterdropdown.SetLabel(" Avg: "+str(self.average)+ # " kHz") self.textmean.SetLabel(str(self.average)) self.spinctrl.SetValue(self.average) @@ -350,7 +347,7 @@ def OnDraw(self, event=None): # Clear the canvas. Looks better. self.canvas.Clear() # Don't show the average - #self.textafterdropdown.SetLabel("") + # self.textafterdropdown.SetLabel("") self.textmean.SetLabel("") return else: @@ -361,18 +358,18 @@ def OnDraw(self, event=None): self.activetrace = self.parent.Background[item-1].trace # We want to have the trace in [s] here. trace = 1.*self.activetrace - trace[:,0] = trace[:,0]/1000 + trace[:, 0] = trace[:, 0]/1000 linesig = plot.PolyLine(trace, legend='', colour='blue', width=1) self.canvas.Draw(plot.PlotGraphics([linesig], - xLabel='time [s]', - yLabel='background signal [kHz]')) - + xLabel='time [s]', + yLabel='background signal [kHz]')) def OnImport(self, event): - self.parent.Background.append(Trace(trace=self.trace, name=self.bgname.GetValue())) + self.parent.Background.append( + Trace(trace=self.trace, name=self.bgname.GetValue())) # Next two lines are taken care of by UpdateDropdown #name = "{} ({:.2f} kHz)".format(self.bgname.GetValue(), self.average) - #self.BGlist.append(name) + # self.BGlist.append(name) self.UpdateDropdown() self.btnremyall.Enable(True) self.btnrem.Enable(True) @@ -383,7 +380,6 @@ def OnImport(self, event): for i in np.arange(self.parent.notebook.GetPageCount()): self.parent.notebook.GetPage(i).OnAmplitudeCheck() - def OnPageChanged(self, page=None, trigger=None): """ This function is called, when something in the panel @@ -416,17 +412,16 @@ def OnPageChanged(self, page=None, trigger=None): self.btnapply.Enable(True) self.btnapplyall.Enable(True) if (self.WXTextPages.GetValue() == "" - and self.parent.notebook.GetPageCount() != 0): + and self.parent.notebook.GetPageCount() != 0): # Initial value for WXTextPages pagenumlist = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) - pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + pagenumlist.append( + int("".join(filter(lambda x: x.isdigit(), Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) - - def OnRadioFile(self, event): # Do not let the user change the spinctrl # setting. @@ -444,7 +439,6 @@ def OnRadioFile(self, event): self.dropdown.SetSelection(0) self.OnDraw() - def OnRadioHand(self, event): # Let user enter a signal. self.spinctrl.Enable(True) @@ -463,7 +457,6 @@ def OnRadioHand(self, event): # Enter something as name self.bgname.SetValue("User") - def OnRemove(self, event): strFull = self.WXTextPages.GetValue() PageNumbers = misc.parseString2Pagenum(self, strFull) @@ -488,7 +481,6 @@ def OnRemove(self, event): # Clean up unused backgrounds CleanupAutomaticBackground(self.parent) - def OnRemoveAll(self, event): N = self.parent.notebook.GetPageCount() for i in np.arange(N): @@ -503,18 +495,16 @@ def OnRemoveAll(self, event): def SetPageNumbers(self, pagestring): self.WXTextPages.SetValue(pagestring) - def SpinCtrlChange(self, event=None): # Let user see the continuous trace we will generate self.average = self.spinctrl.GetValue() - self.trace = np.array([[0,self.average],[1,self.average]]) + self.trace = np.array([[0, self.average], [1, self.average]]) self.textmean.SetLabel(str(self.average)) self.OnDraw() - def UpdateDropdown(self, e=None): self.BGlist = list() - #self.BGlist.append("File/User") + # self.BGlist.append("File/User") for item in self.parent.Background: self.BGlist.append(item.name) self.dropdown.SetItems(self.BGlist) @@ -544,11 +534,12 @@ def ApplyAutomaticBackground(page, bg, parent): # Check if exists: for i in range(len(parent.Background)): if (parent.Background[i].countrate == bglist[b] and - parent.Background[i].name == bgname): + parent.Background[i].name == bgname): bgid[b] = i if bgid[b] == -1: # Add new background - parent.Background.append(Trace(countrate=bglist[b], name=bgname, duration=1)) + parent.Background.append( + Trace(countrate=bglist[b], name=bgname, duration=1)) bgid[b] = len(parent.Background) - 1 # Apply background to page diff --git a/pycorrfit/gui/tools/batchcontrol.py b/pycorrfit/gui/tools/batchcontrol.py index b3031bd0..a606c5a4 100644 --- a/pycorrfit/gui/tools/batchcontrol.py +++ b/pycorrfit/gui/tools/batchcontrol.py @@ -22,19 +22,19 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=parent, title="Batch control", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None - ## Misc + # Misc try: self.curpage = self.parent.notebook.GetCurrentPage() except: self.curpage = None - ## Controls + # Controls panel = wx.Panel(self) self.panel = panel - #Icon + # Icon self.Redraw() if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) @@ -64,7 +64,7 @@ def GetProtectedParameterIDs(self): """ The model parameters that are protected from batch control """ - pbool = [ not cb.GetValue() for cb in self.wxParameterCheckBoxes ] + pbool = [not cb.GetValue() for cb in self.wxParameterCheckBoxes] return np.array(pbool, dtype=bool) def OnApply(self, event): @@ -75,7 +75,7 @@ def OnApply(self, event): for i in np.arange(self.parent.notebook.GetPageCount()): OtherPage = self.parent.notebook.GetPage(i) if (OtherPage.corr.fit_model.id == modelid and - OtherPage.corr.correlation is not None): + OtherPage.corr.correlation is not None): # create a copy of the fitting parameters in # case we want to protect them proparms = OtherPage.corr.fit_parameters @@ -116,7 +116,7 @@ def OnFit(self, event): for ii in np.arange(self.parent.notebook.GetPageCount()): pageii = self.parent.notebook.GetPage(ii) if (pageii.corr.fit_model.id == modelid and - pageii.corr.correlation is not None): + pageii.corr.correlation is not None): fit_page_list.append(pageii) FitProgressDlg(self, fit_page_list, trigger="fit_batch") @@ -125,7 +125,6 @@ def OnFit(self, event): # Autoclose self.OnClose() - def OnPageChanged(self, Page=None, trigger=None): """ This function is called, when something in the panel @@ -176,7 +175,7 @@ def OnRadioThere(self, event=None): # to be changed. wc = opf.session_wildcards wcstring = "PyCorrFit session (*.pcfs)|*{};*{}".format( - wc[0], wc[1]) + wc[0], wc[1]) dlg = wx.FileDialog(self.parent, "Open session file", self.parent.dirname, "", wcstring, wx.FD_OPEN) # user cannot do anything until he clicks "OK" @@ -184,7 +183,7 @@ def OnRadioThere(self, event=None): sessionfile = dlg.GetPath() self.dirname = os.path.split(sessionfile)[0] else: - self.parent.dirname=dlg.GetDirectory() + self.parent.dirname = dlg.GetDirectory() self.rbtnhere.SetValue(True) return @@ -208,14 +207,14 @@ def Redraw(self, e=None): panel.RemoveChild(child) child.Destroy() - ## Parameter source selection + # Parameter source selection boxleft = wx.StaticBox(panel, label="Parameter source") self.rbtnhere = wx.RadioButton(panel, -1, 'This session', - style = wx.RB_GROUP) + style=wx.RB_GROUP) self.rbtnhere.SetValue(True) self.rbtnthere = wx.RadioButton(panel, -1, 'Other session') self.dropdown = wx.ComboBox(panel, -1, "Current page", (15, 30), - wx.DefaultSize, [], wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, [], wx.CB_DROPDOWN | wx.CB_READONLY) # Create the dropdownlist text2 = wx.StaticText(panel, label="""Only data sets that have the same model as the parameter @@ -241,27 +240,27 @@ def Redraw(self, e=None): leftSizer.Add(text2) leftSizer.AddSpacer(5) - ## Parameter selection + # Parameter selection boxright = wx.StaticBox(panel, label="Selected parameters") rightSizer = wx.StaticBoxSizer(boxright, wx.VERTICAL) self.parameter_sizer = rightSizer self.RedrawParameterBox() - ## Buttons + # Buttons btnapply = wx.Button(panel, wx.ID_ANY, 'Apply to applicable pages') btnfit = wx.Button(panel, wx.ID_ANY, 'Fit applicable pages') # Bindings self.Bind(wx.EVT_BUTTON, self.OnApply, btnapply) self.Bind(wx.EVT_BUTTON, self.OnFit, btnfit) - ## Sizers + # Sizers sizer_bag = wx.GridBagSizer(hgap=5, vgap=5) - sizer_bag.Add(leftSizer, (0,0)) - sizer_bag.Add(rightSizer, (0,1)) + sizer_bag.Add(leftSizer, (0, 0)) + sizer_bag.Add(rightSizer, (0, 1)) horsizer = wx.BoxSizer(wx.HORIZONTAL) horsizer.Add(btnapply) horsizer.Add(btnfit) - sizer_bag.Add(horsizer, (1,0), span=wx.GBSpan(1,2)) + sizer_bag.Add(horsizer, (1, 0), span=wx.GBSpan(1, 2)) panel.SetSizer(sizer_bag) sizer_bag.Fit(panel) @@ -292,7 +291,7 @@ def RedrawParameterBox(self, e=None): parms = self.GetParameters() modelid = parms[1] ptext, _pval = mdls.GetHumanReadableParms(modelid, parms[2]) - ptext = [ p.split()[0] for p in ptext ] + ptext = [p.split()[0] for p in ptext] self.wxParameterCheckBoxes = [] for p in ptext: cb = wx.CheckBox(panel, label=p) @@ -316,6 +315,7 @@ def RedrawParameterBox(self, e=None): except: pass + class FitProgressDlg(ThreadedProgressDlg): def __init__(self, parent, pages, trigger=None): """ A progress dialog for fitting in PyCorrFit @@ -337,11 +337,12 @@ def __init__(self, parent, pages, trigger=None): self.pages = pages self.trigger = trigger title = "Fitting data" - messages = [ "Fitting page #{}.".format(pi.counter.strip("# :")) for pi in pages ] + messages = ["Fitting page #{}.".format( + pi.counter.strip("# :")) for pi in pages] targets = [Fit]*len(pages) args = [pi.corr for pi in pages] # write parameters from page instance to correlation - [ pi.apply_parameters() for pi in self.pages ] + [pi.apply_parameters() for pi in self.pages] super(FitProgressDlg, self).__init__(parent, targets, args, title=title, messages=messages) @@ -351,8 +352,8 @@ def finalize(self): cleanup of non-fitted pages. """ if self.aborted: - ## we need to cleanup - fin_index = max(0,self.index_aborted-1) + # we need to cleanup + fin_index = max(0, self.index_aborted-1) pab = self.pages[self.index_aborted] pab.fit_results = None pab.apply_parameters() @@ -360,4 +361,5 @@ def finalize(self): fin_index = len(self.pages) # finalize fitting - [ pi.Fit_finalize(trigger=self.trigger) for pi in self.pages[:fin_index] ] + [pi.Fit_finalize(trigger=self.trigger) + for pi in self.pages[:fin_index]] diff --git a/pycorrfit/gui/tools/chooseimport.py b/pycorrfit/gui/tools/chooseimport.py index ac7c38ba..109192b1 100644 --- a/pycorrfit/gui/tools/chooseimport.py +++ b/pycorrfit/gui/tools/chooseimport.py @@ -15,21 +15,22 @@ class ChooseImportTypes(wx.Dialog): The model function is defined by the model that is in use. """ # This tool is derived from a wx.Dialog. + def __init__(self, parent, curvedict): # parent is the main frame of PyCorrFit self.parent = parent # init - #super(ChooseImportTypes, self).__init__(parent=parent, + # super(ChooseImportTypes, self).__init__(parent=parent, # title="Choose types", size=(250, 200)) wx.Dialog.__init__(self, parent, -1, "Choose models") self.keys = list() - ## Content + # Content self.panel = wx.Panel(self) self.sizer = wx.BoxSizer(wx.VERTICAL) self.boxes = dict() # For the selection of types to import when doing import Data - chooseimport = ("Several types of data were found in\n"+ - "the chosen file. Please select what\n"+ + chooseimport = ("Several types of data were found in\n" + + "the chosen file. Please select what\n" + "type(s) you would like to import.") textinit = wx.StaticText(self.panel, label=chooseimport) self.sizer.Add(textinit) @@ -47,21 +48,19 @@ def __init__(self, parent, curvedict): self.sizer.Add(btnok) self.panel.SetSizer(self.sizer) self.sizer.Fit(self) - #Icon + # Icon if parent.MainIcon is not None: wx.Dialog.SetIcon(self, parent.MainIcon) - #self.Show(True) + # self.Show(True) self.SetFocus() - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. self.EndModal(wx.ID_OK) - #self.Destroy() + # self.Destroy() - - def OnSetkeys(self, event = None): + def OnSetkeys(self, event=None): self.keys = list() for key in self.boxes.keys(): if self.boxes[key].Value == True: @@ -73,6 +72,7 @@ class ChooseImportTypesModel(wx.Dialog): model function on import of data """ # This tool is derived from a wx.frame. + def __init__(self, parent, curvedict, correlations, labels=None): """ curvedict - dictionary, contains indexes to correlations and labels. The keys are different types of curves @@ -83,18 +83,18 @@ def __init__(self, parent, curvedict, correlations, labels=None): # parent is the main frame of PyCorrFit self.parent = parent # init - #super(ChooseImportTypesModel, self).__init__(parent=parent, + # super(ChooseImportTypesModel, self).__init__(parent=parent, # title="Choose types", size=(250, 200)) wx.Dialog.__init__(self, parent, -1, "Choose models") self.curvedict = curvedict - self.kept_curvedict = curvedict.copy() # Can be edited by user + self.kept_curvedict = curvedict.copy() # Can be edited by user self.correlations = correlations self.labels = labels # List of keys that will be imported by our *parent* self.typekeys = list() # Dictionary of modelids corresponding to indices in curvedict self.modelids = dict() - ## Content + # Content self.panel = wx.Panel(self) self.sizer = wx.BoxSizer(wx.VERTICAL) self.boxes = dict() @@ -105,7 +105,8 @@ def __init__(self, parent, curvedict, correlations, labels=None): curvekeys.sort() self.curvekeys = curvekeys # Dropdown model selections: - DropdownList = ["No model selected"] # Contains string in model dropdown + # Contains string in model dropdown + DropdownList = ["No model selected"] self.DropdownIndex = [None] # Contains corresponsing model modelkeys = list(mdls.modeltypes.keys()) modelkeys.sort() @@ -114,22 +115,23 @@ def __init__(self, parent, curvedict, correlations, labels=None): DropdownList.append(modeltype+": "+mdls.modeldict[modelid][1]) self.DropdownIndex.append(modelid) self.ModelDropdown = dict() - dropsizer = wx.FlexGridSizer(rows=len(modelkeys), cols=3, vgap=5, hgap=5) + dropsizer = wx.FlexGridSizer( + rows=len(modelkeys), cols=3, vgap=5, hgap=5) self.Buttons = list() i = 8000 for key in curvekeys: # Text with keys and numer of curves - dropsizer.Add( wx.StaticText(self.panel, label=str(key)) ) - label=" ("+str(len(curvedict[key]))+" curves)" + dropsizer.Add(wx.StaticText(self.panel, label=str(key))) + label = " ("+str(len(curvedict[key]))+" curves)" button = wx.Button(self.panel, i, label) i += 1 self.Bind(wx.EVT_BUTTON, self.OnSelectCurves, button) self.Buttons.append(button) dropsizer.Add(button) # Model selection dropdown - dropdown = wx.ComboBox(self.panel, -1, DropdownList[0], (15,30), - wx.DefaultSize, DropdownList, wx.CB_DROPDOWN|wx.CB_READONLY) - dropsizer.Add( dropdown ) + dropdown = wx.ComboBox(self.panel, -1, DropdownList[0], (15, 30), + wx.DefaultSize, DropdownList, wx.CB_DROPDOWN | wx.CB_READONLY) + dropsizer.Add(dropdown) self.ModelDropdown[key] = dropdown self.Bind(wx.EVT_COMBOBOX, self.OnSetkeys, dropdown) self.sizer.Add(dropsizer) @@ -139,13 +141,11 @@ def __init__(self, parent, curvedict, correlations, labels=None): self.sizer.Add(btnok) self.panel.SetSizer(self.sizer) self.sizer.Fit(self) - #self.Show(True) + # self.Show(True) self.SetFocus() if parent.MainIcon is not None: wx.Dialog.SetIcon(self, parent.MainIcon) - - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. @@ -156,9 +156,8 @@ def OnClose(self, event=None): self.keepcurvesindex[i] = int(self.keepcurvesindex[i]) self.EndModal(wx.ID_OK) - #self.Show - #self.Destroy() - + # self.Show + # self.Destroy() def OnSelectCurves(self, buttonevent): # Get the type of curves we want to look at @@ -179,8 +178,8 @@ def OnSelectCurves(self, buttonevent): for item in self.kept_curvedict.keys(): prev_selected += self.kept_curvedict[item] overlaycurves.Wrapper_OnImport(self.parent, corrcurves, - self.OnSelected, prev_selected, - labels=labeldict) + self.OnSelected, prev_selected, + labels=labeldict) def OnSelected(self, keep, remove): # Set new button label @@ -188,7 +187,7 @@ def OnSelected(self, keep, remove): keep[i] = int(keep[i]) #button = self.Buttons[self.buttonindex] label = " ("+str(len(keep))+" curves)" - #button.SetLabel(label) + # button.SetLabel(label) # Add new content to selected key SelectedKey = self.curvekeys[self.buttonindex] #self.kept_curvedict[SelectedKey] = keep @@ -212,8 +211,7 @@ def OnSelected(self, keep, remove): button = self.Buttons[j] button.SetLabel(label) - - def OnSetkeys(self, event = None): + def OnSetkeys(self, event=None): # initiate objects self.typekeys = list() self.modelids = dict() @@ -232,8 +230,3 @@ def OnSetkeys(self, event = None): # Set different model id for the curves self.modelids[index] = modelid self.typekeys.sort() - - - - - diff --git a/pycorrfit/gui/tools/comment.py b/pycorrfit/gui/tools/comment.py index 2fd00c06..c0c60a8f 100755 --- a/pycorrfit/gui/tools/comment.py +++ b/pycorrfit/gui/tools/comment.py @@ -4,26 +4,27 @@ class EditComment(wx.Frame): """ Little Dialog to edit the comment on the session. """ + def __init__(self, parent): - ## Variables + # Variables # parent is main frame self.parent = parent # Get the window positioning correctly pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=parent, title="Session comment", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - initial_size = (400,300) + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + initial_size = (400, 300) initial_sizec = (initial_size[0], initial_size[1]-50) self.SetSize(initial_size) - self.SetMinSize((400,300)) - ## Content + self.SetMinSize((400, 300)) + # Content self.panel = wx.Panel(self) self.control = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE, - size=initial_sizec, value=self.parent.SessionComment) + size=initial_sizec, value=self.parent.SessionComment) self.Bind(wx.EVT_TEXT, self.OnTextChanged, self.control) text = wx.StaticText(self.panel, - label="Session comments will be saved in the session file.") + label="Session comments will be saved in the session file.") # buttons btnsave = wx.Button(self.panel, wx.ID_SAVE, 'Save Comment') self.Bind(wx.EVT_BUTTON, self.OnSave, btnsave) diff --git a/pycorrfit/gui/tools/datarange.py b/pycorrfit/gui/tools/datarange.py index 1d5f1fac..3b465fa9 100644 --- a/pycorrfit/gui/tools/datarange.py +++ b/pycorrfit/gui/tools/datarange.py @@ -7,6 +7,7 @@ MENUINFO = ["&Data range", "Select an interval of lag times to be used for fitting."] + class SelectChannels(wx.Frame): def __init__(self, parent): # parent is main frame @@ -15,23 +16,23 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Data range selection", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None - ## Start drawing + # Start drawing panel = wx.Panel(self) self.panel = panel # Page self.Page = self.parent.notebook.GetCurrentPage() self.Calc_init(self.Page) - text1 = wx.StaticText(panel, label=u"The lag times Ļ are stored as an "+ + text1 = wx.StaticText(panel, label=u"The lag times Ļ are stored as an " + u"array of length ") self.textend = wx.StaticText(panel, label="%d." % self.lentau) text2 = wx.StaticText(panel, - label=u"You may wish to confine this array. "+ + label=u"You may wish to confine this array. " + u"This can be done here.") - ##Spincontrols: + # Spincontrols: FlexSpinSizer = wx.FlexGridSizer(rows=2, cols=4, vgap=5, hgap=5) FlexSpinSizer.Add(wx.StaticText(panel, label="Channels:")) self.spinstart = wx.SpinCtrl(panel, -1, initial=self.left, @@ -58,7 +59,7 @@ def __init__(self, parent): self.Bind(wx.EVT_SPINCTRL, self.OnChangeChannels, self.spinstart) # Checkbox self.fixcheck = wx.CheckBox(panel, -1, - label="Fix current channel selection for all pages.") + label="Fix current channel selection for all pages.") self.Bind(wx.EVT_CHECKBOX, self.OnCheckbox, self.fixcheck) # Text channelsel = "Leave this window open for a fixed selection." @@ -84,16 +85,15 @@ def __init__(self, parent): self.SetMinSize(topSizer.GetMinSize()) # Get times. self.OnChangeChannels() - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) # Show window self.Show(True) self.OnPageChanged(self.Page) - def Calc_init(self, parent): - ## Variables + # Variables # Parent should be the fitting panel - # The tab, where the fitting is done. self.Page = parent @@ -118,14 +118,12 @@ def Calc_init(self, parent): # set the maximum possible value self.right = self.end0 else: - self.right -=1 - + self.right -= 1 def OnApply(self, event=None): self.SetValues() self.Page.PlotAll() - def OnApplyAll(self, event=None): N = self.parent.notebook.GetPageCount() for i in np.arange(N): @@ -141,7 +139,6 @@ def OnApplyAll(self, event=None): # Autoclose self.OnClose() - def OnChangeTimes(self, e=None): """ Called, whenever data range in seconds is changed. This updates the data range in channels in the window. @@ -149,7 +146,6 @@ def OnChangeTimes(self, e=None): """ pass - def OnChangeChannels(self, e=None): """ Called, whenever data range in channels is changed. This updates the data range in seconds in the window. @@ -169,7 +165,6 @@ def OnChangeChannels(self, e=None): self.TextTimesEnd.SetLabel("%.4e" % t2) self.OnCheckbox() - def OnCheckbox(self, event=None): """ Set the correct value in the spincontrol, if the checkbox is not checked. @@ -182,15 +177,13 @@ def OnCheckbox(self, event=None): else: self.ButtonApply.Enable() self.ButtonApplyAll.Enable() - #self.OnPageChanged(self.Page) - + # self.OnPageChanged(self.Page) def OnClose(self, event=None): self.parent.toolmenu.Check(self.MyID, False) self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnPageChanged(self, page, trigger=None): # We do not need the *Range* Commands here yet. # We open and close the SelectChannelsFrame every time we @@ -219,14 +212,12 @@ def OnPageChanged(self, page, trigger=None): self.textend.SetLabel("%d." % self.lentau) self.OnChangeChannels() - - def SetValues(self, page=None): if page is None: page = self.Page # Get interval start = self.spinstart.GetValue() - end = self.spinend.GetValue() + 1 # +1, [sic] + end = self.spinend.GetValue() + 1 # +1, [sic] if start > end: # swap the variables, we are not angry at the user start, end = end, start @@ -234,6 +225,6 @@ def SetValues(self, page=None): maxlen = len(page.corr.lag_time) # Use the smaller one of both, so we do not get an # index out of bounds error - page.corr.fit_ival = [ start*(start < maxlen - 1 ), - min(end, maxlen) - ] \ No newline at end of file + page.corr.fit_ival = [start*(start < maxlen - 1), + min(end, maxlen) + ] diff --git a/pycorrfit/gui/tools/example.py b/pycorrfit/gui/tools/example.py index 8195708a..9d8e2107 100644 --- a/pycorrfit/gui/tools/example.py +++ b/pycorrfit/gui/tools/example.py @@ -16,13 +16,13 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Example tool", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) btncopy = wx.Button(self.panel, wx.ID_ANY, 'Example button') # Binds the button to the function - close the tool @@ -37,7 +37,6 @@ def __init__(self, parent): wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. @@ -45,7 +44,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnPageChanged(self, page, trigger=None): """ This function is called, when something in the panel @@ -64,5 +62,3 @@ def OnPageChanged(self, page, trigger=None): return self.panel.Enable() self.Page = page - - diff --git a/pycorrfit/gui/tools/globalfit.py b/pycorrfit/gui/tools/globalfit.py index 685ee2f6..74551e33 100644 --- a/pycorrfit/gui/tools/globalfit.py +++ b/pycorrfit/gui/tools/globalfit.py @@ -12,26 +12,27 @@ MENUINFO = ["&Global fitting", "Interconnect parameters from different measurements."] + class GlobalFit(wx.Frame): # This tool is derived from a wx.frame. def __init__(self, parent): # Define a unique name that identifies this tool # Do not change this value. It is important for the Overlay tool # (selectcurves.py, *Wrapper_Tools*). - self.MyName="GLOBALFIT" + self.MyName = "GLOBALFIT" # parent is the main frame of PyCorrFit self.parent = parent # Get the window positioning correctly pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Gobal fitting", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) self.topSizer = wx.BoxSizer(wx.VERTICAL) textinit = """Fitting of multiple data sets with different models. @@ -39,17 +40,18 @@ def __init__(self, parent): check parameters on each page and start 'Global fit'. """ self.topSizer.Add(wx.StaticText(self.panel, label=textinit)) - ## Page selection - self.WXTextPages = wx.TextCtrl(self.panel, value="", size=(330,-1)) + # Page selection + self.WXTextPages = wx.TextCtrl(self.panel, value="", size=(330, -1)) # Set initial value in text control pagenumlist = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) - pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + pagenumlist.append( + int("".join(filter(lambda x: x.isdigit(), Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) self.topSizer.Add(self.WXTextPages) - ## Button + # Button btnfit = wx.Button(self.panel, wx.ID_ANY, 'Global fit') # Binds the button to the function - close the tool self.Bind(wx.EVT_BUTTON, self.OnFit, btnfit) @@ -79,7 +81,7 @@ def OnFit(self, e=None): # Something went wrong and parseString2Pagenum already displayed # an error message. return - ## Get the correlations + # Get the correlations corrs = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) @@ -103,7 +105,8 @@ def OnFit(self, e=None): # update fit results for corr in corrs: corr.fit_results["global parms"] = u", ".join(fit_parm_names) - corr.fit_results["global pages"] = u", ".join([str(g) for g in global_pages]) + corr.fit_results["global pages"] = u", ".join( + [str(g) for g in global_pages]) # Plot resutls for i in np.arange(self.parent.notebook.GetPageCount()): @@ -116,7 +119,6 @@ def OnFit(self, e=None): # Autoclose self.OnClose() - def OnPageChanged(self, page, trigger=None): """ This function is called, when something in the panel @@ -137,6 +139,5 @@ def OnPageChanged(self, page, trigger=None): self.panel.Enable() self.Page = page - def SetPageNumbers(self, pagestring): self.WXTextPages.SetValue(pagestring) diff --git a/pycorrfit/gui/tools/info.py b/pycorrfit/gui/tools/info.py index 169ac04d..e2b94ad8 100644 --- a/pycorrfit/gui/tools/info.py +++ b/pycorrfit/gui/tools/info.py @@ -9,17 +9,18 @@ MENUINFO = ["Page &info", "Display some information on the current page."] + class InfoClass(object): """ This class get's all the Info possible from a Page and makes it available through a dictionary with headings as keys. """ - def __init__(self, CurPage=None, Pagelist=None ): + + def __init__(self, CurPage=None, Pagelist=None): # A list of all Pages currently available: self.Pagelist = Pagelist # The current page we are looking at: self.CurPage = CurPage - def GetAllInfo(self): """ Get a dictionary with page titles and an InfoDict as value. """ @@ -29,19 +30,16 @@ def GetAllInfo(self): MultiInfo[Page.counter[:-2]] = self.GetPageInfo(Page) return MultiInfo - def GetCurInfo(self): """ Get all the information about the current Page. Added for convenience. You may use GetPageInfo. """ return self.GetPageInfo(self.CurPage) - def GetCurFancyInfo(self): """ For convenience. """ return self.GetFancyInfo(self.CurPage) - def GetFancyInfo(self, Page): """ Get a nice string representation of the Info """ InfoDict = self.GetPageInfo(Page) @@ -50,16 +48,16 @@ def GetFancyInfo(self, Page): # Title Title = u"\n" for item in InfoDict["title"]: - Title = Title + item[0]+"\t"+ item[1]+"\n" + Title = Title + item[0]+"\t" + item[1]+"\n" # Parameters Parameters = u"\nParameters:\n" for item in InfoDict["parameters"]: - Parameters = Parameters + u" "+item[0]+"\t"+ str(item[1])+"\n" + Parameters = Parameters + u" "+item[0]+"\t" + str(item[1])+"\n" # Supplementary parameters Supplement = u"\nSupplementary parameters:\n" try: for item in InfoDict["supplement"]: - Supplement = Supplement + " "+item[0]+"\t"+ str(item[1])+"\n" + Supplement = Supplement + " "+item[0]+"\t" + str(item[1])+"\n" except KeyError: Supplement = "" # Fitting @@ -84,11 +82,10 @@ def GetFancyInfo(self, Page): SupDoc = u"\n"+8*" "+InfoDict["modelsupdoc"][0] except: SupDoc = u"" - PageInfo = Version+Title+Parameters+Supplement+Fitting+Background+\ - ModelDoc+SupDoc + PageInfo = Version+Title+Parameters+Supplement+Fitting+Background +\ + ModelDoc+SupDoc return PageInfo - def GetPageInfo(self, Page): """ Needs a Page and gets all information from it """ Page.PlotAll("init") @@ -115,13 +112,13 @@ def GetPageInfo(self, Page): Title.append(["Model ID", str(model.id)]) Title.append(["Model function", fct]) Title.append(["Page number", Page.counter[1:-2]]) - ## Parameters + # Parameters Parameters = list() # Use this function to determine human readable parameters, if possible Units, Newparameters = mdls.GetHumanReadableParms(model.id, parms) # Add Parameters for i in np.arange(len(parms)): - Parameters.append([ Units[i], Newparameters[i] ]) + Parameters.append([Units[i], Newparameters[i]]) InfoDict["parameters"] = Parameters # Add some more information if available # Info is a dictionary or None @@ -138,8 +135,7 @@ def GetPageInfo(self, Page): pass else: InfoDict["modelsupdoc"] = [func_info.__doc__] - ## Fitting - + # Fitting if hasattr(corr, "fit_results"): Fitting = list() @@ -147,58 +143,63 @@ def GetPageInfo(self, Page): if corr.correlation is not None: # Mode AC vs CC if corr.is_cc: - Title.append(["Type AC/CC", "Cross-correlation" ]) + Title.append(["Type AC/CC", "Cross-correlation"]) else: - Title.append(["Type AC/CC", "Autocorrelation" ]) + Title.append(["Type AC/CC", "Autocorrelation"]) if "chi2" in corr.fit_results: - Fitting.append([ u"ĻĀ²", corr.fit_results["chi2"]]) + Fitting.append([u"ĻĀ²", corr.fit_results["chi2"]]) if weightedfit: try: - Fitting.append(["Weighted fit", corr.fit_results["weighted fit type"]]) + Fitting.append( + ["Weighted fit", corr.fit_results["weighted fit type"]]) except KeyError: - Fitting.append(["Weighted fit", u""+Page.Fitbox[1].GetValue()]) + Fitting.append( + ["Weighted fit", u""+Page.Fitbox[1].GetValue()]) if "chi2 type" in corr.fit_results: ChiSqType = corr.fit_results["chi2 type"] else: ChiSqType = "unknown" - Fitting.append([ u"ĻĀ²-type", ChiSqType]) - Fitting.append([ "Algorithm", fit.Algorithms[corr.fit_algorithm][1]]) + Fitting.append([u"ĻĀ²-type", ChiSqType]) + Fitting.append( + ["Algorithm", fit.Algorithms[corr.fit_algorithm][1]]) if len(Page.GlobalParameterShare) != 0: shared = str(Page.GlobalParameterShare[0]) for item in Page.GlobalParameterShare[1:]: shared += ", "+str(item) Fitting.append(["Shared parameters with Pages", shared]) if "weighted fit bins" in corr.fit_results: - Fitting.append(["Std. channels", 2*corr.fit_results["weighted fit bins"]+1]) + Fitting.append( + ["Std. channels", 2*corr.fit_results["weighted fit bins"]+1]) # Fitting range: t1 = 1.*corr.lag_time[corr.fit_ival[0]] t2 = 1.*corr.lag_time[corr.fit_ival[1]-1] - Fitting.append([ "Ival start [ms]", "%.4e" % t1 ]) - Fitting.append([ "Ival end [ms]", "%.4e" % t2 ]) + Fitting.append(["Ival start [ms]", "%.4e" % t1]) + Fitting.append(["Ival end [ms]", "%.4e" % t2]) # Fittet parameters try: fitparmsid = corr.fit_results["fit parameters"] except: fitparmsid = corr.fit_parameters_variable fitparms = np.array(corr.fit_model.parameters[0])[fitparmsid] - fitparms_short = [ f.split()[0] for f in fitparms ] + fitparms_short = [f.split()[0] for f in fitparms] fitparms_short = u", ".join(fitparms_short) Fitting.append(["Fit parm.", fitparms_short]) # global fitting for key in corr.fit_results.keys(): if key.startswith("global"): - Fitting.append([key.capitalize(), corr.fit_results[key]]) + Fitting.append( + [key.capitalize(), corr.fit_results[key]]) # Fit errors if "fit error estimation" in corr.fit_results: errors = corr.fit_results["fit error estimation"] for err, par in zip(errors, fitparms): nam, val = mdls.GetHumanReadableParameterDict( - model.id, [par], [err]) + model.id, [par], [err]) Fitting.append(["Err "+nam[0], val[0]]) InfoDict["fitting"] = Fitting - ## Normalization parameter id to name + # Normalization parameter id to name if corr.normparm is None: normparmtext = "None" elif corr.normparm < len(corr.fit_parameters): @@ -209,29 +210,29 @@ def GetPageInfo(self, Page): normparmtext = MoreInfo[supnum][0] Title.append(["Normalization", normparmtext]) - ## Background + # Background Background = list() if corr.is_cc: if len(corr.backgrounds) == 2: # Channel 1 - Background.append([ "bg name Ch1", - corr.backgrounds[0].name]) - Background.append([ "bg rate Ch1 [kHz]", - corr.backgrounds[0].countrate]) + Background.append(["bg name Ch1", + corr.backgrounds[0].name]) + Background.append(["bg rate Ch1 [kHz]", + corr.backgrounds[0].countrate]) # Channel 2 - Background.append([ "bg name Ch2", - corr.backgrounds[1].name]) - Background.append([ "bg rate Ch2 [kHz]", - corr.backgrounds[1].countrate]) + Background.append(["bg name Ch2", + corr.backgrounds[1].name]) + Background.append(["bg rate Ch2 [kHz]", + corr.backgrounds[1].countrate]) InfoDict["background"] = Background else: if len(corr.backgrounds) == 1: - Background.append([ "bg name", - corr.backgrounds[0].name]) - Background.append([ "bg rate [kHz]", - corr.backgrounds[0].countrate]) + Background.append(["bg name", + corr.backgrounds[0].name]) + Background.append(["bg rate [kHz]", + corr.backgrounds[0].countrate]) InfoDict["background"] = Background - ## Function doc string + # Function doc string InfoDict["modeldoc"] = [corr.fit_model.description_long] InfoDict["title"] = Title @@ -246,23 +247,24 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Info", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page self.Page = self.parent.notebook.GetCurrentPage() # Size - initial_size = wx.Size(650,700) + initial_size = wx.Size(650, 700) initial_sizec = (initial_size[0]-6, initial_size[1]-30) - self.SetMinSize(wx.Size(200,200)) + self.SetMinSize(wx.Size(200, 200)) self.SetSize(initial_size) - ## Content + # Content self.panel = wx.Panel(self) self.control = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE, - size=initial_sizec) + size=initial_sizec) self.control.SetEditable(False) - font1 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Monospace') + font1 = wx.Font(10, wx.MODERN, wx.NORMAL, + wx.NORMAL, False, u'Monospace') self.control.SetFont(font1) btncopy = wx.Button(self.panel, wx.ID_CLOSE, 'Copy to clipboard') self.Bind(wx.EVT_BUTTON, self.OnCopy, btncopy) @@ -271,14 +273,13 @@ def __init__(self, parent): self.topSizer.Add(self.control) self.panel.SetSizer(self.topSizer) self.topSizer.Fit(self) - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) wx.EVT_SIZE(self, self.OnSize) self.Content() - def Content(self): # Fill self.control with content. # Parameters and models @@ -292,13 +293,11 @@ def Content(self): PageInfo = InfoMan.GetCurFancyInfo() self.control.SetValue(PageInfo) - def OnClose(self, event=None): self.parent.toolmenu.Check(self.MyID, False) self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnCopy(self, event): if not wx.TheClipboard.IsOpened(): clipdata = wx.TextDataObject() @@ -309,7 +308,6 @@ def OnCopy(self, event): else: print("Other application has lock on clipboard.") - def OnPageChanged(self, page=None, trigger=None): """ This function is called, when something in the panel @@ -324,7 +322,6 @@ def OnPageChanged(self, page=None, trigger=None): self.Page = page self.Content() - def OnSize(self, event): size = event.GetSize() sizec = wx.Size(size[0]-5, size[1]-30) diff --git a/pycorrfit/gui/tools/overlaycurves.py b/pycorrfit/gui/tools/overlaycurves.py index b9d5e400..b4637ff9 100644 --- a/pycorrfit/gui/tools/overlaycurves.py +++ b/pycorrfit/gui/tools/overlaycurves.py @@ -15,6 +15,7 @@ # Menu entry name MENUINFO = ["&Overlay curves", "Select experimental curves."] + class Wrapper_OnImport(object): """ Wrapper for import function. parent: wx.Frame @@ -24,6 +25,7 @@ class Wrapper_OnImport(object): curvedict. selkeys: preselected values for curves in curvedict """ + def __init__(self, parent, curvedict, onselected, selkeys=None, labels=None): self.onselected = onselected @@ -38,7 +40,6 @@ def OnClose(self, event=None): self.parent.Enable() self.Selector.Destroy() - def OnResults(self, keyskeep, keysrem): """ Here we will close (or disable?) pages that are not wanted by the user. It is important that we do not close pages that @@ -46,7 +47,7 @@ def OnResults(self, keyskeep, keysrem): because we ignored those pages during import. """ self.OnClose() - self.onselected(keyskeep,keysrem) + self.onselected(keyskeep, keysrem) class Wrapper_Tools(object): @@ -57,10 +58,10 @@ def __init__(self, parent): """ # parent is the main frame of PyCorrFit self.parent = parent - ## MYID + # MYID # This ID is given by the parent for an instance of this class self.MyID = None - ## Wrapping + # Wrapping curvedict, labels = self.GetCurvedict() self.labels = labels self.Selector = UserSelectCurves(parent, curvedict, @@ -71,7 +72,6 @@ def __init__(self, parent): if self.parent.notebook.GetPageCount() == 0: self.Selector.sp.Disable() - def Disable(self): self.Selector.Disable() @@ -98,7 +98,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Selector.Destroy() - def OnPageChanged(self, page=None, trigger=None): """ This function is called, when something in the panel @@ -128,12 +127,11 @@ def OnPageChanged(self, page=None, trigger=None): self.labels = labels if oldlabels != self.Selector.curvelabels: self.Selector.SelectBox.SetItems( - self.Selector.curvelabels) + self.Selector.curvelabels) for i in np.arange(len(self.Selector.curvekeys)): self.Selector.SelectBox.SetSelection(i) self.Selector.OnUpdatePlot(trigger=trigger) - def OnResults(self, keyskeep, keysrem): """ Here we will close (or disable?) pages that are not wanted by the user. It is important that we do not close pages that @@ -151,7 +149,7 @@ def OnResults(self, keyskeep, keysrem): for key in keyskeep: textlist += "- "+key+" "+self.labels[key]+"\n" dlg = edclasses.MyScrolledDialog(self.parent, - overtext, textlist, "Warning") + overtext, textlist, "Warning") if dlg.ShowModal() == wx.ID_OK: N = self.parent.notebook.GetPageCount() pagerem = list() @@ -217,7 +215,7 @@ def __init__(self, parent, curvedict, wrapper=None, selkeys=None, self.curvedict = curvedict self.selkeys = selkeys self.labels = labels # can be None - self.curvelabels = None # filled by self.ProcessDict() + self.curvelabels = None # filled by self.ProcessDict() if self.selkeys is not None: newselkeys = list() for item in self.selkeys: @@ -227,15 +225,16 @@ def __init__(self, parent, curvedict, wrapper=None, selkeys=None, pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Overlay curves", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT, - size=(800,500)) - ## Pre-process + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT, + size=(800, 500)) + # Pre-process self.ProcessDict() - ## Content - self.sp = wx.SplitterWindow(self, size=(500,500), style=wx.SP_NOBORDER) + # Content + self.sp = wx.SplitterWindow( + self, size=(500, 500), style=wx.SP_NOBORDER) self.sp.SetMinimumPaneSize(1) # Top panel - panel_top = wx.Panel(self.sp, size=(500,200)) + panel_top = wx.Panel(self.sp, size=(500, 200)) self.upperSizer = wx.BoxSizer(wx.VERTICAL) if platform.system().lower() == 'darwin': ctrl = "Apple" @@ -246,14 +245,15 @@ def __init__(self, parent, curvedict, wrapper=None, selkeys=None, "to select groups." self.upperSizer.Add(wx.StaticText(panel_top, label=text)) # Bottom Panel - self.bottom_sp = wx.SplitterWindow(self.sp, size=(500,300), style=wx.SP_NOBORDER) + self.bottom_sp = wx.SplitterWindow( + self.sp, size=(500, 300), style=wx.SP_NOBORDER) self.bottom_sp.SetMinimumPaneSize(1) sizepanelx = 250 - panel_bottom = wx.Panel(self.bottom_sp, size=(sizepanelx,300)) + panel_bottom = wx.Panel(self.bottom_sp, size=(sizepanelx, 300)) self.boxSizer = wx.BoxSizer(wx.VERTICAL) # Box selection style = wx.LB_EXTENDED - self.SelectBox = wx.ListBox(panel_bottom, size=(sizepanelx,300), + self.SelectBox = wx.ListBox(panel_bottom, size=(sizepanelx, 300), style=style, choices=self.curvelabels) for i in np.arange(len(self.curvekeys)): self.SelectBox.SetSelection(i) @@ -290,7 +290,7 @@ def __init__(self, parent, curvedict, wrapper=None, selkeys=None, np.array(self.upperSizer.GetMinSize()) + np.array((300, 30))) self.SetMinSize(minsize) - #self.SetSize(minsize) + # self.SetSize(minsize) #self.SetMaxSize((9999, self.boxSizer.GetMinSize()[1])) # Canvas self.canvas = plot.PlotCanvas(self.bottom_sp) @@ -316,47 +316,44 @@ def GetSelection(self): keysnosel.append(key) return keyssel, keysnosel - def ProcessDict(self, e=None): # Define the order of keys used. # We want to sort the keys, such that #10: is not before #1: self.curvekeys = list(self.curvedict.keys()) # Sorting key function applied to each key before sorting: - page_num = lambda counter: int(counter.strip().strip(":").strip("#")) + def page_num(counter): return int( + counter.strip().strip(":").strip("#")) try: for item in self.curvekeys: page_num(item) except: - fstr = lambda x: x + def fstr(x): return x else: fstr = page_num - self.curvekeys.sort(key = fstr) + self.curvekeys.sort(key=fstr) if self.labels is None: self.curvelabels = self.curvekeys else: # Use given labels instead of curvekeys. self.curvelabels = list() for key in self.curvekeys: - self.curvelabels.append("#"+str(key).strip(":# ")+" "+self.labels[key]) - + self.curvelabels.append( + "#"+str(key).strip(":# ")+" "+self.labels[key]) def OnCancel(self, e=None): """ Close the tool """ self.wrapper.OnClose() - def OnPushResultsRemove(self, e=None): # Get keys from selection keysrem, keyskeep = self.GetSelection() self.wrapper.OnResults(keyskeep, keysrem) - def OnPushResultsKeep(self, e=None): # Get keys from selection keyskeep, keysrem = self.GetSelection() self.wrapper.OnResults(keyskeep, keysrem) - def OnUpdatePlot(self, e=None, trigger=None): """ What should happen when the selection in *self.SelectBox* is changed? @@ -369,7 +366,7 @@ def OnUpdatePlot(self, e=None, trigger=None): If `trigger` is something that occurs during loading of data, then we will not replot everything. """ - #if e is not None and e.GetEventType() == 10007: + # if e is not None and e.GetEventType() == 10007: # return # Get selected curves @@ -394,9 +391,9 @@ def OnUpdatePlot(self, e=None, trigger=None): self.canvas.enableLegend = True if len(curves) != 0: self.canvas.Draw(plot.PlotGraphics(lines, - xLabel=u'lag time Ļ [ms]', - yLabel=u'G(Ļ)')) - ## This is an addon for 0.7.8 + xLabel=u'lag time Ļ [ms]', + yLabel=u'G(Ļ)')) + # This is an addon for 0.7.8 keyskeep = list() for i in self.SelectBox.GetSelections(): keyskeep.append(self.curvekeys[i]) diff --git a/pycorrfit/gui/tools/parmrange.py b/pycorrfit/gui/tools/parmrange.py index c8555362..20ed994f 100644 --- a/pycorrfit/gui/tools/parmrange.py +++ b/pycorrfit/gui/tools/parmrange.py @@ -18,29 +18,28 @@ def __init__(self, Page): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Parameter Range", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) self.topSizer = wx.BoxSizer(wx.VERTICAL) self.WXboxsizerlist = list() self.WXparmlist = list() self.OnPageChanged(self.Page) - #Icon + # Icon if self.parent.MainIcon is not None: wx.Frame.SetIcon(self, self.parent.MainIcon) self.Show(True) - def FillPanel(self): """ Fill the panel with parameters from the page """ corr = self.Page.corr self.parameter_range = np.zeros_like(corr.fit_parameters_range) leftbound = [] - for item in corr.fit_parameters_range[:,0]: + for item in corr.fit_parameters_range[:, 0]: if item is None: leftbound.append(-np.inf) else: @@ -48,7 +47,7 @@ def FillPanel(self): labels, parmleft = mdls.GetHumanReadableParms(corr.fit_model.id, # @UnusedVariable leftbound) rightbound = [] - for item in corr.fit_parameters_range[:,1]: + for item in corr.fit_parameters_range[:, 1]: if item is None: rightbound.append(np.inf) else: @@ -56,11 +55,12 @@ def FillPanel(self): labels, parmright = mdls.GetHumanReadableParms(corr.fit_model.id, rightbound) - self.parameter_range[:,0] = np.array(parmleft) - self.parameter_range[:,1] = np.array(parmright) + self.parameter_range[:, 0] = np.array(parmleft) + self.parameter_range[:, 1] = np.array(parmright) # create line - self.WXboxsizer = wx.FlexGridSizer(rows=len(labels), cols=5, vgap=5, hgap=5) + self.WXboxsizer = wx.FlexGridSizer( + rows=len(labels), cols=5, vgap=5, hgap=5) for i in range(len(labels)): left = wxutils.PCFFloatTextCtrl(self.panel) right = wxutils.PCFFloatTextCtrl(self.panel) @@ -97,7 +97,6 @@ def OnClose(self, event=None): self.parent.RangeSelector = None self.Destroy() - def OnPageChanged(self, page=None, trigger=None): """ This function is called, when something in the panel @@ -122,10 +121,10 @@ def OnPageChanged(self, page=None, trigger=None): except: pass for i in np.arange(len(self.WXparmlist)): - self.WXparmlist[i][0].Destroy() #start - self.WXparmlist[i][1][0].Destroy() #pname - self.WXparmlist[i][1][1].Destroy() #pname - self.WXparmlist[i][2].Destroy() #end + self.WXparmlist[i][0].Destroy() # start + self.WXparmlist[i][1][0].Destroy() # pname + self.WXparmlist[i][1][1].Destroy() # pname + self.WXparmlist[i][2].Destroy() # end del self.WXparmlist for i in np.arange(len(self.WXboxsizerlist)): self.WXboxsizer.Remove(0) @@ -133,8 +132,6 @@ def OnPageChanged(self, page=None, trigger=None): self.WXparmlist = list() self.FillPanel() - - def OnSetParmRange(self, e): """ Called whenever something is edited in this frame. Writes back parameter ranges to the page @@ -145,13 +142,14 @@ def OnSetParmRange(self, e): self.parameter_range[i][0] = self.WXparmlist[i][0].GetValue() self.parameter_range[i][1] = self.WXparmlist[i][2].GetValue() if self.parameter_range[i][0] > self.parameter_range[i][1]: - self.parameter_range[i][1] = 1.01*np.abs(self.parameter_range[i][0]) + self.parameter_range[i][1] = 1.01 * \ + np.abs(self.parameter_range[i][0]) self.WXparmlist[i][2].SetValue(self.parameter_range[i][1]) # Set parameters parm0 = mdls.GetInternalFromHumanReadableParm(corr.fit_model.id, - self.parameter_range[:,0])[1] + self.parameter_range[:, 0])[1] parm1 = mdls.GetInternalFromHumanReadableParm(corr.fit_model.id, - self.parameter_range[:,1])[1] + self.parameter_range[:, 1])[1] corr.fit_parameters_range = np.dstack((parm0, parm1))[0] if self.parent.MenuAutocloseTools.IsChecked(): diff --git a/pycorrfit/gui/tools/plotexport.py b/pycorrfit/gui/tools/plotexport.py index 566aa700..b8b69864 100644 --- a/pycorrfit/gui/tools/plotexport.py +++ b/pycorrfit/gui/tools/plotexport.py @@ -11,13 +11,13 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Example Tool", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) btnexample = wx.Button(self.panel, wx.ID_ANY, 'Example button') # Binds the button to the function - close the tool @@ -27,12 +27,11 @@ def __init__(self, parent): self.panel.SetSizer(self.topSizer) self.topSizer.Fit(self) self.SetMinSize(self.topSizer.GetMinSize()) - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. @@ -40,7 +39,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnPageChanged(self, page, trigger=None): """ This function is called, when something in the panel @@ -54,4 +52,3 @@ def OnPageChanged(self, page, trigger=None): # This is stuff that should be done when the active page # of the notebook changes. self.Page = page - diff --git a/pycorrfit/gui/tools/simulation.py b/pycorrfit/gui/tools/simulation.py index 782c747f..0f5e0c64 100644 --- a/pycorrfit/gui/tools/simulation.py +++ b/pycorrfit/gui/tools/simulation.py @@ -13,6 +13,7 @@ MENUINFO = ["S&lider simulation", "Fast plotting for different parameters."] + class Slide(wx.Frame): # This tool is derived from a wx.frame. def __init__(self, parent): @@ -22,44 +23,44 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Simulation", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) # Starting positions/factors for spinctrls and sliders self.slidemax = 1000 self.slidestart = 500 self.spinstartfactor = 0.1 self.spinendfactor = 1.9 - ## MYID + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() - ## Content + # Content self.panel = wx.Panel(self) - self.rbtnB = wx.RadioButton (self.panel, -1, 'Vary A and B', - style = wx.RB_GROUP) - self.rbtnOp = wx.RadioButton (self.panel, -1, 'Fix relation') + self.rbtnB = wx.RadioButton(self.panel, -1, 'Vary A and B', + style=wx.RB_GROUP) + self.rbtnOp = wx.RadioButton(self.panel, -1, 'Fix relation') self.btnreset = wx.Button(self.panel, wx.ID_ANY, 'Reset') # Set starting variables self.SetStart() # Populate panel dropsizer = wx.FlexGridSizer(rows=2, cols=3, vgap=5, hgap=5) - dropsizer.Add( wx.StaticText(self.panel, label="Parameter A")) - dropsizer.Add( wx.StaticText(self.panel, label="Operator")) - dropsizer.Add( wx.StaticText(self.panel, label="Parameter B")) + dropsizer.Add(wx.StaticText(self.panel, label="Parameter A")) + dropsizer.Add(wx.StaticText(self.panel, label="Operator")) + dropsizer.Add(wx.StaticText(self.panel, label="Parameter B")) self.droppA = wx.ComboBox(self.panel, -1, self.labelA, (15, 20), - wx.DefaultSize, self.parmAlist, - wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, self.parmAlist, + wx.CB_DROPDOWN | wx.CB_READONLY) self.droppA.SetSelection(0) self.Bind(wx.EVT_COMBOBOX, self.Ondrop, self.droppA) self.dropop = wx.ComboBox(self.panel, -1, "", (10, 20), - wx.DefaultSize, self.oplist, - wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, self.oplist, + wx.CB_DROPDOWN | wx.CB_READONLY) self.dropop.SetSelection(0) self.opfunc = self.opdict[list(self.opdict.keys())[0]] self.Bind(wx.EVT_COMBOBOX, self.Ondrop, self.dropop) self.droppB = wx.ComboBox(self.panel, -1, self.labelB, (15, 30), - wx.DefaultSize, self.parmBlist, - wx.CB_DROPDOWN|wx.CB_READONLY) + wx.DefaultSize, self.parmBlist, + wx.CB_DROPDOWN | wx.CB_READONLY) self.Bind(wx.EVT_COMBOBOX, self.Ondrop, self.droppB) self.droppB.SetSelection(1) dropsizer.Add(self.droppA) @@ -79,7 +80,7 @@ def __init__(self, parent): slidesizer.Add(self.sliderA) self.endspinA = floatspin.FloatSpin(self.panel, digits=7) slidesizer.Add(self.endspinA) - self.textvalueA = wx.StaticText(self.panel, label= "%.5e" % self.valueA) + self.textvalueA = wx.StaticText(self.panel, label="%.5e" % self.valueA) slidesizer.Add(self.textvalueA) # Parameter B self.textstartB = wx.StaticText(self.panel, label=self.labelB) @@ -92,7 +93,7 @@ def __init__(self, parent): slidesizer.Add(self.sliderB) self.endspinB = floatspin.FloatSpin(self.panel, digits=7) slidesizer.Add(self.endspinB) - self.textvalueB = wx.StaticText(self.panel, label= "%.5e" % self.valueB) + self.textvalueB = wx.StaticText(self.panel, label="%.5e" % self.valueB) slidesizer.Add(self.textvalueB) # Result of operation self.textstartOp = wx.StaticText(self.panel, label=self.labelOp) @@ -106,7 +107,7 @@ def __init__(self, parent): self.endspinOp = floatspin.FloatSpin(self.panel, digits=7) slidesizer.Add(self.endspinOp) self.textvalueOp = wx.StaticText(self.panel, - label= "%.5e" % self.valueOp) + label="%.5e" % self.valueOp) slidesizer.Add(self.textvalueOp) # Bindings for slider self.Bind(wx.EVT_SLIDER, self.OnSlider, self.sliderA) @@ -133,7 +134,7 @@ def __init__(self, parent): self.Bind(wx.EVT_SPINCTRL, self.OnSlider, self.endspinOp) # Set values self.SetValues() - ## Sizers + # Sizers self.topSizer = wx.BoxSizer(wx.VERTICAL) self.topSizer.Add(dropsizer) self.topSizer.Add(self.rbtnB) @@ -145,17 +146,16 @@ def __init__(self, parent): self.topSizer.Fit(self) self.OnRadio() self.OnPageChanged(self.Page, init=True) - #Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) - def CalcFct(self, A, B, C): if self.rbtnB.Value == True: func = self.opfunc[0] try: - C = func(A,B) + C = func(A, B) except ZeroDivisionError: pass else: @@ -163,25 +163,23 @@ def CalcFct(self, A, B, C): else: func = self.opfunc[1] try: - B = func(A,C) + B = func(A, C) except ZeroDivisionError: pass else: return B, C - def FillOpDict(self): # Dictionaries: [Calculate C, Calculate B) - self.opdict["A/B"] = [lambda A,B: A/B, lambda A,C: A/C] - self.opdict["B/A"] = [lambda A,B: B/A, lambda A,C: C*A] - self.opdict["A*B"] = [lambda A,B: A*B, lambda A,C: C/A] - self.opdict["A+B"] = [lambda A,B: A+B, lambda A,C: C-A] - self.opdict["A-B"] = [lambda A,B: A-B, lambda A,C: A-C] - self.opdict["A*exp(B)"] = [lambda A,B: A*np.exp(B), - lambda A,C: np.log(C/A)] - self.opdict["B*exp(A)"] = [lambda A,B: B*np.exp(A), - lambda A,C: C/np.exp(A)] - + self.opdict["A/B"] = [lambda A, B: A/B, lambda A, C: A/C] + self.opdict["B/A"] = [lambda A, B: B/A, lambda A, C: C*A] + self.opdict["A*B"] = [lambda A, B: A*B, lambda A, C: C/A] + self.opdict["A+B"] = [lambda A, B: A+B, lambda A, C: C-A] + self.opdict["A-B"] = [lambda A, B: A-B, lambda A, C: A-C] + self.opdict["A*exp(B)"] = [lambda A, B: A*np.exp(B), + lambda A, C: np.log(C/A)] + self.opdict["B*exp(A)"] = [lambda A, B: B*np.exp(A), + lambda A, C: C/np.exp(A)] def OnClose(self, event=None): # This is a necessary function for PyCorrFit. @@ -190,7 +188,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def Ondrop(self, event=None): self.labelOp = self.oplist[self.dropop.GetSelection()] self.labelA = self.parmAlist[self.droppA.GetSelection()] @@ -206,7 +203,6 @@ def Ondrop(self, event=None): self.SetValues() self.OnSize() - def OnPageChanged(self, page=None, trigger=None, init=False): """ This function is called, when something in the panel @@ -216,7 +212,7 @@ def OnPageChanged(self, page=None, trigger=None, init=False): `tools`. 'init' is used by this tool only. """ - #if init: + # if init: # # Get the parameters of the current page. # self.SavedParms = self.parent.PackParameters(self.Page) # When parent changes @@ -249,7 +245,6 @@ def OnPageChanged(self, page=None, trigger=None, init=False): self.Page = page self.panel.Enable() - def OnRadio(self, event=None): if self.rbtnB.Value == True: # Parameter B is vaiable @@ -269,11 +264,10 @@ def OnRadio(self, event=None): self.endspinB.Enable(False) self.Ondrop() - def OnReset(self, e=None): self.parent.UnpackParameters(self.SavedParms, self.Page) self.Page.apply_parameters_reverse() - #self.OnPageChanged(self.Page) + # self.OnPageChanged(self.Page) self.SetStart() self.Ondrop() @@ -284,15 +278,14 @@ def OnSize(self, event=None): self.topSizer.Fit(self) self.panel.SetSize(self.GetSize()) - def OnSlider(self, event=None): - ## Set the slider vlaues + # Set the slider vlaues idmax = self.sliderA.GetMax() slideA = self.sliderA.GetValue() startA = self.startspinA.GetValue() endA = self.endspinA.GetValue() self.valueA = startA + (endA-startA)*slideA/idmax - self.textvalueA.SetLabel( "%.5e" % self.valueA) + self.textvalueA.SetLabel("%.5e" % self.valueA) if self.rbtnB.Value == True: slideB = self.sliderB.GetValue() startB = self.startspinB.GetValue() @@ -306,12 +299,11 @@ def OnSlider(self, event=None): self.valueOp = startOp + (endOp-startOp)*slideOp/idmax self.valueB, self.valueOp = self.CalcFct(self.valueA, self.valueB, self.valueOp) - self.textvalueB.SetLabel( "%.5e" % self.valueB) - self.textvalueOp.SetLabel( "%.5e" % self.valueOp) + self.textvalueB.SetLabel("%.5e" % self.valueB) + self.textvalueOp.SetLabel("%.5e" % self.valueOp) self.SetResult() self.OnSize() - def SetResult(self, event=None): if self.parent.notebook.GetPageCount() == 0: # Nothing to do @@ -327,8 +319,8 @@ def SetResult(self, event=None): # only write back those that have been changed: # parms_0 = 1.*np.array(mdls.valuedict[self.modelid][1]) - parms_0[idA] = self.valueA # human readable units - parms_0[idB] = self.valueB # human readable units + parms_0[idA] = self.valueA # human readable units + parms_0[idB] = self.valueB # human readable units parms_i =\ mdls.GetInternalFromHumanReadableParm(self.modelid, parms_0)[1] self.Page.active_parms[1][idA] = parms_i[idA] @@ -336,21 +328,20 @@ def SetResult(self, event=None): self.Page.apply_parameters_reverse() self.Page.PlotAll() - def SetStart(self): # Sets first and second variable of a page to # Parameters A and B respectively. if self.parent.notebook.GetPageCount() == 0: self.modelid = 6000 ParmLabels, ParmValues = \ - mdls.GetHumanReadableParms(self.modelid, - mdls.valuedict[6000][1]) + mdls.GetHumanReadableParms(self.modelid, + mdls.valuedict[6000][1]) else: self.SavedParms = self.parent.PackParameters(self.Page) self.modelid = self.Page.modelid ParmLabels, ParmValues = \ - mdls.GetHumanReadableParms(self.modelid, - self.Page.active_parms[1]) + mdls.GetHumanReadableParms(self.modelid, + self.Page.active_parms[1]) self.parmAlist = ParmLabels self.parmBlist = ParmLabels @@ -367,8 +358,7 @@ def SetStart(self): self.valueA = ParmValues[0] self.valueB = ParmValues[1] self.valueB, self.valueOp = self.CalcFct(self.valueA, - self.valueB, 0) - + self.valueB, 0) def SetValues(self, event=None): # Set the values for spin and slider @@ -385,13 +375,13 @@ def SetValues(self, event=None): if self.parent.notebook.GetPageCount() == 0: self.modelid = 6000 ParmValues = \ - mdls.GetHumanReadableParms(self.modelid, - mdls.valuedict[6000][1])[1] + mdls.GetHumanReadableParms(self.modelid, + mdls.valuedict[6000][1])[1] else: self.modelid = self.Page.modelid ParmValues = \ - mdls.GetHumanReadableParms(self.modelid, - self.Page.active_parms[1])[1] + mdls.GetHumanReadableParms(self.modelid, + self.Page.active_parms[1])[1] self.valueA = ParmValues[idA] self.valueB = ParmValues[idB] # Operator @@ -416,8 +406,7 @@ def SetValues(self, event=None): self.startspinOp.SetValue(startOp) self.endspinOp.SetValue(endOp) # Set text - self.textvalueA.SetLabel( "%.5e" % self.valueA) - self.textvalueB.SetLabel( "%.5e" % self.valueB) - self.textvalueOp.SetLabel( "%.5e" % self.valueOp) + self.textvalueA.SetLabel("%.5e" % self.valueA) + self.textvalueB.SetLabel("%.5e" % self.valueB) + self.textvalueOp.SetLabel("%.5e" % self.valueOp) self.SetResult() - diff --git a/pycorrfit/gui/tools/statistics.py b/pycorrfit/gui/tools/statistics.py index 63756589..712740ab 100644 --- a/pycorrfit/gui/tools/statistics.py +++ b/pycorrfit/gui/tools/statistics.py @@ -19,6 +19,7 @@ # Menu entry name MENUINFO = ["&Statistics view", "Show some session statistics."] + def run_once(f): def wrapper(*args, **kwargs): if not wrapper.has_run: @@ -31,7 +32,7 @@ def wrapper(*args, **kwargs): class Stat(wx.Frame): # This tool is derived from a wx.frame. def __init__(self, parent): - self.MyName="STATISTICS" + self.MyName = "STATISTICS" # parent is the main frame of PyCorrFit self.boxsizerlist = list() self.parent = parent @@ -39,9 +40,9 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Statistics", - pos=pos, size=(700,600), - style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, size=(700, 600), + style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None self.MyName = "STATISTICS" @@ -50,13 +51,13 @@ def __init__(self, parent): # Page - the currently active page of the notebook. self.Page = self.parent.notebook.GetCurrentPage() # Pagenumbers - self.PageNumbers =range(1,1+self.parent.notebook.GetPageCount()) - ## Splitter window. left side: checkboxes - ## right side: plot with parameters + self.PageNumbers = range(1, 1+self.parent.notebook.GetPageCount()) + # Splitter window. left side: checkboxes + # right side: plot with parameters self.sp = wx.SplitterWindow(self, style=wx.SP_3DSASH) # This is necessary to prevent "Unsplit" of the SplitterWindow: self.sp.SetMinimumPaneSize(1) - ## Content + # Content # We will display a dialog that conains all the settings # - Which model we want statistics on # - What kind of parameters should be printed @@ -74,38 +75,38 @@ def __init__(self, parent): self.panel.Disable() # A dropdown menu for the source Page: text = wx.StaticText(self.panel, - label="Create a table with all the selected\n"+ - "variables below from pages with the\n"+ - "same model as the current page.") - ## Page selection as in average tool + label="Create a table with all the selected\n" + + "variables below from pages with the\n" + + "same model as the current page.") + # Page selection as in average tool Pagetext = wx.StaticText(self.panel, - label="Curves ") + label="Curves ") Psize = text.GetSize()[0]/2 self.WXTextPages = wx.TextCtrl(self.panel, value="", - size=(Psize,-1)) + size=(Psize, -1)) # Set number of pages pagenumlist = list() for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), - Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) - ## Plot parameter dropdown box + # Plot parameter dropdown box self.PlotParms = self.GetListOfPlottableParms() Parmlist = self.PlotParms DDtext = wx.StaticText(self.panel, label="Plot parameter ") self.WXDropdown = wx.ComboBox(self.panel, -1, "", - size=(Psize,-1), choices=Parmlist, - style=wx.CB_DROPDOWN|wx.CB_READONLY) + size=(Psize, -1), choices=Parmlist, + style=wx.CB_DROPDOWN | wx.CB_READONLY) self.Bind(wx.EVT_COMBOBOX, self.OnDropDown, self.WXDropdown) self.Bind(wx.EVT_TEXT, self.OnDropDown, self.WXTextPages) self.WXDropdown.SetSelection(0) - ## Show Average and SD + # Show Average and SD textavg = wx.StaticText(self.panel, label="Average ") textsd = wx.StaticText(self.panel, label="Standard deviation ") - self.WXavg = wx.TextCtrl(self.panel, size=(Psize,-1)) - self.WXsd = wx.TextCtrl(self.panel, size=(Psize,-1)) + self.WXavg = wx.TextCtrl(self.panel, size=(Psize, -1)) + self.WXsd = wx.TextCtrl(self.panel, size=(Psize, -1)) self.WXavg.SetEditable(False) self.WXsd.SetEditable(False) # Create space for parameters @@ -132,13 +133,13 @@ def __init__(self, parent): GridAll.Add(textsd) GridAll.Add(self.WXsd) #Psizer = wx.BoxSizer(wx.HORIZONTAL) - #Psizer.Add(Pagetext) - #Psizer.Add(self.WXTextPages) + # Psizer.Add(Pagetext) + # Psizer.Add(self.WXTextPages) #DDsizer = wx.BoxSizer(wx.HORIZONTAL) - #DDsizer.Add(DDtext) - #DDsizer.Add(self.WXDropdown) - #self.topSizer.Add(Psizer) - #self.topSizer.Add(DDsizer) + # DDsizer.Add(DDtext) + # DDsizer.Add(self.WXDropdown) + # self.topSizer.Add(Psizer) + # self.topSizer.Add(DDsizer) self.topSizer.Add(GridAll) self.topSizer.Add(self.masterboxsizer) self.topSizer.Add(self.btnSave) @@ -147,19 +148,18 @@ def __init__(self, parent): self.topSizer.Fit(self.panel) px = self.topSizer.GetMinSize()[0] - ## Plotting panel + # Plotting panel self.canvas = plot.PlotCanvas(self.sp) self.canvas.enableZoom = True self.sp.SplitVertically(self.panel, self.canvas, px+5) - ## Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) self.OnDropDown() - def GetListOfAllParameters(self, e=None, return_std_checked=False, - page=None): + page=None): """ Returns sorted list of parameters. If return_std_checked is True, then a second list with standart checked parameters is returned. @@ -203,7 +203,8 @@ def GetListOfAllParameters(self, e=None, return_std_checked=False, checked[ii] = True # A list with additional strings that should be default checked # if found somewhere in the data. - checklist = ["cpp", "duration", "bg rate", "avg.", "Model name", "filename/title"] + checklist = ["cpp", "duration", "bg rate", + "avg.", "Model name", "filename/title"] for i in range(len(Info)): item = Info[i] for checkitem in checklist: @@ -217,13 +218,11 @@ def GetListOfAllParameters(self, e=None, return_std_checked=False, if item[0].count(checkitem): checked[i] = False - if return_std_checked: return Info, checked else: return Info - def GetListOfPlottableParms(self, e=None, return_values=False, page=None): """ Returns list of parameters that can be plotted. @@ -255,7 +254,6 @@ def GetListOfPlottableParms(self, e=None, return_values=False, else: return parmlist - def GetWantedParameters(self): """ Updates self.SaveInfo with all the information that will be @@ -286,9 +284,9 @@ def GetWantedParameters(self): # If pagenumber is larger than 10, # pagekeys.sort will not work, because we have strings # Define new compare function - cmp_func = lambda a: int(a.strip().strip("#")) + def cmp_func(a): return int(a.strip().strip("#")) pagekeys.sort(key=cmp_func) - #for Info in pagekeys: + # for Info in pagekeys: # pageinfo = list() # for item in AllInfo[Info]: # for subitem in AllInfo[Info][item]: @@ -319,7 +317,6 @@ def GetWantedParameters(self): pageinfo.append([label, "NaN"]) self.SaveInfo.append(pageinfo) - def OnCheckboxChecked(self, e="restore"): """ Write boolean data of checked checkboxes to Page variable @@ -329,7 +326,7 @@ def OnCheckboxChecked(self, e="restore"): # What happens if a checkbox has been checked? # We write the data to the Page # (it will not be saved in the session). - if e=="restore": + if e == "restore": checklist = self.Page.StatisticsCheckboxes if checklist is not None: if len(checklist) <= len(self.Checkboxes): @@ -341,13 +338,12 @@ def OnCheckboxChecked(self, e="restore"): checklist.append(cb.GetValue()) self.Page.StatisticsCheckboxes = checklist - def OnChooseValues(self, event=None): """ Plot the values for the parameter selected by the user. """ Info, checked = self.GetListOfAllParameters( - return_std_checked=True) + return_std_checked=True) #headcounter = 0 #headlen = len(head) # We will sort the checkboxes in more than one column if there @@ -363,10 +359,10 @@ def OnChooseValues(self, event=None): #itemcount += 1 #headcounter += 1 checkbox = wx.CheckBox(self.panel, label=Info[i][0]) - #if headcounter <= headlen: + # if headcounter <= headlen: # checkbox.SetValue(True) # Additionally default checked items - #for checkitem in checklist: + # for checkitem in checklist: # if item[0].count(checkitem): # checkbox.SetValue(True) checkbox.SetValue(checked[i]) @@ -382,7 +378,6 @@ def OnChooseValues(self, event=None): self.OnCheckboxChecked("restore") self.AllPlotParms = Info - def OnClose(self, event=None): # This is a necessary function for PyCorrFit. # Do not change it. @@ -390,7 +385,6 @@ def OnClose(self, event=None): self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnDropDown(self, e=None): """ Plot the parameter selected in WXDropdown Uses info stored in self.PlotParms and self.InfoClass @@ -403,7 +397,7 @@ def OnDropDown(self, e=None): strFull = self.WXTextPages.GetValue() try: PageNumbers = misc.parseString2Pagenum(self, strFull, - nodialog=True) + nodialog=True) except: PageNumbers = self.PageNumbers else: @@ -425,12 +419,12 @@ def OnDropDown(self, e=None): plotcurve = list() for page in pages: pllabel, pldata = self.GetListOfPlottableParms(page=page, - return_values=True) + return_values=True) # Get the labels and make a plot of the parameters if len(pllabel)-1 >= DDselid and pllabel[DDselid] == label: x = int(page.counter.strip("#: ")) y = pldata[DDselid] - plotcurve.append([x,y]) + plotcurve.append([x, y]) else: # try to get the label by searching for the first # instance @@ -438,16 +432,16 @@ def OnDropDown(self, e=None): if pllabel[k] == label: x = int(page.counter.strip("#: ")) y = pldata[k] - plotcurve.append([x,y]) + plotcurve.append([x, y]) # Prepare plotting self.canvas.Clear() linesig = plot.PolyMarker(plotcurve, size=1.5, marker='circle') plotlist = [linesig] # average line try: - avg = np.average(np.array(plotcurve)[:,1]) - maxpage = int(np.max(np.array(plotcurve)[:,0]) +1) - minpage = int(np.min(np.array(plotcurve)[:,0]) -1) + avg = np.average(np.array(plotcurve)[:, 1]) + maxpage = int(np.max(np.array(plotcurve)[:, 0]) + 1) + minpage = int(np.min(np.array(plotcurve)[:, 0]) - 1) except: minpage = 0 maxpage = 0 @@ -461,13 +455,13 @@ def OnDropDown(self, e=None): plotlist.append(lineclear) # Update Text control self.WXavg.SetValue(str(avg)) - self.WXsd.SetValue(str(np.std(np.array(plotcurve)[:,1]))) + self.WXsd.SetValue(str(np.std(np.array(plotcurve)[:, 1]))) # Draw # This causes a memory leak after this function has been # called several times with the same large data set. # This goes away if only linesig OR lineclear are plotted. # - #graphics = plot.PlotGraphics(plotlist, + # graphics = plot.PlotGraphics(plotlist, # xLabel='page number', # yLabel=label) graphics = plot.PlotGraphics([linesig], @@ -477,8 +471,7 @@ def OnDropDown(self, e=None): # Correctly set x-axis minticks = 2 self.canvas.SetXSpec(max(maxpage-minpage, minticks)) - self.canvas.Draw(graphics, xAxis=(minpage,maxpage)) - + self.canvas.Draw(graphics, xAxis=(minpage, maxpage)) def OnPageChanged(self, page, trigger=None): """ @@ -500,10 +493,10 @@ def OnPageChanged(self, page, trigger=None): if self.Page.corr.fit_model.id == page.corr.fit_model.id: return if (trigger in ["page_add_finalize"] and - self.WXTextPages.GetValue() == "1"): + self.WXTextPages.GetValue() == "1"): # We probably imported data with statistics window open self.PageNumbers = range(1, - 1+self.parent.notebook.GetPageCount()) + 1+self.parent.notebook.GetPageCount()) setstring = misc.parsePagenum2String(self.PageNumbers) self.WXTextPages.SetValue(setstring) @@ -517,8 +510,8 @@ def OnPageChanged(self, page, trigger=None): for i in np.arange(self.parent.notebook.GetPageCount()): Page = self.parent.notebook.GetPage(i) pagenumlist.append(int("".join(filter(lambda x: x.isdigit(), - Page.counter)))) - valstring=misc.parsePagenum2String(pagenumlist) + Page.counter)))) + valstring = misc.parsePagenum2String(pagenumlist) self.WXTextPages.SetValue(valstring) DDselection = self.WXDropdown.GetValue() self.Page = page @@ -536,7 +529,7 @@ def OnPageChanged(self, page, trigger=None): for i in np.arange(len(self.Checkboxes)): self.Checkboxes[i].Destroy() del self.Checkboxes - #self.Checklabels[i].Destroy() # those cannot be destroyed. + # self.Checklabels[i].Destroy() # those cannot be destroyed. for i in np.arange(len(self.boxsizerlist)): self.boxsizer.Remove(0) self.boxsizer.Layout() @@ -555,17 +548,16 @@ def OnPageChanged(self, page, trigger=None): (px, py) = self.topSizer.GetMinSize() self.sp.SetSashPosition(px+5) self.SetMinSize((px+400, py)) - self.SetSize((np.max([px+400,ax,oldsize[0]]), - np.max([py,ay,oldsize[1]]))) + self.SetSize((np.max([px+400, ax, oldsize[0]]), + np.max([py, ay, oldsize[1]]))) # Replot self.OnDropDown() - def OnSaveTable(self, event=None): dirname = self.parent.dirname dlg = wx.FileDialog(self.parent, "Choose file to save", dirname, - "", "Text file (*.txt)|*.txt;*.TXT", - wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) + "", "Text file (*.txt)|*.txt;*.TXT", + wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) # user cannot do anything until he clicks "OK" if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() @@ -646,18 +638,18 @@ def SortParameters(parms): """ startswith_sort = [ - u"avg. signal", - u"n", - u"T", - u"Ļ_trip", - u"F", - u"C", - u"D", - u"Ļ", - u"Ļ_diff", - u"alpha", - u"SP", - ] + u"avg. signal", + u"n", + u"T", + u"Ļ_trip", + u"F", + u"C", + u"D", + u"Ļ", + u"Ļ_diff", + u"alpha", + u"SP", + ] otherparms = list() @@ -676,7 +668,6 @@ def SortParameters(parms): # special offsets to distinguish "T" and "Type": special_off_start = ["Type", "Fit"] - def rate_tuple(item): x = item[0] return rate(x) @@ -726,13 +717,12 @@ def rate(x): if x.startswith(p): r += 300 - if r==0: + if r == 0: r = 10000 return r - - def compare(x,y): + def compare(x, y): """ rates x and y. returns -1, 0, 1 required for common list sort @@ -742,4 +732,4 @@ def compare(x,y): return rx-ry - return sorted(parms, key=rate_tuple) \ No newline at end of file + return sorted(parms, key=rate_tuple) diff --git a/pycorrfit/gui/tools/trace.py b/pycorrfit/gui/tools/trace.py index 6a926f01..df577e71 100644 --- a/pycorrfit/gui/tools/trace.py +++ b/pycorrfit/gui/tools/trace.py @@ -15,13 +15,13 @@ def __init__(self, parent): pos = self.parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent=self.parent, title="Trace view", - pos=pos, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_FLOAT_ON_PARENT) - ## MYID + pos=pos, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT) + # MYID # This ID is given by the parent for an instance of this class self.MyID = None # Page self.Page = self.parent.notebook.GetCurrentPage() - ## Canvas + # Canvas self.canvas = plot.PlotCanvas(self) self.canvas.enableZoom = True if self.parent.notebook.GetPageCount() == 0: @@ -29,53 +29,54 @@ def __init__(self, parent): pass else: self.OnDraw() - initial_size = (780,250) + initial_size = (780, 250) self.SetSize(initial_size) self.SetMinSize(initial_size) - ## Icon + # Icon if parent.MainIcon is not None: wx.Frame.SetIcon(self, parent.MainIcon) self.Show(True) - def OnClose(self, event=None): self.parent.toolmenu.Check(self.MyID, False) self.parent.ToolsOpen.__delitem__(self.MyID) self.Destroy() - def OnDraw(self): traces = self.Page.corr.traces self.canvas.enableLegend = True if len(traces) == 1: self.trace = 1*traces[0].trace # We want to have the trace in [s] here. - self.trace[:,0] = self.trace[:,0]/1000 + self.trace[:, 0] = self.trace[:, 0]/1000 line = plot.PolyLine(self.trace, - legend='{:.2f}kHz'.format(traces[0].countrate), - colour='blue', width=1) + legend='{:.2f}kHz'.format( + traces[0].countrate), + colour='blue', width=1) lines = [line] - xmax = np.max(self.trace[:,0]) - xmin = np.min(self.trace[:,0]) - ymax = np.max(self.trace[:,1]) - ymin = np.min(self.trace[:,1]) + xmax = np.max(self.trace[:, 0]) + xmin = np.min(self.trace[:, 0]) + ymax = np.max(self.trace[:, 1]) + ymin = np.min(self.trace[:, 1]) elif len(traces) == 2: # This means that we have two (CC) traces to plot self.tracea = 1*traces[0].trace - self.tracea[:,0] = self.tracea[:,0]/1000 + self.tracea[:, 0] = self.tracea[:, 0]/1000 self.traceb = 1*traces[1].trace - self.traceb[:,0] = self.traceb[:,0]/1000 + self.traceb[:, 0] = self.traceb[:, 0]/1000 linea = plot.PolyLine(self.tracea, - legend='channel 1 {:.2f}kHz'.format(traces[0].countrate), - colour='blue', width=1) + legend='channel 1 {:.2f}kHz'.format( + traces[0].countrate), + colour='blue', width=1) lineb = plot.PolyLine(self.traceb, - legend='channel 2 {:.2f}kHz'.format(traces[1].countrate), - colour='red', width=1) + legend='channel 2 {:.2f}kHz'.format( + traces[1].countrate), + colour='red', width=1) lines = [linea, lineb] - xmax = max(np.max(self.tracea[:,0]), np.max(self.traceb[:,0])) - xmin = min(np.min(self.tracea[:,0]), np.min(self.traceb[:,0])) - ymax = max(np.max(self.tracea[:,1]), np.max(self.traceb[:,1])) - ymin = min(np.min(self.tracea[:,1]), np.min(self.traceb[:,1])) + xmax = max(np.max(self.tracea[:, 0]), np.max(self.traceb[:, 0])) + xmin = min(np.min(self.tracea[:, 0]), np.min(self.traceb[:, 0])) + ymax = max(np.max(self.tracea[:, 1]), np.max(self.traceb[:, 1])) + ymin = min(np.min(self.tracea[:, 1]), np.min(self.traceb[:, 1])) else: self.canvas.Clear() @@ -84,9 +85,8 @@ def OnDraw(self): self.canvas.Draw(plot.PlotGraphics(lines, xLabel='time [s]', yLabel='count rate [kHz]'), - xAxis=(xmin,xmax), - yAxis=(ymin,ymax)) - + xAxis=(xmin, xmax), + yAxis=(ymin, ymax)) def OnPageChanged(self, page=None, trigger=None): """ @@ -108,4 +108,3 @@ def OnPageChanged(self, page=None, trigger=None): pass return self.OnDraw() - diff --git a/pycorrfit/gui/update.py b/pycorrfit/gui/update.py index ecdf1cad..4b521e48 100644 --- a/pycorrfit/gui/update.py +++ b/pycorrfit/gui/update.py @@ -1,5 +1,5 @@ """PyCorrFit - update checking""" -from distutils.version import LooseVersion # For version checking +from distutils.version import LooseVersion # For version checking import os import tempfile import traceback @@ -18,7 +18,6 @@ from . import misc - class UpdateDlg(wx.Frame): def __init__(self, parent, valuedict): @@ -29,7 +28,7 @@ def __init__(self, parent, valuedict): pos = parent.GetPosition() pos = (pos[0]+100, pos[1]+100) wx.Frame.__init__(self, parent, wx.ID_ANY, title="Update", - size=(230,240), pos=pos) + size=(230, 240), pos=pos) self.changelog = changelog # Fill html content html = wxHTML(self) @@ -45,7 +44,7 @@ def __init__(self, parent, valuedict): if changelog: string = string + \ - 'Change Log'.format(changelog) + 'Change Log'.format(changelog) string += '
' html.SetPage(string) self.Bind(wx.EVT_CLOSE, self.Close) @@ -53,7 +52,6 @@ def __init__(self, parent, valuedict): ico = misc.getMainIcon() wx.Frame.SetIcon(self, ico) - def Close(self, event): if len(self.changelog) != 0: # Cleanup downloaded file, if it was downloaded @@ -93,11 +91,13 @@ def update(parent): delayedresult.startWorker(_update_consumer, _update_worker, wargs=(parent,), cargs=(parent,)) + def _update_consumer(delayedresult, parent): results = delayedresult.get() dlg = UpdateDlg(parent, results) dlg.Show() - parent.StatusBar.SetStatusText("...update status: "+results["Description"][2]) + parent.StatusBar.SetStatusText( + "...update status: "+results["Description"][2]) def _update_worker(parent): @@ -110,7 +110,7 @@ def _update_worker(parent): else: changelog = responseVer.read() - ghrepo="FCS-analysis/PyCorrFit" + ghrepo = "FCS-analysis/PyCorrFit" if hasattr(pcf_version, "repo_tag"): old = LooseVersion(pcf_version.repo_tag) else: @@ -132,7 +132,7 @@ def _update_worker(parent): clfile.write(changelog) clfile.close() else: - changelogfile=doc.StaticChangeLog + changelogfile = doc.StaticChangeLog results = dict() results["Description"] = description results["Homepage"] = doc.HomePage diff --git a/pycorrfit/gui/usermodel.py b/pycorrfit/gui/usermodel.py index b25e4f8c..06e667ae 100644 --- a/pycorrfit/gui/usermodel.py +++ b/pycorrfit/gui/usermodel.py @@ -17,7 +17,7 @@ from sympy.core.function import Function from sympy import sympify except ImportError: - warnings.warn("Importing sympy failed."+\ + warnings.warn("Importing sympy failed." + " Reason: {}.".format(sys.exc_info()[1].message)) # Define Function, so PyCorrFit will start, even if sympy is not there. # wixi needs Function. @@ -47,6 +47,7 @@ class CorrFunc(object): Check the input code of a proposed user model function and return a function for fitting via GetFunction. """ + def __init__(self, labels, values, substitutes, funcstring): self.values = values # a --> a @@ -58,10 +59,10 @@ def __init__(self, labels, values, substitutes, funcstring): for key in substitutes.keys(): # Don't forget to insert the "(" and ")"'s self.funcstring = self.funcstring.replace(key, - "("+substitutes[key]+")") + "("+substitutes[key]+")") for otherkey in substitutes.keys(): substitutes[otherkey] = substitutes[otherkey].replace(key, - "("+substitutes[key]+")") + "("+substitutes[key]+")") # Convert the function string to a simpification object self.simpification = sympify(self.funcstring, sympyfuncdict) self.simstring = str(self.simpification) @@ -80,7 +81,7 @@ def G(parms, tau): # symstring = symstring.replace(key, str(vardict[key])) # symstring = symstring.replace("####", "tau") g = eval(self.funcstring, self.vardict) - ## This would be a safer way to do this, but it is too slow! + # This would be a safer way to do this, but it is too slow! # Once simpy supports arrays, we can use these. # # g = np.zeros(len(tau)) @@ -106,6 +107,7 @@ def TestFunction(self): class UserModel(object): """ Class for importing txt files as models into PyCorrFit. """ + def __init__(self, parent): " Define all important constants and variables. " # Current ID is the last model ID we gave away. diff --git a/pycorrfit/gui/wxutils.py b/pycorrfit/gui/wxutils.py index 673cbd93..bc4e4b99 100644 --- a/pycorrfit/gui/wxutils.py +++ b/pycorrfit/gui/wxutils.py @@ -15,20 +15,21 @@ def float2string_nsf(fval, n=7): Returns: String with only n s.f. and trailing zeros. """ - #sgn=np.sign(fval) + # sgn=np.sign(fval) try: if fval == 0: - npoint=n + npoint = n else: - q=abs(fval) - k=int(np.ceil(np.log10(q/n))) + q = abs(fval) + k = int(np.ceil(np.log10(q/n))) # prevent negative significant digits npoint = max(0, n-k) - string="{:.{}f}".format(fval, npoint) + string = "{:.{}f}".format(fval, npoint) except: - string="{}".format(fval) + string = "{}".format(fval) return string + def nice_string(string): """ Convert a string of a float created by `float2string_nsf` @@ -44,9 +45,10 @@ def nice_string(string): olen = len(string) newstring = string.rstrip("0") if olen > len(newstring): - string=newstring+"0" + string = newstring+"0" return string + class PCFFloatValidator(wx.PyValidator): def __init__(self, flag=None, pyVar=None): wx.PyValidator.__init__(self) @@ -93,8 +95,8 @@ def OnChar(self, event): # not allowed return - if ( char in string.digits or - char in ["+", "-"]+onlyonce): + if (char in string.digits or + char in ["+", "-"]+onlyonce): event.Skip() return @@ -108,7 +110,7 @@ def OnChar(self, event): class PCFFloatTextCtrl(wx.TextCtrl): def __init__(self, *args, **kwargs): - wx.TextCtrl.__init__(self, *args, validator=PCFFloatValidator(), size=(110,-1), + wx.TextCtrl.__init__(self, *args, validator=PCFFloatValidator(), size=(110, -1), style=wx.TE_PROCESS_ENTER, **kwargs) self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave) @@ -116,10 +118,10 @@ def __init__(self, *args, **kwargs): def OnMouseEnter(self, e): self.SetFocus() - self.SetSelection(-1,0) + self.SetSelection(-1, 0) def OnMouseLeave(self, e): - self.SetSelection(0,0) + self.SetSelection(0, 0) self.SetInsertionPoint(0) def SetValue(self, value): @@ -155,7 +157,7 @@ def string2float(string): value. """ if string.count("inf"): - if string[0]=="-": + if string[0] == "-": return -np.inf else: return np.inf diff --git a/pycorrfit/meta.py b/pycorrfit/meta.py index 5941d32c..9a9197c0 100644 --- a/pycorrfit/meta.py +++ b/pycorrfit/meta.py @@ -27,16 +27,16 @@ def get_file_location(filename): """ dirname = os.path.dirname(os.path.abspath(__file__)) locations = ["/./", "/pycorrfit_doc/", "/doc/"] - locations += [ "/.."+l for l in locations] - locations = [ os.path.realpath(dirname+l) for l in locations] + locations += ["/.."+l for l in locations] + locations = [os.path.realpath(dirname+l) for l in locations] for i in range(len(locations)): # check /usr/lib64/32 -> /usr/lib for larch in ["lib32", "lib64"]: if dirname.count(larch): locations.append(locations[i].replace(larch, "lib", 1)) - - ## freezed binaries: + + # freezed binaries: if hasattr(sys, 'frozen'): try: adir = sys._MEIPASS + "/doc/" # @UndefinedVariable @@ -44,10 +44,9 @@ def get_file_location(filename): adir = "./" locations.append(os.path.realpath(adir)) for loc in locations: - thechl = os.path.join(loc,filename) + thechl = os.path.join(loc, filename) if os.path.exists(thechl): return thechl break # if this does not work: return None - diff --git a/pycorrfit/models/MODEL_TIRF_1C.py b/pycorrfit/models/MODEL_TIRF_1C.py index fa7c3c19..8995a492 100755 --- a/pycorrfit/models/MODEL_TIRF_1C.py +++ b/pycorrfit/models/MODEL_TIRF_1C.py @@ -14,9 +14,10 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) + def CF_Gxy_TIR_square(parms, tau): # Model 6000 u""" Two-dimensional diffusion with a square shaped lateral detection @@ -33,7 +34,7 @@ def CF_Gxy_TIR_square(parms, tau): Please refer to the documentation of PyCorrFit for further information on this model function. - + Returns: Normalized Lateral correlation function w/square pinhole. """ D = parms[0] @@ -61,7 +62,7 @@ def CF_Gxyz_TIR_square(parms, tau, wixi=wixi): detection area taking into account the size of the point spread function; and an exponential decaying profile in axial direction. - + *parms* - a list of parameters. Parameters (parms[i]): [0] D Diffusion coefficient @@ -74,7 +75,7 @@ def CF_Gxyz_TIR_square(parms, tau, wixi=wixi): Please refer to the documentation of PyCorrFit for further information on this model function. - + Returns: 3D correlation function for TIR-FCS w/square pinhole """ D = parms[0] @@ -82,18 +83,18 @@ def CF_Gxyz_TIR_square(parms, tau, wixi=wixi): a = parms[2] kappa = 1/parms[3] Conc = parms[4] - ### Calculate gxy + # Calculate gxy - # Axial correlation + # Axial correlation x = np.sqrt(D*tau)*kappa w_ix = wixi(x) gz = np.sqrt(D*tau/np.pi) - (2*D*tau*kappa**2 - 1)/(2*kappa) * w_ix # Lateral correlation gx1 = 2/(a**2*np.sqrt(np.pi)) * np.sqrt(sigma**2+D*tau) * \ - ( np.exp(-a**2/(4*(sigma**2+D*tau))) -1 ) - gx2 = 1/a * sps.erf( a / (2*np.sqrt(sigma**2 + D*tau))) - gx = gx1 + gx2 + (np.exp(-a**2/(4*(sigma**2+D*tau))) - 1) + gx2 = 1/a * sps.erf(a / (2*np.sqrt(sigma**2 + D*tau))) + gx = gx1 + gx2 gxy = gx**2 # Non normalized correlation function @@ -120,10 +121,10 @@ def MoreInfo_6000(parms, countrate=None): #sigma = parms[1] a = parms[2] Conc = parms[3] - Info=list() + Info = list() # Detection area: - Aeff = a**2 + Aeff = a**2 # Particel number Neff = Aeff * Conc # Correlation function at tau = 0 @@ -188,7 +189,6 @@ def MoreInfo_6010(parms, countrate): return Info - # 2D Model Square m_twodsq6000 = [6000, u"2D", u"2D diffusion w/ square pinhole", CF_Gxy_TIR_square] @@ -196,7 +196,7 @@ def MoreInfo_6010(parms, countrate): u"Ļ [100 nm]", u"a [100 nm]", u"C_2D [100 /ĀµmĀ²]"] -values_6000 = [0.054, 2.3, 7.5, .6] # [D,lamb,NA,a,conc] +values_6000 = [0.054, 2.3, 7.5, .6] # [D,lamb,NA,a,conc] # For user comfort we add values that are human readable. # Theese will be used for output that only humans can read. labels_human_readable_6000 = [u"D [ĀµmĀ²/s]", @@ -230,7 +230,6 @@ def MoreInfo_6010(parms, countrate): labels_human_readable_6010, values_factor_human_readable_6010] - # Pack the models model1 = dict() model1["Parameters"] = parms_6000 diff --git a/pycorrfit/models/MODEL_TIRF_2D2D.py b/pycorrfit/models/MODEL_TIRF_2D2D.py index fb90a7ef..954ab4c0 100755 --- a/pycorrfit/models/MODEL_TIRF_2D2D.py +++ b/pycorrfit/models/MODEL_TIRF_2D2D.py @@ -14,11 +14,13 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) # model 6022 # 2D + 2D no binding TIRF + + def CF_Gxy_TIR_square_2d2d(parms, tau, wixi=wixi): u""" Two-component two-dimensional diffusion with a square-shaped lateral detection area taking into account the size of the @@ -45,7 +47,7 @@ def CF_Gxy_TIR_square_2d2d(parms, tau, wixi=wixi): Conc_2D2 = parms[5] alpha = parms[6] - ## First the 2D-diffusion of species 1 + # First the 2D-diffusion of species 1 var1 = sigma**2+D_2D1*tau AA1 = 2*np.sqrt(var1)/(a**2*np.sqrt(np.pi)) BB1 = np.exp(-a**2/(4*(var1))) - 1 @@ -53,9 +55,9 @@ def CF_Gxy_TIR_square_2d2d(parms, tau, wixi=wixi): # gx = AA*BB+CC # gxy = gx**2 # g2D = Conc_2D * gxy - g2D1 = Conc_2D1 * (AA1*BB1+CC1)**2 + g2D1 = Conc_2D1 * (AA1*BB1+CC1)**2 - ## Second the 2D-diffusion of species 2 + # Second the 2D-diffusion of species 2 var2 = sigma**2+D_2D2*tau AA2 = 2*np.sqrt(var2)/(a**2*np.sqrt(np.pi)) BB2 = np.exp(-a**2/(4*(var2))) - 1 @@ -63,60 +65,60 @@ def CF_Gxy_TIR_square_2d2d(parms, tau, wixi=wixi): # gx = AA*BB+CC # gxy = gx**2 # g2D = Conc_2D * gxy - g2D2 = alpha**2 * Conc_2D2 * (AA2*BB2+CC2)**2 + g2D2 = alpha**2 * Conc_2D2 * (AA2*BB2+CC2)**2 - ## Finally the Prefactor + # Finally the Prefactor F = Conc_2D1 + alpha * Conc_2D2 G = (g2D1 + g2D2) / F**2 return G # 2D-2D Model TIR -m_tir_2d_2d_mix_6022 = [6022, u"2D+2D","Separate 2D diffusion, TIR", +m_tir_2d_2d_mix_6022 = [6022, u"2D+2D", "Separate 2D diffusion, TIR", CF_Gxy_TIR_square_2d2d] -labels_6022 = [ u"D"+u"\u2081"+u" [10 ĀµmĀ²/s]", - u"D"+u"\u2082"+u" [10 ĀµmĀ²/s]", - u"Ļ [100 nm]", - u"a [100 nm]", - u"C"+u"\u2081"+u" [100 /ĀµmĀ²]", - u"C"+u"\u2082"+u" [100 /ĀµmĀ²]", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" - ] +labels_6022 = [u"D"+u"\u2081"+u" [10 ĀµmĀ²/s]", + u"D"+u"\u2082"+u" [10 ĀµmĀ²/s]", + u"Ļ [100 nm]", + u"a [100 nm]", + u"C"+u"\u2081"+u" [100 /ĀµmĀ²]", + u"C"+u"\u2082"+u" [100 /ĀµmĀ²]", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" + ] values_6022 = [ - 0.01, # D_2Dā [10 ĀµmĀ²/s] - 0.90, # D_2Dā [10 ĀµmĀ²/s] - 2.3, # Ļ [100 nm] - 7.50, # a [100 nm] - 0.01, # conc.2Dā [100 /ĀµmĀ²] - 0.03, # conc.2Dā [100 /ĀµmĀ²] - 1 # alpha - ] + 0.01, # D_2Dā [10 ĀµmĀ²/s] + 0.90, # D_2Dā [10 ĀµmĀ²/s] + 2.3, # Ļ [100 nm] + 7.50, # a [100 nm] + 0.01, # conc.2Dā [100 /ĀµmĀ²] + 0.03, # conc.2Dā [100 /ĀµmĀ²] + 1 # alpha +] # For user comfort we add values that are human readable. # Theese will be used for output that only humans can read. labels_human_readable_6022 = [ - u"D"+u"\u2081"+u" [ĀµmĀ²/s]", - u"D"+u"\u2082"+u" [ĀµmĀ²/s]", - u"Ļ [nm]", - u"a [nm]", - u"C"+u"\u2081"+u" [1/ĀµmĀ²]", - u"C"+u"\u2082"+u" [1/ĀµmĀ²]", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" - ] + u"D"+u"\u2081"+u" [ĀµmĀ²/s]", + u"D"+u"\u2082"+u" [ĀµmĀ²/s]", + u"Ļ [nm]", + u"a [nm]", + u"C"+u"\u2081"+u" [1/ĀµmĀ²]", + u"C"+u"\u2082"+u" [1/ĀµmĀ²]", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" +] values_factor_human_readable_6022 = [ - 10, # D_2Dā [10 ĀµmĀ²/s], - 10, # D_2Dā [10 ĀµmĀ²/s] - 100, # Ļ [100 nm] - 100, # a [100 nm] - 100, # conc.2Dā [100 /ĀµmĀ²] - 100, # conc.2Dā [100 /ĀµmĀ²] - 1 - ] + 10, # D_2Dā [10 ĀµmĀ²/s], + 10, # D_2Dā [10 ĀµmĀ²/s] + 100, # Ļ [100 nm] + 100, # a [100 nm] + 100, # conc.2Dā [100 /ĀµmĀ²] + 100, # conc.2Dā [100 /ĀµmĀ²] + 1 +] valuestofit_6022 = [False, True, False, False, False, True, False] -parms_6022 = [labels_6022, values_6022, valuestofit_6022, +parms_6022 = [labels_6022, values_6022, valuestofit_6022, labels_human_readable_6022, values_factor_human_readable_6022] -boundaries = [ [0, np.inf] ] * len(values_6022) +boundaries = [[0, np.inf]] * len(values_6022) model1 = dict() diff --git a/pycorrfit/models/MODEL_TIRF_3D2D.py b/pycorrfit/models/MODEL_TIRF_3D2D.py index 1f3e2b8d..a6e084cf 100755 --- a/pycorrfit/models/MODEL_TIRF_3D2D.py +++ b/pycorrfit/models/MODEL_TIRF_3D2D.py @@ -14,7 +14,7 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) @@ -49,7 +49,7 @@ def CF_Gxyz_TIR_square_3d2d(parms, tau, wixi=wixi): Conc_2D = parms[6] alpha = parms[7] - ## First the 2D-diffusion at z=0 + # First the 2D-diffusion at z=0 var1 = sigma**2+D_2D*tau AA = 2*np.sqrt(var1)/(a**2*np.sqrt(np.pi)) BB = np.exp(-a**2/(4*(var1))) - 1 @@ -57,23 +57,23 @@ def CF_Gxyz_TIR_square_3d2d(parms, tau, wixi=wixi): # gx = AA*BB+CC # gxy = gx**2 # g2D = Conc_2D * gxy - g2D = Conc_2D * (AA*BB+CC)**2 + g2D = Conc_2D * (AA*BB+CC)**2 - ## Second the 3D diffusion for z>0 - # Axial correlation + # Second the 3D diffusion for z>0 + # Axial correlation x = np.sqrt(D_3D*tau)*kappa w_ix = wixi(x) gz = np.sqrt(D_3D*tau/np.pi) - (2*D_3D*tau*kappa**2 - 1)/(2*kappa) * w_ix # Lateral correlation gx1 = 2/(a**2*np.sqrt(np.pi)) * np.sqrt(sigma**2+D_3D*tau) * \ - ( np.exp(-a**2/(4*(sigma**2+D_3D*tau))) -1 ) - gx2 = 1/a * sps.erf( a / (2*np.sqrt(sigma**2 + D_3D*tau))) - gx = gx1 + gx2 + (np.exp(-a**2/(4*(sigma**2+D_3D*tau))) - 1) + gx2 = 1/a * sps.erf(a / (2*np.sqrt(sigma**2 + D_3D*tau))) + gx = gx1 + gx2 gxy = gx**2 # Non normalized correlation function g3D = alpha**2 * Conc_3D * gxy * gz - ## Finally the Prefactor + # Finally the Prefactor F = alpha * Conc_3D / kappa + Conc_2D G = (g3D + g2D) / F**2 return G @@ -86,46 +86,46 @@ def CF_Gxyz_TIR_square_3d2d(parms, tau, wixi=wixi): labels_6020 = [u"D_3D [10 ĀµmĀ²/s]", u"D_2D [10 ĀµmĀ²/s]", u"Ļ [100 nm]", - u"a [100 nm]", - u"d_eva [100 nm]", - u"C_3D [1000 /ĀµmĀ³]", - u"C_2D [100 /ĀµmĀ²]", + u"a [100 nm]", + u"d_eva [100 nm]", + u"C_3D [1000 /ĀµmĀ³]", + u"C_2D [100 /ĀµmĀ²]", u"\u03b1"+" (q3D/q2D)" - ] + ] values_6020 = [ - 50.0, # D_3D [10 ĀµmĀ²/s] - 0.81, # D_2D [10 ĀµmĀ²/s] - 2.3, # Ļ [100 nm] - 7.50, # a [100 nm] - 1.0, # d_eva [100 nm] - 0.01, # conc.3D [1000 /ĀµmĀ³] - 0.03, # conc.2D [100 /ĀµmĀ²] - 1 # alpha - ] + 50.0, # D_3D [10 ĀµmĀ²/s] + 0.81, # D_2D [10 ĀµmĀ²/s] + 2.3, # Ļ [100 nm] + 7.50, # a [100 nm] + 1.0, # d_eva [100 nm] + 0.01, # conc.3D [1000 /ĀµmĀ³] + 0.03, # conc.2D [100 /ĀµmĀ²] + 1 # alpha +] # For user comfort we add values that are human readable. # Theese will be used for output that only humans can read. labels_human_readable_6020 = [ - u"D_3D [ĀµmĀ²/s]", - u"D_2D [ĀµmĀ²/s]", - u"Ļ [nm]", - u"a [nm]", - u"d_eva [nm]", - u"C_3D [1/ĀµmĀ³]", - u"C_2D [1/ĀµmĀ²]", - u"\u03b1"+" (q3D/q2D)" - ] + u"D_3D [ĀµmĀ²/s]", + u"D_2D [ĀµmĀ²/s]", + u"Ļ [nm]", + u"a [nm]", + u"d_eva [nm]", + u"C_3D [1/ĀµmĀ³]", + u"C_2D [1/ĀµmĀ²]", + u"\u03b1"+" (q3D/q2D)" +] values_factor_human_readable_6020 = [ - 10, # D_3D [ĀµmĀ²/s] - 10, # D_2D [10 ĀµmĀ²/s] - 100, # Ļ [100 nm] - 100, # a [100 nm] - 100, # d_eva [100 nm] - 1000, # conc.3D [1000 /ĀµmĀ³] - 100, # conc.2D [100 /ĀµmĀ²] - 1 # alpha - ] + 10, # D_3D [ĀµmĀ²/s] + 10, # D_2D [10 ĀµmĀ²/s] + 100, # Ļ [100 nm] + 100, # a [100 nm] + 100, # d_eva [100 nm] + 1000, # conc.3D [1000 /ĀµmĀ³] + 100, # conc.2D [100 /ĀµmĀ²] + 1 # alpha +] valuestofit_6020 = [False, True, False, False, False, False, True, False] -parms_6020 = [labels_6020, values_6020, valuestofit_6020, +parms_6020 = [labels_6020, values_6020, valuestofit_6020, labels_human_readable_6020, values_factor_human_readable_6020] diff --git a/pycorrfit/models/MODEL_TIRF_3D2Dkin_Ries.py b/pycorrfit/models/MODEL_TIRF_3D2Dkin_Ries.py index 12f8126f..7a80781e 100755 --- a/pycorrfit/models/MODEL_TIRF_3D2Dkin_Ries.py +++ b/pycorrfit/models/MODEL_TIRF_3D2Dkin_Ries.py @@ -9,6 +9,7 @@ import scipy.special as sps import numpy.lib.scimath as nps + def wixi(x): """ Complex Error Function (Faddeeva/Voigt). w(i*x) = exp(x**2) * ( 1-erf(x) ) @@ -93,15 +94,15 @@ def CF_gz_CC(parms, tau, wixi=wixi): k_d = parms[10] # Define some other constants: K = k_a/k_d # equilibrium constant - Beta = 1/(1 + K*Conc_3D) # This is wrong in the Ries paper + Beta = 1/(1 + K*Conc_3D) # This is wrong in the Ries paper #Re = D / d_eva**2 Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: - sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt( Rr**2/(4*Rt) - Rr ) - sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt( Rr**2/(4*Rt) - Rr ) - R1 = sqrtR1 **2 - R2 = sqrtR2 **2 + sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt(Rr**2/(4*Rt) - Rr) + sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt(Rr**2/(4*Rt) - Rr) + R1 = sqrtR1 ** 2 + R2 = sqrtR2 ** 2 # Calculate return function A1 = eta_2D * Conc_2D / (eta_3D * Conc_3D) * Beta A2 = sqrtR1 * wixi(-nps.sqrt(tau*R2)) - sqrtR2 * wixi(-nps.sqrt(tau*R1)) @@ -151,10 +152,10 @@ def CF_gz_AC(parms, tau, wixi=wixi): Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: - sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt( Rr**2/(4*Rt) - Rr ) - sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt( Rr**2/(4*Rt) - Rr ) - R1 = sqrtR1 **2 - R2 = sqrtR2 **2 + sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt(Rr**2/(4*Rt) - Rr) + sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt(Rr**2/(4*Rt) - Rr) + R1 = sqrtR1 ** 2 + R2 = sqrtR2 ** 2 # And even more more: sqrtR3 = sqrtR1 + nps.sqrt(Re) sqrtR4 = sqrtR2 + nps.sqrt(Re) @@ -163,9 +164,9 @@ def CF_gz_AC(parms, tau, wixi=wixi): # Calculate return function A1 = eta_2D * Conc_2D * k_d / (eta_3D * Conc_3D) A2 = sqrtR4*wixi(-nps.sqrt(tau*R1)) - sqrtR3*wixi(-nps.sqrt(tau*R2)) - A3 = ( sqrtR1 - sqrtR2 ) * wixi( nps.sqrt(tau*Re) ) - A4 = ( sqrtR1 - sqrtR2 ) * sqrtR3 * sqrtR4 - Solution = A1 * ( A2 + A3 ) / A4 + A3 = (sqrtR1 - sqrtR2) * wixi(nps.sqrt(tau*Re)) + A4 = (sqrtR1 - sqrtR2) * sqrtR3 * sqrtR4 + Solution = A1 * (A2 + A3) / A4 # There are some below numerical errors-imaginary numbers. # We do not want them. return np.real_if_close(Solution) @@ -211,30 +212,30 @@ def CF_gz_AA(parms, tau, wixi=wixi): Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: - sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt( Rr**2/(4*Rt) - Rr ) - sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt( Rr**2/(4*Rt) - Rr ) - R1 = sqrtR1 **2 - R2 = sqrtR2 **2 + sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt(Rr**2/(4*Rt) - Rr) + sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt(Rr**2/(4*Rt) - Rr) + R1 = sqrtR1 ** 2 + R2 = sqrtR2 ** 2 # And even more more: sqrtR3 = sqrtR1 + nps.sqrt(Re) sqrtR4 = sqrtR2 + nps.sqrt(Re) - R3 = sqrtR3 **2 - R4 = sqrtR4 **2 + R3 = sqrtR3 ** 2 + R4 = sqrtR4 ** 2 # Calculate return function - Sum1 = d * nps.sqrt( Re*tau/np.pi ) - Sum2 = -d/2*(2*tau*Re -1) * wixi(np.sqrt(tau*Re)) - Sum3Mult1 = - eta_2D * Conc_2D * k_d / ( eta_3D * Conc_3D * - (sqrtR1 - sqrtR2) ) + Sum1 = d * nps.sqrt(Re*tau/np.pi) + Sum2 = -d/2*(2*tau*Re - 1) * wixi(np.sqrt(tau*Re)) + Sum3Mult1 = - eta_2D * Conc_2D * k_d / (eta_3D * Conc_3D * + (sqrtR1 - sqrtR2)) S3M2S1M1 = sqrtR1/R3 S3M2S1M2S1 = wixi(-nps.sqrt(tau*R1)) + -2*nps.sqrt(tau*R3/np.pi) - S3M2S1M2S2 = ( 2*tau*sqrtR1*nps.sqrt(Re) + 2*tau*Re -1 ) * \ - wixi(nps.sqrt(tau*Re)) + S3M2S1M2S2 = (2*tau*sqrtR1*nps.sqrt(Re) + 2*tau*Re - 1) * \ + wixi(nps.sqrt(tau*Re)) S3M2S2M1 = -sqrtR2/R4 S3M2S2M2S1 = wixi(-nps.sqrt(tau*R2)) + -2*nps.sqrt(tau*R4/np.pi) - S3M2S2M2S2 = ( 2*tau*sqrtR2*nps.sqrt(Re) + 2*tau*Re -1 ) * \ - wixi(nps.sqrt(tau*Re)) - Sum3 = Sum3Mult1 * ( S3M2S1M1 * (S3M2S1M2S1 + S3M2S1M2S2) + - S3M2S2M1 * (S3M2S2M2S1 + S3M2S2M2S2) ) + S3M2S2M2S2 = (2*tau*sqrtR2*nps.sqrt(Re) + 2*tau*Re - 1) * \ + wixi(nps.sqrt(tau*Re)) + Sum3 = Sum3Mult1 * (S3M2S1M1 * (S3M2S1M2S1 + S3M2S1M2S2) + + S3M2S2M1 * (S3M2S2M2S1 + S3M2S2M2S2)) Sum = Sum1 + Sum2 + Sum3 # There are some below numerical errors-imaginary numbers. # We do not want them. @@ -242,9 +243,9 @@ def CF_gz_AA(parms, tau, wixi=wixi): # 3D-2D binding/unbinding TIRF -def CF_Gxyz_TIR_square_ubibi(parms, tau, - gAAz=CF_gz_AA, gACz=CF_gz_AC, gCCz=CF_gz_CC, - gxy=CF_gxy_square): +def CF_Gxyz_TIR_square_ubibi(parms, tau, + gAAz=CF_gz_AA, gACz=CF_gz_AC, gCCz=CF_gz_CC, + gxy=CF_gxy_square): u""" Two-component two- and three-dimensional diffusion with a square-shaped lateral detection area taking into account the size of the point spread function; and an exponential @@ -287,7 +288,7 @@ def CF_Gxyz_TIR_square_ubibi(parms, tau, eta_2D = parms[8] #k_a = parms[9] #k_d = parms[10] - ## We now need to copmute a real beast: + # We now need to copmute a real beast: # Inter species non-normalized correlation functions # gAA = gAAz * gxy(D_3D) # gAC = gACz * np.sqrt ( gxy(D_3D) * gxy(D_2D) ) @@ -310,11 +311,11 @@ def CF_Gxyz_TIR_square_ubibi(parms, tau, parms_xy_3D = [D_3D, sigma, a] # Here we go. gAA = gAAz(parms, tau) * gxy(parms_xy_3D, tau) - gAC = gACz(parms, tau) * nps.sqrt( gxy(parms_xy_3D, tau) * - gxy(parms_xy_2D, tau) ) + gAC = gACz(parms, tau) * nps.sqrt(gxy(parms_xy_3D, tau) * + gxy(parms_xy_2D, tau)) gCC = gCCz(parms, tau) * gxy(parms_xy_2D, tau) # Nonnormalized correlation function - g = eta_3D * Conc_3D * ( gAA + 2*gAC + gCC ) + g = eta_3D * Conc_3D * (gAA + 2*gAC + gCC) # Expectation value of fluorescence signal F = eta_3D * Conc_3D / kappa + eta_2D * Conc_2D # Normalized correlation function @@ -324,10 +325,7 @@ def CF_Gxyz_TIR_square_ubibi(parms, tau, return G.real #FNEW = eta_3D * Conc_3D / kappa #GNEW = eta_3D * Conc_3D * gCCz(parms, tau) / FNEW**2 - #return GNEW.real - - - + # return GNEW.real # 3D-2D binding Model TIR @@ -337,61 +335,61 @@ def CF_Gxyz_TIR_square_ubibi(parms, tau, labels_6021 = [u"D_3D [10 ĀµmĀ²/s]", u"D_2D [10 ĀµmĀ²/s]", u"Ļ [100 nm]", - u"a [100 nm]", - u"d_eva [100 nm]", - u"C_3D [1000 /ĀµmĀ³]", - u"C_2D[100 /ĀµmĀ²]", - u"Ī·_3D", - u"Ī·_2D", - u"k_a [ĀµmĀ³/s]", + u"a [100 nm]", + u"d_eva [100 nm]", + u"C_3D [1000 /ĀµmĀ³]", + u"C_2D[100 /ĀµmĀ²]", + u"Ī·_3D", + u"Ī·_2D", + u"k_a [ĀµmĀ³/s]", u"k_d [10Ā³ /s]" - ] + ] values_6021 = [ - 9.0, # D_3D [10 ĀµmĀ²/s] - 0.0, # D_2D [10 ĀµmĀ²/s] - 2.3, # Ļ [100 nm] - 7.50, # a [100 nm] - 1.0, # d_eva [100 nm] - 0.01, # conc.3D [1000 /ĀµmĀ³] - 0.03, # conc.2D [100 /ĀµmĀ²] - 1, # Ī·_3D - 1, # Ī·_2D - 0.00001, # k_a [ĀµmĀ³/s] - 0.000064 # k_d [10Ā³ /s] - ] + 9.0, # D_3D [10 ĀµmĀ²/s] + 0.0, # D_2D [10 ĀµmĀ²/s] + 2.3, # Ļ [100 nm] + 7.50, # a [100 nm] + 1.0, # d_eva [100 nm] + 0.01, # conc.3D [1000 /ĀµmĀ³] + 0.03, # conc.2D [100 /ĀµmĀ²] + 1, # Ī·_3D + 1, # Ī·_2D + 0.00001, # k_a [ĀµmĀ³/s] + 0.000064 # k_d [10Ā³ /s] +] valuestofit_6021 = [False, True, False, False, False, False, True, False, False, False, False] # For user comfort we add values that are human readable. # Theese will be used for output that only humans can read. labels_human_readable_6021 = [ - u"D_3D [ĀµmĀ²/s]", - u"D_2D [ĀµmĀ²/s]", - u"Ļ [nm]", - u"a [nm]", - u"d_eva [nm]", - u"C_3D [1/ĀµmĀ³]", - u"C_2D [1/ĀµmĀ²]", - u"Ī·_3D", - u"Ī·_2D", - u"k_a [ĀµmĀ³/s]", - u"k_d [1/s]" - ] -values_factor_human_readable_6021 = [10, # "D_3D [ĀµmĀ²/s]", - 10, # D_2D [10 ĀµmĀ²/s] - 100, # Ļ [100 nm] - 100, # a [100 nm] - 100, # d_eva [100 nm] - 1000, # conc.3D [1000 /ĀµmĀ³] - 100, # conc.2D [100 /ĀµmĀ²] - 1, # Ī·_3D - 1, # Ī·_2D - 1, # k_a [ĀµmĀ³/s] - 1000 # k_d [10Ā³ /s] - ] + u"D_3D [ĀµmĀ²/s]", + u"D_2D [ĀµmĀ²/s]", + u"Ļ [nm]", + u"a [nm]", + u"d_eva [nm]", + u"C_3D [1/ĀµmĀ³]", + u"C_2D [1/ĀµmĀ²]", + u"Ī·_3D", + u"Ī·_2D", + u"k_a [ĀµmĀ³/s]", + u"k_d [1/s]" +] +values_factor_human_readable_6021 = [10, # "D_3D [ĀµmĀ²/s]", + 10, # D_2D [10 ĀµmĀ²/s] + 100, # Ļ [100 nm] + 100, # a [100 nm] + 100, # d_eva [100 nm] + 1000, # conc.3D [1000 /ĀµmĀ³] + 100, # conc.2D [100 /ĀµmĀ²] + 1, # Ī·_3D + 1, # Ī·_2D + 1, # k_a [ĀµmĀ³/s] + 1000 # k_d [10Ā³ /s] + ] parms_6021 = [labels_6021, values_6021, valuestofit_6021, labels_human_readable_6021, values_factor_human_readable_6021] -boundaries = [ [0, np.inf] ] * len(values_6021) +boundaries = [[0, np.inf]] * len(values_6021) model1 = dict() model1["Parameters"] = parms_6021 diff --git a/pycorrfit/models/MODEL_TIRF_3D3D.py b/pycorrfit/models/MODEL_TIRF_3D3D.py index b01334bb..10131cd4 100755 --- a/pycorrfit/models/MODEL_TIRF_3D3D.py +++ b/pycorrfit/models/MODEL_TIRF_3D3D.py @@ -14,7 +14,7 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) @@ -49,37 +49,37 @@ def CF_Gxyz_TIR_square_3d3d(parms, tau, wixi=wixi): Conc_3D2 = parms[6] alpha = parms[7] - ## First, the 3D diffusion of species 1 - # Axial correlation + # First, the 3D diffusion of species 1 + # Axial correlation x1 = np.sqrt(D_3D1*tau)*kappa w_ix1 = wixi(x1) gz1 = np.sqrt(D_3D1*tau/np.pi) - (2*D_3D1*tau*kappa**2 - 1)/(2*kappa) * \ - w_ix1 + w_ix1 # Lateral correlation gx1_1 = 2/(a**2*np.sqrt(np.pi)) * np.sqrt(sigma**2+D_3D1*tau) * \ - ( np.exp(-a**2/(4*(sigma**2+D_3D1*tau))) -1 ) - gx2_1 = 1/a * sps.erf( a / (2*np.sqrt(sigma**2 + D_3D1*tau))) - gx1 = gx1_1 + gx2_1 + (np.exp(-a**2/(4*(sigma**2+D_3D1*tau))) - 1) + gx2_1 = 1/a * sps.erf(a / (2*np.sqrt(sigma**2 + D_3D1*tau))) + gx1 = gx1_1 + gx2_1 gxy1 = gx1**2 # Non normalized correlation function g3D1 = Conc_3D1 * gxy1 * gz1 - ## Second, the 3D diffusion of species 2 - # Axial correlation + # Second, the 3D diffusion of species 2 + # Axial correlation x2 = np.sqrt(D_3D2*tau)*kappa w_ix2 = wixi(x2) gz2 = np.sqrt(D_3D2*tau/np.pi) - (2*D_3D2*tau*kappa**2 - 1)/(2*kappa) * \ - w_ix2 + w_ix2 # Lateral correlation gx1_2 = 2/(a**2*np.sqrt(np.pi)) * np.sqrt(sigma**2+D_3D2*tau) * \ - ( np.exp(-a**2/(4*(sigma**2+D_3D2*tau))) -1 ) - gx2_2 = 1/a * sps.erf( a / (2*np.sqrt(sigma**2 + D_3D2*tau))) - gx2 = gx1_2 + gx2_2 + (np.exp(-a**2/(4*(sigma**2+D_3D2*tau))) - 1) + gx2_2 = 1/a * sps.erf(a / (2*np.sqrt(sigma**2 + D_3D2*tau))) + gx2 = gx1_2 + gx2_2 gxy2 = gx2**2 # Non normalized correlation function g3D2 = alpha**2 * Conc_3D2 * gxy2 * gz2 - ## Finally the Prefactor + # Finally the Prefactor F = (Conc_3D1 + alpha * Conc_3D2) / kappa G = (g3D1 + g3D2) / F**2 return G @@ -92,45 +92,45 @@ def CF_Gxyz_TIR_square_3d3d(parms, tau, wixi=wixi): labels_6023 = [u"D"+u"\u2081"+u" [10 ĀµmĀ²/s]", u"D"+u"\u2082"+u" [10 ĀµmĀ²/s]", u"Ļ [100 nm]", - u"a [100 nm]", - u"d_eva [100 nm]", - u"C"+u"\u2081"+u" [1000 /ĀµmĀ³]", - u"C"+u"\u2082"+u" [1000 /ĀµmĀ³]", + u"a [100 nm]", + u"d_eva [100 nm]", + u"C"+u"\u2081"+u" [1000 /ĀµmĀ³]", + u"C"+u"\u2082"+u" [1000 /ĀµmĀ³]", u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" - ] + ] values_6023 = [ - 0.9, # D_3Dā [10 ĀµmĀ²/s] - 9.0, # D_3Dā [10 ĀµmĀ²/s] - 2.3, # Ļ [100 nm] - 7.50, # a [100 nm] - 1.0, # d_eva [100 nm] - 0.01, # conc.3Dā [1000 /ĀµmĀ³] - 0.03, # conc.3Dā [1000 /ĀµmĀ³] - 1 # alpha - ] + 0.9, # D_3Dā [10 ĀµmĀ²/s] + 9.0, # D_3Dā [10 ĀµmĀ²/s] + 2.3, # Ļ [100 nm] + 7.50, # a [100 nm] + 1.0, # d_eva [100 nm] + 0.01, # conc.3Dā [1000 /ĀµmĀ³] + 0.03, # conc.3Dā [1000 /ĀµmĀ³] + 1 # alpha +] # For user comfort we add values that are human readable. # Theese will be used for output that only humans can read. labels_human_readable_6023 = [ - u"D"+u"\u2081"+u" [ĀµmĀ²/s]", - u"D"+u"\u2082"+u" [ĀµmĀ²/s]", - u"Ļ [nm]", - u"a [nm]", - u"d_eva [nm]", - u"C"+u"\u2081"+u" [1/ĀµmĀ³]", - u"C"+u"\u2082"+u" [1/ĀµmĀ³]", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" - ] -values_factor_human_readable_6023 = [10, # "D_3Dā [ĀµmĀ²/s]", - 10, # D_3Dā [10 ĀµmĀ²/s] - 100, # Ļ [100 nm] - 100, # a [100 nm] - 100, # d_eva [100 nm] - 1000, # conc.3Dā [1000 /ĀµmĀ³] - 1000, # conc.3Dā [1000 /ĀµmĀ³] - 1 # alpha - ] + u"D"+u"\u2081"+u" [ĀµmĀ²/s]", + u"D"+u"\u2082"+u" [ĀµmĀ²/s]", + u"Ļ [nm]", + u"a [nm]", + u"d_eva [nm]", + u"C"+u"\u2081"+u" [1/ĀµmĀ³]", + u"C"+u"\u2082"+u" [1/ĀµmĀ³]", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")" +] +values_factor_human_readable_6023 = [10, # "D_3Dā [ĀµmĀ²/s]", + 10, # D_3Dā [10 ĀµmĀ²/s] + 100, # Ļ [100 nm] + 100, # a [100 nm] + 100, # d_eva [100 nm] + 1000, # conc.3Dā [1000 /ĀµmĀ³] + 1000, # conc.3Dā [1000 /ĀµmĀ³] + 1 # alpha + ] valuestofit_6023 = [False, True, False, False, False, False, True, False] -parms_6023 = [labels_6023, values_6023, valuestofit_6023, +parms_6023 = [labels_6023, values_6023, valuestofit_6023, labels_human_readable_6023, values_factor_human_readable_6023] diff --git a/pycorrfit/models/MODEL_TIRF_gaussian_1C.py b/pycorrfit/models/MODEL_TIRF_gaussian_1C.py index 2be593e7..70fd33fc 100755 --- a/pycorrfit/models/MODEL_TIRF_gaussian_1C.py +++ b/pycorrfit/models/MODEL_TIRF_gaussian_1C.py @@ -1,6 +1,7 @@ import numpy as np import scipy.special as sps + def wixi(x): """ Complex Error Function (Faddeeva/Voigt). w(i*x) = exp(x**2) * ( 1-erf(x) ) @@ -13,9 +14,10 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) + def CF_Gxyz_TIR_gauss(parms, tau): u""" Three-dimensional free diffusion with a Gaussian lateral detection profile and an exponentially decaying profile @@ -50,16 +52,17 @@ def CF_Gxyz_TIR_gauss(parms, tau): taudiff = r0**2/(4*D) # 2D gauss component # G2D = 1/N2D * g2D = 1/(Aeff*Conc.2D) * g2D - g2D = 1 / ( (1.+tau/taudiff) ) + g2D = 1 / ((1.+tau/taudiff)) # 1d TIR component - # Axial correlation + # Axial correlation kappa = 1/deva x = np.sqrt(D*tau)*kappa w_ix = wixi(x) # Gz = 1/N1D * gz = kappa / Conc.1D * gz - gz = kappa * (np.sqrt(D*tau/np.pi) - (2*D*tau*kappa**2 - 1)/(2*kappa) * w_ix) + gz = kappa * (np.sqrt(D*tau/np.pi) - + (2*D*tau*kappa**2 - 1)/(2*kappa) * w_ix) # gz * g2D * 1/( deva *A2D) * 1 / Conc3D @@ -69,7 +72,6 @@ def CF_Gxyz_TIR_gauss(parms, tau): # 1 / (Conc * deva * np.pi * r0) * gz * g2D return 1 / (Neff) * g2D * gz - def CF_Gxyz_TIR_gauss_trip(parms, tau): @@ -102,8 +104,8 @@ def CF_Gxyz_TIR_gauss_trip(parms, tau): r0 = parms[1] deva = parms[2] Conc = parms[3] - tautrip=parms[4] - T=parms[5] + tautrip = parms[4] + T = parms[5] # Calculate sigma: width of the gaussian approximation of the PSF Veff = np.pi * r0**2 * deva @@ -112,18 +114,19 @@ def CF_Gxyz_TIR_gauss_trip(parms, tau): taudiff = r0**2/(4*D) # 2D gauss component # G2D = 1/N2D * g2D = 1/(Aeff*Conc.2D) * g2D - g2D = 1 / ( (1.+tau/taudiff) ) + g2D = 1 / ((1.+tau/taudiff)) # 1d TIR component - # Axial correlation + # Axial correlation kappa = 1/deva x = np.sqrt(D*tau)*kappa w_ix = wixi(x) # Gz = 1/N1D * gz = kappa / Conc.1D * gz - gz = kappa * (np.sqrt(D*tau/np.pi) - (2*D*tau*kappa**2 - 1)/(2*kappa) * w_ix) + gz = kappa * (np.sqrt(D*tau/np.pi) - + (2*D*tau*kappa**2 - 1)/(2*kappa) * w_ix) - ### triplet + # triplet if tautrip == 0 or T == 0: triplet = 1 else: @@ -137,7 +140,6 @@ def CF_Gxyz_TIR_gauss_trip(parms, tau): return 1 / (Neff) * g2D * gz * triplet - def MoreInfo_6013(parms, countrate=None): u"""Supplementary variables: Beware that the effective volume is chosen arbitrarily. @@ -152,7 +154,7 @@ def MoreInfo_6013(parms, countrate=None): r0 = parms[1] deva = parms[2] Conc = parms[3] - Info=list() + Info = list() # Detection area: Veff = np.pi * r0**2 * deva Neff = Conc * Veff @@ -182,7 +184,7 @@ def MoreInfo_6014(parms, countrate=None): r0 = parms[1] deva = parms[2] Conc = parms[3] - Info=list() + Info = list() # Detection area: Veff = np.pi * r0**2 * deva Neff = Conc * Veff @@ -204,6 +206,7 @@ def get_boundaries_6014(parms): boundaries[5] = [0, 1] return boundaries + def get_boundaries_6013(parms): # strictly positive boundaries = [[0, None]]*len(parms) @@ -211,7 +214,7 @@ def get_boundaries_6013(parms): # 3D Model TIR gaussian -m_3dtirsq6013 = [6013, "3D","Simple 3D diffusion w/ TIR", +m_3dtirsq6013 = [6013, "3D", "Simple 3D diffusion w/ TIR", CF_Gxyz_TIR_gauss] labels_6013 = [u"D [10 ĀµmĀ²/s]", u"rā [100 nm]", @@ -227,13 +230,13 @@ def get_boundaries_6013(parms): u"rā [nm]", u"d_eva [nm]", u"C_3D [1/ĀµmĀ³]"] -values_factor_human_readable_6013 = [10, +values_factor_human_readable_6013 = [10, 100, 100, 1000] valuestofit_6013 = [True, False, False, True] parms_6013 = [labels_6013, values_6013, valuestofit_6013, - labels_human_readable_6013, values_factor_human_readable_6013] + labels_human_readable_6013, values_factor_human_readable_6013] # Pack the models model1 = dict() @@ -244,7 +247,7 @@ def get_boundaries_6013(parms): # 3D Model TIR gaussian + triplet -m_3dtirsq6014 = [6014, "T+3D","Simple 3D diffusion + triplet w/ TIR", +m_3dtirsq6014 = [6014, "T+3D", "Simple 3D diffusion + triplet w/ TIR", CF_Gxyz_TIR_gauss_trip] labels_6014 = [u"D [10 ĀµmĀ²/s]", u"rā [100 nm]", @@ -272,7 +275,7 @@ def get_boundaries_6013(parms): 1] valuestofit_6014 = [True, False, False, True, False, False] parms_6014 = [labels_6014, values_6014, valuestofit_6014, - labels_human_readable_6014, values_factor_human_readable_6014] + labels_human_readable_6014, values_factor_human_readable_6014] # Pack the models model2 = dict() diff --git a/pycorrfit/models/MODEL_TIRF_gaussian_3D2D.py b/pycorrfit/models/MODEL_TIRF_gaussian_3D2D.py index c1f762f2..c823f75a 100755 --- a/pycorrfit/models/MODEL_TIRF_gaussian_3D2D.py +++ b/pycorrfit/models/MODEL_TIRF_gaussian_3D2D.py @@ -14,11 +14,13 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - + return np.real_if_close(wixi) # 3D + 2D + T # model 6033 + + def CF_Gxyz_3d2dT_gauss(parms, tau): u""" Two-component, two- and three-dimensional diffusion with a Gaussian lateral detection profile and @@ -58,45 +60,45 @@ def CF_Gxyz_3d2dT_gauss(parms, tau): [9] offset *tau* - lag time """ - n=parms[0] - D2D=parms[1] - D3D=parms[2] - F=parms[3] - r0=parms[4] - deva=parms[5] - alpha=parms[6] - tautrip=parms[7] - T=parms[8] - off=parms[9] - - ### 2D species + n = parms[0] + D2D = parms[1] + D3D = parms[2] + F = parms[3] + r0 = parms[4] + deva = parms[5] + alpha = parms[6] + tautrip = parms[7] + T = parms[8] + off = parms[9] + + # 2D species taud2D = r0**2/(4*D2D) - particle2D = (1-F)/ (1+tau/taud2D) + particle2D = (1-F) / (1+tau/taud2D) - ### 3D species + # 3D species taud3D = r0**2/(4*D3D) # 2D gauss component - g2D3D = 1 / ( (1.+tau/taud3D) ) + g2D3D = 1 / ((1.+tau/taud3D)) # 1d TIR component - # Axial correlation + # Axial correlation kappa = 1/deva x = np.sqrt(D3D*tau)*kappa w_ix = wixi(x) # Gz = 1/N1D * gz = kappa / Conc.1D * gz - gz = kappa * (np.sqrt(D3D*tau/np.pi) - - (2*D3D*tau*kappa**2 - 1)/(2*kappa) * w_ix) + gz = kappa * (np.sqrt(D3D*tau/np.pi) - + (2*D3D*tau*kappa**2 - 1)/(2*kappa) * w_ix) particle3D = alpha**2*F * g2D3D * gz - ### triplet + # triplet if tautrip == 0 or T == 0: triplet = 1 else: triplet = 1 + T/(1-T) * np.exp(-tau/tautrip) - ### Norm + # Norm norm = (1-F + alpha*F)**2 - ### Correlation function + # Correlation function G = 1/n*(particle2D + particle3D)*triplet/norm return G + off @@ -128,15 +130,15 @@ def MoreInfo(parms, countrate=None): [15] C_3D [nM] = n3D/V_eff """ # We can only give you the effective particle number - n=parms[0] - #D2D=parms[1] - #D3D=parms[2] - F=parms[3] - r0=parms[4] - deva=parms[5] - #alpha=parms[6] - - Info=list() + n = parms[0] + # D2D=parms[1] + # D3D=parms[2] + F = parms[3] + r0 = parms[4] + deva = parms[5] + # alpha=parms[6] + + Info = list() # The enumeration of these parameters is very important for # plotting the normalized curve. Countrate must come out last! Info.append([u"n3D", n*F]) @@ -144,7 +146,7 @@ def MoreInfo(parms, countrate=None): # Detection area: Veff = np.pi * r0**2 * deva C3D = n*F / Veff - C2D = n*(1-F) / ( np.pi*r0**2 ) + C2D = n*(1-F) / (np.pi*r0**2) # Correlation function at tau = 0 G_0 = CF_Gxyz_3d2dT_gauss(parms, 0) Info.append([u"G(0)", G_0]) @@ -161,57 +163,58 @@ def MoreInfo(parms, countrate=None): # 3D + 3D + T model gauss m_gauss_3d_2d_t = [6033, "T+3D+2D", - "Separate 3D and 2D diffusion + triplet w/ TIR", - CF_Gxyz_3d2dT_gauss] -labels = [ u"n", - u"D_2D [10 ĀµmĀ²/s]", - u"D_3D [10 ĀµmĀ²/s]", - u"F_3D", - u"rā [100 nm]", - u"d_eva [100 nm]", - u"\u03b1"+" (q_3D/q_2D)", - u"Ļ_trip [ms]", + "Separate 3D and 2D diffusion + triplet w/ TIR", + CF_Gxyz_3d2dT_gauss] +labels = [u"n", + u"D_2D [10 ĀµmĀ²/s]", + u"D_3D [10 ĀµmĀ²/s]", + u"F_3D", + u"rā [100 nm]", + u"d_eva [100 nm]", + u"\u03b1"+" (q_3D/q_2D)", + u"Ļ_trip [ms]", + u"T", + u"offset" + ] +values = [ + 25, # n + 0.51, # D2D + 25.1, # D3D + 0.45, # F3D + 9.44, # r0 + 1.0, # deva + 1.0, # alpha + 0.001, # tautrip + 0.01, # T + 0.0 # offset +] +# Human readable stuff +labelshr = [u"n", + u"D_2D [ĀµmĀ²/s]", + u"D_3D [ĀµmĀ²/s]", + u"F_3D", + u"rā [nm]", + u"d_eva [nm]", + u"\u03b1"+u" (q_3D/q_2D)", + u"Ļ_trip [Āµs]", u"T", u"offset" - ] -values = [ - 25, # n - 0.51, # D2D - 25.1, # D3D - 0.45, # F3D - 9.44, # r0 - 1.0, # deva - 1.0, # alpha - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] -# Human readable stuff -labelshr = [u"n", - u"D_2D [ĀµmĀ²/s]", - u"D_3D [ĀµmĀ²/s]", - u"F_3D", - u"rā [nm]", - u"d_eva [nm]", - u"\u03b1"+u" (q_3D/q_2D)", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ] -valueshr = [ - 1., # n - 10., # D2D - 10., # D3D - 1., # F3D - 100., # r0 - 100., # deva - 1., # alpha - 1000., # tautrip - 1., # T - 1. # offset - ] - -valuestofit = [True, True, True, True, False, False, False, False, False, False] + ] +valueshr = [ + 1., # n + 10., # D2D + 10., # D3D + 1., # F3D + 100., # r0 + 100., # deva + 1., # alpha + 1000., # tautrip + 1., # T + 1. # offset +] + +valuestofit = [True, True, True, True, + False, False, False, False, False, False] parms = [labels, values, valuestofit, labelshr, valueshr] diff --git a/pycorrfit/models/MODEL_TIRF_gaussian_3D3D.py b/pycorrfit/models/MODEL_TIRF_gaussian_3D3D.py index 060c04f6..ba81ce22 100755 --- a/pycorrfit/models/MODEL_TIRF_gaussian_3D3D.py +++ b/pycorrfit/models/MODEL_TIRF_gaussian_3D3D.py @@ -14,11 +14,13 @@ def wixi(x): wixi = sps.wofz(z) # We should have a real solution. Make sure nobody complains about # some zero-value imaginary numbers. - - return np.real_if_close(wixi) + + return np.real_if_close(wixi) # 3D + 3D + T # model 6034 + + def CF_Gxyz_3D3DT_gauss(parms, tau): u""" Two-component three-dimensional diffusion with a Gaussian lateral detection profile and an exponentially decaying profile @@ -64,26 +66,25 @@ def CF_Gxyz_3D3DT_gauss(parms, tau): [9] offset *tau* - lag time """ - n=parms[0] - D1=parms[1] - D2=parms[2] - F=parms[3] - r0=parms[4] - deva=parms[5] - alpha=parms[6] - tautrip=parms[7] - T=parms[8] - off=parms[9] + n = parms[0] + D1 = parms[1] + D2 = parms[2] + F = parms[3] + r0 = parms[4] + deva = parms[5] + alpha = parms[6] + tautrip = parms[7] + T = parms[8] + off = parms[9] kappa = 1/deva - - ### 1st species + # 1st species tauD1 = r0**2/(4*D1) # 2D gauss component - g2D1 = 1 / ( (1.+tau/tauD1) ) + g2D1 = 1 / ((1.+tau/tauD1)) # 1d TIR component - # Axial correlation + # Axial correlation x1 = np.sqrt(D1*tau)*kappa w_ix1 = wixi(x1) # Gz = 1/N1D * gz = kappa / Conc.1D * gz @@ -91,12 +92,12 @@ def CF_Gxyz_3D3DT_gauss(parms, tau): (2*D1*tau*kappa**2 - 1)/(2*kappa) * w_ix1) particle1 = F * g2D1 * gz1 - ### 2nd species + # 2nd species tauD2 = r0**2/(4*D2) # 2D gauss component - g2D2 = 1 / ( (1.+tau/tauD2) ) + g2D2 = 1 / ((1.+tau/tauD2)) # 1d TIR component - # Axial correlation + # Axial correlation x2 = np.sqrt(D2*tau)*kappa w_ix2 = wixi(x2) # Gz = 1/N1D * gz = kappa / Conc.1D * gz @@ -104,16 +105,16 @@ def CF_Gxyz_3D3DT_gauss(parms, tau): (2*D2*tau*kappa**2 - 1)/(2*kappa) * w_ix2) particle2 = alpha**2*(1-F) * g2D2 * gz2 - ### triplet + # triplet if tautrip == 0 or T == 0: triplet = 1 else: triplet = 1 + T/(1-T) * np.exp(-tau/tautrip) - ### Norm + # Norm norm = (F + alpha*(1-F))**2 - ### Correlation function + # Correlation function G = 1/n*(particle1 + particle2)*triplet/norm return G + off @@ -146,15 +147,15 @@ def MoreInfo(parms, countrate=None): [15] Cā [nM] = nā/V_eff """ # We can only give you the effective particle number - n=parms[0] - #D1=parms[1] - #D2=parms[2] - F=parms[3] - r0=parms[4] - deva=parms[5] - #alpha=parms[6] - - Info=list() + n = parms[0] + # D1=parms[1] + # D2=parms[2] + F = parms[3] + r0 = parms[4] + deva = parms[5] + # alpha=parms[6] + + Info = list() # The enumeration of these parameters is very important for # plotting the normalized curve. Countrate must come out last! Info.append([u"n\u2081", n*F]) @@ -179,57 +180,58 @@ def MoreInfo(parms, countrate=None): # 3D + 3D + T model gauss m_gauss_3d_3d_t = [6034, "T+3D+3D", - "Combined 3D diffusion + triplet w/ TIR", - CF_Gxyz_3D3DT_gauss] -labels = [u"n", - u"D"+u"\u2081"+u" [10 ĀµmĀ²/s]", - u"D"+u"\u2082"+u" [10 ĀµmĀ²/s]", - u"F"+u"\u2081", - u"rā [100 nm]", - u"d_eva [100 nm]", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [ms]", - u"T", - u"offset" - ] -values = [ - 25, # n - 0.9, # D1 - 25.0, # D2 - 0.5, # F1 - 9.44, # r0 - 1.0, # deva - 1.0, # alpha - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] + "Combined 3D diffusion + triplet w/ TIR", + CF_Gxyz_3D3DT_gauss] +labels = [u"n", + u"D"+u"\u2081"+u" [10 ĀµmĀ²/s]", + u"D"+u"\u2082"+u" [10 ĀµmĀ²/s]", + u"F"+u"\u2081", + u"rā [100 nm]", + u"d_eva [100 nm]", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [ms]", + u"T", + u"offset" + ] +values = [ + 25, # n + 0.9, # D1 + 25.0, # D2 + 0.5, # F1 + 9.44, # r0 + 1.0, # deva + 1.0, # alpha + 0.001, # tautrip + 0.01, # T + 0.0 # offset +] # Human readable stuff -labelshr = [ u"n", - u"D"+u"\u2081"+u" [ĀµmĀ²/s]", - u"D"+u"\u2082"+u" [ĀµmĀ²/s]", - u"F"+u"\u2081", - u"rā [nm]", - u"d_eva [nm]", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ] -valueshr = [ - 1., # n - 10., # D1 - 10., # D2 - 1., # F1 - 100., # r0 - 100., # deva - 1., # alpha - 1000., # tautrip - 1., # T - 1. # offset - ] - -valuestofit = [True, True, True, True, False, False, False, False, False, False] +labelshr = [u"n", + u"D"+u"\u2081"+u" [ĀµmĀ²/s]", + u"D"+u"\u2082"+u" [ĀµmĀ²/s]", + u"F"+u"\u2081", + u"rā [nm]", + u"d_eva [nm]", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ] +valueshr = [ + 1., # n + 10., # D1 + 10., # D2 + 1., # F1 + 100., # r0 + 100., # deva + 1., # alpha + 1000., # tautrip + 1., # T + 1. # offset +] + +valuestofit = [True, True, True, True, + False, False, False, False, False, False] parms = [labels, values, valuestofit, labelshr, valueshr] diff --git a/pycorrfit/models/__init__.py b/pycorrfit/models/__init__.py index dcdfe846..fde098e8 100644 --- a/pycorrfit/models/__init__.py +++ b/pycorrfit/models/__init__.py @@ -134,6 +134,7 @@ def GetModelType(modelid): warnings.warn("No shorttype defined for `{}`.".format(key)) return key + def GetModelFunctionFromId(modelid): return modeldict[modelid][3] @@ -145,6 +146,7 @@ def GetModelParametersFromId(modelid): def GetModelFitBoolFromId(modelid): return valuedict[modelid][2] + def GetMoreInfo(modelid, Page): """ This functino is called by someone who has already calculated some stuff or wants to know more about the model he is looking at. @@ -160,16 +162,16 @@ def GetMoreInfo(modelid, Page): Info = list() corr = Page.corr if corr.is_ac: - if len(corr.traces)==1: + if len(corr.traces) == 1: countrate = corr.traces[0].countrate else: countrate = None - ## First import the supplementary parameters of the model - ## The order is important for plot normalization and session - ## saving as of version 0.7.8 + # First import the supplementary parameters of the model + # The order is important for plot normalization and session + # saving as of version 0.7.8 # Try to get the dictionary entry of a model # Background information - if len(corr.backgrounds)==1: + if len(corr.backgrounds) == 1: bgaverage = corr.backgrounds[0].countrate # Now set the correct countrate # We already printed the countrate, so there's no harm done. @@ -199,12 +201,12 @@ def GetMoreInfo(modelid, Page): # Background might overwrite countrate. Info.append(["avg. signal [kHz]", corr.traces[0].countrate]) else: - ## Cross correlation curves usually have two traces. Since we - ## do not know how to compute the cpp, we will pass the argument - ## "None" as the countrate. - ## First import the supplementary parameters of the model - ## The order is important for plot normalization and session - ## saving as of version 0.7.8 + # Cross correlation curves usually have two traces. Since we + # do not know how to compute the cpp, we will pass the argument + # "None" as the countrate. + # First import the supplementary parameters of the model + # The order is important for plot normalization and session + # saving as of version 0.7.8 # Try to get the dictionary entry of a model try: # This function should return all important information @@ -216,7 +218,7 @@ def GetMoreInfo(modelid, Page): except KeyError: # No information available pass - if len(corr.traces)==2: + if len(corr.traces) == 2: # Measurement time duration = corr.traces[0].duration/1000 Info.append(["duration [s]", duration]) diff --git a/pycorrfit/models/classes.py b/pycorrfit/models/classes.py index 898f18ba..af840095 100644 --- a/pycorrfit/models/classes.py +++ b/pycorrfit/models/classes.py @@ -7,6 +7,7 @@ class Model(object): """General class for handling FCS fitting models""" + def __init__(self, datadict): """datadict is an item in Modelarray""" self._parameters = datadict["Parameters"] @@ -32,7 +33,7 @@ def __init__(self, datadict): # in e.g. confocal t_3d_3d_3d model. if (isinstance(cc[0], numbers.Integral) and isinstance(cc[2], numbers.Integral) and - cc[0] < cc[2]): + cc[0] < cc[2]): if cc[1] == ">": cc = [cc[2], "<", cc[0]] elif cc[1] == "<": @@ -51,8 +52,8 @@ def __getitem__(self, key): def __repr__(self): text = "Model {} - {}".format( - self.id, - self.description_short) + self.id, + self.description_short) return text def apply(self, parameters, tau): @@ -106,7 +107,8 @@ def func_supplements(self): @property def func_verification(self): - warnings.warn("`func_verification is deprecated: please do not use it!") + warnings.warn( + "`func_verification is deprecated: please do not use it!") return lambda x: x def get_supplementary_parameters(self, values, countrate=None): @@ -135,7 +137,7 @@ def get_supplementary_values(self, values, countrate=None): count rate in Hz """ out = list() - for item in self.get_supplementary_parameters(values, countrate): + for item in self.get_supplementary_parameters(values, countrate): out.append(item[1]) return out diff --git a/pycorrfit/models/control.py b/pycorrfit/models/control.py index c4c24fba..937171ee 100644 --- a/pycorrfit/models/control.py +++ b/pycorrfit/models/control.py @@ -1,4 +1,29 @@ # -*- coding: utf-8 -*- +from . import MODEL_TIRF_3D2Dkin_Ries +from . import MODEL_TIRF_3D3D +from . import MODEL_TIRF_3D2D +from . import MODEL_TIRF_2D2D +from . import MODEL_TIRF_1C +from . import MODEL_TIRF_gaussian_3D3D +from . import MODEL_TIRF_gaussian_3D2D +from . import MODEL_TIRF_gaussian_1C +from . import model_confocal_tt_3d_2d +from . import model_confocal_tt_2d_2d +from . import model_confocal_tt_2d +from . import model_confocal_tt_3d_3d +from . import model_confocal_tt_3d +from . import model_confocal_t_3d_3d_2d +from . import model_confocal_t_3d_3d_3d +from . import model_confocal_t_3d_2d +from . import model_confocal_t_2d_2d +from . import model_confocal_t_2d +from . import model_confocal_t_3d_3d +from . import model_confocal_t_3d +from . import model_confocal_3d_2d +from . import model_confocal_2d_2d +from . import model_confocal_2d +from . import model_confocal_3d_3d +from . import model_confocal_3d """ pycorrfit.models.control Controls which fitting models are imported an in which order. @@ -7,6 +32,7 @@ from .classes import Model + def append_model(modelarray): """ Append a new model from a modelarray. *Modelarray* has to be a list whose elements have two items: @@ -118,7 +144,8 @@ def model_setup(modelid, name, comp, mtype, fctn, par_labels, par_values, par_hr_factors, ]: if p is not None: - assert len(p) == len(par_values), "Number of parameters must match!" + assert len(p) == len( + par_values), "Number of parameters must match!" if par_hr_factors is None or par_hr_labels is None: assert par_hr_factors is None, "human readable requires two parameter" @@ -134,7 +161,7 @@ def model_setup(modelid, name, comp, mtype, fctn, par_labels, par_values, par_hr_labels = par_labels par_hr_factors = np.ones_like(par_values) - model={} + model = {} model["Parameters"] = [par_labels, par_values, par_vary, par_hr_labels, par_hr_factors] @@ -181,25 +208,6 @@ def model_setup(modelid, name, comp, mtype, fctn, par_labels, par_values, # The order of the import matters! # These models perform the integration by themselves using the `model_setup` method. -from . import model_confocal_3d -from . import model_confocal_3d_3d -from . import model_confocal_2d -from . import model_confocal_2d_2d -from . import model_confocal_3d_2d - -from . import model_confocal_t_3d -from . import model_confocal_t_3d_3d -from . import model_confocal_t_2d -from . import model_confocal_t_2d_2d -from . import model_confocal_t_3d_2d -from . import model_confocal_t_3d_3d_3d -from . import model_confocal_t_3d_3d_2d - -from . import model_confocal_tt_3d -from . import model_confocal_tt_3d_3d -from . import model_confocal_tt_2d -from . import model_confocal_tt_2d_2d -from . import model_confocal_tt_3d_2d # These lines can be removed once all models are converted @@ -208,15 +216,7 @@ def model_setup(modelid, name, comp, mtype, fctn, par_labels, par_values, modeltypes[u"TIR (ā”xĻ/Exp.)"] = [6010, 6023, 6000, 6022, 6020, 6021] -## Models -from . import MODEL_TIRF_gaussian_1C -from . import MODEL_TIRF_gaussian_3D2D -from . import MODEL_TIRF_gaussian_3D3D -from . import MODEL_TIRF_1C -from . import MODEL_TIRF_2D2D -from . import MODEL_TIRF_3D2D -from . import MODEL_TIRF_3D3D -from . import MODEL_TIRF_3D2Dkin_Ries +# Models # Load all models from the imported "MODEL_*" submodules # These are the models that were not imported using the `model_setup` method. diff --git a/pycorrfit/models/cp_confocal.py b/pycorrfit/models/cp_confocal.py index 75892335..485605ff 100644 --- a/pycorrfit/models/cp_confocal.py +++ b/pycorrfit/models/cp_confocal.py @@ -7,4 +7,4 @@ def threed(tau, taudiff, SP): def twod(tau, taudiff): - return 1/((1 + tau/taudiff)) \ No newline at end of file + return 1/((1 + tau/taudiff)) diff --git a/pycorrfit/models/cp_mix.py b/pycorrfit/models/cp_mix.py index 5ad89cb6..3753ccb4 100644 --- a/pycorrfit/models/cp_mix.py +++ b/pycorrfit/models/cp_mix.py @@ -84,4 +84,4 @@ def triple_pnum(n, G = 1/n * (g1 + g2 + g3) / norm - return G \ No newline at end of file + return G diff --git a/pycorrfit/models/model_confocal_2d.py b/pycorrfit/models/model_confocal_2d.py index 739c9c9d..93163d75 100644 --- a/pycorrfit/models/model_confocal_2d.py +++ b/pycorrfit/models/model_confocal_2d.py @@ -4,6 +4,8 @@ from .cp_confocal import twod # 2D simple gauss + + def CF_Gxy_gauss(parms, tau): u""" Two-dimensional diffusion with a Gaussian laser profile. @@ -44,21 +46,21 @@ def supplements(parms, countrate=None): parms = [4.0, 0.4, 0.0] -## boundaries +# boundaries boundaries = [[0, np.inf]]*len(parms) boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6001, - name="2D diffusion (confocal)", - comp="2D", - mtype="Confocal (Gaussian)", - fctn=CF_Gxy_gauss, - par_labels=[ u"n", - u"Ļ_diff [ms]", - u"offset"], - par_values=parms, - par_vary=[True, True, False], - par_boundaries=boundaries, - supplementary_method=supplements - ) + modelid=6001, + name="2D diffusion (confocal)", + comp="2D", + mtype="Confocal (Gaussian)", + fctn=CF_Gxy_gauss, + par_labels=[u"n", + u"Ļ_diff [ms]", + u"offset"], + par_values=parms, + par_vary=[True, True, False], + par_boundaries=boundaries, + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_2d_2d.py b/pycorrfit/models/model_confocal_2d_2d.py index c65c68ff..4f9ee609 100644 --- a/pycorrfit/models/model_confocal_2d_2d.py +++ b/pycorrfit/models/model_confocal_2d_2d.py @@ -6,7 +6,7 @@ # 2D + 2D GauĆ - # Model 6037 +# Model 6037 def CF_Gxyz_gauss_2D2D(parms, tau): u""" Two-component, two-dimensional diffusion with a Gaussian laser profile, including a triplet component. @@ -32,22 +32,22 @@ def CF_Gxyz_gauss_2D2D(parms, tau): [5] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - alpha=parms[4] - off=parms[5] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + alpha = parms[4] + off = parms[5] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=twod, comp2=twod, - kwargs1={"tau":tau, - "taudiff":taud1}, - kwargs2={"tau":tau, - "taudiff":taud2}, + kwargs1={"tau": tau, + "taudiff": taud1}, + kwargs2={"tau": tau, + "taudiff": taud2}, ) G = off + g @@ -75,39 +75,39 @@ def supplements(parms, countrate=None): parms = [ - 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 1.0, # alpha - 0.0 # offset - ] + 25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 1.0, # alpha + 0.0 # offset +] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6037, - name="Separate 2D diffusion (confocal)", - comp="2D+2D", - mtype="Confocal (Gaussian)", - fctn=CF_Gxyz_gauss_2D2D, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+u" [ms]", - u"Ļ"+u"\u2082"+u" [ms]", - u"F"+u"\u2081", - u"\u03b1"+u" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1]], - supplementary_method=supplements - ) + modelid=6037, + name="Separate 2D diffusion (confocal)", + comp="2D+2D", + mtype="Confocal (Gaussian)", + fctn=CF_Gxyz_gauss_2D2D, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+u" [ms]", + u"Ļ"+u"\u2082"+u" [ms]", + u"F"+u"\u2081", + u"\u03b1"+u" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1]], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_3d.py b/pycorrfit/models/model_confocal_3d.py index 5d88ec7f..f0405780 100644 --- a/pycorrfit/models/model_confocal_3d.py +++ b/pycorrfit/models/model_confocal_3d.py @@ -4,6 +4,8 @@ from .cp_confocal import threed # 3D simple gauss + + def CF_Gxyz_gauss(parms, tau): # Model 6012 u""" Three-dimanesional free diffusion with a Gaussian laser profile @@ -36,7 +38,7 @@ def CF_Gxyz_gauss(parms, tau): off = parms[3] BB = threed(tau, taudiff, SP) - + G = off + 1/n * BB return G @@ -57,18 +59,18 @@ def supplements(parms, countrate=None): boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6012, - name="3D diffusion (confocal)", - comp="3D", - mtype="Confocal (Gaussian)", - fctn=CF_Gxyz_gauss, - par_labels=[ - u"n", - u"Ļ_diff [ms]", - u"SP", - u"offset"], - par_values=parms, - par_vary=[True, True, False, False], - par_boundaries=boundaries, - supplementary_method=supplements - ) + modelid=6012, + name="3D diffusion (confocal)", + comp="3D", + mtype="Confocal (Gaussian)", + fctn=CF_Gxyz_gauss, + par_labels=[ + u"n", + u"Ļ_diff [ms]", + u"SP", + u"offset"], + par_values=parms, + par_vary=[True, True, False, False], + par_boundaries=boundaries, + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_3d_2d.py b/pycorrfit/models/model_confocal_3d_2d.py index 9bc457d7..4b0ec3f3 100644 --- a/pycorrfit/models/model_confocal_3d_2d.py +++ b/pycorrfit/models/model_confocal_3d_2d.py @@ -9,7 +9,7 @@ def CF_Gxyz_3d2d_gauss(parms, tau): u""" Two-component, two- and three-dimensional diffusion with a Gaussian laser profile. - + particle2D = (1-F)/ (1+Ļ/Ļ_2D) particle3D = Ī±Ā²*F/( (1+Ļ/Ļ_3D) * sqrt(1+Ļ/(Ļ_3D*SPĀ²))) norm = (1-F + Ī±*F)Ā² @@ -30,29 +30,30 @@ def CF_Gxyz_3d2d_gauss(parms, tau): [6] offset *tau* - lag time """ - n=parms[0] - taud2D=parms[1] - taud3D=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - off=parms[6] + n = parms[0] + taud2D = parms[1] + taud3D = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + off = parms[6] g = double_pnum(n=n, F1=1-F, alpha=alpha, comp1=twod, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud2D}, - kwargs2={"tau":tau, - "taudiff":taud3D, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud2D}, + kwargs2={"tau": tau, + "taudiff": taud3D, + "SP": SP}, ) G = off + g return G + def supplements(parms, countrate=None): u"""Supplementary parameters: Effective number of freely diffusing particles in 3D solution: @@ -75,42 +76,42 @@ def supplements(parms, countrate=None): return Info -parms = [ - 25, # n - 240, # taud2D - 0.1, # taud3D - 0.5, # F3D - 7, # SP - 1.0, # alpha - 0.0 # offset - ] +parms = [ + 25, # n + 240, # taud2D + 0.1, # taud3D + 0.5, # F3D + 7, # SP + 1.0, # alpha + 0.0 # offset +] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6036, - name="Separate 3D and 2D diffusion (confocal)", - comp="3D+2D", - mtype="Confocal (Gaussian)", - fctn=CF_Gxyz_3d2d_gauss, - par_labels=[ - u"n", - u"Ļ_2D [ms]", - u"Ļ_3D [ms]", - u"F_3D", - u"SP", - u"\u03b1"+" (q_3D/q_2D)", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, "<", 1]], - supplementary_method=supplements - ) + modelid=6036, + name="Separate 3D and 2D diffusion (confocal)", + comp="3D+2D", + mtype="Confocal (Gaussian)", + fctn=CF_Gxyz_3d2d_gauss, + par_labels=[ + u"n", + u"Ļ_2D [ms]", + u"Ļ_3D [ms]", + u"F_3D", + u"SP", + u"\u03b1"+" (q_3D/q_2D)", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, "<", 1]], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_3d_3d.py b/pycorrfit/models/model_confocal_3d_3d.py index 74a40c47..9339dda9 100644 --- a/pycorrfit/models/model_confocal_3d_3d.py +++ b/pycorrfit/models/model_confocal_3d_3d.py @@ -29,30 +29,31 @@ def CF_Gxyz_gauss_3D3D(parms, tau): [6] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - off=parms[6] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + off = parms[6] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=threed, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud1, - "SP":SP}, - kwargs2={"tau":tau, - "taudiff":taud2, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud1, + "SP": SP}, + kwargs2={"tau": tau, + "taudiff": taud2, + "SP": SP}, ) G = off + g return G + def supplements(parms, countrate=None): u"""Supplementary parameters: [7] nā = n*Fā Particle number of species 1 @@ -74,41 +75,41 @@ def supplements(parms, countrate=None): return Info -parms = [ 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 5, # SP - 1.0, # alpha - 0.0 # offset - ] +parms = [25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 5, # SP + 1.0, # alpha + 0.0 # offset + ] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6035, - name="Separate 3D diffusion (confocal)", - comp="3D+3D", - mtype="Confocal (Gaussian)", - fctn=CF_Gxyz_gauss_3D3D, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"F"+u"\u2081", - u"SP", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1]], - supplementary_method=supplements - ) + modelid=6035, + name="Separate 3D diffusion (confocal)", + comp="3D+3D", + mtype="Confocal (Gaussian)", + fctn=CF_Gxyz_gauss_3D3D, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"F"+u"\u2081", + u"SP", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1]], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_2d.py b/pycorrfit/models/model_confocal_t_2d.py index bc4c390b..da120651 100644 --- a/pycorrfit/models/model_confocal_t_2d.py +++ b/pycorrfit/models/model_confocal_t_2d.py @@ -15,7 +15,7 @@ def CF_Gxy_T_gauss(parms, tau): triplet = 1 + T/(1-T)*exp(-Ļ/Ļ_trip) G(Ļ) = offset + 1/( n * (1+Ļ/Ļ_diff) )*triplet - + Calculation of diffusion coefficient and concentration from the effective radius of the detection profile (rā = 2*Ļ): D = rāĀ²/(4*Ļ_diff) @@ -40,7 +40,7 @@ def CF_Gxy_T_gauss(parms, tau): triplet = trip(tau=tau, tautrip=tautrip, T=T) BB = twod(tau=tau, taudiff=taudiff) - + G = dc + 1/n * BB * triplet return G @@ -58,35 +58,35 @@ def supplements(parms, countrate=None): parms = [4.0, 0.4, 0.001, 0.01, 0.0] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6002, - name="2D diffusion with triplet (confocal)", - comp="T+2D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxy_T_gauss, - par_labels=[ - u"n", - u"Ļ_diff [ms]", - u"Ļ_trip [ms]", - u"T", - u"offset"], - par_values=parms, - par_vary=[True, True, True, True, False], - par_boundaries=boundaries, - par_constraints=[[2, "<", 1]], - par_hr_labels=[ - u"n", - u"Ļ_diff [ms]", - u"Ļ_trip [Āµs]", - u"T", - u"offset"], - par_hr_factors=[1., 1., 1000., 1., 1.], - supplementary_method=supplements - ) + modelid=6002, + name="2D diffusion with triplet (confocal)", + comp="T+2D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxy_T_gauss, + par_labels=[ + u"n", + u"Ļ_diff [ms]", + u"Ļ_trip [ms]", + u"T", + u"offset"], + par_values=parms, + par_vary=[True, True, True, True, False], + par_boundaries=boundaries, + par_constraints=[[2, "<", 1]], + par_hr_labels=[ + u"n", + u"Ļ_diff [ms]", + u"Ļ_trip [Āµs]", + u"T", + u"offset"], + par_hr_factors=[1., 1., 1000., 1., 1.], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_2d_2d.py b/pycorrfit/models/model_confocal_t_2d_2d.py index 77532f31..fe24c928 100644 --- a/pycorrfit/models/model_confocal_t_2d_2d.py +++ b/pycorrfit/models/model_confocal_t_2d_2d.py @@ -7,7 +7,7 @@ # 2D + 2D + Triplet GauĆ - # Model 6031 +# Model 6031 def CF_Gxyz_gauss_2D2DT(parms, tau): u""" Two-component, two-dimensional diffusion with a Gaussian laser profile, including a triplet component. @@ -37,24 +37,24 @@ def CF_Gxyz_gauss_2D2DT(parms, tau): [7] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - alpha=parms[4] - tautrip=parms[5] - T=parms[6] - off=parms[7] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + alpha = parms[4] + tautrip = parms[5] + T = parms[6] + off = parms[7] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=twod, comp2=twod, - kwargs1={"tau":tau, - "taudiff":taud1}, - kwargs2={"tau":tau, - "taudiff":taud2}, + kwargs1={"tau": tau, + "taudiff": taud1}, + kwargs2={"tau": tau, + "taudiff": taud2}, ) tr = trip(tau=tau, T=T, tautrip=tautrip) @@ -84,65 +84,65 @@ def supplements(parms, countrate=None): parms = [ - 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 1.0, # alpha - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] + 25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 1.0, # alpha + 0.001, # tautrip + 0.01, # T + 0.0 # offset +] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[6] = [0,.9999999999999] +boundaries[6] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6031, - name="Separate 2D diffusion with triplet (confocal)", - comp="T+2D+2D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_gauss_2D2DT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+u" [ms]", - u"Ļ"+u"\u2082"+u" [ms]", - u"F"+u"\u2081", - u"\u03b1"+u" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [ms]", - u"T", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [5, "<", 1]], - par_hr_labels=[ - u"n", - u"Ļ"+u"\u2081"+u" [ms]", - u"Ļ"+u"\u2082"+u" [ms]", - u"F"+u"\u2081", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ], - par_hr_factors=[ - 1., # "n", - 1., # "Ļ"+u"\u2081"+" [ms]", - 1., # "Ļ"+u"\u2082"+" [ms]", - 1., # "F"+u"\u2081", - 1., # u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - 1000., # "Ļ_trip [Āµs]", - 1., # "T", - 1. # "offset" - ], - supplementary_method=supplements - ) + modelid=6031, + name="Separate 2D diffusion with triplet (confocal)", + comp="T+2D+2D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_gauss_2D2DT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+u" [ms]", + u"Ļ"+u"\u2082"+u" [ms]", + u"F"+u"\u2081", + u"\u03b1"+u" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [ms]", + u"T", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [5, "<", 1]], + par_hr_labels=[ + u"n", + u"Ļ"+u"\u2081"+u" [ms]", + u"Ļ"+u"\u2082"+u" [ms]", + u"F"+u"\u2081", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ], + par_hr_factors=[ + 1., # "n", + 1., # "Ļ"+u"\u2081"+" [ms]", + 1., # "Ļ"+u"\u2082"+" [ms]", + 1., # "F"+u"\u2081", + 1., # u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + 1000., # "Ļ_trip [Āµs]", + 1., # "T", + 1. # "offset" + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_3d.py b/pycorrfit/models/model_confocal_t_3d.py index 1b57433c..fefc66a8 100644 --- a/pycorrfit/models/model_confocal_t_3d.py +++ b/pycorrfit/models/model_confocal_t_3d.py @@ -40,7 +40,7 @@ def CF_Gxyz_blink(parms, tau): AA = trip(tau, tautrip, T) BB = threed(tau, taudiff, SP) - + G = off + 1/n * AA * BB return G @@ -58,37 +58,37 @@ def supplements(parms, countrate=None): parms = [4.0, 0.2, 0.001, 0.4, 5.0, 0.0] -## Boundaries +# Boundaries boundaries = [[0, np.inf]]*len(parms) # T -boundaries[1] = [0,.9999999999999] +boundaries[1] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6011, - name="3D diffusion with triplet (confocal)", - comp="T+3D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_blink, - par_labels=[ - u"n", - u"T", - u"Ļ_trip [ms]", - u"Ļ_diff [ms]", - u"SP", - u"offset"], - par_values=parms, - par_vary=[True, True, True, True, False, False], - par_boundaries=boundaries, - par_constraints=[[3, ">", 2]], - par_hr_labels=[ - u"n", - u"T", - u"Ļ_trip [Āµs]", - u"Ļ_diff [ms]", - u"SP", - u"offset"], - par_hr_factors=[1., 1., 1000., 1., 1., 1.], - supplementary_method=supplements - ) + modelid=6011, + name="3D diffusion with triplet (confocal)", + comp="T+3D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_blink, + par_labels=[ + u"n", + u"T", + u"Ļ_trip [ms]", + u"Ļ_diff [ms]", + u"SP", + u"offset"], + par_values=parms, + par_vary=[True, True, True, True, False, False], + par_boundaries=boundaries, + par_constraints=[[3, ">", 2]], + par_hr_labels=[ + u"n", + u"T", + u"Ļ_trip [Āµs]", + u"Ļ_diff [ms]", + u"SP", + u"offset"], + par_hr_factors=[1., 1., 1000., 1., 1., 1.], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_3d_2d.py b/pycorrfit/models/model_confocal_t_3d_2d.py index bf201d65..38487a93 100644 --- a/pycorrfit/models/model_confocal_t_3d_2d.py +++ b/pycorrfit/models/model_confocal_t_3d_2d.py @@ -38,26 +38,26 @@ def CF_Gxyz_3d2dT_gauss(parms, tau): [8] offset *tau* - lag time """ - n=parms[0] - taud2D=parms[1] - taud3D=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - tautrip=parms[6] - T=parms[7] - off=parms[8] + n = parms[0] + taud2D = parms[1] + taud3D = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + tautrip = parms[6] + T = parms[7] + off = parms[8] g = double_pnum(n=n, F1=1-F, alpha=alpha, comp1=twod, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud2D}, - kwargs2={"tau":tau, - "taudiff":taud3D, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud2D}, + kwargs2={"tau": tau, + "taudiff": taud3D, + "SP": SP}, ) tr = trip(tau=tau, T=T, tautrip=tautrip) @@ -65,6 +65,7 @@ def CF_Gxyz_3d2dT_gauss(parms, tau): G = off + g*tr return G + def supplements(parms, countrate=None): u"""Supplementary parameters: Effective number of freely diffusing particles in 3D solution: @@ -87,70 +88,70 @@ def supplements(parms, countrate=None): return Info -parms = [ - 25, # n - 240, # taud2D - 0.1, # taud3D - 0.5, # F3D - 7, # SP - 1.0, # alpha - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] +parms = [ + 25, # n + 240, # taud2D + 0.1, # taud3D + 0.5, # F3D + 7, # SP + 1.0, # alpha + 0.001, # tautrip + 0.01, # T + 0.0 # offset +] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[7] = [0,.9999999999999] +boundaries[7] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6032, - name="Separate 3D and 2D diffusion with triplet (confocal)", - comp="T+3D+2D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_3d2dT_gauss, - par_labels=[ - u"n", - u"Ļ_2D [ms]", - u"Ļ_3D [ms]", - u"F_3D", - u"SP", - u"\u03b1"+" (q_3D/q_2D)", - u"Ļ_trip [ms]", - u"T", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, "<", 1], [6, "<", 2]], - par_hr_labels=[ - u"n", - u"Ļ_2D [ms]", - u"Ļ_3D [ms]", - u"F_3D", - u"SP", - u"\u03b1"+" (q_3D/q_2D)", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ], - par_hr_factors=[ - 1., # "n", - 1., # "Ļ_2D [ms]", - 1., # "Ļ_3D [ms]", - 1., # "F_3D", - 1., # "SP", - 1., # u"\u03b1"+" (q_3D/q_2D)", - 1000., # "Ļ_trip [Āµs]", - 1., # "T", - 1. # "offset" - ], - supplementary_method=supplements - ) + modelid=6032, + name="Separate 3D and 2D diffusion with triplet (confocal)", + comp="T+3D+2D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_3d2dT_gauss, + par_labels=[ + u"n", + u"Ļ_2D [ms]", + u"Ļ_3D [ms]", + u"F_3D", + u"SP", + u"\u03b1"+" (q_3D/q_2D)", + u"Ļ_trip [ms]", + u"T", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, "<", 1], [6, "<", 2]], + par_hr_labels=[ + u"n", + u"Ļ_2D [ms]", + u"Ļ_3D [ms]", + u"F_3D", + u"SP", + u"\u03b1"+" (q_3D/q_2D)", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ], + par_hr_factors=[ + 1., # "n", + 1., # "Ļ_2D [ms]", + 1., # "Ļ_3D [ms]", + 1., # "F_3D", + 1., # "SP", + 1., # u"\u03b1"+" (q_3D/q_2D)", + 1000., # "Ļ_trip [Āµs]", + 1., # "T", + 1. # "offset" + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_3d_3d.py b/pycorrfit/models/model_confocal_t_3d_3d.py index 81b5e9f3..9fc53830 100644 --- a/pycorrfit/models/model_confocal_t_3d_3d.py +++ b/pycorrfit/models/model_confocal_t_3d_3d.py @@ -36,27 +36,27 @@ def CF_Gxyz_gauss_3D3DT(parms, tau): [8] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - tautrip=parms[6] - T=parms[7] - off=parms[8] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + tautrip = parms[6] + T = parms[7] + off = parms[8] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=threed, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud1, - "SP":SP}, - kwargs2={"tau":tau, - "taudiff":taud2, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud1, + "SP": SP}, + kwargs2={"tau": tau, + "taudiff": taud2, + "SP": SP}, ) tr = trip(tau=tau, T=T, tautrip=tautrip) @@ -64,6 +64,7 @@ def CF_Gxyz_gauss_3D3DT(parms, tau): G = off + g*tr return G + def supplements(parms, countrate=None): u"""Supplementary parameters: [9] nā = n*Fā Particle number of species 1 @@ -84,69 +85,69 @@ def supplements(parms, countrate=None): return Info -parms = [ 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 5, # SP - 1.0, # alpha - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] +parms = [25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 5, # SP + 1.0, # alpha + 0.001, # tautrip + 0.01, # T + 0.0 # offset + ] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[7] = [0,.9999999999999] +boundaries[7] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6030, - name="Separate 3D diffusion with triplet (confocal)", - comp="T+3D+3D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_gauss_3D3DT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"F"+u"\u2081", - u"SP", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [ms]", - u"T", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [6, "<", 1]], - par_hr_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"F"+u"\u2081", - u"SP", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taud1 - 1., # taud2 - 1., # F - 1., # SP - 1., # alpha - 1000., # tautrip [Āµs] - 1., # T - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6030, + name="Separate 3D diffusion with triplet (confocal)", + comp="T+3D+3D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_gauss_3D3DT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"F"+u"\u2081", + u"SP", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [ms]", + u"T", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [6, "<", 1]], + par_hr_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"F"+u"\u2081", + u"SP", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taud1 + 1., # taud2 + 1., # F + 1., # SP + 1., # alpha + 1000., # tautrip [Āµs] + 1., # T + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_3d_3d_2d.py b/pycorrfit/models/model_confocal_t_3d_3d_2d.py index 8d2ae1db..54a3b94c 100644 --- a/pycorrfit/models/model_confocal_t_3d_3d_2d.py +++ b/pycorrfit/models/model_confocal_t_3d_3d_2d.py @@ -43,18 +43,18 @@ def CF_Gxyz_gauss_3D3D2DT(parms, tau): [11] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - taud3=parms[3] - F1=parms[4] - F2=parms[5] - SP=parms[6] - alpha21=parms[7] - alpha31=parms[8] - tautrip=parms[9] - T=parms[10] - off=parms[11] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + taud3 = parms[3] + F1 = parms[4] + F2 = parms[5] + SP = parms[6] + alpha21 = parms[7] + alpha31 = parms[8] + tautrip = parms[9] + T = parms[10] + off = parms[11] g = triple_pnum(n=n, F1=F1, @@ -64,14 +64,14 @@ def CF_Gxyz_gauss_3D3D2DT(parms, tau): comp1=threed, comp2=threed, comp3=twod, - kwargs1={"tau":tau, - "taudiff":taud1, - "SP":SP}, - kwargs2={"tau":tau, - "taudiff":taud2, - "SP":SP}, - kwargs3={"tau":tau, - "taudiff":taud3}, + kwargs1={"tau": tau, + "taudiff": taud1, + "SP": SP}, + kwargs2={"tau": tau, + "taudiff": taud2, + "SP": SP}, + kwargs3={"tau": tau, + "taudiff": taud3}, ) tr = trip(tau=tau, T=T, tautrip=tautrip) @@ -103,84 +103,84 @@ def supplements(parms, countrate=None): return Info -parms = [ 25, # n - 5, # taud1 - 1000, # taud2 - 11000, # taud3 - 0.5, # F1 - 0.01, # F2 - 5, # SP - 1.0, # alpha21 - 1.0, # alpha31 - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] +parms = [25, # n + 5, # taud1 + 1000, # taud2 + 11000, # taud3 + 0.5, # F1 + 0.01, # F2 + 5, # SP + 1.0, # alpha21 + 1.0, # alpha31 + 0.001, # tautrip + 0.01, # T + 0.0 # offset + ] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[4] = [0,.9999999999999] -boundaries[5] = [0,.9999999999999] +boundaries[4] = [0, .9999999999999] +boundaries[5] = [0, .9999999999999] # T -boundaries[10] = [0,.9999999999999] +boundaries[10] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6082, - name="Twofold 3D and one 2D diffusion with triplet (confocal)", - comp="T+3D+3D+2D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_gauss_3D3D2DT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"Ļ"+u"\u2083"+" [ms]", - u"F"+u"\u2081", - u"F"+u"\u2082", - u"SP", - u"\u03b1\u2082\u2081", - u"\u03b1\u2083\u2081", - u"Ļ_trip [ms]", - u"T", - u"offset" - ], - par_values=parms, - par_vary=[True, True, False, True, - False, True, False, False, - False, False, True, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [3, ">", 2], [9, "<", 1], [5, 4, "<", "1"]], - par_hr_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"Ļ"+u"\u2083"+" [ms]", - u"F"+u"\u2081", - u"F"+u"\u2082", - u"SP", - u"\u03b1\u2082\u2081", - u"\u03b1\u2083\u2081", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taud1 - 1., # taud2 - 1., # taud3 - 1., # F1 - 1., # F2 - 1., # SP - 1., # alpha21 - 1., # alpha31 - 1000., # tautrip [Āµs] - 1., # T - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6082, + name="Twofold 3D and one 2D diffusion with triplet (confocal)", + comp="T+3D+3D+2D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_gauss_3D3D2DT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"Ļ"+u"\u2083"+" [ms]", + u"F"+u"\u2081", + u"F"+u"\u2082", + u"SP", + u"\u03b1\u2082\u2081", + u"\u03b1\u2083\u2081", + u"Ļ_trip [ms]", + u"T", + u"offset" + ], + par_values=parms, + par_vary=[True, True, False, True, + False, True, False, False, + False, False, True, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [3, ">", 2], [9, "<", 1], [5, 4, "<", "1"]], + par_hr_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"Ļ"+u"\u2083"+" [ms]", + u"F"+u"\u2081", + u"F"+u"\u2082", + u"SP", + u"\u03b1\u2082\u2081", + u"\u03b1\u2083\u2081", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taud1 + 1., # taud2 + 1., # taud3 + 1., # F1 + 1., # F2 + 1., # SP + 1., # alpha21 + 1., # alpha31 + 1000., # tautrip [Āµs] + 1., # T + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_t_3d_3d_3d.py b/pycorrfit/models/model_confocal_t_3d_3d_3d.py index 2d4061ac..fa068640 100644 --- a/pycorrfit/models/model_confocal_t_3d_3d_3d.py +++ b/pycorrfit/models/model_confocal_t_3d_3d_3d.py @@ -43,18 +43,18 @@ def CF_Gxyz_gauss_3D3D3DT(parms, tau): [11] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - taud3=parms[3] - F1=parms[4] - F2=parms[5] - SP=parms[6] - alpha21=parms[7] - alpha31=parms[8] - tautrip=parms[9] - T=parms[10] - off=parms[11] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + taud3 = parms[3] + F1 = parms[4] + F2 = parms[5] + SP = parms[6] + alpha21 = parms[7] + alpha31 = parms[8] + tautrip = parms[9] + T = parms[10] + off = parms[11] g = triple_pnum(n=n, F1=F1, @@ -64,15 +64,15 @@ def CF_Gxyz_gauss_3D3D3DT(parms, tau): comp1=threed, comp2=threed, comp3=threed, - kwargs1={"tau":tau, - "taudiff":taud1, - "SP":SP}, - kwargs2={"tau":tau, - "taudiff":taud2, - "SP":SP}, - kwargs3={"tau":tau, - "taudiff":taud3, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud1, + "SP": SP}, + kwargs2={"tau": tau, + "taudiff": taud2, + "SP": SP}, + kwargs3={"tau": tau, + "taudiff": taud3, + "SP": SP}, ) tr = trip(tau=tau, T=T, tautrip=tautrip) @@ -104,84 +104,84 @@ def supplements(parms, countrate=None): return Info -parms = [ 25, # n - 5, # taud1 - 1000, # taud2 - 11000, # taud3 - 0.5, # F1 - 0.01, # F2 - 5, # SP - 1.0, # alpha21 - 1.0, # alpha31 - 0.001, # tautrip - 0.01, # T - 0.0 # offset - ] +parms = [25, # n + 5, # taud1 + 1000, # taud2 + 11000, # taud3 + 0.5, # F1 + 0.01, # F2 + 5, # SP + 1.0, # alpha21 + 1.0, # alpha31 + 0.001, # tautrip + 0.01, # T + 0.0 # offset + ] -## Boundaries +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[4] = [0,.9999999999999] -boundaries[5] = [0,.9999999999999] +boundaries[4] = [0, .9999999999999] +boundaries[5] = [0, .9999999999999] # T -boundaries[10] = [0,.9999999999999] +boundaries[10] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6081, - name="Threefold 3D diffusion with triplet (confocal)", - comp="T+3D+3D+3D", - mtype="Confocal (Gaussian) and triplet", - fctn=CF_Gxyz_gauss_3D3D3DT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"Ļ"+u"\u2083"+" [ms]", - u"F"+u"\u2081", - u"F"+u"\u2082", - u"SP", - u"\u03b1\u2082\u2081", - u"\u03b1\u2083\u2081", - u"Ļ_trip [ms]", - u"T", - u"offset" - ], - par_values=parms, - par_vary=[True, True, False, True, - False, True, False, False, - False, False, True, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [3, ">", 2], [9, "<", 1], [5, 4, "<", "1"]], - par_hr_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"Ļ"+u"\u2083"+" [ms]", - u"F"+u"\u2081", - u"F"+u"\u2082", - u"SP", - u"\u03b1\u2082\u2081", - u"\u03b1\u2083\u2081", - u"Ļ_trip [Āµs]", - u"T", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taud1 - 1., # taud2 - 1., # taud3 - 1., # F1 - 1., # F2 - 1., # SP - 1., # alpha21 - 1., # alpha31 - 1000., # tautrip [Āµs] - 1., # T - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6081, + name="Threefold 3D diffusion with triplet (confocal)", + comp="T+3D+3D+3D", + mtype="Confocal (Gaussian) and triplet", + fctn=CF_Gxyz_gauss_3D3D3DT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"Ļ"+u"\u2083"+" [ms]", + u"F"+u"\u2081", + u"F"+u"\u2082", + u"SP", + u"\u03b1\u2082\u2081", + u"\u03b1\u2083\u2081", + u"Ļ_trip [ms]", + u"T", + u"offset" + ], + par_values=parms, + par_vary=[True, True, False, True, + False, True, False, False, + False, False, True, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [3, ">", 2], [9, "<", 1], [5, 4, "<", "1"]], + par_hr_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"Ļ"+u"\u2083"+" [ms]", + u"F"+u"\u2081", + u"F"+u"\u2082", + u"SP", + u"\u03b1\u2082\u2081", + u"\u03b1\u2083\u2081", + u"Ļ_trip [Āµs]", + u"T", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taud1 + 1., # taud2 + 1., # taud3 + 1., # F1 + 1., # F2 + 1., # SP + 1., # alpha21 + 1., # alpha31 + 1000., # tautrip [Āµs] + 1., # T + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_tt_2d.py b/pycorrfit/models/model_confocal_tt_2d.py index 99ccfa0c..4580e0f5 100644 --- a/pycorrfit/models/model_confocal_tt_2d.py +++ b/pycorrfit/models/model_confocal_tt_2d.py @@ -31,13 +31,13 @@ def CF_Gxy_gauss_2DTT(parms, tau): [6] offset *tau* - lag time """ - n=parms[0] - taud=parms[1] - tautrip1=parms[2] - T1=parms[3] - tautrip2=parms[4] - T2=parms[5] - off=parms[6] + n = parms[0] + taud = parms[1] + tautrip1 = parms[2] + T1 = parms[3] + tautrip2 = parms[4] + T2 = parms[5] + off = parms[6] g = twod(tau=tau, taudiff=taud) @@ -61,61 +61,61 @@ def supplements(parms, countrate=None): parms = [ - 4, # n - .4, # taud - 0.001, # tautrip1 - 0.01, # T1 - 0.002, # tautrip2 - 0.01, # T2 - 0.0 # offset - ] - -## Boundaries + 4, # n + .4, # taud + 0.001, # tautrip1 + 0.01, # T1 + 0.002, # tautrip2 + 0.01, # T2 + 0.0 # offset +] + +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # T -boundaries[3] = [0,.9999999999999] -boundaries[5] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] +boundaries[5] = [0, .9999999999999] # offset boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6003, - name="2D diffusion with double triplet (confocal)", - comp="T+T+2D", - mtype="Confocal (Gaussian) with double triplet", - fctn=CF_Gxy_gauss_2DTT, - par_labels=[ - u"n", - u"Ļ_diff [ms]", - u"Ļ_tripā [ms]", - u"Tā", - u"Ļ_tripā [ms]", - u"Tā", - u"offset" - ], - par_values=parms, - par_vary=[True, True, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, "<", 1], [4, ">", 2]], - par_hr_labels=[ - u"n", - u"Ļ_diff [ms]", - u"Ļ_tripā [Āµs]", - u"Tā", - u"Ļ_tripā [Āµs]", - u"Tā", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taudiff - 1000., # tautrip1 [Āµs] - 1., # T1 - 1000., # tautrip2 [Āµs] - 1., # T2 - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6003, + name="2D diffusion with double triplet (confocal)", + comp="T+T+2D", + mtype="Confocal (Gaussian) with double triplet", + fctn=CF_Gxy_gauss_2DTT, + par_labels=[ + u"n", + u"Ļ_diff [ms]", + u"Ļ_tripā [ms]", + u"Tā", + u"Ļ_tripā [ms]", + u"Tā", + u"offset" + ], + par_values=parms, + par_vary=[True, True, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, "<", 1], [4, ">", 2]], + par_hr_labels=[ + u"n", + u"Ļ_diff [ms]", + u"Ļ_tripā [Āµs]", + u"Tā", + u"Ļ_tripā [Āµs]", + u"Tā", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taudiff + 1000., # tautrip1 [Āµs] + 1., # T1 + 1000., # tautrip2 [Āµs] + 1., # T2 + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_tt_2d_2d.py b/pycorrfit/models/model_confocal_tt_2d_2d.py index 4f68f204..b10e182a 100644 --- a/pycorrfit/models/model_confocal_tt_2d_2d.py +++ b/pycorrfit/models/model_confocal_tt_2d_2d.py @@ -40,26 +40,26 @@ def CF_Gxy_gauss_2D2DTT(parms, tau): [9] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - alpha=parms[4] - tautrip1=parms[5] - T1=parms[6] - tautrip2=parms[7] - T2=parms[8] - off=parms[9] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + alpha = parms[4] + tautrip1 = parms[5] + T1 = parms[6] + tautrip2 = parms[7] + T2 = parms[8] + off = parms[9] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=twod, comp2=twod, - kwargs1={"tau":tau, - "taudiff":taud1}, - kwargs2={"tau":tau, - "taudiff":taud2}, + kwargs1={"tau": tau, + "taudiff": taud1}, + kwargs2={"tau": tau, + "taudiff": taud2}, ) tr1 = trip(tau=tau, T=T1, tautrip=tautrip1) @@ -91,74 +91,75 @@ def supplements(parms, countrate=None): parms = [ - 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 1.0, # alpha - 0.001, # tautrip1 - 0.01, # T1 - 0.002, # tautrip2 - 0.01, # T2 - 0.0 # offset - ] - -## Boundaries + 25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 1.0, # alpha + 0.001, # tautrip1 + 0.01, # T1 + 0.002, # tautrip2 + 0.01, # T2 + 0.0 # offset +] + +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[6] = [0,.9999999999999] -boundaries[8] = [0,.9999999999999] +boundaries[6] = [0, .9999999999999] +boundaries[8] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6044, - name="Separate 2D diffusion with double triplet (confocal)", - comp="T+T+2D+2D", - mtype="Confocal (Gaussian) with double triplet", - fctn=CF_Gxy_gauss_2D2DTT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"F"+u"\u2081", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_tripā [ms]", - u"Tā", - u"Ļ_tripā [ms]", - u"Tā", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [5, "<", 1], [7, ">", 5]], - par_hr_labels=[ - u"n", - u"Ļā [ms]", - u"Ļā [ms]", - u"Fā", - u"\u03b1"+u" (qā/qā)", - u"Ļ_tripā [Āµs]", - u"Tā", - u"Ļ_tripā [Āµs]", - u"Tā", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taud1 - 1., # taud2 - 1., # F - 1., # alpha - 1000., # tautrip1 [Āµs] - 1., # T1 - 1000., # tautrip2 [Āµs] - 1., # T2 - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6044, + name="Separate 2D diffusion with double triplet (confocal)", + comp="T+T+2D+2D", + mtype="Confocal (Gaussian) with double triplet", + fctn=CF_Gxy_gauss_2D2DTT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"F"+u"\u2081", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_tripā [ms]", + u"Tā", + u"Ļ_tripā [ms]", + u"Tā", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, + False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [5, "<", 1], [7, ">", 5]], + par_hr_labels=[ + u"n", + u"Ļā [ms]", + u"Ļā [ms]", + u"Fā", + u"\u03b1"+u" (qā/qā)", + u"Ļ_tripā [Āµs]", + u"Tā", + u"Ļ_tripā [Āµs]", + u"Tā", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taud1 + 1., # taud2 + 1., # F + 1., # alpha + 1000., # tautrip1 [Āµs] + 1., # T1 + 1000., # tautrip2 [Āµs] + 1., # T2 + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_tt_3d.py b/pycorrfit/models/model_confocal_tt_3d.py index 3b837e58..81e79095 100644 --- a/pycorrfit/models/model_confocal_tt_3d.py +++ b/pycorrfit/models/model_confocal_tt_3d.py @@ -34,17 +34,17 @@ def CF_Gxyz_gauss_3DTT(parms, tau): [7] offset *tau* - lag time """ - n=parms[0] - taudiff=parms[1] - SP=parms[2] - tautrip1=parms[3] - T1=parms[4] - tautrip2=parms[5] - T2=parms[6] - off=parms[7] + n = parms[0] + taudiff = parms[1] + SP = parms[2] + tautrip1 = parms[3] + T1 = parms[4] + tautrip2 = parms[5] + T2 = parms[6] + off = parms[7] g = threed(tau=tau, taudiff=taudiff, SP=SP) - + tr1 = trip(tau=tau, T=T1, tautrip=tautrip1) tr2 = trip(tau=tau, T=T2, tautrip=tautrip2) @@ -65,65 +65,65 @@ def supplements(parms, countrate=None): parms = [ - 4, # n - .4, # taud1 - 5, # SP - 0.001, # tautrip1 - 0.01, # T1 - 0.002, # tautrip2 - 0.01, # T2 - 0.0 # offset - ] - -## Boundaries + 4, # n + .4, # taud1 + 5, # SP + 0.001, # tautrip1 + 0.01, # T1 + 0.002, # tautrip2 + 0.01, # T2 + 0.0 # offset +] + +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # T -boundaries[4] = [0,.9999999999999] -boundaries[6] = [0,.9999999999999] +boundaries[4] = [0, .9999999999999] +boundaries[6] = [0, .9999999999999] # offset boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6009, - name="3D diffusion with double triplet (confocal)", - comp="T+T+3D", - mtype="Confocal (Gaussian) with double triplet", - fctn=CF_Gxyz_gauss_3DTT, - par_labels=[ - u"n", - u"Ļ_diff [ms]", - u"SP", - u"Ļ_tripā [ms]", - u"Tā", - u"Ļ_tripā [ms]", - u"Tā", - u"offset" - ], - par_values=parms, - par_vary=[True, True, False, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[3, "<", 1], [5, ">", 3]], - par_hr_labels=[ - u"n", - u"Ļ_diff [ms]", - u"SP", - u"Ļ_tripā [Āµs]", - u"Tā", - u"Ļ_tripā [Āµs]", - u"Tā", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taudiff - 1., # SP - 1000., # tautrip1 [Āµs] - 1., # T1 - 1000., # tautrip2 [Āµs] - 1., # T2 - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6009, + name="3D diffusion with double triplet (confocal)", + comp="T+T+3D", + mtype="Confocal (Gaussian) with double triplet", + fctn=CF_Gxyz_gauss_3DTT, + par_labels=[ + u"n", + u"Ļ_diff [ms]", + u"SP", + u"Ļ_tripā [ms]", + u"Tā", + u"Ļ_tripā [ms]", + u"Tā", + u"offset" + ], + par_values=parms, + par_vary=[True, True, False, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[3, "<", 1], [5, ">", 3]], + par_hr_labels=[ + u"n", + u"Ļ_diff [ms]", + u"SP", + u"Ļ_tripā [Āµs]", + u"Tā", + u"Ļ_tripā [Āµs]", + u"Tā", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taudiff + 1., # SP + 1000., # tautrip1 [Āµs] + 1., # T1 + 1000., # tautrip2 [Āµs] + 1., # T2 + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_tt_3d_2d.py b/pycorrfit/models/model_confocal_tt_3d_2d.py index 36835904..5120ef18 100644 --- a/pycorrfit/models/model_confocal_tt_3d_2d.py +++ b/pycorrfit/models/model_confocal_tt_3d_2d.py @@ -42,28 +42,28 @@ def CF_Gxyz_gauss_3D2DTT(parms, tau): [10] offset *tau* - lag time """ - n=parms[0] - taud2D=parms[1] - taud3D=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - tautrip1=parms[6] - T1=parms[7] - tautrip2=parms[8] - T2=parms[9] - off=parms[10] + n = parms[0] + taud2D = parms[1] + taud3D = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + tautrip1 = parms[6] + T1 = parms[7] + tautrip2 = parms[8] + T2 = parms[9] + off = parms[10] g = double_pnum(n=n, F1=1-F, alpha=alpha, comp1=twod, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud2D}, - kwargs2={"tau":tau, - "taudiff":taud3D, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud2D}, + kwargs2={"tau": tau, + "taudiff": taud3D, + "SP": SP}, ) tr1 = trip(tau=tau, T=T1, tautrip=tautrip1) @@ -93,82 +93,83 @@ def supplements(parms, countrate=None): # CPP cpp = countrate/n Info.append([u"cpp [kHz]", cpp]) - return Info - + return Info + parms = [ - 25, # n - 240, # taud2D - 0.1, # taud3D - 0.5, # F3D - 5, # SP - 1.0, # alpha - 0.001, # tautrip1 - 0.01, # T1 - 0.002, # tautrip2 - 0.01, # T2 - 0.0 # offset - ] - -## Boundaries + 25, # n + 240, # taud2D + 0.1, # taud3D + 0.5, # F3D + 5, # SP + 1.0, # alpha + 0.001, # tautrip1 + 0.01, # T1 + 0.002, # tautrip2 + 0.01, # T2 + 0.0 # offset +] + +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[7] = [0,.9999999999999] -boundaries[9] = [0,.9999999999999] +boundaries[7] = [0, .9999999999999] +boundaries[9] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6045, - name="Separate 3D and 2D diffusion with double triplet (confocal)", - comp="T+T+3D+2D", - mtype="Confocal (Gaussian) with double triplet", - fctn=CF_Gxyz_gauss_3D2DTT, - par_labels=[ - u"n", - u"Ļ_2D [ms]", - u"Ļ_3D [ms]", - u"F_3D", - u"SP", - u"\u03b1"+" (q_3D/q_2D)", - u"Ļ_tripā [ms]", - u"Tā", - u"Ļ_tripā [ms]", - u"Tā", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, "<", 1], [6, "<", 2], [8, ">", 6]], - par_hr_labels=[ - u"n", - u"Ļ_2D [ms]", - u"Ļ_3D [ms]", - u"F_3D", - u"SP", - u"\u03b1"+" (q_3D/q_2D)", - u"Ļ_tripā [Āµs]", - u"Tā", - u"Ļ_tripā [Āµs]", - u"Tā", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # "Ļ_2D [ms]", - 1., # "Ļ_3D [ms]", - 1., # "F_3D", - 1., # "SP", - 1., # u"\u03b1"+" (q_3D/q_2D)", - 1000., # tautrip1 [Āµs] - 1., # T1 - 1000., # tautrip2 [Āµs] - 1., # T2 - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6045, + name="Separate 3D and 2D diffusion with double triplet (confocal)", + comp="T+T+3D+2D", + mtype="Confocal (Gaussian) with double triplet", + fctn=CF_Gxyz_gauss_3D2DTT, + par_labels=[ + u"n", + u"Ļ_2D [ms]", + u"Ļ_3D [ms]", + u"F_3D", + u"SP", + u"\u03b1"+" (q_3D/q_2D)", + u"Ļ_tripā [ms]", + u"Tā", + u"Ļ_tripā [ms]", + u"Tā", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, + False, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, "<", 1], [6, "<", 2], [8, ">", 6]], + par_hr_labels=[ + u"n", + u"Ļ_2D [ms]", + u"Ļ_3D [ms]", + u"F_3D", + u"SP", + u"\u03b1"+" (q_3D/q_2D)", + u"Ļ_tripā [Āµs]", + u"Tā", + u"Ļ_tripā [Āµs]", + u"Tā", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # "Ļ_2D [ms]", + 1., # "Ļ_3D [ms]", + 1., # "F_3D", + 1., # "SP", + 1., # u"\u03b1"+" (q_3D/q_2D)", + 1000., # tautrip1 [Āµs] + 1., # T1 + 1000., # tautrip2 [Āµs] + 1., # T2 + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/models/model_confocal_tt_3d_3d.py b/pycorrfit/models/model_confocal_tt_3d_3d.py index 0b89b1d3..3a51c71f 100644 --- a/pycorrfit/models/model_confocal_tt_3d_3d.py +++ b/pycorrfit/models/model_confocal_tt_3d_3d.py @@ -42,29 +42,29 @@ def CF_Gxyz_gauss_3D3DTT(parms, tau): [10] offset *tau* - lag time """ - n=parms[0] - taud1=parms[1] - taud2=parms[2] - F=parms[3] - SP=parms[4] - alpha=parms[5] - tautrip1=parms[6] - T1=parms[7] - tautrip2=parms[8] - T2=parms[9] - off=parms[10] + n = parms[0] + taud1 = parms[1] + taud2 = parms[2] + F = parms[3] + SP = parms[4] + alpha = parms[5] + tautrip1 = parms[6] + T1 = parms[7] + tautrip2 = parms[8] + T2 = parms[9] + off = parms[10] g = double_pnum(n=n, F1=F, alpha=alpha, comp1=threed, comp2=threed, - kwargs1={"tau":tau, - "taudiff":taud1, - "SP":SP}, - kwargs2={"tau":tau, - "taudiff":taud2, - "SP":SP}, + kwargs1={"tau": tau, + "taudiff": taud1, + "SP": SP}, + kwargs2={"tau": tau, + "taudiff": taud2, + "SP": SP}, ) tr1 = trip(tau=tau, T=T1, tautrip=tautrip1) @@ -96,78 +96,79 @@ def supplements(parms, countrate=None): parms = [ - 25, # n - 5, # taud1 - 1000, # taud2 - 0.5, # F - 5, # SP - 1.0, # alpha - 0.001, # tautrip1 - 0.01, # T1 - 0.002, # tautrip2 - 0.01, # T2 - 0.0 # offset - ] - -## Boundaries + 25, # n + 5, # taud1 + 1000, # taud2 + 0.5, # F + 5, # SP + 1.0, # alpha + 0.001, # tautrip1 + 0.01, # T1 + 0.002, # tautrip2 + 0.01, # T2 + 0.0 # offset +] + +# Boundaries # strictly positive boundaries = [[0, np.inf]]*len(parms) # F -boundaries[3] = [0,.9999999999999] +boundaries[3] = [0, .9999999999999] # T -boundaries[7] = [0,.9999999999999] -boundaries[9] = [0,.9999999999999] +boundaries[7] = [0, .9999999999999] +boundaries[9] = [0, .9999999999999] boundaries[-1] = [-np.inf, np.inf] model_setup( - modelid=6043, - name="Separate 3D diffusion with double triplet (confocal)", - comp="T+T+3D+3D", - mtype="Confocal (Gaussian) with double triplet", - fctn=CF_Gxyz_gauss_3D3DTT, - par_labels=[ - u"n", - u"Ļ"+u"\u2081"+" [ms]", - u"Ļ"+u"\u2082"+" [ms]", - u"F"+u"\u2081", - u"SP", - u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", - u"Ļ_tripā [ms]", - u"Tā", - u"Ļ_tripā [ms]", - u"Tā", - u"offset" - ], - par_values=parms, - par_vary=[True, True, True, True, False, False, False, False, False, False, False], - par_boundaries=boundaries, - par_constraints=[[2, ">", 1], [6, "<", 1], [8, ">", 6]], - par_hr_labels=[ - u"n", - u"Ļā [ms]", - u"Ļā [ms]", - u"Fā", - u"SP", - u"\u03b1"+u" (qā/qā)", - u"Ļ_tripā [Āµs]", - u"Tā", - u"Ļ_tripā [Āµs]", - u"Tā", - u"offset" - ], - par_hr_factors=[ - 1., # n - 1., # taud1 - 1., # taud2 - 1., # F - 1., # SP - 1., # alpha - 1000., # tautrip1 [Āµs] - 1., # T1 - 1000., # tautrip2 [Āµs] - 1., # T2 - 1. # offset - ], - supplementary_method=supplements - ) + modelid=6043, + name="Separate 3D diffusion with double triplet (confocal)", + comp="T+T+3D+3D", + mtype="Confocal (Gaussian) with double triplet", + fctn=CF_Gxyz_gauss_3D3DTT, + par_labels=[ + u"n", + u"Ļ"+u"\u2081"+" [ms]", + u"Ļ"+u"\u2082"+" [ms]", + u"F"+u"\u2081", + u"SP", + u"\u03b1"+" (q"+u"\u2082"+"/q"+u"\u2081"+")", + u"Ļ_tripā [ms]", + u"Tā", + u"Ļ_tripā [ms]", + u"Tā", + u"offset" + ], + par_values=parms, + par_vary=[True, True, True, True, False, + False, False, False, False, False, False], + par_boundaries=boundaries, + par_constraints=[[2, ">", 1], [6, "<", 1], [8, ">", 6]], + par_hr_labels=[ + u"n", + u"Ļā [ms]", + u"Ļā [ms]", + u"Fā", + u"SP", + u"\u03b1"+u" (qā/qā)", + u"Ļ_tripā [Āµs]", + u"Tā", + u"Ļ_tripā [Āµs]", + u"Tā", + u"offset" + ], + par_hr_factors=[ + 1., # n + 1., # taud1 + 1., # taud2 + 1., # F + 1., # SP + 1., # alpha + 1000., # tautrip1 [Āµs] + 1., # T1 + 1000., # tautrip2 [Āµs] + 1., # T2 + 1. # offset + ], + supplementary_method=supplements +) diff --git a/pycorrfit/openfile.py b/pycorrfit/openfile.py index a7fea6d7..e351559a 100644 --- a/pycorrfit/openfile.py +++ b/pycorrfit/openfile.py @@ -80,7 +80,7 @@ def LoadSessionData(sessionfile, parameters_only=False): # As of version 0.7.4 we save chi2 and shared pages -global fit Infodict["Supplements"][idp[0]]["Chi sq"] = idp[2] Infodict["Supplements"][idp[0]]["Global Share"] = idp[3] - ## Preferences: Reserved for a future version of PyCorrFit :) + # Preferences: Reserved for a future version of PyCorrFit :) prefname = "Preferences.yaml" try: Arc.getinfo(prefname) @@ -102,19 +102,21 @@ def LoadSessionData(sessionfile, parameters_only=False): # No more functions to import key = 8000 else: - funcfile = Arc.open(funcfilename) + funcfile = Arc.open(funcfilename) Infodict["External Functions"][key] = funcfile.read() funcfile.close() - key=key+1 + key = key+1 # Get the correlation arrays Infodict["Correlations"] = dict() for i in np.arange(len(Infodict["Parameters"])): # The *number* is used to identify the correct file - number = str(Infodict["Parameters"][i][0]).strip().strip(":").strip("#") + number = str(Infodict["Parameters"][i][0] + ).strip().strip(":").strip("#") pageid = int(number) expfilename = "data"+number+".csv" expfile = Arc.open(expfilename, 'r') - readdata = csv.reader(io.StringIO(expfile.read().decode()), delimiter=',') + readdata = csv.reader(io.StringIO( + expfile.read().decode()), delimiter=',') dataexp = list() tau = list() if str(readdata.__next__()[0]) == "# tau only": @@ -130,7 +132,7 @@ def LoadSessionData(sessionfile, parameters_only=False): if (str(row[0])[0:1] != '#'): dataexp.append((float(row[0]), float(row[1]))) dataexp = np.array(dataexp) - tau = dataexp[:,0] + tau = dataexp[:, 0] Infodict["Correlations"][pageid] = [tau, dataexp] del readdata expfile.close() @@ -138,7 +140,8 @@ def LoadSessionData(sessionfile, parameters_only=False): Infodict["Traces"] = dict() for i in np.arange(len(Infodict["Parameters"])): # The *number* is used to identify the correct file - number = str(Infodict["Parameters"][i][0]).strip().strip(":").strip("#") + number = str(Infodict["Parameters"][i][0] + ).strip().strip(":").strip("#") pageid = int(number) # Find out, if we have a cross correlation data type IsCross = False @@ -152,7 +155,7 @@ def LoadSessionData(sessionfile, parameters_only=False): else: # Cross correlation uses two traces tracefilenames = ["trace"+number+"A.csv", - "trace"+number+"B.csv" ] + "trace"+number+"B.csv"] thistrace = list() for tracefilename in tracefilenames: try: @@ -161,7 +164,8 @@ def LoadSessionData(sessionfile, parameters_only=False): pass else: tracefile = Arc.open(tracefilename, 'r') - traceread = csv.reader(io.StringIO(tracefile.read().decode()), delimiter=',') + traceread = csv.reader(io.StringIO( + tracefile.read().decode()), delimiter=',') singletrace = list() for row in traceread: # Exclude commentaries @@ -188,7 +192,8 @@ def LoadSessionData(sessionfile, parameters_only=False): commentfile = Arc.open(commentfilename, 'r') Infodict["Comments"] = dict() for i in np.arange(len(Infodict["Parameters"])): - number = str(Infodict["Parameters"][i][0]).strip().strip(":").strip("#") + number = str(Infodict["Parameters"][i][0] + ).strip().strip(":").strip("#") pageid = int(number) # Strip line ending characters for all the Pages. Infodict["Comments"][pageid] = commentfile.readline().strip() @@ -209,19 +214,22 @@ def LoadSessionData(sessionfile, parameters_only=False): # Open the file Infodict["Backgrounds"] = list() bgfile = Arc.open(bgfilename, 'r') - bgread = csv.reader(io.StringIO(bgfile.read().decode()), delimiter='\t') + bgread = csv.reader(io.StringIO( + bgfile.read().decode()), delimiter='\t') i = 0 for bgrow in bgread: bgtracefilename = "bg_trace"+str(i)+".csv" bgtracefile = Arc.open(bgtracefilename, 'r') - bgtraceread = csv.reader(io.StringIO(bgtracefile.read().decode()), delimiter=',') + bgtraceread = csv.reader(io.StringIO( + bgtracefile.read().decode()), delimiter=',') bgtrace = list() for row in bgtraceread: # Exclude commentaries if (str(row[0])[0:1] != '#'): bgtrace.append((np.float(row[0]), np.float(row[1]))) bgtrace = np.array(bgtrace) - newbackground = Trace(trace=bgtrace, name=str(bgrow[1]), countrate=np.float(bgrow[0])) + newbackground = Trace(trace=bgtrace, name=str( + bgrow[1]), countrate=np.float(bgrow[0])) Infodict["Backgrounds"].append(newbackground) i = i + 1 bgfile.close() @@ -255,7 +263,7 @@ def LoadSessionData(sessionfile, parameters_only=False): Wdata.append(np.float(row[0])) Weightsdict[pageid][Nkey] = np.array(Wdata) Infodict["External Weights"] = Weightsdict - ## Preferences + # Preferences preferencesname = "preferences.cfg" try: # Raises KeyError, if file is not present: @@ -274,7 +282,7 @@ def LoadSessionData(sessionfile, parameters_only=False): key = key.strip() value = value.strip() if value.count(","): - value = [ v.strip() for v in value.split(",")] + value = [v.strip() for v in value.split(",")] prefdict[key] = value Infodict["Preferences"] = prefdict Arc.close() @@ -318,7 +326,7 @@ def SaveSessionData(sessionfile, Infodict): parmsfilename = "Parameters.yaml" # Parameters have to be floats in lists # in order for yaml.safe_load to work. - Parms = Infodict["Parameters"] + Parms = Infodict["Parameters"] ParmsKeys = list(Parms.keys()) ParmsKeys.sort() Parmlist = list() @@ -326,11 +334,11 @@ def SaveSessionData(sessionfile, Infodict): # Make sure we do not accidently save arrays. # This would not work correctly with yaml. # Parameters - Parms[idparm][2] = np.array(Parms[idparm][2],dtype="float").tolist() + Parms[idparm][2] = np.array(Parms[idparm][2], dtype="float").tolist() # Parameter varied - Parms[idparm][3] = np.array(Parms[idparm][3],dtype="bool").tolist() + Parms[idparm][3] = np.array(Parms[idparm][3], dtype="bool").tolist() # Channel selection - Parms[idparm][4] = np.array(Parms[idparm][4],dtype="int").tolist() + Parms[idparm][4] = np.array(Parms[idparm][4], dtype="int").tolist() # Background selection for ii in range(len(Parms[idparm][6])): if Parms[idparm][6][ii] is not None: @@ -339,7 +347,7 @@ def SaveSessionData(sessionfile, Infodict): if Parms[idparm][8] is not None: Parms[idparm][8] = int(Parms[idparm][8]) # Fit parameter range - Parms[idparm][9] = np.array(Parms[idparm][9],dtype="float").tolist() + Parms[idparm][9] = np.array(Parms[idparm][9], dtype="float").tolist() Parmlist.append(Parms[idparm]) try: @@ -363,7 +371,7 @@ def SaveSessionData(sessionfile, Infodict): os.remove(os.path.join(tempdir, parmsfilename)) # Supplementary data (errors of fit) errsfilename = "Supplements.yaml" - Sups = Infodict["Supplements"] + Sups = Infodict["Supplements"] SupKeys = list(Sups.keys()) SupKeys.sort() Suplist = list() @@ -379,7 +387,7 @@ def SaveSessionData(sessionfile, Infodict): # Save external functions for key in Infodict["External Functions"].keys(): funcfilename = "model_"+str(key)+".txt" - funcfile = codecs.open(funcfilename, 'w', encoding="utf-8") + funcfile = codecs.open(funcfilename, 'w', encoding="utf-8") funcfile.write(Infodict["External Functions"][key]) funcfile.close() Arc.write(funcfilename) @@ -402,9 +410,9 @@ def SaveSessionData(sessionfile, Infodict): # Otherwise, the experimental data will not be saved entirely, # if it has been cropped. Because tau might be smaller, than # exp[:,0] --> tau = exp[startcrop:endcrop,0] - for j in np.arange(len(exp[:,0])): - dataWriter.writerow(["%.20e" % exp[j,0], - "%.20e" % exp[j,1]]) + for j in np.arange(len(exp[:, 0])): + dataWriter.writerow(["%.20e" % exp[j, 0], + "%.20e" % exp[j, 1]]) else: # Only write tau dataWriter.writerow(['# tau'+' only']) @@ -423,12 +431,12 @@ def SaveSessionData(sessionfile, Infodict): if Infodict["Traces"][pageid] is not None and len(Infodict["Traces"][pageid]) != 0: if Parms[pageid][7] is True: # We have cross correlation: save two traces - ## A + # A tracefilenamea = "trace"+number+"A.csv" tracefile = open(tracefilenamea, 'w') traceWriter = csv.writer(tracefile, delimiter=',') - time = Infodict["Traces"][pageid][0][:,0] - rate = Infodict["Traces"][pageid][0][:,1] + time = Infodict["Traces"][pageid][0][:, 0] + rate = Infodict["Traces"][pageid][0][:, 1] # Names of Columns traceWriter.writerow(['# time', 'count rate']) # Actual Data @@ -439,7 +447,7 @@ def SaveSessionData(sessionfile, Infodict): # Add to archive Arc.write(tracefilenamea) os.remove(os.path.join(tempdir, tracefilenamea)) - ## B (only if it exists...) + # B (only if it exists...) try: _ = Infodict["Traces"][pageid][1] except IndexError: @@ -448,8 +456,8 @@ def SaveSessionData(sessionfile, Infodict): tracefilenameb = "trace"+number+"B.csv" tracefile = open(tracefilenameb, 'w') traceWriter = csv.writer(tracefile, delimiter=',') - time = Infodict["Traces"][pageid][1][:,0] - rate = Infodict["Traces"][pageid][1][:,1] + time = Infodict["Traces"][pageid][1][:, 0] + rate = Infodict["Traces"][pageid][1][:, 1] # Names of Columns traceWriter.writerow(['# time', 'count rate']) # Actual Data @@ -465,8 +473,8 @@ def SaveSessionData(sessionfile, Infodict): tracefilename = "trace"+number+".csv" tracefile = open(tracefilename, 'w') traceWriter = csv.writer(tracefile, delimiter=',') - time = Infodict["Traces"][pageid][0][:,0] - rate = Infodict["Traces"][pageid][0][:,1] + time = Infodict["Traces"][pageid][0][:, 0] + rate = Infodict["Traces"][pageid][0][:, 1] # Names of Columns traceWriter.writerow(['# time', 'count rate']) # Actual Data @@ -494,7 +502,7 @@ def SaveSessionData(sessionfile, Infodict): commentfile.close() Arc.write(commentfilename) os.remove(os.path.join(tempdir, commentfilename)) - ## Save Background information: + # Save Background information: Background = Infodict["Backgrounds"] if len(Background) > 0: # We do not use a comma separated, but a tab separated file, @@ -503,15 +511,16 @@ def SaveSessionData(sessionfile, Infodict): bgfile = open(bgfilename, 'w') bgwriter = csv.writer(bgfile, delimiter='\t') for i in np.arange(len(Background)): - bgwriter.writerow([str(Background[i].countrate), Background[i].name]) + bgwriter.writerow( + [str(Background[i].countrate), Background[i].name]) # Traces bgtracefilename = "bg_trace"+str(i)+".csv" bgtracefile = open(bgtracefilename, 'w') bgtraceWriter = csv.writer(bgtracefile, delimiter=',') bgtraceWriter.writerow(['# time', 'count rate']) # Actual Data - time = Background[i][:,0] - rate = Background[i][:,1] + time = Background[i][:, 0] + rate = Background[i][:, 1] for j in np.arange(len(time)): bgtraceWriter.writerow(["%.20e" % time[j], "%.20e" % rate[j]]) @@ -522,7 +531,7 @@ def SaveSessionData(sessionfile, Infodict): bgfile.close() Arc.write(bgfilename) os.remove(os.path.join(tempdir, bgfilename)) - ## Save External Weights information + # Save External Weights information WeightedPageID = list(Infodict["External Weights"].keys()) WeightedPageID.sort() WeightFilename = "externalweights.txt" @@ -537,7 +546,7 @@ def SaveSessionData(sessionfile, Infodict): for Nkey in NestWeights: WeightWriter.writerow([number, str(Nkey).strip()]) # Add data to a File - WeightDataFilename = "externalweights_data"+number+\ + WeightDataFilename = "externalweights_data"+number +\ "_"+str(Nkey).strip()+".csv" WeightDataFile = open(WeightDataFilename, 'w') WeightDataWriter = csv.writer(WeightDataFile) @@ -550,7 +559,7 @@ def SaveSessionData(sessionfile, Infodict): WeightFile.close() Arc.write(WeightFilename) os.remove(os.path.join(tempdir, WeightFilename)) - ## Preferences + # Preferences preferencesname = "preferences.cfg" with codecs.open(preferencesname, 'w', encoding="utf-8") as fd: for key in Infodict["Preferences"]: @@ -562,7 +571,7 @@ def SaveSessionData(sessionfile, Infodict): fd.write("{} = {}\n".format(key, value)) Arc.write(preferencesname) os.remove(os.path.join(tempdir, preferencesname)) - ## Readme + # Readme rmfilename = "Readme.txt" rmfile = codecs.open(rmfilename, 'w', encoding="utf-8") rmfile.write(ReadmeSession) @@ -573,7 +582,7 @@ def SaveSessionData(sessionfile, Infodict): Arc.close() # Move archive to destination directory shutil.move(os.path.join(tempdir, filename), - os.path.join(dirname, filename) ) + os.path.join(dirname, filename)) # Go to destination directory os.chdir(returnWD) os.rmdir(tempdir) @@ -605,7 +614,7 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): the total particle number `n`. """ openedfile = codecs.open(exportfile, 'w', encoding='utf-8') - ## First, some doc text + # First, some doc text openedfile.write(ReadmeCSV.replace('\n', '\r\n')) # The info for line in page_info.splitlines(): @@ -614,13 +623,13 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): # Get all the data we need from the Page # Modeled data corr = correlation - mod = corr.modeled_plot[:,1] + mod = corr.modeled_plot[:, 1] if corr.correlation is not None: # Experimental data - tau = corr.correlation_plot[:,0] - exp = corr.correlation_plot[:,1] - res = corr.residuals_plot[:,0] + tau = corr.correlation_plot[:, 0] + exp = corr.correlation_plot[:, 1] + res = corr.residuals_plot[:, 0] # Plotting! Because we only export plotted area. if corr.is_weighted_fit: @@ -634,9 +643,9 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): pass elif len(weight) != len(exp): - text = "Weights have not been calculated for the "+\ - "area you want to export. Pressing 'Fit' "+\ - "again should solve this issue. Weights will "+\ + text = "Weights have not been calculated for the " +\ + "area you want to export. Pressing 'Fit' " +\ + "again should solve this issue. Weights will " +\ "not be saved." warnings.warn(text) weight = None @@ -651,22 +660,22 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): # PyCorrFit thinks in [ms], but we will save as [s] timefactor = 0.001 tau = [timefactor * t for t in tau] - ## Now we want to write all that data into the file + # Now we want to write all that data into the file # This is for csv writing: - ## Correlation curve + # Correlation curve dataWriter = csv.writer(openedfile, delimiter='\t') if exp is not None: - header = '# Lag time [s]'+"\t"+ \ - 'Experimental correlation'+"\t"+ \ - 'Fitted correlation'+ "\t"+ \ + header = '# Lag time [s]'+"\t" + \ + 'Experimental correlation'+"\t" + \ + 'Fitted correlation' + "\t" + \ 'Residuals'+"\r\n" data = [tau, exp, mod, res] if corr.is_weighted_fit and weight is not None: header = "{} \t Weights [{}] \r\n".format( - header.strip(), weightname) + header.strip(), weightname) data.append(weight) else: - header = '# Lag time [s]'+"\t"+ \ + header = '# Lag time [s]'+"\t" + \ 'Correlation function'+"\r\n" data = [tau, mod] # Write header @@ -679,7 +688,7 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): rowcoli = "{:.10e}".format(data[j][i]) datarow.append(rowcoli) dataWriter.writerow(datarow) - ## Trace + # Trace # Only save the trace if user wants us to: if savetrace: # We will also save the trace in [s] @@ -688,11 +697,11 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): # Mark beginning of Trace openedfile.write('#\r\n#\r\n# BEGIN TRACE\r\n#\r\n') # Columns - time = corr.traces[0][:,0] * timefactor - intensity = corr.traces[0][:,1] + time = corr.traces[0][:, 0] * timefactor + intensity = corr.traces[0][:, 1] # Write openedfile.write('# Time [s]'+"\t" - 'Intensity trace [kHz]'+" \r\n") + 'Intensity trace [kHz]'+" \r\n") for i in np.arange(len(time)): dataWriter.writerow(["{:.10e}".format(time[i]), "{:.10e}".format(intensity[i])]) @@ -701,12 +710,12 @@ def ExportCorrelation(exportfile, correlation, page_info, savetrace=True): # Mark beginning of Trace B openedfile.write('#\r\n#\r\n# BEGIN SECOND TRACE\r\n#\r\n') # Columns - time = corr.traces[1][:,0] * timefactor - intensity = corr.traces[1][:,1] + time = corr.traces[1][:, 0] * timefactor + intensity = corr.traces[1][:, 1] # Write openedfile.write('# Time [s]'+"\t" - 'Intensity trace [kHz]'+" \r\n") + 'Intensity trace [kHz]'+" \r\n") for i in np.arange(len(time)): dataWriter.writerow(["{:.10e}".format(time[i]), "{:.10e}".format(intensity[i])]) diff --git a/pycorrfit/readfiles/__init__.py b/pycorrfit/readfiles/__init__.py index 80cf4fb8..39112298 100644 --- a/pycorrfit/readfiles/__init__.py +++ b/pycorrfit/readfiles/__init__.py @@ -43,7 +43,7 @@ def get_supported_extensions(): for kf in list(filetypes_dict.keys()): ext = kf.split("|")[-1] ext = ext.split(";") - ext = [ e.lower().strip("*. ") for e in ext] + ext = [e.lower().strip("*. ") for e in ext] ext = list(np.unique(ext)) extlist += ext extlist = list(np.unique(extlist)) @@ -119,13 +119,13 @@ def openZIP(path, filename=None): path = path / filename filename = path.name - ## Open the archive: + # Open the archive: Arc = zipfile.ZipFile(path, mode='r') - Correlations = [] # Correlation information + Correlations = [] # Correlation information Curvelist = [] # Type information Filelist = [] # List of filenames corresponding to *Curvelist* Trace = [] # Corresponding traces - ## First test, if we are opening a session file + # First test, if we are opening a session file sessionwc = [".fcsfit-session.zip", ".pcfs"] if filename.endswith(sessionwc[0]) or filename.endswith(sessionwc[1]): # Get the yaml parms dump: @@ -142,7 +142,8 @@ def openZIP(path, filename=None): number = str(Parms[i][0]) expfilename = "data"+number[1:len(number)-2]+".csv" expfile = Arc.open(expfilename, 'r') - readdata = csv.reader(io.StringIO(expfile.read().decode()), delimiter=',') + readdata = csv.reader(io.StringIO( + expfile.read().decode()), delimiter=',') dataexp = list() if str(readdata.__next__()[0]) == "# tau only": # We do not have a curve here @@ -178,7 +179,7 @@ def openZIP(path, filename=None): else: # Cross correlation uses two traces tracefilenames = ["trace"+number[1:len(number)-2]+"A.csv", - "trace"+number[1:len(number)-2]+"B.csv" ] + "trace"+number[1:len(number)-2]+"B.csv"] Curvelist.append("CC") thistrace = list() for tracefilename in tracefilenames: @@ -189,7 +190,8 @@ def openZIP(path, filename=None): pass else: tracefile = Arc.open(tracefilename, 'r') - traceread = csv.reader(io.StringIO(tracefile.read().decode()), delimiter=',') + traceread = csv.reader(io.StringIO( + tracefile.read().decode()), delimiter=',') singletrace = list() for row in traceread: # Exclude commentaries @@ -221,7 +223,7 @@ def openZIP(path, filename=None): Trace += data["Trace"] Curvelist += data["Type"] fnames = data["Filename"] - Filelist += [ filename+"/"+fs for fs in fnames ] + Filelist += [filename+"/"+fs for fs in fnames] shutil.rmtree(path=tempdir, ignore_errors=True) Arc.close() dictionary = {} @@ -232,32 +234,31 @@ def openZIP(path, filename=None): return dictionary - # The string that is shown when opening all supported files # We add an empty space so it is listed first in the dialogs. ALL_SUP_STRING = " All supported files" # Dictionary with filetypes that we can open # The wildcards point to the appropriate functions. -filetypes_dict = {"Correlator.com (*.SIN)|*.SIN;*.sin" : openSIN, - "ALV (*.ASC)|*.ASC;*.asc" : openASC, - "PyCorrFit (*.csv)|*.csv" : openCSV, - "Matlab 'Ries (*.mat)|*.mat" : openMAT, - "PicoQuant (*.pt3)|*.pt3" : openPT3, - "Zeiss ConfoCor3 (*.fcs)|*.fcs" : openFCS, - "Zip file (*.zip)|*.zip" : openZIP, - "PyCorrFit session (*.pcfs)|*.pcfs" : openZIP +filetypes_dict = {"Correlator.com (*.SIN)|*.SIN;*.sin": openSIN, + "ALV (*.ASC)|*.ASC;*.asc": openASC, + "PyCorrFit (*.csv)|*.csv": openCSV, + "Matlab 'Ries (*.mat)|*.mat": openMAT, + "PicoQuant (*.pt3)|*.pt3": openPT3, + "Zeiss ConfoCor3 (*.fcs)|*.fcs": openFCS, + "Zip file (*.zip)|*.zip": openZIP, + "PyCorrFit session (*.pcfs)|*.pcfs": openZIP } # For user comfort, add "All supported files" wildcard: add_all_supported_filetype_entry(filetypes_dict) # Dictionary with filetypes we can open that have intensity traces in them. -filetypes_bg_dict = {"Correlator.com (*.SIN)|*.SIN;*.sin" : openSIN, - "ALV (*.ASC)|*.ASC" : openASC, - "PyCorrFit (*.csv)|*.csv" : openCSV, - "PicoQuant (*.pt3)|*.pt3" : openPT3, - "Zeiss ConfoCor3 (*.fcs)|*.fcs" : openFCS, - "Zip file (*.zip)|*.zip" : openZIP, - "PyCorrFit session (*.pcfs)|*.pcfs" : openZIP +filetypes_bg_dict = {"Correlator.com (*.SIN)|*.SIN;*.sin": openSIN, + "ALV (*.ASC)|*.ASC": openASC, + "PyCorrFit (*.csv)|*.csv": openCSV, + "PicoQuant (*.pt3)|*.pt3": openPT3, + "Zeiss ConfoCor3 (*.fcs)|*.fcs": openFCS, + "Zip file (*.zip)|*.zip": openZIP, + "PyCorrFit session (*.pcfs)|*.pcfs": openZIP } add_all_supported_filetype_entry(filetypes_bg_dict) diff --git a/pycorrfit/readfiles/read_ASC_ALV.py b/pycorrfit/readfiles/read_ASC_ALV.py index aad10e81..462f6eb8 100644 --- a/pycorrfit/readfiles/read_ASC_ALV.py +++ b/pycorrfit/readfiles/read_ASC_ALV.py @@ -115,16 +115,16 @@ def openASC_old(path): Alldata = openfile.readlines() # End of trace EndT = Alldata.__len__() - ## Correlation function + # Correlation function # Find out where the correlation function is for i in np.arange(len(Alldata)): if Alldata[i].startswith('Mode'): mode = Alldata[i][5:].strip(' ":').strip().strip('"') single_strings = ["a-ch0", "a-ch1", "auto ch0", "auto ch1", "fast auto ch0", "fast auto ch1", - ] + ] if (mode.lower().count('single') or - mode.lower().strip() in single_strings): + mode.lower().strip() in single_strings): single = True channel = mode.split(" ")[-1] else: @@ -139,7 +139,7 @@ def openASC_old(path): # This tells us if there is only one curve or if there are # multiple curves with an average. if (Alldata[i].strip().lower() == - '"correlation (multi, averaged)"' ): + '"correlation (multi, averaged)"'): multidata = True else: multidata = False @@ -160,7 +160,7 @@ def openASC_old(path): EndT = i-1 # Get the header Namedata = Alldata[StartC-1: StartC] - ## Define *curvelist* + # Define *curvelist* curvelist = csv.reader(Namedata, delimiter='\t').__next__() if len(curvelist) <= 2: # Then we have just one single correlation curve @@ -172,7 +172,7 @@ def openASC_old(path): curvelist.remove(curvelist[0]) # Last column is empty curvelist.remove(curvelist[-1]) - ## Correlation function + # Correlation function Truedata = Alldata[StartC: EndC] readdata = csv.reader(Truedata, delimiter='\t') # Add lists to *data* according to the length of *curvelist* @@ -181,14 +181,14 @@ def openASC_old(path): for row in readdata: for i in np.arange(len(curvelist)): if len(row) > 0: - data[i].append( (np.float(row[0]), np.float(row[i+1])) ) - ## Trace + data[i].append((np.float(row[0]), np.float(row[i+1]))) + # Trace # Trace is stored in two columns # 1st column: time [s] # 2nd column: trace [kHz] # Get the trace Tracedata = Alldata[StartT: EndT] - timefactor = 1000 # because we want ms instead of s + timefactor = 1000 # because we want ms instead of s readtrace = csv.reader(Tracedata, delimiter='\t') trace = list() trace2 = list() @@ -273,7 +273,7 @@ def openASC_old(path): channel = "CH1" splittrace2 = mysplit(trace2[0], len(curvelist)/2-nav) i = 0 - for t in range(int(len(curvelist)/2),int(len(curvelist))): + for t in range(int(len(curvelist)/2), int(len(curvelist))): typ = curvelist[t] if typ.lower()[:7] == "average": typelist.append("{} average".format(channel)) @@ -300,7 +300,7 @@ def openASC_old(path): typelist.append("{} average".format(channel)) corrlist.append(np.array(data[t])) tracelist.append([np.array(trace[0]), - np.array(trace2[0]) ]) + np.array(trace2[0])]) else: typelist.append("{} {}".format(accc, channel)) corrlist.append(np.array(data[t])) @@ -309,14 +309,14 @@ def openASC_old(path): # CHANNEL 1 channel = "CC10" i = 0 - for t in range(int(len(curvelist)/2),int(len(curvelist))): + for t in range(int(len(curvelist)/2), int(len(curvelist))): typ = curvelist[t] if typ.lower()[:7] == "average": typelist.append("{} average".format(channel)) corrlist.append(np.array(data[t])) # order must be the same as above tracelist.append([np.array(trace[0]), - np.array(trace2[0]) ]) + np.array(trace2[0])]) else: typelist.append("{} {}".format(accc, channel)) corrlist.append(np.array(data[t])) @@ -388,7 +388,7 @@ def openASC_ALV_7004(path): # trace array: " " allcorr = [] alltrac = [] - i=0 + i = 0 intrace = False mode = False for item in Alldata: @@ -401,41 +401,41 @@ def openASC_ALV_7004(path): if item.count("\t") == 4: if intrace: it = item.split("\t") - it = [ float(t.strip()) for t in it ] + it = [float(t.strip()) for t in it] alltrac.append(it) else: ic = item.split("\t") - ic = [ float(c.strip()) for c in ic ] + ic = [float(c.strip()) for c in ic] allcorr.append(ic) allcorr = np.array(allcorr) alltrac = np.array(alltrac) - tau = allcorr[:,0] - time = alltrac[:,0] * 1000 + tau = allcorr[:, 0] + time = alltrac[:, 0] * 1000 lenc = allcorr.shape[0] lent = alltrac.shape[0] # Traces trace1 = np.zeros((lent, 2), dtype=np.float_) - trace1[:,0] = time - trace1[:,1] = alltrac[:,1] + trace1[:, 0] = time + trace1[:, 1] = alltrac[:, 1] trace2 = trace1.copy() - trace2[:,1] = alltrac[:,2] + trace2[:, 1] = alltrac[:, 2] trace3 = trace1.copy() - trace3[:,1] = alltrac[:,3] + trace3[:, 1] = alltrac[:, 3] trace4 = trace1.copy() - trace4[:,1] = alltrac[:,4] + trace4[:, 1] = alltrac[:, 4] # Correlations corr1 = np.zeros((lenc, 2), dtype=np.float_) - corr1[:,0] = tau - corr1[:,1] = allcorr[:,1] + corr1[:, 0] = tau + corr1[:, 1] = allcorr[:, 1] corr2 = corr1.copy() - corr2[:,1] = allcorr[:,2] + corr2[:, 1] = allcorr[:, 2] corr3 = corr1.copy() - corr3[:,1] = allcorr[:,3] + corr3[:, 1] = allcorr[:, 3] corr4 = corr1.copy() - corr4[:,1] = allcorr[:,4] + corr4[:, 1] = allcorr[:, 4] typelist = [] corrlist = [] @@ -450,69 +450,69 @@ def openASC_ALV_7004(path): if not (np.allclose(trace1, trace3, rtol=.01) and np.allclose(trace2, trace4, rtol=.01)): raise LoadALVError("Unexpected data format: {}".format(path)) - if not np.allclose(corr1[:,1], 0): + if not np.allclose(corr1[:, 1], 0): corrlist.append(corr1) filelist.append(filename) tracelist.append(trace1) typelist.append("AC1") - if not np.allclose(corr2[:,1], 0): + if not np.allclose(corr2[:, 1], 0): corrlist.append(corr2) filelist.append(filename) tracelist.append(trace2) typelist.append("AC2") - if not np.allclose(corr3[:,1], 0): + if not np.allclose(corr3[:, 1], 0): corrlist.append(corr3) filelist.append(filename) tracelist.append([trace1, trace2]) typelist.append("CC12") - if not np.allclose(corr4[:,1], 0): + if not np.allclose(corr4[:, 1], 0): corrlist.append(corr4) filelist.append(filename) tracelist.append([trace1, trace2]) typelist.append("CC21") elif mode in ["a-ch0", "a-ch0 a-"]: - if not (np.allclose(trace2[:,1], 0) and - np.allclose(trace3[:,1], 0) and - np.allclose(trace4[:,1], 0) and - np.allclose(corr2[:,1], 0) and - np.allclose(corr3[:,1], 0) and - np.allclose(corr4[:,1], 0)): + if not (np.allclose(trace2[:, 1], 0) and + np.allclose(trace3[:, 1], 0) and + np.allclose(trace4[:, 1], 0) and + np.allclose(corr2[:, 1], 0) and + np.allclose(corr3[:, 1], 0) and + np.allclose(corr4[:, 1], 0)): raise LoadALVError("Unexpected data format: {}".format(path)) corrlist.append(corr1) filelist.append(filename) tracelist.append(trace1) typelist.append("AC") elif mode in ["a-ch1", "a-ch1 a-"]: - if not (np.allclose(trace1[:,1], 0) and - np.allclose(trace3[:,1], 0) and - np.allclose(trace4[:,1], 0) and - np.allclose(corr1[:,1], 0) and - np.allclose(corr3[:,1], 0) and - np.allclose(corr4[:,1], 0)): + if not (np.allclose(trace1[:, 1], 0) and + np.allclose(trace3[:, 1], 0) and + np.allclose(trace4[:, 1], 0) and + np.allclose(corr1[:, 1], 0) and + np.allclose(corr3[:, 1], 0) and + np.allclose(corr4[:, 1], 0)): raise LoadALVError("Unexpected data format: {}".format(path)) corrlist.append(corr2) filelist.append(filename) tracelist.append(trace2) typelist.append("AC") elif mode in ["a-ch2", "a- a-ch2"]: - if not (np.allclose(trace1[:,1], 0) and - np.allclose(trace2[:,1], 0) and - np.allclose(trace4[:,1], 0) and - np.allclose(corr1[:,1], 0) and - np.allclose(corr2[:,1], 0) and - np.allclose(corr4[:,1], 0)): + if not (np.allclose(trace1[:, 1], 0) and + np.allclose(trace2[:, 1], 0) and + np.allclose(trace4[:, 1], 0) and + np.allclose(corr1[:, 1], 0) and + np.allclose(corr2[:, 1], 0) and + np.allclose(corr4[:, 1], 0)): raise LoadALVError("Unexpected data format: {}".format(path)) corrlist.append(corr3) filelist.append(filename) tracelist.append(trace3) typelist.append("AC") elif mode in ["a-ch3", "a- a-ch3"]: - if not (np.allclose(trace1[:,1], 0) and - np.allclose(trace2[:,1], 0) and - np.allclose(trace3[:,1], 0) and - np.allclose(corr1[:,1], 0) and - np.allclose(corr2[:,1], 0) and - np.allclose(corr3[:,1], 0)): + if not (np.allclose(trace1[:, 1], 0) and + np.allclose(trace2[:, 1], 0) and + np.allclose(trace3[:, 1], 0) and + np.allclose(corr1[:, 1], 0) and + np.allclose(corr2[:, 1], 0) and + np.allclose(corr3[:, 1], 0)): raise LoadALVError("Unexpected data format: {}".format(path)) corrlist.append(corr4) filelist.append(filename) @@ -543,24 +543,23 @@ def mysplit(a, n): lensplit = np.int(np.ceil(N/n)) # xp is actually rounded -> recalculate - xp = np.linspace(a[:,0][0], a[:,0][-1], N, endpoint=True) + xp = np.linspace(a[:, 0][0], a[:, 0][-1], N, endpoint=True) # let xp start at zero - xp -= a[:,0][0] - yp = a[:,1] + xp -= a[:, 0][0] + yp = a[:, 1] # time frame for each new curve #dx = xp[-1]/n # perform interpolation of new trace x, newstep = np.linspace(0, xp[-1], lensplit*n, - endpoint=True, retstep=True) + endpoint=True, retstep=True) # interpolating reduces the variance and possibly changes the avg - y = np.interp(x,xp,yp) + y = np.interp(x, xp, yp) - data = np.zeros((lensplit*n,2)) - data[:,0] = x + newstep + data = np.zeros((lensplit*n, 2)) + data[:, 0] = x + newstep # make sure that the average stays the same: - data[:,1] = y - np.average(y) + np.average(yp) - return np.split(data,n) - + data[:, 1] = y - np.average(y) + np.average(yp) + return np.split(data, n) diff --git a/pycorrfit/readfiles/read_CSV_PyCorrFit.py b/pycorrfit/readfiles/read_CSV_PyCorrFit.py index 5563cde1..4b486cbc 100644 --- a/pycorrfit/readfiles/read_CSV_PyCorrFit.py +++ b/pycorrfit/readfiles/read_CSV_PyCorrFit.py @@ -77,7 +77,7 @@ def openCSV(path, filename=None): return None # Define what will happen to the file - timefactor = 1000 # because we want ms instead of s + timefactor = 1000 # because we want ms instead of s csvfile = path.open('r', encoding='utf-8') readdata = csv.reader(csvfile, delimiter=',') data = list() @@ -85,7 +85,7 @@ def openCSV(path, filename=None): weightname = "external" trace = None traceA = None - DataType="AC" # May be changed + DataType = "AC" # May be changed numtraces = 0 prev_row = None for row in readdata: @@ -99,15 +99,15 @@ def openCSV(path, filename=None): corrtype = str(row[0])[12:].strip().strip(":").strip() if corrtype[:17].lower() == "cross-correlation": # We will later try to import a second trace - DataType="CC" + DataType = "CC" DataType += corrtype[17:].strip() elif corrtype[0:15].lower() == "autocorrelation": - DataType="AC" + DataType = "AC" DataType += corrtype[15:].strip() elif str(row[0])[0:13].upper() == '# BEGIN TRACE': # Correlation is over. We have a trace corr = np.array(data) - data=list() + data = list() numtraces = 1 elif str(row[0])[0:20].upper() == '# BEGIN SECOND TRACE': # First trace is over. We have a second trace @@ -119,8 +119,8 @@ def openCSV(path, filename=None): # Read the 1st section # On Windows we had problems importing nan values that # had some white-spaces around them. Therefore: strip() - ## As of version 0.7.8 we are supporting white space - ## separated values as well + # As of version 0.7.8 we are supporting white space + # separated values as well if len(row) == 1: row = row[0].split() data.append((np.float(row[0].strip())*timefactor, @@ -130,7 +130,9 @@ def openCSV(path, filename=None): weights.append(np.float(row[4].strip())) if weightname == "external": try: - weightname = "ext. "+prev_row[0].split("Weights")[1].split("[")[1].split("]")[0] + weightname = "ext. " + \ + prev_row[0].split("Weights")[1].split( + "[")[1].split("]")[0] except: pass prev_row = row @@ -141,7 +143,7 @@ def openCSV(path, filename=None): elif numtraces >= 1: trace = rest del data - ## Remove any NaN numbers from thearray + # Remove any NaN numbers from thearray # Explanation: # np.isnan(data) # finds the position of NaNs in the array (True positions); 2D array, bool @@ -154,7 +156,7 @@ def openCSV(path, filename=None): # Also check for infinities. corr = corr[~np.isinf(corr).any(1)] csvfile.close() - Traces=list() + Traces = list() # Set correct trace data for import if numtraces == 1 and DataType[:2] == "AC": Traces.append(trace) @@ -171,6 +173,6 @@ def openCSV(path, filename=None): dictionary["Type"] = [DataType] dictionary["Filename"] = [filename] if len(weights) != 0: - dictionary["Weight"] = [ np.array(weights)] + dictionary["Weight"] = [np.array(weights)] dictionary["Weight Name"] = [weightname] return dictionary diff --git a/pycorrfit/readfiles/read_FCS_Confocor3.py b/pycorrfit/readfiles/read_FCS_Confocor3.py index bd8b41e2..c8b2c281 100644 --- a/pycorrfit/readfiles/read_FCS_Confocor3.py +++ b/pycorrfit/readfiles/read_FCS_Confocor3.py @@ -48,7 +48,7 @@ def openFCS_Multiple(path): files created from the newer ZEN Software. """ filename = path.name - ### TODO: + # TODO: # match curves with their timestamp # (actimelist and cctimelist) # @@ -96,14 +96,14 @@ def openFCS_Multiple(path): aclist.append(FoundType) else: for ch2num in np.arange(4)+1: - if FCStype == "Cross-correlation detector "+\ - str(chnum)+" versus detector "+\ + if FCStype == "Cross-correlation detector " +\ + str(chnum)+" versus detector " +\ str(ch2num): FoundType = "CC"+str(chnum)+str(ch2num) cclist.append(FoundType) - elif FCStype == "Cross-correlation detector Meta"+\ - str(chnum)+" versus detector Meta"+\ - str(ch2num): + elif FCStype == "Cross-correlation detector Meta" +\ + str(chnum)+" versus detector Meta" +\ + str(ch2num): FoundType = "CC"+str(chnum)+str(ch2num) cclist.append(FoundType) if FoundType is False: @@ -121,9 +121,9 @@ def openFCS_Multiple(path): # traces in those files are usually very large. We will bin # the trace and import a lighter version of it. tracelength = \ - int(Alldata[i].partition("=")[2].strip().partition(" ")[0]) + int(Alldata[i].partition("=")[2].strip().partition(" ")[0]) if tracelength != 0: - tracedata = Alldata[i+1 : i+tracelength+1] + tracedata = Alldata[i+1: i+tracelength+1] # Jump foward in the index i = i + tracelength readtrace = csv.reader(tracedata, delimiter='\t') @@ -132,8 +132,8 @@ def openFCS_Multiple(path): for row in readtrace: # tau in ms, trace in kHz # So we need to put some factors here - trace.append( (np.float(row[3])*1000, - np.float(row[4])/1000) ) + trace.append((np.float(row[3])*1000, + np.float(row[4])/1000)) trace = np.array(trace) # If the trace is too big. Wee need to bin it. newtrace = util.downsample_trace(trace) @@ -141,27 +141,27 @@ def openFCS_Multiple(path): traces.append(newtrace) if FoundType[:2] != "AC": # For every trace there is an entry in aclist - print("Trace data saved in CC section."+ \ + print("Trace data saved in CC section." + "I cannot handle that.") gottrace = True if Alldata[i].partition("=")[0].strip() == "CorrelationArraySize": # Get the correlation information corrlength = int(Alldata[i].partition("=")[2].strip()) - if corrlength !=0: + if corrlength != 0: # For cross correlation or something sometimes # there is no trace information. - if gottrace == False and FoundType[:2] =="AC": + if gottrace == False and FoundType[:2] == "AC": # We think we know that there is no trace in CC curves traces.append(None) - corrdata = Alldata[i + 2 : i + corrlength + 2] + corrdata = Alldata[i + 2: i + corrlength + 2] # Jump foward i = i + corrlength readcorr = csv.reader(corrdata, delimiter='\t') corr = list() for row in readcorr: # tau in ms, corr-function - corr.append( (np.float(row[3])*1000, - np.float(row[4])-1) ) + corr.append((np.float(row[3])*1000, + np.float(row[4])-1)) if FoundType[:2] == "AC": ac_correlations.append(np.array(corr)) elif FoundType[:2] == "CC": @@ -203,7 +203,7 @@ def openFCS_Multiple(path): # These "None" type items should be at the end of these lists. # If the user created .fcs files with averages between the curves, # the *traces* contains *None* values at those positions. - ## We now create: + # We now create: # curvelist: All actually used data # tracelist: Traces brought into right form (also for CCs) # corrlist: Correlation curves @@ -233,7 +233,8 @@ def openFCS_Multiple(path): corrlist.append(ac_correlations[actids[0]]) else: if traces[actids[0]] is not None: - warnings.warn("File {} curve {} does not contain AC data.".format(filename, tid)) + warnings.warn( + "File {} curve {} does not contain AC data.".format(filename, tid)) elif len(actids) == 2: # Get AC data if aclist[actids[0]] == "AC1": @@ -247,16 +248,17 @@ def openFCS_Multiple(path): acdat2 = ac_correlations[actids[0]] trace2 = traces[actids[0]] else: - warnings.warn("File {} curve {}: unknown AC data.".format(filename, tid)) + warnings.warn( + "File {} curve {}: unknown AC data.".format(filename, tid)) continue if acdat1 is not None: - #AC1 + # AC1 curvelist.append("AC1") tracelist.append(trace1) corrlist.append(acdat1) if acdat2 is not None: - #AC2 + # AC2 curvelist.append("AC2") tracelist.append(trace2) corrlist.append(acdat2) @@ -270,17 +272,18 @@ def openFCS_Multiple(path): ccdat12 = cc_correlations[cctids[1]] ccdat21 = cc_correlations[cctids[0]] else: - warnings.warn("File {} curve {}: unknown CC data.".format(filename, tid)) + warnings.warn( + "File {} curve {}: unknown CC data.".format(filename, tid)) continue tracecc = [trace1, trace2] if ccdat12 is not None: - #CC12 + # CC12 curvelist.append("CC12") tracelist.append(tracecc) corrlist.append(ccdat12) if ccdat21 is not None: - #CC21 + # CC21 curvelist.append("CC21") tracelist.append(tracecc) corrlist.append(ccdat21) @@ -318,7 +321,7 @@ def openFCS_Single(path): if Alldata[i].partition("=")[0].strip() == "##DATA TYPE": # Find out what type of correlation curve we have. # Might be interesting to the user. - Type = Alldata[i].partition("=")[2].strip() + Type = Alldata[i].partition("=")[2].strip() if Type == "FCS Correlogram": fcscurve = True tracecurve = False @@ -345,7 +348,7 @@ def openFCS_Single(path): for row in readtrace: # tau in ms, trace in kHz # So we need to put some factors here - trace.append( (np.float(row[0])*1000, np.float(row[1])) ) + trace.append((np.float(row[0])*1000, np.float(row[1]))) trace = np.array(trace) # If the trace is too big. Wee need to bin it. newtrace = util.downsample_trace(trace) @@ -355,7 +358,7 @@ def openFCS_Single(path): # Get the correlation information corrlength = int(Alldata[i].partition("=")[2].strip()) i = i + 2 - if corrlength !=0: + if corrlength != 0: corrdata = Alldata.__getslice__(i, i+corrlength) # Jump foward i = i + corrlength @@ -363,7 +366,7 @@ def openFCS_Single(path): corr = list() for row in readcorr: # tau in ms, corr-function - corr.append( (np.float(row[0]), np.float(row[1])-1) ) + corr.append((np.float(row[0]), np.float(row[1])-1)) corr = np.array(corr) fcscurve = False diff --git a/pycorrfit/readfiles/read_SIN_correlator_com.py b/pycorrfit/readfiles/read_SIN_correlator_com.py index 1bc0d45b..c91cdfa6 100644 --- a/pycorrfit/readfiles/read_SIN_correlator_com.py +++ b/pycorrfit/readfiles/read_SIN_correlator_com.py @@ -26,7 +26,7 @@ def openSIN(path, filename=None): if line.lower().startswith("mode"): mode = line.split("=")[1].strip().split() # Find out what kind of mode it is - + # The rationale is that when the mode # consists of single characters separated # by empty spaces, then we have integer mode. @@ -38,17 +38,17 @@ def openSIN(path, filename=None): def openSIN_integer_mode(path): """Integer mode file format of e.g. flex03lq-1 correlator (correlator.com) - + This is a file format where the type (AC/CC) of the curve is determined using integers in the "Mode=" line, e.g. - + Mode= 2 3 3 2 0 1 1 0 - + which means the first correlation is CC23, the second CC32, the third CC01, and the fourth CC10. Similarly, - + Mode= 1 1 2 2 0 4 4 4 - + would translate to AC11, AC22, CC04, and AC44. """ with path.open() as fd: @@ -59,16 +59,16 @@ def openSIN_integer_mode(path): line = line.strip() if line.lower().startswith("mode"): mode = line.split("=")[1].strip().split() - mode = [ int(m) for m in mode ] + mode = [int(m) for m in mode] if len(mode) % 2 != 0: msg = "mode must be multiples of two: {}".format(path) raise OpenSINError(msg) - + # build up the lists corr_func = [] intensity = [] section = "" - + # loop through lines for line in data: line = line.strip().lower() @@ -89,49 +89,49 @@ def openSIN_integer_mode(path): corr_func = np.array(corr_func, dtype=float) intensity = np.array(intensity, dtype=float) - timefactor = 1000 # because we want ms instead of s - timedivfac = 1000 # because we want kHz instead of Hz - intensity[:,0] *= timefactor - corr_func[:,0] *= timefactor - intensity[:,1:] /= timedivfac - + timefactor = 1000 # because we want ms instead of s + timedivfac = 1000 # because we want kHz instead of Hz + intensity[:, 0] *= timefactor + corr_func[:, 0] *= timefactor + intensity[:, 1:] /= timedivfac + # correlator.com correlation is normalized to 1, not to 0 - corr_func[:,1:] -= 1 + corr_func[:, 1:] -= 1 # Now sort the information for pycorrfit correlations = [] traces = [] curvelist = [] - + for ii in range(len(mode)//2): modea = mode[2*ii] modeb = mode[2*ii+1] - + if modea == modeb: # curve type AC curvelist.append("AC{}".format(modea)) # trace - atrace = np.zeros((intensity.shape[0],2), dtype=float) - atrace[:,0] = intensity[:, 0] - atrace[:,1] = intensity[:, modea+1] + atrace = np.zeros((intensity.shape[0], 2), dtype=float) + atrace[:, 0] = intensity[:, 0] + atrace[:, 1] = intensity[:, modea+1] traces.append(atrace) else: # curve type CC - curvelist.append("CC{}{}".format(modea,modeb)) + curvelist.append("CC{}{}".format(modea, modeb)) # trace modmin = min(modea, modeb) modmax = max(modea, modeb) - tracea = np.zeros((intensity.shape[0],2), dtype=float) - tracea[:,0] = intensity[:, 0] - tracea[:,1] = intensity[:, modmin+1] - traceb = np.zeros((intensity.shape[0],2), dtype=float) - traceb[:,0] = intensity[:, 0] - traceb[:,1] = intensity[:, modmax+1] + tracea = np.zeros((intensity.shape[0], 2), dtype=float) + tracea[:, 0] = intensity[:, 0] + tracea[:, 1] = intensity[:, modmin+1] + traceb = np.zeros((intensity.shape[0], 2), dtype=float) + traceb[:, 0] = intensity[:, 0] + traceb[:, 1] = intensity[:, modmax+1] traces.append([tracea, traceb]) # correlation - corr = np.zeros((corr_func.shape[0],2), dtype=float) - corr[:,0] = corr_func[:, 0] - corr[:,1] = corr_func[:, ii+1] + corr = np.zeros((corr_func.shape[0], 2), dtype=float) + corr[:, 0] = corr_func[:, 0] + corr[:, 1] = corr_func[:, ii+1] correlations.append(corr) dictionary = {} @@ -147,7 +147,7 @@ def openSIN_integer_mode(path): def openSIN_old(path): """Parses the simple sin file format (correlator.com) - + Read data from a .SIN file, usually created by the software using correlators from correlator.com. @@ -240,7 +240,7 @@ def openSIN_old(path): # Find out where the correlation function and trace are for i in np.arange(len(Alldata)): if Alldata[i][0:4] == "Mode": - + Mode = Alldata[i].split("=")[1].strip() if Alldata[i][0:21] == "[CorrelationFunction]": StartC = i+1 @@ -248,7 +248,7 @@ def openSIN_old(path): EndC = i-2 if Alldata[i][0:18] == "[IntensityHistory]": # plus 2, because theres a line with the trace length - StartT = i+2 + StartT = i+2 if Alldata[i][0:11] == "[Histogram]": EndT = i-2 curvelist = [] @@ -256,17 +256,17 @@ def openSIN_old(path): traces = [] # Get the correlation function Truedata = Alldata[StartC:EndC] - timefactor = 1000 # because we want ms instead of s + timefactor = 1000 # because we want ms instead of s readcorr = csv.reader(Truedata, delimiter='\t') # Trace # Trace is stored in three columns # 1st column: time [s] - # 2nd column: trace [Hz] + # 2nd column: trace [Hz] # 3rd column: trace [Hz] - Single Auto: equivalent to 2nd # Get the trace Tracedata = Alldata[StartT:EndT] # timefactor = 1000 # because we want ms instead of s - timedivfac = 1000 # because we want kHz instead of Hz + timedivfac = 1000 # because we want kHz instead of Hz readtrace = csv.reader(Tracedata, delimiter='\t') # Process all Data: if Mode == "Single Auto": @@ -280,7 +280,7 @@ def openSIN_old(path): for row in readtrace: # tau in ms, corr-function minus "1" trace.append((np.float(row[0])*timefactor, - np.float(row[1])/timedivfac)) + np.float(row[1])/timedivfac)) traces.append(np.array(trace)) elif Mode == "Single Cross": curvelist.append("CC") @@ -353,8 +353,10 @@ def openSIN_old(path): # tau in ms, corr-function minus "1" corrdata1.append((np.float(row[0])*timefactor, np.float(row[1])-1)) corrdata2.append((np.float(row[0])*timefactor, np.float(row[2])-1)) - corrdata12.append((np.float(row[0])*timefactor, np.float(row[3])-1)) - corrdata21.append((np.float(row[0])*timefactor, np.float(row[4])-1)) + corrdata12.append( + (np.float(row[0])*timefactor, np.float(row[3])-1)) + corrdata21.append( + (np.float(row[0])*timefactor, np.float(row[4])-1)) correlations.append(np.array(corrdata1)) correlations.append(np.array(corrdata2)) correlations.append(np.array(corrdata12)) @@ -373,9 +375,9 @@ def openSIN_old(path): traces.append([np.array(trace1), np.array(trace2)]) else: raise NotImplemented( - "'Mode' type '{}' in {} not supported by this method!". - Mode, format(path)) - + "'Mode' type '{}' in {} not supported by this method!". + Mode, format(path)) + dictionary = {} dictionary["Correlation"] = correlations dictionary["Trace"] = traces diff --git a/pycorrfit/readfiles/read_mat_ries.py b/pycorrfit/readfiles/read_mat_ries.py index 6e258bd2..b69457e0 100644 --- a/pycorrfit/readfiles/read_mat_ries.py +++ b/pycorrfit/readfiles/read_mat_ries.py @@ -68,10 +68,10 @@ def openMAT(path, filename=None): # Another workaround # Sometimes, there's just one curve, which # means that corr[0] has no length. - if len( np.atleast_1d(corr[0]) ) == 1: + if len(np.atleast_1d(corr[0])) == 1: final = np.zeros((len(corr), 2)) - final[:,0] = times - final[:,1] = corr + final[:, 0] = times + final[:, 1] = corr correlations.append(final) curvelist.append("AC"+str(i+1)) try: @@ -81,18 +81,17 @@ def openMAT(path, filename=None): # No trace traces.append(None) else: - trace = np.zeros((2,2)) - trace[1,0] = 1.0 - trace[:,1] = traceavg + trace = np.zeros((2, 2)) + trace[1, 0] = 1.0 + trace[:, 1] = traceavg traces.append(trace) - elif len(corr) == len(times): for j in np.arange(len(corr[0])): final = np.zeros((len(corr), 2)) - final[:,0] = times - final[:,1] = corr[:,j] + final[:, 0] = times + final[:, 1] = corr[:, j] correlations.append(final) curvelist.append("AC"+str(i+1)) try: @@ -102,9 +101,9 @@ def openMAT(path, filename=None): # No trace traces.append(None) else: - trace = np.zeros((2,2)) - trace[1,0] = 1.0 - trace[:,1] = traceavg + trace = np.zeros((2, 2)) + trace[1, 0] = 1.0 + trace[:, 1] = traceavg traces.append(trace) # Get dc "dual color" functions try: @@ -123,8 +122,8 @@ def openMAT(path, filename=None): for j in np.arange(len(corr[0])): final = np.zeros((len(corr), 2)) - final[:,0] = times - final[:,1] = corr[:,j] + final[:, 0] = times + final[:, 1] = corr[:, j] correlations.append(final) curvelist.append("CC dual color "+str(i+1)) traces.append(None) @@ -145,8 +144,8 @@ def openMAT(path, filename=None): for j in np.arange(len(corr[0])): final = np.zeros((len(corr), 2)) - final[:,0] = times - final[:,1] = corr[:,j] + final[:, 0] = times + final[:, 1] = corr[:, j] correlations.append(final) curvelist.append("CC two foci "+str(i+1)) traces.append(None) @@ -167,8 +166,8 @@ def openMAT(path, filename=None): for j in np.arange(len(corr[0])): final = np.zeros((len(corr), 2)) - final[:,0] = times - final[:,1] = corr[:,j] + final[:, 0] = times + final[:, 1] = corr[:, j] correlations.append(final) curvelist.append("CC dual color two foci "+str(i+1)) traces.append(None) @@ -202,7 +201,8 @@ def _check_keys(adict): for key in adict: if isinstance(adict[key], mat_struct): adict[key] = _todict(adict[key]) - return adict + return adict + def _todict(matobj): ''' diff --git a/pycorrfit/readfiles/read_pt3_PicoQuant.py b/pycorrfit/readfiles/read_pt3_PicoQuant.py index a3beb672..31d95f46 100644 --- a/pycorrfit/readfiles/read_pt3_PicoQuant.py +++ b/pycorrfit/readfiles/read_pt3_PicoQuant.py @@ -14,24 +14,26 @@ class ParameterClass(): """Stores parameters for correlation """ + def __init__(self): - #Where the data is stored. + # Where the data is stored. self.data = [] - self.objectRef =[] - self.subObjectRef =[] - self.colors = ['blue','green','red','cyan','magenta','yellow','black'] + self.objectRef = [] + self.subObjectRef = [] + self.colors = ['blue', 'green', 'red', + 'cyan', 'magenta', 'yellow', 'black'] self.numOfLoaded = 0 self.NcascStart = 0 self.NcascEnd = 25 self.Nsub = 6 self.winInt = 10 self.photonCountBin = 25 - + def getTrace(picoObject, number): """ Extracts trace `number` from a `picoObject`. - + Parameters ---------- picoObject: instance of picoObject @@ -39,7 +41,7 @@ def getTrace(picoObject, number): number: The id of the trace, can be 1 or 2. """ - + attrint = "timeSeries{}".format(number) attrtime = "timeSeriesScale{}".format(number) @@ -49,21 +51,20 @@ def getTrace(picoObject, number): time = np.array(getattr(picoObject, attrtime)) # time delta deltat = np.abs(time[2]-time[1]) - - trace = np.zeros((intensity.shape[0],2)) - trace[:,0] = time # ms - trace[:,1] = intensity / deltat # kHz - + + trace = np.zeros((intensity.shape[0], 2)) + trace[:, 0] = time # ms + trace[:, 1] = intensity / deltat # kHz + # If the trace is too big. Wee need to bin it. newtrace = util.downsample_trace(trace) - + return newtrace - def openPT3(path, filename=None): """ Retreive correlation curves from PicoQuant data files - + This function is a wrapper around the PicoQuant capability of FCS_Viewer by Dominic Waithe. """ @@ -74,7 +75,7 @@ def openPT3(path, filename=None): filename = path.name par_obj = ParameterClass() - + pt3file = picoObject(str(path), par_obj, None) po = pt3file @@ -87,43 +88,42 @@ def openPT3(path, filename=None): typelist = list() tracelist = list() # Some data points are zero for some reason - id1 = np.where(autotime!=0) - + id1 = np.where(autotime != 0) # AC0 - autocorrelation CH0 - corrac0 = auto[:,0,0] + corrac0 = auto[:, 0, 0] if np.sum(np.abs(corrac0[id1])) != 0: typelist.append("AC0") # autotime,auto[:,0,0] - corrlist.append(np.hstack( (autotime[id1].reshape(-1,1), - corrac0[id1].reshape(-1,1)) )) + corrlist.append(np.hstack((autotime[id1].reshape(-1, 1), + corrac0[id1].reshape(-1, 1)))) tracelist.append([getTrace(po, 1)]) - + # AC1 - autocorrelation CH1 - corrac1 = auto[:,1,1] + corrac1 = auto[:, 1, 1] if np.sum(np.abs(corrac1[id1])) != 0: typelist.append("AC1") # autotime,auto[:,1,1] - corrlist.append(np.hstack( (autotime[id1].reshape(-1,1), - corrac1[id1].reshape(-1,1)) )) + corrlist.append(np.hstack((autotime[id1].reshape(-1, 1), + corrac1[id1].reshape(-1, 1)))) tracelist.append([getTrace(po, 2)]) - + # CC01 - Cross-Correlation CH0-CH1 - corrcc01 = auto[:,0,1] + corrcc01 = auto[:, 0, 1] if np.sum(np.abs(corrcc01[id1])) != 0: typelist.append("CC01") # autotime,auto[:,0,1] - corrlist.append(np.hstack( (autotime[id1].reshape(-1,1), - corrcc01[id1].reshape(-1,1)) )) + corrlist.append(np.hstack((autotime[id1].reshape(-1, 1), + corrcc01[id1].reshape(-1, 1)))) tracelist.append([getTrace(po, 1), getTrace(po, 2)]) - + # CC10 - Cross-Correlation CH1-CH0 - corrcc10 = auto[:,1,0] + corrcc10 = auto[:, 1, 0] if np.sum(np.abs(corrcc10[id1])) != 0: typelist.append("CC10") # autotime,auto[:,1,0] - corrlist.append(np.hstack( (autotime[id1].reshape(-1,1), - corrcc10[id1].reshape(-1,1)) )) + corrlist.append(np.hstack((autotime[id1].reshape(-1, 1), + corrcc10[id1].reshape(-1, 1)))) tracelist.append([getTrace(po, 1), getTrace(po, 2)]) filelist = [filename] * len(typelist) diff --git a/pycorrfit/readfiles/read_pt3_scripts/__init__.py b/pycorrfit/readfiles/read_pt3_scripts/__init__.py index c1bb8a7d..9986b1dd 100644 --- a/pycorrfit/readfiles/read_pt3_scripts/__init__.py +++ b/pycorrfit/readfiles/read_pt3_scripts/__init__.py @@ -1 +1 @@ -from .__version__ import version \ No newline at end of file +from .__version__ import version diff --git a/pycorrfit/readfiles/read_pt3_scripts/__version__.py b/pycorrfit/readfiles/read_pt3_scripts/__version__.py index f3d21331..c529bd6e 100644 --- a/pycorrfit/readfiles/read_pt3_scripts/__version__.py +++ b/pycorrfit/readfiles/read_pt3_scripts/__version__.py @@ -1,2 +1,2 @@ # This file contains the GitHub hash of the file versions -version = "8399ff7401" \ No newline at end of file +version = "8399ff7401" diff --git a/pycorrfit/readfiles/read_pt3_scripts/correlation_methods.py b/pycorrfit/readfiles/read_pt3_scripts/correlation_methods.py index 92f1967e..3e9754de 100644 --- a/pycorrfit/readfiles/read_pt3_scripts/correlation_methods.py +++ b/pycorrfit/readfiles/read_pt3_scripts/correlation_methods.py @@ -22,7 +22,7 @@ """ -def tttr2xfcs (y,num,NcascStart,NcascEnd, Nsub): +def tttr2xfcs(y, num, NcascStart, NcascEnd, Nsub): """autocorr, autotime = tttr2xfcs(y,num,10,20) Translation into python of: Fast calculation of fluorescence correlation data with asynchronous time-correlated single-photon counting. @@ -30,116 +30,106 @@ def tttr2xfcs (y,num,NcascStart,NcascEnd, Nsub): """ dt = np.max(y)-np.min(y) - y = np.round(y[:],0) + y = np.round(y[:], 0) numshape = num.shape[0] - autotime = np.zeros(((NcascEnd+1)*(Nsub+1),1)); - auto = np.zeros(((NcascEnd+1)*(Nsub+1), num.shape[1], num.shape[1])).astype(np.float64) + autotime = np.zeros(((NcascEnd+1)*(Nsub+1), 1)) + auto = np.zeros( + ((NcascEnd+1)*(Nsub+1), num.shape[1], num.shape[1])).astype(np.float64) shift = float(0) delta = float(1) + for j in range(0, NcascEnd): + # Finds the unique photon times and their indices. The division of 'y' by '2' each cycle makes this more likely. - for j in range(0,NcascEnd): - - #Finds the unique photon times and their indices. The division of 'y' by '2' each cycle makes this more likely. - - y,k1 = np.unique(y,1) + y, k1 = np.unique(y, 1) k1shape = k1.shape[0] - #Sums up the photon times in each bin. - cs =np.cumsum(num,0).T + # Sums up the photon times in each bin. + cs = np.cumsum(num, 0).T - #Prepares difference array so starts with zero. - diffArr1 = np.zeros(( k1shape+1)); - diffArr2 = np.zeros(( k1shape+1)); + # Prepares difference array so starts with zero. + diffArr1 = np.zeros((k1shape+1)) + diffArr2 = np.zeros((k1shape+1)) - #Takes the cumulative sum of the unique photon arrivals - diffArr1[1:] = cs[0,k1].reshape(-1) - diffArr2[1:] = cs[1,k1].reshape(-1) + # Takes the cumulative sum of the unique photon arrivals + diffArr1[1:] = cs[0, k1].reshape(-1) + diffArr2[1:] = cs[1, k1].reshape(-1) #del k1 #del cs - num =np.zeros((k1shape,2)) - + num = np.zeros((k1shape, 2)) - - #Finds the total photons in each bin. and represents as count. - #This is achieved because we have the indices of each unique time photon and cumulative total at each point. - num[:,0] = np.diff(diffArr1) - num[:,1] = np.diff(diffArr2) + # Finds the total photons in each bin. and represents as count. + # This is achieved because we have the indices of each unique time photon and cumulative total at each point. + num[:, 0] = np.diff(diffArr1) + num[:, 1] = np.diff(diffArr2) #diffArr1 = []; #diffArr2 = []; - for k in range(0,Nsub): + for k in range(0, Nsub): shift = shift + delta - lag = np.round(shift/delta,0) - + lag = np.round(shift/delta, 0) - #Allows the script to be sped up. + # Allows the script to be sped up. if j >= NcascStart: - - #Old method + # Old method #i1= np.in1d(y,y+lag,assume_unique=True) #i2= np.in1d(y+lag,y,assume_unique=True) - #New method, cython - i1,i2 = dividAndConquer(y, y+lag,y.shape[0]) + # New method, cython + i1, i2 = dividAndConquer(y, y+lag, y.shape[0]) - #If the weights (num) are one as in the first Ncasc round, then the correlation is equal to np.sum(i1) + # If the weights (num) are one as in the first Ncasc round, then the correlation is equal to np.sum(i1) i1 = np.where(i1.astype(np.bool))[0] i2 = np.where(i2.astype(np.bool))[0] - #Now we want to weight each photon corectly. - #Faster dot product method, faster than converting to matrix. + # Now we want to weight each photon corectly. + # Faster dot product method, faster than converting to matrix. if i1.size and i2.size: - auto[(k+(j)*Nsub),:,:] = np.dot((num[i1,:]).T,num[i2,:])/delta + auto[(k+(j)*Nsub), :, :] = np.dot((num[i1, :]).T, + num[i2, :])/delta - autotime[k+(j)*Nsub] =shift; + autotime[k+(j)*Nsub] = shift - #Equivalent to matlab round when numbers are %.5 + # Equivalent to matlab round when numbers are %.5 y = np.ceil(np.array(0.5*y)) delta = 2*delta for j in range(0, auto.shape[0]): - auto[j,:,:] = auto[j,:,:]*dt/(dt-autotime[j]) + auto[j, :, :] = auto[j, :, :]*dt/(dt-autotime[j]) autotime = autotime/1000000 - - #Removes the trailing zeros. + # Removes the trailing zeros. idauto = np.where(autotime != 0)[0] autotime = autotime[idauto] - auto = auto[idauto,:,:] + auto = auto[idauto, :, :] return auto, autotime def delayTime2bin(dTimeArr, chanArr, chanNum, winInt): decayTime = np.array(dTimeArr) - #This is the point and which each channel is identified. - decayTimeCh =decayTime[chanArr == chanNum] + # This is the point and which each channel is identified. + decayTimeCh = decayTime[chanArr == chanNum] - #Find the first and last entry - firstDecayTime = 0;#np.min(decayTimeCh).astype(np.int32) + # Find the first and last entry + firstDecayTime = 0 # np.min(decayTimeCh).astype(np.int32) tempLastDecayTime = np.max(decayTimeCh).astype(np.int32) - #We floor this as the last bin is always incomplete and so we discard photons. + # We floor this as the last bin is always incomplete and so we discard photons. numBins = np.floor((tempLastDecayTime-firstDecayTime)/winInt) lastDecayTime = numBins*winInt - - bins = np.linspace(firstDecayTime,lastDecayTime, int(numBins)+1) - + bins = np.linspace(firstDecayTime, lastDecayTime, int(numBins)+1) photonsInBin, jnk = np.histogram(decayTimeCh, bins) - #bins are valued as half their span. + # bins are valued as half their span. decayScale = bins[:-1]+(winInt/2) #decayScale = np.arange(0,decayTimeCh.shape[0]) - - - return list(photonsInBin), list(decayScale) diff --git a/pycorrfit/readfiles/read_pt3_scripts/correlation_objects.py b/pycorrfit/readfiles/read_pt3_scripts/correlation_objects.py index f292aa6e..fc15c669 100644 --- a/pycorrfit/readfiles/read_pt3_scripts/correlation_objects.py +++ b/pycorrfit/readfiles/read_pt3_scripts/correlation_objects.py @@ -32,9 +32,9 @@ class picoObject(): # This is the class which holds the .pt3 data and parameters - def __init__(self,filepath, par_obj, fit_obj): + def __init__(self, filepath, par_obj, fit_obj): - #parameter object and fit object. If + # parameter object and fit object. If self.par_obj = par_obj self.fit_obj = fit_obj self.type = 'mainObject' @@ -45,21 +45,20 @@ def __init__(self,filepath, par_obj, fit_obj): self.name = self.nameAndExt[0] self.ext = self.nameAndExt[-1] - self.par_obj.data.append(filepath); + self.par_obj.data.append(filepath) self.par_obj.objectRef.append(self) - #Imports pt3 file format to object. + # Imports pt3 file format to object. self.unqID = self.par_obj.numOfLoaded - #For fitting. + # For fitting. self.objId1 = None self.objId2 = None self.objId3 = None self.objId4 = None - self.processData(); - - self.plotOn = True; + self.processData() + self.plotOn = True def processData(self): @@ -69,136 +68,144 @@ def processData(self): self.winInt = self.par_obj.winInt self.photonCountBin = self.par_obj.photonCountBin - #File import + # File import if self.ext == 'pt3': - self.subChanArr, self.trueTimeArr, self.dTimeArr,self.resolution = pt3import(self.filepath) + self.subChanArr, self.trueTimeArr, self.dTimeArr, self.resolution = pt3import( + self.filepath) if self.ext == 'csv': - self.subChanArr, self.trueTimeArr, self.dTimeArr,self.resolution = csvimport(self.filepath) - #If the file is empty. + self.subChanArr, self.trueTimeArr, self.dTimeArr, self.resolution = csvimport( + self.filepath) + # If the file is empty. if self.subChanArr == None: - #Undoes any preparation of resource. - self.par_obj.data.pop(-1); + # Undoes any preparation of resource. + self.par_obj.data.pop(-1) self.par_obj.objectRef.pop(-1) self.exit = True - self.par_obj.image_status_text.showMessage("Your sample is not in the correct format.") + self.par_obj.image_status_text.showMessage( + "Your sample is not in the correct format.") self.par_obj.fit_obj.app.processEvents() return - - - #Colour assigned to file. + # Colour assigned to file. self.color = self.par_obj.colors[self.unqID % len(self.par_obj.colors)] - #How many channels there are in the files. - self.numOfCH = np.unique(np.array(self.subChanArr)).__len__()-1 #Minus 1 because not interested in channel 15. + # How many channels there are in the files. + # Minus 1 because not interested in channel 15. + self.numOfCH = np.unique(np.array(self.subChanArr)).__len__()-1 - #Finds the numbers which address the channels. + # Finds the numbers which address the channels. self.ch_present = np.unique(np.array(self.subChanArr[0:100])) - #Calculates decay function for both channels. - self.photonDecayCh1,self.decayScale1 = delayTime2bin(np.array(self.dTimeArr),np.array(self.subChanArr),self.ch_present[0],self.winInt) + # Calculates decay function for both channels. + self.photonDecayCh1, self.decayScale1 = delayTime2bin(np.array( + self.dTimeArr), np.array(self.subChanArr), self.ch_present[0], self.winInt) - if self.numOfCH == 2: - self.photonDecayCh2,self.decayScale2 = delayTime2bin(np.array(self.dTimeArr),np.array(self.subChanArr),self.ch_present[1],self.winInt) + if self.numOfCH == 2: + self.photonDecayCh2, self.decayScale2 = delayTime2bin(np.array( + self.dTimeArr), np.array(self.subChanArr), self.ch_present[1], self.winInt) - #Time series of photon counts. For visualisation. - self.timeSeries1,self.timeSeriesScale1 = delayTime2bin(np.array(self.trueTimeArr)/1000000,np.array(self.subChanArr),self.ch_present[0],self.photonCountBin) + # Time series of photon counts. For visualisation. + self.timeSeries1, self.timeSeriesScale1 = delayTime2bin(np.array( + self.trueTimeArr)/1000000, np.array(self.subChanArr), self.ch_present[0], self.photonCountBin) unit = self.timeSeriesScale1[-1]/self.timeSeriesScale1.__len__() - #Converts to counts per + # Converts to counts per self.kcount_CH1 = np.average(self.timeSeries1) - raw_count = np.average(self.timeSeries1) #This is the unnormalised intensity count for int_time duration (the first moment) + # This is the unnormalised intensity count for int_time duration (the first moment) + raw_count = np.average(self.timeSeries1) var_count = np.var(self.timeSeries1) - self.brightnessNandBCH0=(((var_count -raw_count)/(raw_count))/(float(unit))) + self.brightnessNandBCH0 = ( + ((var_count - raw_count)/(raw_count))/(float(unit))) if (var_count-raw_count) == 0: - self.numberNandBCH0 =0 + self.numberNandBCH0 = 0 else: self.numberNandBCH0 = (raw_count**2/(var_count-raw_count)) + if self.numOfCH == 2: - - if self.numOfCH == 2: - - self.timeSeries2,self.timeSeriesScale2 = delayTime2bin(np.array(self.trueTimeArr)/1000000,np.array(self.subChanArr),self.ch_present[1],self.photonCountBin) + self.timeSeries2, self.timeSeriesScale2 = delayTime2bin(np.array( + self.trueTimeArr)/1000000, np.array(self.subChanArr), self.ch_present[1], self.photonCountBin) unit = self.timeSeriesScale2[-1]/self.timeSeriesScale2.__len__() self.kcount_CH2 = np.average(self.timeSeries2) - raw_count = np.average(self.timeSeries2) #This is the unnormalised intensity count for int_time duration (the first moment) + # This is the unnormalised intensity count for int_time duration (the first moment) + raw_count = np.average(self.timeSeries2) var_count = np.var(self.timeSeries2) - self.brightnessNandBCH1= (((var_count -raw_count)/(raw_count))/(float(unit))) + self.brightnessNandBCH1 = ( + ((var_count - raw_count)/(raw_count))/(float(unit))) if (var_count-raw_count) == 0: - self.numberNandBCH1 =0 + self.numberNandBCH1 = 0 else: self.numberNandBCH1 = (raw_count**2/(var_count-raw_count)) - - - #Calculates the Auto and Cross-correlation functions. - self.crossAndAuto(np.array(self.trueTimeArr),np.array(self.subChanArr)) + # Calculates the Auto and Cross-correlation functions. + self.crossAndAuto(np.array(self.trueTimeArr), + np.array(self.subChanArr)) if self.fit_obj != None: - #If fit object provided then creates fit objects. + # If fit object provided then creates fit objects. if self.objId1 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId1 = corrObj.objId self.fit_obj.objIdArr.append(corrObj.objId) self.objId1.param = copy.deepcopy(self.fit_obj.def_param) self.objId1.name = self.name+'_CH0_Auto_Corr' - self.objId1.ch_type = 0 #channel 0 Auto + self.objId1.ch_type = 0 # channel 0 Auto self.objId1.siblings = None self.objId1.prepare_for_fit() self.objId1.kcount = self.kcount_CH1 - self.objId1.autoNorm = np.array(self.autoNorm[:,0,0]).reshape(-1) + self.objId1.autoNorm = np.array(self.autoNorm[:, 0, 0]).reshape(-1) self.objId1.autotime = np.array(self.autotime).reshape(-1) self.objId1.param = copy.deepcopy(self.fit_obj.def_param) - - if self.numOfCH == 2: + if self.numOfCH == 2: if self.objId3 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId3 = corrObj.objId self.objId3.param = copy.deepcopy(self.fit_obj.def_param) self.fit_obj.objIdArr.append(corrObj.objId) self.objId3.name = self.name+'_CH1_Auto_Corr' - self.objId3.ch_type = 1 #channel 1 Auto + self.objId3.ch_type = 1 # channel 1 Auto self.objId3.siblings = None self.objId3.prepare_for_fit() self.objId3.kcount = self.kcount_CH2 - self.objId3.autoNorm = np.array(self.autoNorm[:,1,1]).reshape(-1) + self.objId3.autoNorm = np.array( + self.autoNorm[:, 1, 1]).reshape(-1) self.objId3.autotime = np.array(self.autotime).reshape(-1) self.objId3.param = copy.deepcopy(self.fit_obj.def_param) if self.objId2 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId2 = corrObj.objId self.objId2.param = copy.deepcopy(self.fit_obj.def_param) self.fit_obj.objIdArr.append(corrObj.objId) self.objId2.name = self.name+'_CH01_Cross_Corr' - self.objId2.ch_type = 2 #01cross + self.objId2.ch_type = 2 # 01cross self.objId2.siblings = None self.objId2.prepare_for_fit() - self.objId2.autoNorm = np.array(self.autoNorm[:,0,1]).reshape(-1) + self.objId2.autoNorm = np.array( + self.autoNorm[:, 0, 1]).reshape(-1) self.objId2.autotime = np.array(self.autotime).reshape(-1) self.objId2.param = copy.deepcopy(self.fit_obj.def_param) - if self.objId4 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId4 = corrObj.objId self.objId4.param = copy.deepcopy(self.fit_obj.def_param) self.fit_obj.objIdArr.append(corrObj.objId) self.objId4.name = self.name+'_CH10_Cross_Corr' - self.objId4.ch_type = 3 #10cross + self.objId4.ch_type = 3 # 10cross self.objId4.siblings = None self.objId4.prepare_for_fit() - self.objId4.autoNorm = np.array(self.autoNorm[:,1,0]).reshape(-1) + self.objId4.autoNorm = np.array( + self.autoNorm[:, 1, 0]).reshape(-1) self.objId4.autotime = np.array(self.autotime).reshape(-1) self.objId4.param = copy.deepcopy(self.fit_obj.def_param) @@ -211,59 +218,63 @@ def processData(self): del self.subChanArr del self.trueTimeArr del self.dTimeArr - def crossAndAuto(self,trueTimeArr,subChanArr): - #For each channel we loop through and find only those in the correct time gate. - #We only want photons in channel 1 or two. - y = trueTimeArr[subChanArr < 3] - validPhotons = subChanArr[subChanArr < 3 ] - - #Creates boolean for photon events in either channel. - num = np.zeros((validPhotons.shape[0],2)) - num[:,0] = (np.array([np.array(validPhotons) ==self.ch_present[0]])).astype(np.int32) - if self.numOfCH ==2: - num[:,1] = (np.array([np.array(validPhotons) ==self.ch_present[1]])).astype(np.int32) + def crossAndAuto(self, trueTimeArr, subChanArr): + # For each channel we loop through and find only those in the correct time gate. + # We only want photons in channel 1 or two. + y = trueTimeArr[subChanArr < 3] + validPhotons = subChanArr[subChanArr < 3] + # Creates boolean for photon events in either channel. + num = np.zeros((validPhotons.shape[0], 2)) + num[:, 0] = (np.array([np.array(validPhotons) == + self.ch_present[0]])).astype(np.int32) + if self.numOfCH == 2: + num[:, 1] = (np.array([np.array(validPhotons) == + self.ch_present[1]])).astype(np.int32) - self.count0 = np.sum(num[:,0]) - self.count1 = np.sum(num[:,1]) + self.count0 = np.sum(num[:, 0]) + self.count1 = np.sum(num[:, 1]) t1 = time.time() - auto, self.autotime = tttr2xfcs(y,num,self.NcascStart,self.NcascEnd, self.Nsub) + auto, self.autotime = tttr2xfcs( + y, num, self.NcascStart, self.NcascEnd, self.Nsub) t2 = time.time() - - - #Normalisation of the TCSPC data: + # Normalisation of the TCSPC data: maxY = np.ceil(max(self.trueTimeArr)) self.autoNorm = np.zeros((auto.shape)) - self.autoNorm[:,0,0] = ((auto[:,0,0]*maxY)/(self.count0*self.count0))-1 - - if self.numOfCH == 2: - self.autoNorm[:,1,1] = ((auto[:,1,1]*maxY)/(self.count1*self.count1))-1 - self.autoNorm[:,1,0] = ((auto[:,1,0]*maxY)/(self.count1*self.count0))-1 - self.autoNorm[:,0,1] = ((auto[:,0,1]*maxY)/(self.count0*self.count1))-1 - - - #Normalisaation of the decay functions. - self.photonDecayCh1Min = self.photonDecayCh1-np.min(self.photonDecayCh1) - self.photonDecayCh1Norm = self.photonDecayCh1Min/np.max(self.photonDecayCh1Min) + self.autoNorm[:, 0, 0] = ( + (auto[:, 0, 0]*maxY)/(self.count0*self.count0))-1 + if self.numOfCH == 2: + self.autoNorm[:, 1, 1] = ( + (auto[:, 1, 1]*maxY)/(self.count1*self.count1))-1 + self.autoNorm[:, 1, 0] = ( + (auto[:, 1, 0]*maxY)/(self.count1*self.count0))-1 + self.autoNorm[:, 0, 1] = ( + (auto[:, 0, 1]*maxY)/(self.count0*self.count1))-1 + + # Normalisaation of the decay functions. + self.photonDecayCh1Min = self.photonDecayCh1 - \ + np.min(self.photonDecayCh1) + self.photonDecayCh1Norm = self.photonDecayCh1Min / \ + np.max(self.photonDecayCh1Min) - if self.numOfCH == 2: - self.photonDecayCh2Min = self.photonDecayCh2-np.min(self.photonDecayCh2) - self.photonDecayCh2Norm = self.photonDecayCh2Min/np.max(self.photonDecayCh2Min) + if self.numOfCH == 2: + self.photonDecayCh2Min = self.photonDecayCh2 - \ + np.min(self.photonDecayCh2) + self.photonDecayCh2Norm = self.photonDecayCh2Min / \ + np.max(self.photonDecayCh2Min) return - - class subPicoObject(): - def __init__(self,parentId,xmin,xmax,TGid,par_obj): - #Binning window for decay function + def __init__(self, parentId, xmin, xmax, TGid, par_obj): + # Binning window for decay function self.TGid = TGid - #Parameters for auto-correlation and cross-correlation. + # Parameters for auto-correlation and cross-correlation. self.parentId = parentId self.par_obj = par_obj self.NcascStart = self.parentId.NcascStart @@ -273,7 +284,7 @@ def __init__(self,parentId,xmin,xmax,TGid,par_obj): self.ext = self.parentId.ext self.type = 'subObject' - #Appends the object to the subObject register. + # Appends the object to the subObject register. self.par_obj.subObjectRef.append(self) self.unqID = self.par_obj.subNum self.parentUnqID = self.parentId.unqID @@ -290,180 +301,183 @@ def __init__(self,parentId,xmin,xmax,TGid,par_obj): self.xmax = xmax self.nameAndExt = os.path.basename(self.filepath).split('.') - self.name = 'TG-'+str(self.unqID)+'-xmin_'+str(round(xmin,0))+'-xmax_'+str(round(xmax,0))+'-'+self.nameAndExt[0] + self.name = 'TG-'+str(self.unqID)+'-xmin_'+str(round(xmin, 0)) + \ + '-xmax_'+str(round(xmax, 0))+'-'+self.nameAndExt[0] self.objId1 = None self.objId2 = None self.objId3 = None self.objId4 = None - self.processData(); + self.processData() self.plotOn = True - def processData(self): - self.NcascStart= self.par_obj.NcascStart - self.NcascEnd= self.par_obj.NcascEnd + self.NcascStart = self.par_obj.NcascStart + self.NcascEnd = self.par_obj.NcascEnd self.Nsub = self.par_obj.Nsub self.winInt = self.par_obj.winInt - #self.subChanArr, self.trueTimeArr, self.dTimeArr,self.resolution = pt3import(self.filepath) if self.ext == 'pt3': - self.subChanArr, self.trueTimeArr, self.dTimeArr,self.resolution = pt3import(self.filepath) + self.subChanArr, self.trueTimeArr, self.dTimeArr, self.resolution = pt3import( + self.filepath) if self.ext == 'csv': - self.subChanArr, self.trueTimeArr, self.dTimeArr,self.resolution = csvimport(self.filepath) - #If the file is empty. - #if self.subChanArr == None: - #Undoes any preparation of resource. + self.subChanArr, self.trueTimeArr, self.dTimeArr, self.resolution = csvimport( + self.filepath) + # If the file is empty. + # if self.subChanArr == None: + # Undoes any preparation of resource. # self.par_obj.subObjectRef.pop(-1) - #self.exit = True + #self.exit = True # return - - self.subArrayGeneration(self.xmin,self.xmax) + self.subArrayGeneration(self.xmin, self.xmax) self.dTimeMin = self.parentId.dTimeMin self.dTimeMax = self.parentId.dTimeMax self.subDTimeMin = self.dTimeMin self.subDTimeMax = self.dTimeMax - #Time series of photon counts. For visualisation. - self.timeSeries1,self.timeSeriesScale1 = delayTime2bin(np.array(self.trueTimeArr)/1000000,np.array(self.subChanArr),self.ch_present[0],self.photonCountBin) + # Time series of photon counts. For visualisation. + self.timeSeries1, self.timeSeriesScale1 = delayTime2bin(np.array( + self.trueTimeArr)/1000000, np.array(self.subChanArr), self.ch_present[0], self.photonCountBin) unit = self.timeSeriesScale1[-1]/self.timeSeriesScale1.__len__() self.kcount_CH1 = np.average(self.timeSeries1) - if self.numOfCH == 2: + if self.numOfCH == 2: - self.timeSeries2,self.timeSeriesScale2 = delayTime2bin(np.array(self.trueTimeArr)/1000000,np.array(self.subChanArr),self.ch_present[1],self.photonCountBin) + self.timeSeries2, self.timeSeriesScale2 = delayTime2bin(np.array( + self.trueTimeArr)/1000000, np.array(self.subChanArr), self.ch_present[1], self.photonCountBin) unit = self.timeSeriesScale2[-1]/self.timeSeriesScale2.__len__() self.kcount_CH2 = np.average(self.timeSeries2) - - - #Adds names to the fit function for later fitting. + # Adds names to the fit function for later fitting. if self.objId1 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId1 = corrObj.objId self.fit_obj.objIdArr.append(corrObj.objId) self.objId1.param = copy.deepcopy(self.fit_obj.def_param) self.objId1.name = self.name+'_CH0_Auto_Corr' - self.objId1.ch_type = 0 #channel 0 Auto + self.objId1.ch_type = 0 # channel 0 Auto self.objId1.siblings = None self.objId1.prepare_for_fit() self.objId1.kcount = self.kcount_CH1 - self.objId1.autoNorm = np.array(self.autoNorm[:,0,0]).reshape(-1) + self.objId1.autoNorm = np.array(self.autoNorm[:, 0, 0]).reshape(-1) self.objId1.autotime = np.array(self.autotime).reshape(-1) self.objId1.param = copy.deepcopy(self.fit_obj.def_param) - if self.numOfCH == 2: if self.objId3 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId3 = corrObj.objId self.fit_obj.objIdArr.append(corrObj.objId) self.objId3.param = copy.deepcopy(self.fit_obj.def_param) self.objId3.name = self.name+'_CH1_Auto_Corr' - self.objId3.ch_type = 1 #channel 1 Auto + self.objId3.ch_type = 1 # channel 1 Auto self.objId3.siblings = None self.objId3.prepare_for_fit() self.objId3.kcount = self.kcount_CH2 - self.objId3.autoNorm = np.array(self.autoNorm[:,1,1]).reshape(-1) + self.objId3.autoNorm = np.array(self.autoNorm[:, 1, 1]).reshape(-1) self.objId3.autotime = np.array(self.autotime).reshape(-1) self.objId3.param = copy.deepcopy(self.fit_obj.def_param) if self.objId2 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId2 = corrObj.objId self.objId2.param = copy.deepcopy(self.fit_obj.def_param) self.fit_obj.objIdArr.append(corrObj.objId) self.objId2.name = self.name+'_CH01_Cross_Corr' - self.objId2.ch_type = 2 #channel 01 Cross + self.objId2.ch_type = 2 # channel 01 Cross self.objId2.siblings = None self.objId2.prepare_for_fit() - self.objId2.autoNorm = np.array(self.autoNorm[:,0,1]).reshape(-1) + self.objId2.autoNorm = np.array(self.autoNorm[:, 0, 1]).reshape(-1) self.objId2.autotime = np.array(self.autotime).reshape(-1) self.objId2.param = copy.deepcopy(self.fit_obj.def_param) if self.objId4 == None: - corrObj= corrObject(self.filepath,self.fit_obj); + corrObj = corrObject(self.filepath, self.fit_obj) self.objId4 = corrObj.objId self.objId4.param = copy.deepcopy(self.fit_obj.def_param) self.fit_obj.objIdArr.append(corrObj.objId) self.objId4.name = self.name+'_CH10_Cross_Corr' - self.objId4.ch_type = 3 #channel 10 Cross + self.objId4.ch_type = 3 # channel 10 Cross self.objId4.siblings = None self.objId4.prepare_for_fit() - self.objId4.autoNorm = np.array(self.autoNorm[:,1,0]).reshape(-1) + self.objId4.autoNorm = np.array(self.autoNorm[:, 1, 0]).reshape(-1) self.objId4.autotime = np.array(self.autotime).reshape(-1) - - self.fit_obj.fill_series_list() del self.subChanArr del self.trueTimeArr del self.dTimeArr - - - def subArrayGeneration(self,xmin,xmax): - if(xmax