From 77f4e58ff42c4fc56d3d40d8ce5e4ca471b1acfd Mon Sep 17 00:00:00 2001 From: 8bitsam Date: Tue, 11 Jun 2024 13:59:39 -0400 Subject: [PATCH 1/8] added configs for vscode and any jetbrains IDEs to .gitignore --- .idea/.gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml From 49fbc23672bfaec1d34a0876e6fd48fde0e38a91 Mon Sep 17 00:00:00 2001 From: 8bitsam Date: Tue, 11 Jun 2024 14:00:42 -0400 Subject: [PATCH 2/8] Added relevant IDE config files to .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 7a8f6d5b..3298c515 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,10 @@ lib64 tags errors.err +# IDE configs +.idea +.vscode + # Installer logs pip-log.txt MANIFEST From 64da5cc28edce6a36f4744775c71f2d9bad8144c Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 11:41:00 -0400 Subject: [PATCH 3/8] Add pyproject.toml with black config --- pyproject.toml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 pyproject.toml diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..d7351b5e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +[tool.black] +line-length = 115 +include = '\.pyi?$' +exclude = ''' +/( + \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | \.rst + | \.txt + | _build + | buck-out + | build + | dist + + # The following are specific to Black, you probably don't want those. + | blib2to3 + | tests/data +)/ +''' \ No newline at end of file From 7ee646176877bbdba4d708e7b4b4e964323f2f82 Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 11:43:26 -0400 Subject: [PATCH 4/8] Run black --- diffpy/__init__.py | 1 + diffpy/pdffit2/ipy_ext.py | 22 +- diffpy/pdffit2/output.py | 3 + diffpy/pdffit2/pdffit.py | 213 +++--- diffpy/pdffit2/tests/ExceptionsTest.py | 307 ++++----- diffpy/pdffit2/tests/TestPdfFit.py | 750 ++++++++++----------- diffpy/pdffit2/tests/TestPhaseFractions.py | 105 ++- diffpy/pdffit2/tests/TestShapeFactors.py | 192 +++--- diffpy/pdffit2/tests/__init__.py | 34 +- diffpy/pdffit2/tests/debug.py | 5 +- diffpy/pdffit2/tests/pdffit2testutils.py | 14 +- diffpy/pdffit2/tests/run.py | 5 +- diffpy/pdffit2/tests/rundeps.py | 3 +- diffpy/pdffit2/version.py | 20 +- 14 files changed, 758 insertions(+), 916 deletions(-) diff --git a/diffpy/__init__.py b/diffpy/__init__.py index 1a099c09..f093b937 100644 --- a/diffpy/__init__.py +++ b/diffpy/__init__.py @@ -21,6 +21,7 @@ from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) diff --git a/diffpy/pdffit2/ipy_ext.py b/diffpy/pdffit2/ipy_ext.py index 13b41214..df8bc537 100644 --- a/diffpy/pdffit2/ipy_ext.py +++ b/diffpy/pdffit2/ipy_ext.py @@ -9,9 +9,10 @@ def load_ipython_extension(ipython): from diffpy.pdffit2 import PdfFit + pf = PdfFit() pdf = EasyPDFPlotting(pf) - print(' Type help(pdffit) or help(topic) for information.\n') + print(" Type help(pdffit) or help(topic) for information.\n") ns = dict(pdffit=PdfFit, pdf=pdf) pf._exportAll(ns) ipython.user_ns.update(ns) @@ -19,8 +20,7 @@ def load_ipython_extension(ipython): class EasyPDFPlotting(object): - """Convenience functions for accessing and plotting PDFfit2 data. - """ + """Convenience functions for accessing and plotting PDFfit2 data.""" def __init__(self, pdffit_instance): self._pdffit = pdffit_instance @@ -55,6 +55,7 @@ def showfit(self, offset=None): """ from matplotlib.pyplot import gca from math import floor + cr = self.r cGobs = self.Gobs cGcalc = self.Gcalc @@ -62,29 +63,32 @@ def showfit(self, offset=None): if offset is None: offset = floor(min([min(cGobs), min(cGcalc)]) - max(cGdiff)) ax = gca() - ax.plot(cr, cGobs, 'r.', cr, cGcalc, 'b-', cr, cGdiff + offset, 'g-') + ax.plot(cr, cGobs, "r.", cr, cGcalc, "b-", cr, cGdiff + offset, "g-") xl = ax.xaxis.get_label().get_text() yl = ax.yaxis.get_label().get_text() if xl == "": - ax.set_xlabel('r (A)') + ax.set_xlabel("r (A)") if yl == "": - ax.set_ylabel('G (A**-2)') + ax.set_ylabel("G (A**-2)") return def showRw(self): "Plot cumulative Rw." from matplotlib.pyplot import gca + cRw = self._asarray(self._pdffit.getcrw()) ax = gca() ax.plot(self.r, cRw) - ax.set_title('Cumulative Rw = %.4f' % cRw[-1]) - ax.set_xlabel('r') - ax.set_ylabel('Rw') + ax.set_title("Cumulative Rw = %.4f" % cRw[-1]) + ax.set_xlabel("r") + ax.set_ylabel("Rw") return @staticmethod def _asarray(x, dtype=None): import numpy + return numpy.asarray(x, dtype=dtype) + # End of class EasyPDFPlotting diff --git a/diffpy/pdffit2/output.py b/diffpy/pdffit2/output.py index 71bcfe76..6d1247cf 100644 --- a/diffpy/pdffit2/output.py +++ b/diffpy/pdffit2/output.py @@ -21,6 +21,7 @@ # create module variable stdout from sys import stdout as stdout + # silence pyflakes checker assert stdout @@ -30,9 +31,11 @@ def redirect_stdout(dst): The dst value is stored in module variable stdout. """ from diffpy.pdffit2.pdffit2 import redirect_stdout + redirect_stdout(dst) global stdout stdout = dst return + # End of file diff --git a/diffpy/pdffit2/pdffit.py b/diffpy/pdffit2/pdffit.py index a3bc2d17..e39b6694 100644 --- a/diffpy/pdffit2/pdffit.py +++ b/diffpy/pdffit2/pdffit.py @@ -31,6 +31,7 @@ # helper routines + def _format_value_std(value, stdev): """Convert value to a string with standard deviation in brackets. @@ -39,9 +40,9 @@ def _format_value_std(value, stdev): Return string. """ - if stdev > abs(value)*1e-8: + if stdev > abs(value) * 1e-8: s = "%g (%g)" % (value, stdev) - elif str(stdev) == 'nan': + elif str(stdev) == "nan": s = "%g (NaN)" % value else: s = "%g" % value @@ -63,7 +64,7 @@ def _format_bond_length(dij, ddij, ij1, symij): s0 = "%s (#%i)" % (symij[0], ij1[0]) s1 = "%s (#%i)" % (symij[1], ij1[1]) leader0 = " " + s0.ljust(w_smbidx) + " - " + s1 + " " - leader1 = leader0.ljust(w_equals) + '= ' + leader1 = leader0.ljust(w_equals) + "= " s = leader1 + _format_value_std(dij, ddij) + " A" return s @@ -111,14 +112,14 @@ class PdfFit(object): # constants and enumerators from pdffit.h: # selection of all atoms - selalias = { 'ALL' : -1 } + selalias = {"ALL": -1} # constraint type identifiers - FCON = { 'USER' : 0, 'IDENT' : 1, 'FCOMP' : 2, 'FSQR' : 3 } + FCON = {"USER": 0, "IDENT": 1, "FCOMP": 2, "FSQR": 3} # scattering type identifiers - Sctp = { 'X' : 0, 'N' : 1 } + Sctp = {"X": 0, "N": 1} def _exportAll(self, namespace): - """ _exportAll(self, namespace) --> Export all 'public' class methods + """_exportAll(self, namespace) --> Export all 'public' class methods into namespace. This function allows for a module-level PdfFit object which doesn't have @@ -129,27 +130,29 @@ def _exportAll(self, namespace): # string aliases (var = "var") for a in itertools.chain(self.selalias, self.FCON, self.Sctp): exec("%s = %r" % (a, a), namespace) - public = [ a for a in dir(self) if "__" not in a and a not in - ["_handle", "_exportAll", "selalias", "FCON", "Sctp" ] ] + public = [ + a + for a in dir(self) + if "__" not in a and a not in ["_handle", "_exportAll", "selalias", "FCON", "Sctp"] + ] for funcname in public: namespace[funcname] = getattr(self, funcname) return def intro(): - """Show introductory message. - """ + """Show introductory message.""" import re from diffpy.pdffit2 import __version__, __date__ + date = __date__[:10] - d = {'version' : __version__, 'date' : date, - 'year' : date[:4] or '2019'} + d = {"version": __version__, "date": date, "year": date[:4] or "2019"} msg = __intro_message__ % d - filler = lambda mx : (mx.group(0).rstrip(' *').ljust(77) + '*') - msg_ljust = re.sub('(?m)^(.{1,77}|.{79}.*)$', filler, msg) + filler = lambda mx: (mx.group(0).rstrip(" *").ljust(77) + "*") + msg_ljust = re.sub("(?m)^(.{1,77}|.{79}.*)$", filler, msg) print(msg_ljust, file=output.stdout) return - intro = staticmethod(intro) + intro = staticmethod(intro) def add_structure(self, stru): """add_structure(stru) --> Add new structure to PdfFit instance. @@ -160,11 +163,10 @@ def add_structure(self, stru): Raises pdffit2.structureError when stru contains unknown atom species. """ - s = stru.writeStr('pdffit') + s = stru.writeStr("pdffit") self.read_struct_string(s) return - def read_struct(self, struct): """read_struct(struct) --> Read structure from file into memory. @@ -180,7 +182,6 @@ def read_struct(self, struct): self.stru_files.append(struct) return - def read_struct_string(self, struct, name=""): """read_struct_string(struct, name = "") --> Read structure from a string into memory. @@ -197,7 +198,6 @@ def read_struct_string(self, struct, name=""): self.stru_files.append(name) return - def read_data(self, data, stype, qmax, qdamp): """read_data(data, stype, qmax, qdamp) --> Read pdf data from file into memory. @@ -214,7 +214,6 @@ def read_data(self, data, stype, qmax, qdamp): self.data_files.append(data) return - def read_data_string(self, data, stype, qmax, qdamp, name=""): """read_data_string(data, stype, qmax, qdamp, name = "") --> Read pdf data from a string into memory. @@ -226,15 +225,12 @@ def read_data_string(self, data, stype, qmax, qdamp, name=""): qdamp -- instrumental Q-resolution factor name -- tag with which to label data """ - pdffit2.read_data_string(self._handle, data, six.b(stype), qmax, - qdamp, name) + pdffit2.read_data_string(self._handle, data, six.b(stype), qmax, qdamp, name) name = data self.data_files.append(name) return - - def read_data_lists(self, stype, qmax, qdamp, r_data, Gr_data, - dGr_data = None, name = "list"): + def read_data_lists(self, stype, qmax, qdamp, r_data, Gr_data, dGr_data=None, name="list"): """read_data_lists(stype, qmax, qdamp, r_data, Gr_data, dGr_data = None, name = "list") --> Read pdf data into memory from lists. @@ -250,12 +246,10 @@ def read_data_lists(self, stype, qmax, qdamp, r_data, Gr_data, Raises: ValueError when the data lists are of different length """ - pdffit2.read_data_arrays(self._handle, six.b(stype), qmax, qdamp, - r_data, Gr_data, dGr_data, name) + pdffit2.read_data_arrays(self._handle, six.b(stype), qmax, qdamp, r_data, Gr_data, dGr_data, name) self.data_files.append(name) return - def pdfrange(self, iset, rmin, rmax): """pdfrange(iset, rmin, rmax) --> Set the range of the fit. @@ -268,15 +262,13 @@ def pdfrange(self, iset, rmin, rmax): pdffit2.pdfrange(self._handle, iset, rmin, rmax) return - def reset(self): """reset() --> Clear all stored fit, structure, and parameter data.""" self.stru_files = [] self.data_files = [] - pdffit2.reset(self._handle); + pdffit2.reset(self._handle) return - def alloc(self, stype, qmax, qdamp, rmin, rmax, bin): """alloc(stype, qmax, qdamp, rmin, rmax, bin) --> Allocate space for a PDF calculation. @@ -295,11 +287,9 @@ def alloc(self, stype, qmax, qdamp, rmin, rmax, bin): ValueError for bad input values pdffit.unassignedError when no structure has been loaded """ - pdffit2.alloc(self._handle, six.b(stype), qmax, qdamp, rmin, - rmax, bin) + pdffit2.alloc(self._handle, six.b(stype), qmax, qdamp, rmin, rmax, bin) return - def calc(self): """calc() --> Calculate the PDF of the imported structure. @@ -315,7 +305,6 @@ def calc(self): pdffit2.calc(self._handle) return - def refine(self, toler=0.00000001): """refine(toler = 0.00000001) --> Fit the theory to the imported data. @@ -335,7 +324,6 @@ def refine(self, toler=0.00000001): step += 1 return - def refine_step(self, toler=0.00000001): """refine_step(toler = 0.00000001) --> Run a single step of the fit. @@ -353,7 +341,6 @@ def refine_step(self, toler=0.00000001): self.finished = pdffit2.refine_step(self._handle, toler) return self.finished - def save_pdf(self, iset, fname): """save_pdf(iset, fname) --> Save calculated or fitted PDF to file. @@ -366,7 +353,6 @@ def save_pdf(self, iset, fname): pdffit2.save_pdf(self._handle, iset, fname) return - def save_pdf_string(self, iset): """save_pdf_string(iset) --> Save calculated or fitted PDF to string. @@ -380,7 +366,6 @@ def save_pdf_string(self, iset): pdffilestring = pdffit2.save_pdf(self._handle, iset, "") return pdffilestring - def save_dif(self, iset, fname): """save_dif(iset, fname) --> Save data and fitted PDF difference to file. @@ -394,7 +379,6 @@ def save_dif(self, iset, fname): pdffit2.save_dif(self._handle, iset, fname) return - def save_dif_string(self, iset): """save_dif_string(iset) --> Save data and fitted PDF difference to string. @@ -409,7 +393,6 @@ def save_dif_string(self, iset): diffilestring = pdffit2.save_dif(self._handle, iset, "") return diffilestring - def save_res(self, fname): """save_res(fname) --> Save fit-specific data to file. @@ -420,7 +403,6 @@ def save_res(self, fname): pdffit2.save_res(self._handle, fname) return - def save_res_string(self): """save_res_string() --> Save fit-specific data to a string. @@ -432,7 +414,6 @@ def save_res_string(self): resfilestring = pdffit2.save_res(self._handle, "") return resfilestring - def get_structure(self, ip): """get_structure(ip) --> Get a copy of specified phase data. @@ -442,12 +423,12 @@ def get_structure(self, ip): Raise pdffit2.unassignedError if phase ip is undefined. """ from diffpy.structure import PDFFitStructure + s = self.save_struct_string(ip) stru = PDFFitStructure() - stru.readStr(s, 'pdffit') + stru.readStr(s, "pdffit") return stru - def save_struct(self, ip, fname): """save_struct(ip, fname) --> Save structure resulting from fit to file. @@ -461,7 +442,6 @@ def save_struct(self, ip, fname): pdffit2.save_struct(self._handle, ip, fname) return - def save_struct_string(self, ip): """save_struct(ip) --> Save structure resulting from fit to string. @@ -475,7 +455,6 @@ def save_struct_string(self, ip): structfilestring = pdffit2.save_struct(self._handle, ip, "") return structfilestring - def show_struct(self, ip): """show_struct(ip) --> Print structure resulting from fit. @@ -486,7 +465,6 @@ def show_struct(self, ip): pdffit2.show_struct(self._handle, ip) return - def constrain(self, var, par, fcon=None): """constrain(var, par[, fcon]) --> Constrain a variable to a parameter. @@ -520,7 +498,6 @@ def constrain(self, var, par, fcon=None): pdffit2.constrain_int(self._handle, var_ref, varnc, par) return - def setpar(self, par, val): """setpar(par, val) --> Set value of constrained parameter. @@ -540,7 +517,6 @@ def setpar(self, par, val): pdffit2.setpar_RV(self._handle, par, var_ref) return - def setvar(self, var, val): """setvar(var, val) --> Set the value of a variable. @@ -552,7 +528,6 @@ def setvar(self, var, val): pdffit2.setvar(self._handle, var_ref, val) return - def getvar(self, var): """getvar(var) --> Get stored value of a variable. @@ -564,7 +539,6 @@ def getvar(self, var): retval = pdffit2.getvar(self._handle, var_ref) return retval - def getrw(self): """getrw() --> Get normalized total error of the fit rw. @@ -575,7 +549,6 @@ def getrw(self): rw = pdffit2.getrw(self._handle) return rw - def getcrw(self): """getcrw() --> Get cumulative Rw for the current dataset. @@ -591,7 +564,6 @@ def getcrw(self): crw = pdffit2.getcrw(self._handle) return crw - def getR(self): """getR() --> Get r-points used in the fit. @@ -606,7 +578,6 @@ def getR(self): R = pdffit2.getR(self._handle) return R - def getpdf_fit(self): """getpdf_fit() --> Get fitted PDF. @@ -620,7 +591,6 @@ def getpdf_fit(self): pdfdata = pdffit2.getpdf_fit(self._handle) return pdfdata - def getpdf_obs(self): """getpdf_obs() --> Get observed PDF. @@ -635,7 +605,6 @@ def getpdf_obs(self): pdfdata = pdffit2.getpdf_obs(self._handle) return pdfdata - def getpdf_diff(self): """Obtain difference between observed and fitted PDF. @@ -650,7 +619,6 @@ def getpdf_diff(self): Gdiff = pdffit2.getpdf_diff(self._handle) return Gdiff - def get_atoms(self, ip=None): """get_atoms() --> Get element symbols of all atoms in the structure. @@ -663,11 +631,12 @@ def get_atoms(self, ip=None): Returns: List of atom names in structure. """ - if ip is None: rv = pdffit2.get_atoms(self._handle) - else: rv = pdffit2.get_atoms(self._handle, ip) + if ip is None: + rv = pdffit2.get_atoms(self._handle) + else: + rv = pdffit2.get_atoms(self._handle, ip) return rv - def get_atom_types(self, ip=None): """get_atom_types() --> Ordered unique element symbols in the structure. @@ -681,11 +650,12 @@ def get_atom_types(self, ip=None): Returns: List of unique atom symbols as they occur in structure. """ - if ip is None: rv = pdffit2.get_atom_types(self._handle) - else: rv = pdffit2.get_atom_types(self._handle, ip) + if ip is None: + rv = pdffit2.get_atom_types(self._handle) + else: + rv = pdffit2.get_atom_types(self._handle, ip) return rv - def getpar(self, par): """getpar(par) --> Get value of parameter. @@ -693,7 +663,6 @@ def getpar(self, par): """ return pdffit2.getpar(self._handle, par) - def fixpar(self, par): """fixpar(par) --> Fix a parameter. @@ -707,7 +676,6 @@ def fixpar(self, par): pdffit2.fixpar(self._handle, par) return - def freepar(self, par): """freepar(par) --> Free a parameter. @@ -721,7 +689,6 @@ def freepar(self, par): pdffit2.freepar(self._handle, par) return - def setphase(self, ip): """setphase(ip) --> Switch to phase ip. @@ -735,7 +702,6 @@ def setphase(self, ip): pdffit2.setphase(self._handle, ip) return - def setdata(self, iset): """setdata(iset) --> Set the data set in focus. @@ -746,7 +712,6 @@ def setdata(self, iset): pdffit2.setdata(self._handle, iset) return - def psel(self, ip): """psel(ip) --> Include phase ip in calculation of total PDF @@ -759,7 +724,6 @@ def psel(self, ip): pdffit2.psel(self._handle, ip) return - def pdesel(self, ip): """pdesel(ip) --> Exclude phase ip from calculation of total PDF. @@ -772,7 +736,6 @@ def pdesel(self, ip): pdffit2.pdesel(self._handle, ip) return - def selectAtomType(self, ip, ijchar, symbol, flag): """Configure partial PDF - mark the specified atom type in phase ip as included or excluded as a first or second in pair for distance @@ -790,7 +753,6 @@ def selectAtomType(self, ip, ijchar, symbol, flag): pdffit2.selectAtomType(self._handle, ip, six.b(ijchar), symbol, flag) return - def selectAtomIndex(self, ip, ijchar, aidx, flag): """Configure partial PDF - mark the atom of given index in phase ip as included or excluded as a first or second in pair for distance @@ -808,7 +770,6 @@ def selectAtomIndex(self, ip, ijchar, aidx, flag): pdffit2.selectAtomIndex(self._handle, ip, six.b(ijchar), aidx, flag) return - def selectAll(self, ip, ijchar): """Configure partial PDF - include all atoms of phase ip as first or second element in pair for distance evaluation. @@ -823,7 +784,6 @@ def selectAll(self, ip, ijchar): pdffit2.selectAll(self._handle, ip, six.b(ijchar)) return - def selectNone(self, ip, ijchar): """Configure partial PDF - exclude all atoms of phase ip from first or second element of pair distance evaluation. @@ -838,7 +798,6 @@ def selectNone(self, ip, ijchar): pdffit2.selectNone(self._handle, ip, six.b(ijchar)) return - def bang(self, i, j, k): """bang(i, j, k) --> Show bond angle defined by atoms i, j, k. @@ -850,14 +809,18 @@ def bang(self, i, j, k): angle, stdev = pdffit2.bond_angle(self._handle, i, j, k) # indices should be already checked here by bond_angle atom_symbols = self.get_atoms() - leader = " %s (#%i) - %s (#%i) - %s (#%i) = " % \ - (atom_symbols[i-1], i, atom_symbols[j-1], j, - atom_symbols[k-1], k) + leader = " %s (#%i) - %s (#%i) - %s (#%i) = " % ( + atom_symbols[i - 1], + i, + atom_symbols[j - 1], + j, + atom_symbols[k - 1], + k, + ) s = leader + _format_value_std(angle, stdev) + " degrees" print(s, file=output.stdout) return - def bond_angle(self, i, j, k): """bond_angle(i, j, k) --> bond angle defined by atoms i, j, k. Angle is calculated using the shortest ji and jk lengths with @@ -873,7 +836,6 @@ def bond_angle(self, i, j, k): rv = pdffit2.bond_angle(self._handle, i, j, k) return rv - def blen(self, *args): """blen(i, j) --> Show bond length defined by atoms i and j. @@ -897,42 +859,42 @@ def blen(self, *args): pdffit.unassignedError when no structure has been loaded """ # first form - if len(args)==2: + if len(args) == 2: dij, ddij = self.bond_length_atoms(*args[0:2]) atom_symbols = self.get_atoms() ij = (args[0], args[1]) # indices were already checked in bond_length_atoms call assert (0 <= min(ij) - 1) and (max(ij) - 1 < len(atom_symbols)) - symij = ( atom_symbols[ij[0] - 1].upper(), - atom_symbols[ij[1] - 1].upper() ) + symij = (atom_symbols[ij[0] - 1].upper(), atom_symbols[ij[1] - 1].upper()) print(_format_bond_length(dij, ddij, ij, symij), file=output.stdout) # second form - elif len(args)==4: + elif len(args) == 4: a1, a2, lb, ub = args try: atom_types = self.get_atom_types() - if isinstance(a1, numbers.Integral): a1 = atom_types[a1 - 1] - if isinstance(a2, numbers.Integral): a2 = atom_types[a2 - 1] + if isinstance(a1, numbers.Integral): + a1 = atom_types[a1 - 1] + if isinstance(a2, numbers.Integral): + a2 = atom_types[a2 - 1] except IndexError: # index of non-existant atom type return # arguments are OK here, get bond length dictionary bld = pdffit2.bond_length_types(self._handle, a1, a2, lb, ub) - s = "(%s,%s) bond lengths in [%gA,%gA] for current phase :" % \ - (a1, a2, lb, ub) + s = "(%s,%s) bond lengths in [%gA,%gA] for current phase :" % (a1, a2, lb, ub) print(s, file=output.stdout) atom_symbols = self.get_atoms() - npts = len(bld['dij']) + npts = len(bld["dij"]) for idx in range(npts): - dij = bld['dij'][idx] - ddij = bld['ddij'][idx] - ij0 = bld['ij0'][idx] - ij1 = bld['ij1'][idx] + dij = bld["dij"][idx] + ddij = bld["ddij"][idx] + ij0 = bld["ij0"][idx] + ij1 = bld["ij1"][idx] symij = (atom_symbols[ij0[0]], atom_symbols[ij0[1]]) s = _format_bond_length(dij, ddij, ij1, symij) print(s, file=output.stdout) print(file=output.stdout) - if not bld['dij']: + if not bld["dij"]: print(" *** No pairs found ***", file=output.stdout) else: emsg = "blen() takes 2 or 4 arguments (%i given)" % len(args) @@ -940,7 +902,6 @@ def blen(self, *args): # done return - def bond_length_atoms(self, i, j): """bond_length_atoms(i, j) --> shortest distance between atoms i, j. Periodic boundary conditions are applied to find the shortest bond. @@ -956,7 +917,6 @@ def bond_length_atoms(self, i, j): rv = pdffit2.bond_length_atoms(self._handle, i, j) return rv - def bond_length_types(self, a1, a2, lb, ub): """bond_length_types(a1, a2, lb, ub) --> get all a1-a2 distances. @@ -978,7 +938,6 @@ def bond_length_types(self, a1, a2, lb, ub): rv = pdffit2.bond_length_types(self._handle, a1, a2, lb, ub) return rv - def show_scat(self, stype): """show_scat(stype) --> Print scattering length for all atoms in the current phase. @@ -990,7 +949,6 @@ def show_scat(self, stype): print(self.get_scat_string(stype), file=output.stdout) return - def get_scat_string(self, stype): """get_scat_string(stype) --> Get string with scattering factors of all atoms in the current phase. @@ -1004,7 +962,6 @@ def get_scat_string(self, stype): """ return pdffit2.get_scat_string(self._handle, six.b(stype)) - def get_scat(self, stype, element): """get_scat(stype, element) --> Get active scattering factor for given element. If scattering factor has been changed using @@ -1022,7 +979,6 @@ def get_scat(self, stype, element): rv = pdffit2.get_scat(self._handle, six.b(stype), element) return rv - def set_scat(self, stype, element, value): """set_scat(stype, element, value) --> Set custom scattering factor for given element. The new scattering factor applies only for the @@ -1043,7 +999,6 @@ def set_scat(self, stype, element, value): pdffit2.set_scat(self._handle, six.b(stype), element, value) return - def reset_scat(self, element): """reset_scat(stype, element) --> Reset scattering factors for given element to their standard values. The reset_scat applies @@ -1057,7 +1012,6 @@ def reset_scat(self, element): pdffit2.reset_scat(self._handle, element) return - def num_atoms(self): """num_atoms() --> Get number of atoms in current phase. @@ -1065,7 +1019,6 @@ def num_atoms(self): """ return pdffit2.num_atoms(self._handle) - def num_phases(self): """num_phases() --> Number of phases loaded in PdfFit instance. @@ -1076,7 +1029,6 @@ def num_phases(self): n = pdffit2.num_phases(self._handle) return n - def num_datasets(self): """num_datasets() --> Number of datasets loaded in PdfFit instance. @@ -1087,7 +1039,6 @@ def num_datasets(self): n = pdffit2.num_datasets(self._handle) return n - def phase_fractions(self): """phase_fractions() --> relative phase fractions for current dataset. Convert phase scale factors to relative phase fractions given the @@ -1119,30 +1070,30 @@ def lat(n): 5 <==> 'beta' 6 <==> 'gamma' """ - LatParams = { 'a':1, 'b':2, 'c':3, 'alpha':4, 'beta':5, 'gamma':6 } + LatParams = {"a": 1, "b": 2, "c": 3, "alpha": 4, "beta": 5, "gamma": 6} if isinstance(n, six.string_types): n = LatParams[n] return "lat(%i)" % n - lat = staticmethod(lat) + lat = staticmethod(lat) def x(i): """x(i) --> Get reference to x-value of atom i.""" return "x(%i)" % i - x = staticmethod(x) + x = staticmethod(x) def y(i): """y(i) --> Get reference to y-value of atom i.""" return "y(%i)" % i - y = staticmethod(y) + y = staticmethod(y) def z(i): """z(i) --> Get reference to z-value of atom i.""" return "z(%i)" % i - z = staticmethod(z) + z = staticmethod(z) def u11(i): """u11(i) --> Get reference to U(1,1) for atom i. @@ -1150,8 +1101,8 @@ def u11(i): U is the anisotropic thermal factor tensor. """ return "u11(%i)" % i - u11 = staticmethod(u11) + u11 = staticmethod(u11) def u22(i): """u22(i) --> Get reference to U(2,2) for atom i. @@ -1159,8 +1110,8 @@ def u22(i): U is the anisotropic thermal factor tensor. """ return "u22(%i)" % i - u22 = staticmethod(u22) + u22 = staticmethod(u22) def u33(i): """u33(i) --> Get reference to U(3,3) for atom i. @@ -1168,8 +1119,8 @@ def u33(i): U is the anisotropic thermal factor tensor. """ return "u33(%i)" % i - u33 = staticmethod(u33) + u33 = staticmethod(u33) def u12(i): """u12(i) --> Get reference to U(1,2) for atom i. @@ -1177,8 +1128,8 @@ def u12(i): U is the anisotropic thermal factor tensor. """ return "u12(%i)" % i - u12 = staticmethod(u12) + u12 = staticmethod(u12) def u13(i): """u13(i) --> Get reference to U(1,3) for atom i. @@ -1186,8 +1137,8 @@ def u13(i): U is the anisotropic thermal factor tensor. """ return "u13(%i)" % i - u13 = staticmethod(u13) + u13 = staticmethod(u13) def u23(i): """u23(i) --> Get reference to U(2,3) for atom i. @@ -1195,14 +1146,14 @@ def u23(i): U is the anisotropic thermal factor tensor. """ return "u23(%i)" % i - u23 = staticmethod(u23) + u23 = staticmethod(u23) def occ(i): """occ(i) --> Get reference to occupancy of atom i.""" return "occ(%i)" % i - occ = staticmethod(occ) + occ = staticmethod(occ) def pscale(): """pscale() --> Get reference to pscale. @@ -1211,8 +1162,8 @@ def pscale(): represents. """ return "pscale" - pscale = staticmethod(pscale) + pscale = staticmethod(pscale) def sratio(): """sratio() --> Get reference to sigma ratio. @@ -1221,15 +1172,14 @@ def sratio(): distances below rcut. """ return "sratio" - sratio = staticmethod(sratio) + sratio = staticmethod(sratio) def delta1(): - """delta1() --> Get reference to 1/R peak sharpening factor. - """ + """delta1() --> Get reference to 1/R peak sharpening factor.""" return "delta1" - delta1 = staticmethod(delta1) + delta1 = staticmethod(delta1) def delta2(): """delta2() --> Reference to (1/R^2) sharpening factor. @@ -1237,8 +1187,8 @@ def delta2(): The (1/R^2) peak sharpening factor. """ return "delta2" - delta2 = staticmethod(delta2) + delta2 = staticmethod(delta2) def dscale(): """dscale() --> Get reference to dscale. @@ -1246,8 +1196,8 @@ def dscale(): The data scale factor. """ return "dscale" - dscale = staticmethod(dscale) + dscale = staticmethod(dscale) def qdamp(): """qdamp() --> Get reference to qdamp. @@ -1255,8 +1205,8 @@ def qdamp(): Qdamp controls PDF damping due to instrument Q-resolution. """ return "qdamp" - qdamp = staticmethod(qdamp) + qdamp = staticmethod(qdamp) def qbroad(): """qbroad() --> Get reference to qbroad. @@ -1264,8 +1214,8 @@ def qbroad(): Quadratic peak broadening factor. """ return "qbroad" - qbroad = staticmethod(qbroad) + qbroad = staticmethod(qbroad) def spdiameter(): """spdiameter() --> Get reference to spdiameter (phase property). @@ -1274,8 +1224,8 @@ def spdiameter(): Spherical envelope is not applied when spdiameter equals 0. """ return "spdiameter" - spdiameter = staticmethod(spdiameter) + spdiameter = staticmethod(spdiameter) def stepcut(): """stepcut() --> Get reference to stepcut (phase property). @@ -1287,8 +1237,8 @@ def stepcut(): Step cutoff is not applied when stepcut equals 0. """ return "stepcut" - stepcut = staticmethod(stepcut) + stepcut = staticmethod(stepcut) def rcut(): """rcut() --> Get reference to rcut. @@ -1297,8 +1247,8 @@ def rcut(): the sigma ratio (sratio), applies. rcut cannot be refined. """ return "rcut" - rcut = staticmethod(rcut) + rcut = staticmethod(rcut) # End refinable variables. @@ -1311,7 +1261,6 @@ def __init__(self): self.intro() return - def __getRef(self, var_string): """Return the actual reference to the variable in the var_string. @@ -1328,7 +1277,7 @@ def __getRef(self, var_string): method_string, arg_string = var_string.split("(") method_string = method_string.strip() arg_int = int(arg_string.strip(")").strip()) - except ValueError: #There is no arg_string + except ValueError: # There is no arg_string method_string = var_string.strip() f = getattr(pdffit2, method_string) diff --git a/diffpy/pdffit2/tests/ExceptionsTest.py b/diffpy/pdffit2/tests/ExceptionsTest.py index a1b800a0..a88decbe 100644 --- a/diffpy/pdffit2/tests/ExceptionsTest.py +++ b/diffpy/pdffit2/tests/ExceptionsTest.py @@ -22,7 +22,6 @@ class read_structExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -35,17 +34,15 @@ def test_IOError(self): def test_structureError(self): """raise pdffit2.structureError when structure is malformed""" - self.assertRaises(pdffit2.structureError, self.P.read_struct, - datafile("badNi.stru")) + self.assertRaises(pdffit2.structureError, self.P.read_struct, datafile("badNi.stru")) def test_structureErrorZeroVolume(self): """raise pdffit2.structureError when unit cell volume is negative""" - #I don't know how to test for this, but it's in the library code - self.assertRaises(pdffit2.structureError, - self.P.read_struct, datafile("badNiZeroVolume.stru")) + # I don't know how to test for this, but it's in the library code + self.assertRaises(pdffit2.structureError, self.P.read_struct, datafile("badNiZeroVolume.stru")) -class read_dataExceptions(unittest.TestCase): +class read_dataExceptions(unittest.TestCase): def setUp(self): self.P = PdfFit() @@ -54,16 +51,14 @@ def tearDown(self): def test_IOError(self): """raise IOError when data file does not exist""" - self.assertRaises(IOError, self.P.read_data, "Nofile.dat", - 'X', 25.0, 0.5) + self.assertRaises(IOError, self.P.read_data, "Nofile.dat", "X", 25.0, 0.5) def test_dataError(self): """raise pdffit2.dataError when data has improper spacing""" - self.assertRaises(pdffit2.dataError, self.P.read_data, - datafile("badNi.dat"), 'X', 25.0, 0.5) + self.assertRaises(pdffit2.dataError, self.P.read_data, datafile("badNi.dat"), "X", 25.0, 0.5) -class read_data_listsExceptions(unittest.TestCase): +class read_data_listsExceptions(unittest.TestCase): def setUp(self): self.P = PdfFit() self.r_data = [0.1, 0.2] @@ -76,28 +71,31 @@ def tearDown(self): def test_ValueError1(self): """raise ValueError when lists are of different length""" - self.assertRaises(ValueError, self.P.read_data_lists, 'X', self.qmax, - self.qdamp, self.r_data, self.Gr_data) + self.assertRaises( + ValueError, self.P.read_data_lists, "X", self.qmax, self.qdamp, self.r_data, self.Gr_data + ) def test_ValueError2(self): """raise ValueError when qmax < 0""" - self.assertRaises(ValueError, self.P.read_data_lists, 'X', -self.qmax, - self.qdamp, self.r_data, self.Gr_data) + self.assertRaises( + ValueError, self.P.read_data_lists, "X", -self.qmax, self.qdamp, self.r_data, self.Gr_data + ) def test_ValueError3(self): """raise ValueError when qdamp < 0""" - self.assertRaises(ValueError, self.P.read_data_lists, 'X', self.qmax, - -self.qdamp, self.r_data, self.Gr_data) + self.assertRaises( + ValueError, self.P.read_data_lists, "X", self.qmax, -self.qdamp, self.r_data, self.Gr_data + ) def test_dataError(self): """raise pdffit2.dataError when data has improper spacing""" r_data = [0.1, 0.52, 0.2] - self.assertRaises(pdffit2.dataError, self.P.read_data_lists, 'X', self.qmax, - self.qdamp, r_data, self.Gr_data) + self.assertRaises( + pdffit2.dataError, self.P.read_data_lists, "X", self.qmax, self.qdamp, r_data, self.Gr_data + ) class pdfrangeExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.iset = 1 @@ -109,24 +107,20 @@ def tearDown(self): def test_ValueError1(self): """raise ValueError when iset does not exist""" - self.assertRaises(ValueError, self.P.pdfrange, self.iset, self.rmin, - self.rmax) + self.assertRaises(ValueError, self.P.pdfrange, self.iset, self.rmin, self.rmax) def test_ValueError2(self): """raise ValueError when rmax < rmin""" - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.5) - self.assertRaises(ValueError, self.P.pdfrange, self.iset, self.rmax, - self.rmin) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.5) + self.assertRaises(ValueError, self.P.pdfrange, self.iset, self.rmax, self.rmin) def test_ValueError3(self): """raise ValueError when range outside of data""" - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.5) - self.assertRaises(ValueError, self.P.pdfrange, self.iset, -self.rmin, - self.rmax) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.5) + self.assertRaises(ValueError, self.P.pdfrange, self.iset, -self.rmin, self.rmax) class allocExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.qmax = 25 @@ -141,48 +135,40 @@ def tearDown(self): def test_ValueError1(self): """raise ValueError when qmax < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', -self.qmax, self.qdamp, - self.rmin, self.rmax, self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", -self.qmax, self.qdamp, self.rmin, self.rmax, self.bin) def test_ValueError2(self): """raise ValueError when qdamp < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, -self.qdamp, - self.rmin, self.rmax, self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, -self.qdamp, self.rmin, self.rmax, self.bin) def test_ValueError3(self): """raise ValueError when rmin < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, self.qdamp, - -self.rmin, self.rmax, self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, self.qdamp, -self.rmin, self.rmax, self.bin) def test_ValueError4(self): """raise ValueError when rmax < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, self.qdamp, - self.rmin, -self.rmax, self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, self.qdamp, self.rmin, -self.rmax, self.bin) def test_ValueError5(self): """raise ValueError when bin < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, self.qdamp, - self.rmin, self.rmax, -self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, self.qdamp, self.rmin, self.rmax, -self.bin) def test_ValueError6(self): """raise ValueError when rmax < rmin""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, self.qdamp, - self.rmax, self.rmin, self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, self.qdamp, self.rmax, self.rmin, self.bin) def test_ValueError7(self): """raise ValueError when qdamp < 0""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.alloc, 'X', self.qmax, self.qdamp, - self.rmin, self.rmax, -self.bin) + self.assertRaises(ValueError, self.P.alloc, "X", self.qmax, self.qdamp, self.rmin, self.rmax, -self.bin) class calcExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.P.read_struct(datafile("Ni.stru")) @@ -194,6 +180,7 @@ def test_unassignedError(self): """raise pdffit2.unassignedError when no space has been allocated""" self.assertRaises(pdffit2.unassignedError, self.P.calc) + # PJ 2006-03-06 # # test_calculationError raised exception, because for Qmax=0.5, rmax would @@ -207,8 +194,8 @@ def test_unassignedError(self): # self.assertRaises(pdffit2.calculationError, self.P.calc) -#class refineExceptions(unittest.TestCase): - #I'm not sure how to test these +# class refineExceptions(unittest.TestCase): +# I'm not sure how to test these # def setUp(self): # self.P = PdfFit() @@ -222,8 +209,8 @@ def test_unassignedError(self): # #self.assertRaises(pdffit2.constraintError, self.P.calc) -#class refine_stepExceptions(unittest.TestCase): - #I'm not sure how to test these +# class refine_stepExceptions(unittest.TestCase): +# I'm not sure how to test these # def setUp(self): # self.P = PdfFit() @@ -238,7 +225,6 @@ def test_unassignedError(self): class save_pdfExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.strufile = "temp.pdf" @@ -249,19 +235,16 @@ def tearDown(self): def test_IOError(self): """raise IOError when structure cannot be saved""" self.P.read_struct(datafile("Ni.stru")) - self.P.alloc('X', 30.0, 0.05, 2, 10, 100) + self.P.alloc("X", 30.0, 0.05, 2, 10, 100) self.P.calc() - self.assertRaises(IOError, self.P.save_pdf, 1, - "nodir183160/"+self.strufile) + self.assertRaises(IOError, self.P.save_pdf, 1, "nodir183160/" + self.strufile) def test_unassignedError(self): """raise pdffit2.unassignedError when structure is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.save_pdf, 1, - self.strufile) + self.assertRaises(pdffit2.unassignedError, self.P.save_pdf, 1, self.strufile) class save_difExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.strufile = "temp.dif" @@ -272,20 +255,17 @@ def tearDown(self): def test_IOError(self): """raise IOError when dif cannot be saved""" self.P.read_struct(datafile("Ni.stru")) - self.P.alloc('X', 30.0, 0.05, 2, 10, 100) + self.P.alloc("X", 30.0, 0.05, 2, 10, 100) self.P.calc() - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.5) - self.assertRaises(IOError, self.P.save_dif, 1, - "nodir183160/"+self.strufile) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.5) + self.assertRaises(IOError, self.P.save_dif, 1, "nodir183160/" + self.strufile) def test_unassignedError(self): """raise pdffit2.unassignedError when structure is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.save_dif, 1, - self.strufile) + self.assertRaises(pdffit2.unassignedError, self.P.save_dif, 1, self.strufile) class save_resExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.resfile = "temp.res" @@ -296,22 +276,20 @@ def tearDown(self): def test_IOError(self): """raise IOError when residual file cannot be saved""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 30.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 30.0, 0.0) self.P.constrain(self.P.lat(1), 1) self.P.setpar(1, 3.0) - self.P.pdfrange(1,2.0,10.0) + self.P.pdfrange(1, 2.0, 10.0) self.P.refine_step() - self.assertRaises(IOError, self.P.save_res, - "nodir183160/"+self.resfile) + self.assertRaises(IOError, self.P.save_res, "nodir183160/" + self.resfile) def test_unassignedError(self): """raise pdffit2.unassignedError when structure is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.save_res, - self.resfile) + self.assertRaises(pdffit2.unassignedError, self.P.save_res, self.resfile) class save_structExceptions(unittest.TestCase): - #Same code as show_struct + # Same code as show_struct def setUp(self): self.P = PdfFit() @@ -323,17 +301,14 @@ def tearDown(self): def test_IOError(self): """raise IOError when structure cannot be saved""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(IOError, self.P.save_struct, 1, - "nodir183160/"+self.strufile) + self.assertRaises(IOError, self.P.save_struct, 1, "nodir183160/" + self.strufile) def test_unassignedError(self): """raise pdffit2.unassignedError when structure is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.save_struct, 1, - self.strufile) + self.assertRaises(pdffit2.unassignedError, self.P.save_struct, 1, self.strufile) class constrainExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.par = 1 @@ -346,8 +321,8 @@ def tearDown(self): def test_constraintError(self): """raise constraintError when constraint is bad""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.constrain('x(1)', 'junk+@1') + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.constrain("x(1)", "junk+@1") self.P.setpar(1, 0.01) self.assertRaises(pdffit2.constraintError, self.P.calc) self.assertRaises(pdffit2.constraintError, self.P.refine) @@ -355,33 +330,26 @@ def test_constraintError(self): def test_unassignedError(self): """raise pdffit2.unassignedError when variable is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.constrain, self.P.x(1), - self.par) + self.assertRaises(pdffit2.unassignedError, self.P.constrain, self.P.x(1), self.par) return def test_ValueError(self): """raise ValueError when a variable index does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.constrain, self.P.x(6), - self.par) + self.assertRaises(ValueError, self.P.constrain, self.P.x(6), self.par) return def test_constrainNonRefVar(self): "raise constraintError when attempting to constrain non-refinables" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.assertRaises(pdffit2.constraintError, - self.P.constrain, 'rcut', '@7') - self.assertRaises(pdffit2.constraintError, - self.P.constrain, 'rcut', 13) - self.assertRaises(pdffit2.constraintError, - self.P.constrain, 'stepcut', '@17') + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.assertRaises(pdffit2.constraintError, self.P.constrain, "rcut", "@7") + self.assertRaises(pdffit2.constraintError, self.P.constrain, "rcut", 13) + self.assertRaises(pdffit2.constraintError, self.P.constrain, "stepcut", "@17") return - class setvarExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.val = 3.0 @@ -391,18 +359,15 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when variable is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.setvar, self.P.lat(1), - self.val) + self.assertRaises(pdffit2.unassignedError, self.P.setvar, self.P.lat(1), self.val) def test_ValueError(self): """raise ValueError when a variable index does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.assertRaises(ValueError, self.P.setvar, self.P.lat(7), - self.val) + self.assertRaises(ValueError, self.P.setvar, self.P.lat(7), self.val) class getvarExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -411,8 +376,7 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when variable is undefined""" - self.assertRaises(pdffit2.unassignedError, self.P.getvar, - self.P.pscale()) + self.assertRaises(pdffit2.unassignedError, self.P.getvar, self.P.pscale()) def test_ValueError(self): """raise ValueError when a variable index does not exist""" @@ -421,7 +385,6 @@ def test_ValueError(self): class getRExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -434,7 +397,6 @@ def test_unassignedError(self): class getpdf_fitExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -447,7 +409,6 @@ def test_unassignedError(self): class getpdf_obsExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -460,7 +421,6 @@ def test_unassignedError(self): class getpdf_diffExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -473,7 +433,6 @@ def test_unassignedError(self): class get_atomsExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -486,7 +445,6 @@ def test_unassignedError(self): class getparExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -505,7 +463,6 @@ def test_unassignedError2(self): class pselExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.ip = 1 @@ -523,7 +480,6 @@ def test_unassignedError2(self): class pdeselExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.ip = 1 @@ -542,7 +498,6 @@ def test_unassignedError2(self): class selectAtomTypeExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.iset = 1 @@ -553,32 +508,28 @@ def tearDown(self): def test_unassignedError1(self): """raise pdffit2.unassignedError when set does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.selectAtomType, - self.iset, 'i', 'Ni', True) + self.assertRaises(pdffit2.unassignedError, self.P.selectAtomType, self.iset, "i", "Ni", True) def test_unassignedError2(self): """raise pdffit2.unassignedError when set does not exist""" self.P.read_struct(datafile("Ni.stru")) # selectAtomType should pass with one phase defined - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.selectAtomType(self.iset, 'i', 'Ni', True) - self.P.selectAtomType(self.iset, 'j', 'Ni', False) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.selectAtomType(self.iset, "i", "Ni", True) + self.P.selectAtomType(self.iset, "j", "Ni", False) # but fail for phase 2 which is not present - self.assertRaises(pdffit2.unassignedError, self.P.selectAtomType, - 2, 'i', 'Ca', True) + self.assertRaises(pdffit2.unassignedError, self.P.selectAtomType, 2, "i", "Ca", True) def test_ijcharValueError(self): """raise ValueError when ijchar is neither 'i' nor 'j'""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.selectAtomType(self.iset, 'i', 'Ni', True) - self.P.selectAtomType(self.iset, 'j', 'Ni', True) - self.assertRaises(ValueError, self.P.selectAtomType, - self.iset, 'k', 'Ni', True) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.selectAtomType(self.iset, "i", "Ni", True) + self.P.selectAtomType(self.iset, "j", "Ni", True) + self.assertRaises(ValueError, self.P.selectAtomType, self.iset, "k", "Ni", True) class selectAtomIndexExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.iset = 1 @@ -589,30 +540,26 @@ def tearDown(self): def test_unassignedError1(self): """raise pdffit2.unassignedError when set does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.selectAtomIndex, - self.iset, 'i', self.i, True) + self.assertRaises(pdffit2.unassignedError, self.P.selectAtomIndex, self.iset, "i", self.i, True) def test_unassignedError2(self): """raise pdffit2.unassignedError when set does not exist""" self.P.read_struct(datafile("Ni.stru")) # pass for phase 1 - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.selectAtomIndex(self.iset, 'i', 1, True) - self.P.selectAtomIndex(self.iset, 'i', 2, False) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.selectAtomIndex(self.iset, "i", 1, True) + self.P.selectAtomIndex(self.iset, "i", 2, False) # fail for phase 2 - self.assertRaises(pdffit2.unassignedError, self.P.selectAtomIndex, - 2, 'i', 1, True) + self.assertRaises(pdffit2.unassignedError, self.P.selectAtomIndex, 2, "i", 1, True) def test_ValueError(self): """raise ValueError when selected atom does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.assertRaises(ValueError, self.P.selectAtomIndex, - self.iset, 'i', 6, True) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.assertRaises(ValueError, self.P.selectAtomIndex, self.iset, "i", 6, True) class selectAllExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.iset = 1 @@ -623,26 +570,23 @@ def tearDown(self): def test_unassignedError1(self): """raise pdffit2.unassignedError when set does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.selectAll, - self.iset, 'i') + self.assertRaises(pdffit2.unassignedError, self.P.selectAll, self.iset, "i") def test_unassignedError2(self): """raise pdffit2.unassignedError when set does not exist""" self.P.read_struct(datafile("Ni.stru")) # fail when there is no dataset - self.assertRaises(pdffit2.unassignedError, self.P.selectAll, - self.iset, 'i') + self.assertRaises(pdffit2.unassignedError, self.P.selectAll, self.iset, "i") # pass with dataset - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.selectAll(self.iset, 'i') - self.P.selectAll(self.iset, 'j') + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.selectAll(self.iset, "i") + self.P.selectAll(self.iset, "j") # fail for phase 2 - self.assertRaises(pdffit2.unassignedError, self.P.selectAll, 2, 'i') - self.assertRaises(pdffit2.unassignedError, self.P.selectAll, 2, 'j') + self.assertRaises(pdffit2.unassignedError, self.P.selectAll, 2, "i") + self.assertRaises(pdffit2.unassignedError, self.P.selectAll, 2, "j") class selectNoneExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.iset = 1 @@ -653,26 +597,23 @@ def tearDown(self): def test_unassignedError1(self): """raise pdffit2.unassignedError when set does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.selectNone, - self.iset, 'i') + self.assertRaises(pdffit2.unassignedError, self.P.selectNone, self.iset, "i") def test_unassignedError2(self): """raise pdffit2.unassignedError when set does not exist""" self.P.read_struct(datafile("Ni.stru")) # fail when there is no dataset - self.assertRaises(pdffit2.unassignedError, self.P.selectNone, - self.iset, 'i') + self.assertRaises(pdffit2.unassignedError, self.P.selectNone, self.iset, "i") # pass with dataset - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.P.selectNone(self.iset, 'i') - self.P.selectNone(self.iset, 'j') + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.P.selectNone(self.iset, "i") + self.P.selectNone(self.iset, "j") # fail for phase 2 - self.assertRaises(pdffit2.unassignedError, self.P.selectNone, 2, 'i') - self.assertRaises(pdffit2.unassignedError, self.P.selectNone, 2, 'j') + self.assertRaises(pdffit2.unassignedError, self.P.selectNone, 2, "i") + self.assertRaises(pdffit2.unassignedError, self.P.selectNone, 2, "j") class bangExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.a1 = 1 @@ -684,31 +625,26 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when phase does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.bang, self.a1, - self.a2, self.a3) + self.assertRaises(pdffit2.unassignedError, self.P.bang, self.a1, self.a2, self.a3) def test_ValueError1(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) - self.assertRaises(ValueError, self.P.bang, 0, - self.a2, self.a3) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) + self.assertRaises(ValueError, self.P.bang, 0, self.a2, self.a3) def test_ValueError2(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) - self.assertRaises(ValueError, self.P.bang, self.a1, - -1, self.a3) + self.P.read_struct(datafile("Ni.stru")) + self.assertRaises(ValueError, self.P.bang, self.a1, -1, self.a3) def test_ValueError3(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) - self.assertRaises(ValueError, self.P.bang, self.a1, - self.a2, 6) + self.P.read_struct(datafile("Ni.stru")) + self.assertRaises(ValueError, self.P.bang, self.a1, self.a2, 6) class blenExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() self.a1 = 1 @@ -719,27 +655,25 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when no data exists""" - self.assertRaises(pdffit2.unassignedError, self.P.blen, self.a1, - self.a2) + self.assertRaises(pdffit2.unassignedError, self.P.blen, self.a1, self.a2) def test_ValueError1(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) self.assertRaises(ValueError, self.P.blen, 0, self.a2) def test_ValueError2(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) self.assertRaises(ValueError, self.P.blen, self.a1, 6) def test_ValueError3(self): """raise ValueError when selected atom(s) does not exist""" - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) self.assertRaises(ValueError, self.P.blen, 0, 6) class show_scatExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -748,11 +682,11 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when phase does not exist""" - self.assertRaises(pdffit2.unassignedError, self.P.show_scat, 'X') + self.assertRaises(pdffit2.unassignedError, self.P.show_scat, "X") -#class set_scatExceptions(unittest.TestCase): - #I'm not sure how to use this function +# class set_scatExceptions(unittest.TestCase): +# I'm not sure how to use this function # def setUp(self): # self.P = PdfFit() @@ -771,7 +705,6 @@ def test_unassignedError(self): class num_atomsExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -782,8 +715,8 @@ def test_unassignedError(self): """raise pdffit2.unassignedError when no atoms exist""" self.assertRaises(pdffit2.unassignedError, self.P.num_atoms) -class fixparExceptions(unittest.TestCase): +class fixparExceptions(unittest.TestCase): def setUp(self): self.P = PdfFit() @@ -793,12 +726,11 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when parameter does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) self.assertRaises(pdffit2.unassignedError, self.P.fixpar, 1) class freeparExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -808,12 +740,11 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when parameter does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) self.assertRaises(pdffit2.unassignedError, self.P.freepar, 1) class setphaseExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -823,12 +754,11 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when phase does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) self.assertRaises(pdffit2.unassignedError, self.P.setphase, 2) class setdataExceptions(unittest.TestCase): - def setUp(self): self.P = PdfFit() @@ -838,11 +768,11 @@ def tearDown(self): def test_unassignedError(self): """raise pdffit2.unassignedError when data set does not exist""" self.P.read_struct(datafile("Ni.stru")) - self.P.read_data(datafile("Ni.dat"), 'X', 25.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) self.assertRaises(pdffit2.unassignedError, self.P.setdata, 2) -class getcrwExceptions(unittest.TestCase): +class getcrwExceptions(unittest.TestCase): def setUp(self): self.P = PdfFit() @@ -854,13 +784,12 @@ def test_unassignedError(self): self.assertRaises(pdffit2.unassignedError, self.P.getcrw) - -#main -if __name__ == '__main__': - #suite = unittest.makeSuite(num_atomsExceptions) - #unittest.TextTestRunner(verbosity=3).run(suite) - #testcase = calcExceptions('test_unassignedError') - #unittest.TextTestRunner(verbosity=3).run(testcase) +# main +if __name__ == "__main__": + # suite = unittest.makeSuite(num_atomsExceptions) + # unittest.TextTestRunner(verbosity=3).run(suite) + # testcase = calcExceptions('test_unassignedError') + # unittest.TextTestRunner(verbosity=3).run(testcase) unittest.main() # End of file diff --git a/diffpy/pdffit2/tests/TestPdfFit.py b/diffpy/pdffit2/tests/TestPdfFit.py index 90f1ad7c..8102b8b9 100644 --- a/diffpy/pdffit2/tests/TestPdfFit.py +++ b/diffpy/pdffit2/tests/TestPdfFit.py @@ -14,6 +14,7 @@ # ---------------------------------------------------------------------------- + class TestPdfFit(unittest.TestCase): places = 6 @@ -30,299 +31,289 @@ def test__exportAll(self): "check PdfFit._exportAll()" ns = {} self.P._exportAll(ns) - self.assertEqual('ALL', ns['ALL']) - self.assertEqual('FSQR', ns['FSQR']) - self.assertEqual('N', ns['N']) - self.assertIs('N', ns['N']) - self.assertIs(self.P.lat, ns['lat']) - self.assertEqual(self.P.reset, ns['reset']) + self.assertEqual("ALL", ns["ALL"]) + self.assertEqual("FSQR", ns["FSQR"]) + self.assertEqual("N", ns["N"]) + self.assertIs("N", ns["N"]) + self.assertIs(self.P.lat, ns["lat"]) + self.assertEqual(self.P.reset, ns["reset"]) return -# def test_intro(self): -# """check PdfFit.intro() -# """ -# return + # def test_intro(self): + # """check PdfFit.intro() + # """ + # return def test_add_structure(self): - """check PdfFit.add_structure() - """ - ni = loadStructure(datafile('Ni.stru')) + """check PdfFit.add_structure()""" + ni = loadStructure(datafile("Ni.stru")) self.P.add_structure(ni) self.assertEqual(4, self.P.num_atoms()) return -# def test_read_struct(self): -# """check PdfFit.read_struct() -# """ -# return -# -# def test_read_struct_string(self): -# """check PdfFit.read_struct_string() -# """ -# return -# -# def test_read_data(self): -# """check PdfFit.read_data() -# """ -# return + # def test_read_struct(self): + # """check PdfFit.read_struct() + # """ + # return + # + # def test_read_struct_string(self): + # """check PdfFit.read_struct_string() + # """ + # return + # + # def test_read_data(self): + # """check PdfFit.read_data() + # """ + # return def test_read_data_string(self): - """check PdfFit.read_data_string() - """ + """check PdfFit.read_data_string()""" pf = self.P - with open(datafile('300K.gr')) as fp: + with open(datafile("300K.gr")) as fp: s = fp.read() self.assertEqual([], pf.data_files) - pf.read_data_string(s, 'N', 32, 0.03, 'lmo') + pf.read_data_string(s, "N", 32, 0.03, "lmo") self.assertEqual(1, len(pf.data_files)) gobs = pf.getpdf_obs() self.assertEqual(2000, len(gobs)) self.assertEqual(0.384, gobs[-1]) - self.assertEqual(0.03, pf.getvar('qdamp')) - return - -# def test_read_data_lists(self): -# """check PdfFit.read_data_lists() -# """ -# return -# -# def test_pdfrange(self): -# """check PdfFit.pdfrange() -# """ -# return -# -# def test_reset(self): -# """check PdfFit.reset() -# """ -# return + self.assertEqual(0.03, pf.getvar("qdamp")) + return + + # def test_read_data_lists(self): + # """check PdfFit.read_data_lists() + # """ + # return + # + # def test_pdfrange(self): + # """check PdfFit.pdfrange() + # """ + # return + # + # def test_reset(self): + # """check PdfFit.reset() + # """ + # return def test_alloc(self): - """check PdfFit.alloc() - """ + """check PdfFit.alloc()""" # alloc and read_struct can be called in any order. - self.P.alloc('X', 25, 0.0, 0.01, 10, 1000) + self.P.alloc("X", 25, 0.0, 0.01, 10, 1000) # without a structure calculated PDF is all zero self.P.calc() Gzero = self.P.getpdf_fit() - self.assertEqual(1000*[0.0], Gzero) - self.P.read_struct(datafile('Ni.stru')) + self.assertEqual(1000 * [0.0], Gzero) + self.P.read_struct(datafile("Ni.stru")) self.P.calc() # check r-values r = self.P.getR() self.assertEqual(1000, len(r)) for i in range(1000): - self.assertAlmostEqual(0.01*(i + 1), r[i], self.places) + self.assertAlmostEqual(0.01 * (i + 1), r[i], self.places) Gfit_alloc_read = self.P.getpdf_fit() # now try the other order self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 25, 0.0, 0.01, 10, 1000) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 25, 0.0, 0.01, 10, 1000) self.P.calc() Gfit_read_alloc = self.P.getpdf_fit() # and they should be the same self.assertEqual(Gfit_read_alloc, Gfit_alloc_read) return -# def test_calc(self): -# """check PdfFit.calc() -# """ -# return -# -# def test_refine(self): -# """check PdfFit.refine() -# """ -# return -# -# def test_refine_step(self): -# """check PdfFit.refine_step() -# """ -# return -# -# def test_save_pdf(self): -# """check PdfFit.save_pdf() -# """ -# return -# -# def test_save_pdf_string(self): -# """check PdfFit.save_pdf_string() -# """ -# return -# -# def test_save_dif(self): -# """check PdfFit.save_dif() -# """ -# return -# -# def test_save_dif_string(self): -# """check PdfFit.save_dif_string() -# """ -# return -# -# def test_save_res(self): -# """check PdfFit.save_res() -# """ -# return -# -# def test_save_res_string(self): -# """check PdfFit.save_res_string() -# """ -# return + # def test_calc(self): + # """check PdfFit.calc() + # """ + # return + # + # def test_refine(self): + # """check PdfFit.refine() + # """ + # return + # + # def test_refine_step(self): + # """check PdfFit.refine_step() + # """ + # return + # + # def test_save_pdf(self): + # """check PdfFit.save_pdf() + # """ + # return + # + # def test_save_pdf_string(self): + # """check PdfFit.save_pdf_string() + # """ + # return + # + # def test_save_dif(self): + # """check PdfFit.save_dif() + # """ + # return + # + # def test_save_dif_string(self): + # """check PdfFit.save_dif_string() + # """ + # return + # + # def test_save_res(self): + # """check PdfFit.save_res() + # """ + # return + # + # def test_save_res_string(self): + # """check PdfFit.save_res_string() + # """ + # return def test_get_structure(self): - """check PdfFit.get_structure() - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + """check PdfFit.get_structure()""" + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) stru1 = self.P.get_structure(1) self.assertEqual(4, len(stru1)) - self.assertEqual('Ni', stru1[0].element) + self.assertEqual("Ni", stru1[0].element) stru2 = self.P.get_structure(2) self.assertEqual(56, len(stru2)) - self.assertEqual('Ti', stru2[-1].element) - return - -# def test_save_struct(self): -# """check PdfFit.save_struct() -# """ -# return -# -# def test_save_struct_string(self): -# """check PdfFit.save_struct_string() -# """ -# return -# -# def test_show_struct(self): -# """check PdfFit.show_struct() -# """ -# return -# -# def test_constrain(self): -# """check PdfFit.constrain() -# """ -# return + self.assertEqual("Ti", stru2[-1].element) + return + + # def test_save_struct(self): + # """check PdfFit.save_struct() + # """ + # return + # + # def test_save_struct_string(self): + # """check PdfFit.save_struct_string() + # """ + # return + # + # def test_show_struct(self): + # """check PdfFit.show_struct() + # """ + # return + # + # def test_constrain(self): + # """check PdfFit.constrain() + # """ + # return def test_setpar(self): - """check PdfFit.setpar() - """ + """check PdfFit.setpar()""" pf = self.P - pf.read_struct(datafile('Ni.stru')) - pf.setpar(1, 'lat(1)') + pf.read_struct(datafile("Ni.stru")) + pf.setpar(1, "lat(1)") self.assertEqual(3.52, pf.getpar(1)) pf.setpar(1, 4.0) self.assertEqual(4, pf.getpar(1)) - pf.setpar(1, pf.lat('a')) + pf.setpar(1, pf.lat("a")) self.assertEqual(3.52, pf.getpar(1)) return def test_setvar(self): - """check PdfFit.setvar() - """ + """check PdfFit.setvar()""" pf = self.P - pf.read_struct(datafile('Ni.stru')) + pf.read_struct(datafile("Ni.stru")) pf.setvar(pf.delta1, 1.2) self.assertEqual(1.2, pf.getvar(pf.delta1)) - pf.setvar('delta1', 1.7) - self.assertEqual(1.7, pf.getvar('delta1')) - return - -# def test_getvar(self): -# """check PdfFit.getvar() -# """ -# return -# -# def test_getrw(self): -# """check PdfFit.getrw() -# """ -# return -# -# def test_getR(self): -# """check PdfFit.getR() -# """ -# return -# -# def test_getpdf_fit(self): -# """check PdfFit.getpdf_fit() -# """ -# return -# -# def test_getpdf_obs(self): -# """check PdfFit.getpdf_obs() -# """ -# return -# -# def test_getpdf_diff(self): -# """check PdfFit.getpdf_diff() -# """ -# return + pf.setvar("delta1", 1.7) + self.assertEqual(1.7, pf.getvar("delta1")) + return + + # def test_getvar(self): + # """check PdfFit.getvar() + # """ + # return + # + # def test_getrw(self): + # """check PdfFit.getrw() + # """ + # return + # + # def test_getR(self): + # """check PdfFit.getR() + # """ + # return + # + # def test_getpdf_fit(self): + # """check PdfFit.getpdf_fit() + # """ + # return + # + # def test_getpdf_obs(self): + # """check PdfFit.getpdf_obs() + # """ + # return + # + # def test_getpdf_diff(self): + # """check PdfFit.getpdf_diff() + # """ + # return def test_get_atoms(self): - """check PdfFit.get_atoms() - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + """check PdfFit.get_atoms()""" + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) self.P.setphase(1) a1 = self.P.get_atoms() a2 = self.P.get_atoms(2) - self.assertEqual(4*['NI'], a1) - self.assertEqual(8*['PB']+24*['O']+8*['SC']+8*['W']+8*['TI'], a2) + self.assertEqual(4 * ["NI"], a1) + self.assertEqual(8 * ["PB"] + 24 * ["O"] + 8 * ["SC"] + 8 * ["W"] + 8 * ["TI"], a2) return def test_get_atom_types(self): - """check PdfFit.get_atom_types() - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + """check PdfFit.get_atom_types()""" + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) self.P.setphase(1) atp1 = self.P.get_atom_types() atp2 = self.P.get_atom_types(2) - self.assertEqual(['NI'], atp1) - self.assertEqual(['PB', 'O', 'SC', 'W', 'TI'], atp2) + self.assertEqual(["NI"], atp1) + self.assertEqual(["PB", "O", "SC", "W", "TI"], atp2) return def test_num_phases(self): - """check PdfFit.num_phases() - """ + """check PdfFit.num_phases()""" self.assertEqual(0, self.P.num_phases()) - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) self.assertEqual(1, self.P.num_phases()) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("PbScW25TiO3.stru")) self.assertEqual(2, self.P.num_phases()) self.P.reset() self.assertEqual(0, self.P.num_phases()) return def test_num_datasets(self): - """check PdfFit.num_datasets() - """ + """check PdfFit.num_datasets()""" self.assertEqual(0, self.P.num_datasets()) - self.P.read_data(datafile('Ni.dat'), 'X', 25.0, 0.5) + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.5) self.assertEqual(1, self.P.num_datasets()) # failed data should not increase num_datasets try: - self.P.read_data(datafile('badNi.dat')) + self.P.read_data(datafile("badNi.dat")) except: pass self.assertEqual(1, self.P.num_datasets()) # alloc should increase number of datasets # alloc requires a loaded structure - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 30.0, 0.05, 2, 10, 100) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 30.0, 0.05, 2, 10, 100) self.assertEqual(2, self.P.num_datasets()) self.P.reset() self.assertEqual(0, self.P.num_datasets()) return def test_getcrw(self): - """check PdfFit.getcrw() - """ + """check PdfFit.getcrw()""" import numpy + self.assertEqual(0, self.P.num_datasets()) # Setting qmax=0 so that partial crw are not disturbed by # termination ripples. - self.P.read_data(datafile('Ni.dat'), 'X', 0.0, 0.0) + self.P.read_data(datafile("Ni.dat"), "X", 0.0, 0.0) # crw is empty before data refinement self.assertEqual([], self.P.getcrw()) - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) self.P.pdfrange(1, 2, 19) self.P.refine() crw19 = numpy.array(self.P.getcrw()) @@ -334,10 +325,10 @@ def test_getcrw(self): self.assertAlmostEqual(self.P.getrw(), rw19, self.places) # renormalize cumulative Rw and compare with Rw at r=15 Gobs19 = numpy.array(self.P.getpdf_obs()) - Gnorm19 = numpy.sqrt(numpy.sum(Gobs19**2)) + Gnorm19 = numpy.sqrt(numpy.sum(Gobs19 ** 2)) r = numpy.array(self.P.getR()) idx = numpy.nonzero(r <= 15)[0] - Gnorm15 = numpy.sqrt(numpy.sum(Gobs19[idx]**2)) + Gnorm15 = numpy.sqrt(numpy.sum(Gobs19[idx] ** 2)) i15 = idx[-1] rw15 = crw19[i15] * Gnorm19 / Gnorm15 self.P.pdfrange(1, 2, r[i15] + 1e-5) @@ -346,17 +337,16 @@ def test_getcrw(self): return def test_getcrw_two_datasets(self): - """check that getcrw() and getrw() are consistent for two datasets. - """ - self.P.read_data(datafile('Ni.dat'), 'X', 25.0, 0.0) + """check that getcrw() and getrw() are consistent for two datasets.""" + self.P.read_data(datafile("Ni.dat"), "X", 25.0, 0.0) self.P.pdfrange(1, 2, 8) - self.P.read_data(datafile('300K.gr'), 'N', 32.0, 0.0) + self.P.read_data(datafile("300K.gr"), "N", 32.0, 0.0) self.P.pdfrange(2, 1, 11) - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) # mess lattice parameters to have comparable Rw contributions - self.P.setvar('lat(1)', 3) - self.P.setvar('lat(2)', 3) - self.P.setvar('lat(3)', 3) + self.P.setvar("lat(1)", 3) + self.P.setvar("lat(2)", 3) + self.P.setvar("lat(3)", 3) self.P.refine() rwtot = self.P.getrw() self.assertTrue(rwtot > 0.0) @@ -364,72 +354,70 @@ def test_getcrw_two_datasets(self): rw1 = self.P.getcrw()[-1] self.P.setdata(2) rw2 = self.P.getcrw()[-1] - self.assertAlmostEqual(rwtot**2, rw1**2 + rw2**2, self.places) + self.assertAlmostEqual(rwtot ** 2, rw1 ** 2 + rw2 ** 2, self.places) return -# def test_getpar(self): -# """check PdfFit.getpar() -# """ -# return + # def test_getpar(self): + # """check PdfFit.getpar() + # """ + # return def test_fixpar(self): - """check PdfFit.fixpar() - """ - self.P.fixpar('all') - self.assertRaises(TypeError, self.P.fixpar, 'x') + """check PdfFit.fixpar()""" + self.P.fixpar("all") + self.assertRaises(TypeError, self.P.fixpar, "x") return def test_freepar(self): - """check PdfFit.freepar() - """ - self.P.freepar('all') - self.assertRaises(TypeError, self.P.freepar, 'x') - return - -# def test_setphase(self): -# """check PdfFit.setphase() -# """ -# return -# -# def test_setdata(self): -# """check PdfFit.setdata() -# """ -# return -# + """check PdfFit.freepar()""" + self.P.freepar("all") + self.assertRaises(TypeError, self.P.freepar, "x") + return + + # def test_setphase(self): + # """check PdfFit.setphase() + # """ + # return + # + # def test_setdata(self): + # """check PdfFit.setdata() + # """ + # return + # def test_psel(self): - """check PdfFit.psel() - """ + """check PdfFit.psel()""" + def doalloc(): - self.P.alloc('X', 30.0, 0.05, 2, 10, 100) + self.P.alloc("X", 30.0, 0.05, 2, 10, 100) return + self.assertRaises(pdffit2.unassignedError, self.P.psel, 0) self.assertRaises(pdffit2.unassignedError, self.P.psel, 1) - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) doalloc() self.P.calc() G1 = self.P.getpdf_fit() self.P.reset() - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("PbScW25TiO3.stru")) doalloc() self.P.calc() G2 = self.P.getpdf_fit() self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) doalloc() - self.P.pdesel('ALL') + self.P.pdesel("ALL") self.P.psel(1) self.P.calc() self.assertEqual(G1, self.P.getpdf_fit()) - self.P.pdesel('ALL') + self.P.pdesel("ALL") self.P.psel(2) self.P.calc() self.assertEqual(G2, self.P.getpdf_fit()) - self.P.psel('ALL') + self.P.psel("ALL") self.P.calc() Gall = self.P.getpdf_fit() - dGmax = max([abs(g1 + g2 - gall) - for g1, g2, gall in zip(G1, G2, Gall)]) + dGmax = max([abs(g1 + g2 - gall) for g1, g2, gall in zip(G1, G2, Gall)]) self.assertAlmostEqual(0, dGmax, self.places) self.assertRaises(pdffit2.unassignedError, self.P.psel, 10) self.assertRaises(pdffit2.unassignedError, self.P.psel, 0) @@ -437,67 +425,68 @@ def doalloc(): return def test_pdesel(self): - """check PdfFit.pdesel() - """ + """check PdfFit.pdesel()""" + def doalloc(): - self.P.alloc('X', 30.0, 0.05, 2, 10, 100) + self.P.alloc("X", 30.0, 0.05, 2, 10, 100) return + self.assertRaises(pdffit2.unassignedError, self.P.pdesel, 0) self.assertRaises(pdffit2.unassignedError, self.P.pdesel, 1) - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) doalloc() self.P.calc() G1 = self.P.getpdf_fit() self.P.reset() - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("PbScW25TiO3.stru")) doalloc() self.P.calc() G2 = self.P.getpdf_fit() self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) doalloc() - self.P.psel('ALL') + self.P.psel("ALL") self.P.pdesel(2) self.P.calc() self.assertEqual(G1, self.P.getpdf_fit()) - self.P.psel('ALL') + self.P.psel("ALL") self.P.pdesel(1) self.P.calc() self.assertEqual(G2, self.P.getpdf_fit()) - self.P.pdesel('ALL') + self.P.pdesel("ALL") self.P.calc() G0 = self.P.getpdf_fit() - self.assertEqual([0.0]*len(G0), G0) + self.assertEqual([0.0] * len(G0), G0) self.assertRaises(pdffit2.unassignedError, self.P.pdesel, 10) self.assertRaises(pdffit2.unassignedError, self.P.pdesel, 0) self.assertRaises(pdffit2.unassignedError, self.P.pdesel, -100) return -# -# def test_selectAtomType(self): -# """check PdfFit.selectAtomType() -# """ -# return -# -# def test_selectAtomIndex(self): -# """check PdfFit.selectAtomIndex() -# """ -# return -# -# def test_selectAll(self): -# """check PdfFit.selectAll() -# """ -# return -# -# def test_selectNone(self): -# """check PdfFit.selectNone() -# """ -# return + + # + # def test_selectAtomType(self): + # """check PdfFit.selectAtomType() + # """ + # return + # + # def test_selectAtomIndex(self): + # """check PdfFit.selectAtomIndex() + # """ + # return + # + # def test_selectAll(self): + # """check PdfFit.selectAll() + # """ + # return + # + # def test_selectNone(self): + # """check PdfFit.selectNone() + # """ + # return def test_bond_angle(self): - """check PdfFit.bond_angle() - """ - self.P.read_struct(datafile('Ni.stru')) + """check PdfFit.bond_angle()""" + self.P.read_struct(datafile("Ni.stru")) a, e = self.P.bond_angle(1, 2, 3) self.assertAlmostEqual(60.0, a, self.places) self.assertRaises(ValueError, self.P.bond_angle, 0, 1, 2) @@ -506,17 +495,16 @@ def test_bond_angle(self): def test_bang(self): "check PdfFit.bang() function" - self.P.read_struct(datafile('Ni.stru')) + self.P.read_struct(datafile("Ni.stru")) out = capture_output(self.P.bang, 1, 2, 3).strip() - self.assertTrue(out.endswith('60 degrees')) - self.assertTrue(out.startswith('NI (#1) - NI (#2) - NI (#3)')) + self.assertTrue(out.endswith("60 degrees")) + self.assertTrue(out.startswith("NI (#1) - NI (#2) - NI (#3)")) return def test_bond_length_atoms(self): - """check PdfFit.bond_length_atoms() - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + """check PdfFit.bond_length_atoms()""" + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) dij, ddij = self.P.bond_length_atoms(1, 5) self.assertAlmostEqual(4.03635, dij, self.places) self.P.setphase(1) @@ -524,152 +512,145 @@ def test_bond_length_atoms(self): return def test_bond_length_types(self): - """check PdfFit.bond_length_types() - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - dPbO = self.P.bond_length_types('Pb', 'O', 0.1, 3.0) + """check PdfFit.bond_length_types()""" + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + dPbO = self.P.bond_length_types("Pb", "O", 0.1, 3.0) # check if keys are present - self.assertTrue('dij' in dPbO) - self.assertTrue('ddij' in dPbO) - self.assertTrue('ij0' in dPbO) - self.assertTrue('ij1' in dPbO) + self.assertTrue("dij" in dPbO) + self.assertTrue("ddij" in dPbO) + self.assertTrue("ij0" in dPbO) + self.assertTrue("ij1" in dPbO) # check if they have the same length - npts = len(dPbO['dij']) - self.assertEqual(npts, len(dPbO['ddij'])) - self.assertEqual(npts, len(dPbO['ij0'])) - self.assertEqual(npts, len(dPbO['ij1'])) + npts = len(dPbO["dij"]) + self.assertEqual(npts, len(dPbO["ddij"])) + self.assertEqual(npts, len(dPbO["ij0"])) + self.assertEqual(npts, len(dPbO["ij1"])) # 8 Pb atoms have coordination 12 in perovskite structure - self.assertEqual(8*12, len(dPbO['dij'])) + self.assertEqual(8 * 12, len(dPbO["dij"])) self.P.setphase(1) - dfcc = self.P.bond_length_types('ALL', 'ALL', 0.1, 2.6) + dfcc = self.P.bond_length_types("ALL", "ALL", 0.1, 2.6) # 4 Ni atoms with coordination 12 - self.assertEqual(4*12, len(dfcc['dij'])) + self.assertEqual(4 * 12, len(dfcc["dij"])) # invalid element - self.assertRaises(ValueError, self.P.bond_length_types, 'Ni', 'Nix', 0.1, 5.0) + self.assertRaises(ValueError, self.P.bond_length_types, "Ni", "Nix", 0.1, 5.0) # check indices ij0 - allij0 = sum(dfcc['ij0'], tuple()) + allij0 = sum(dfcc["ij0"], tuple()) self.assertEqual(0, min(allij0)) self.assertEqual(3, max(allij0)) # check indices ij1 - allij1 = sum(dfcc['ij1'], tuple()) + allij1 = sum(dfcc["ij1"], tuple()) self.assertEqual(1, min(allij1)) self.assertEqual(4, max(allij1)) # check index values - ij0check = [(i1 - 1, j1 - 1) for i1, j1 in dfcc['ij1']] - self.assertEqual(ij0check, dfcc['ij0']) + ij0check = [(i1 - 1, j1 - 1) for i1, j1 in dfcc["ij1"]] + self.assertEqual(ij0check, dfcc["ij0"]) # test valid element which is not present in the structure - dnone = self.P.bond_length_types('Ni', 'Au', 0.1, 5.0) - self.assertEqual(0, len(dnone['dij'])) - self.assertEqual(0, len(dnone['ddij'])) - self.assertEqual(0, len(dnone['ij0'])) - self.assertEqual(0, len(dnone['ij1'])) + dnone = self.P.bond_length_types("Ni", "Au", 0.1, 5.0) + self.assertEqual(0, len(dnone["dij"])) + self.assertEqual(0, len(dnone["ddij"])) + self.assertEqual(0, len(dnone["ij0"])) + self.assertEqual(0, len(dnone["ij1"])) return def test_blen(self): - """check PdfFit.blen() - """ - self.P.read_struct(datafile('PbScW25TiO3.stru')) + """check PdfFit.blen()""" + self.P.read_struct(datafile("PbScW25TiO3.stru")) blen = self.P.blen o = capture_output(blen, 1, 5).strip() - self.assertTrue(o.endswith('4.03635 A')) - self.assertTrue('PB (#1)' in o) - self.assertTrue('PB (#5)' in o) + self.assertTrue(o.endswith("4.03635 A")) + self.assertTrue("PB (#1)" in o) + self.assertTrue("PB (#5)" in o) self.assertRaises(ValueError, blen, 1, 99) self.assertRaises(ValueError, blen, 0, 1) o1 = capture_output(blen, 1, 1, 0.1, 1) - self.assertTrue('No pairs found' in o1) + self.assertTrue("No pairs found" in o1) o2 = capture_output(blen, 1, 50, 0.1, 1) - self.assertEqual('', o2) - o3 = capture_output(blen, 'Sc', 'O', 0.5, 2.3).strip() - self.assertEqual(1 + 48, len(o3.split('\n'))) + self.assertEqual("", o2) + o3 = capture_output(blen, "Sc", "O", 0.5, 2.3).strip() + self.assertEqual(1 + 48, len(o3.split("\n"))) self.assertEqual(6, o3.count("SC (#33)")) self.assertEqual(2, o3.count("O (#9)")) self.assertRaises(TypeError, blen, "Sc", "O", 0.5) return -# def test_show_scat(self): -# """check PdfFit.show_scat() -# """ -# return -# -# def test_get_scat_string(self): -# """check PdfFit.get_scat_string() -# """ -# return + # def test_show_scat(self): + # """check PdfFit.show_scat() + # """ + # return + # + # def test_get_scat_string(self): + # """check PdfFit.get_scat_string() + # """ + # return def test_get_scat(self): - """check PdfFit.get_scat() - """ + """check PdfFit.get_scat()""" # x-ray scattering factors - fPb = self.P.get_scat('X', 'Pb') + fPb = self.P.get_scat("X", "Pb") self.assertEqual(82.0, fPb) - fTi = self.P.get_scat('X', 'tI') + fTi = self.P.get_scat("X", "tI") self.assertEqual(22.0, fTi) # neutron scattering lengths - bPb = self.P.get_scat('N', 'PB') + bPb = self.P.get_scat("N", "PB") self.assertAlmostEqual(9.401, bPb, 3) - bTi = self.P.get_scat('N', 'ti') + bTi = self.P.get_scat("N", "ti") self.assertAlmostEqual(-3.370, bTi, 3) # exceptions - self.assertRaises(ValueError, self.P.get_scat, 'N', 'zz') - self.assertRaises(ValueError, self.P.get_scat, 'Z', 'Ti') + self.assertRaises(ValueError, self.P.get_scat, "N", "zz") + self.assertRaises(ValueError, self.P.get_scat, "Z", "Ti") return def test_set_scat(self): - """check PdfFit.set_scat() - """ + """check PdfFit.set_scat()""" # raises exception when no phase exists - self.assertRaises(pdffit2.unassignedError, - self.P.set_scat, 'N', 'Ti', -11) + self.assertRaises(pdffit2.unassignedError, self.P.set_scat, "N", "Ti", -11) # check if it is local to phase - fPb = self.P.get_scat('X', 'Pb') - bPb = self.P.get_scat('N', 'Pb') - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.set_scat('X', 'Pb', 142) - self.assertEqual(142, self.P.get_scat('X', 'Pb')) - self.assertEqual(bPb, self.P.get_scat('N', 'Pb')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.assertEqual(fPb, self.P.get_scat('X', 'Pb')) + fPb = self.P.get_scat("X", "Pb") + bPb = self.P.get_scat("N", "Pb") + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.set_scat("X", "Pb", 142) + self.assertEqual(142, self.P.get_scat("X", "Pb")) + self.assertEqual(bPb, self.P.get_scat("N", "Pb")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.assertEqual(fPb, self.P.get_scat("X", "Pb")) self.P.setphase(1) - self.assertEqual(142, self.P.get_scat('X', 'Pb')) + self.assertEqual(142, self.P.get_scat("X", "Pb")) self.P.setphase(2) - self.assertEqual(fPb, self.P.get_scat('X', 'Pb')) + self.assertEqual(fPb, self.P.get_scat("X", "Pb")) # check exception for invalid inputs - self.assertRaises(ValueError, self.P.set_scat, 'Z', 'C', 123) - self.assertRaises(ValueError, self.P.set_scat, 'X', 'ZZ', 123) + self.assertRaises(ValueError, self.P.set_scat, "Z", "C", 123) + self.assertRaises(ValueError, self.P.set_scat, "X", "ZZ", 123) return def test_reset_scat(self): - """check PdfFit.reset_scat() - """ + """check PdfFit.reset_scat()""" # raises exception when no phase exists - self.assertRaises(pdffit2.unassignedError, self.P.reset_scat, 'Ti') + self.assertRaises(pdffit2.unassignedError, self.P.reset_scat, "Ti") # check if it is local to phase - fPb = self.P.get_scat('X', 'Pb') - bPb = self.P.get_scat('N', 'Pb') - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.set_scat('X', 'Pb', 142) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.set_scat('N', 'Pb', -17) + fPb = self.P.get_scat("X", "Pb") + bPb = self.P.get_scat("N", "Pb") + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.set_scat("X", "Pb", 142) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.set_scat("N", "Pb", -17) self.P.setphase(1) - self.assertNotEqual(fPb, self.P.get_scat('X', 'Pb')) - self.P.reset_scat('Pb') - self.assertEqual(fPb, self.P.get_scat('X', 'Pb')) + self.assertNotEqual(fPb, self.P.get_scat("X", "Pb")) + self.P.reset_scat("Pb") + self.assertEqual(fPb, self.P.get_scat("X", "Pb")) self.P.setphase(2) - self.assertNotEqual(bPb, self.P.get_scat('N', 'Pb')) - self.P.reset_scat('Pb') - self.assertEqual(bPb, self.P.get_scat('N', 'Pb')) + self.assertNotEqual(bPb, self.P.get_scat("N", "Pb")) + self.P.reset_scat("Pb") + self.assertEqual(bPb, self.P.get_scat("N", "Pb")) # check exception for invalid inputs - self.assertRaises(ValueError, self.P.reset_scat, 'Zz') + self.assertRaises(ValueError, self.P.reset_scat, "Zz") return def test_num_atoms(self): - """check PdfFit.num_atoms() - """ - self.P.read_struct(datafile('Ni.stru')) + """check PdfFit.num_atoms()""" + self.P.read_struct(datafile("Ni.stru")) self.assertEqual(4, self.P.num_atoms()) - self.P.read_struct(datafile('PbScW25TiO3.stru')) + self.P.read_struct(datafile("PbScW25TiO3.stru")) self.assertEqual(56, self.P.num_atoms()) self.P.setphase(1) self.assertEqual(4, self.P.num_atoms()) @@ -678,30 +659,27 @@ def test_num_atoms(self): return def test_lat(self): - """check PdfFit.lat() - """ + """check PdfFit.lat()""" pf = self.P - pf.read_struct(datafile('Ni.stru')) - for i in ('a', 'b', 'c', 1, 2, 3): + pf.read_struct(datafile("Ni.stru")) + for i in ("a", "b", "c", 1, 2, 3): self.assertEqual(3.52, pf.getvar(pf.lat(i))) - for i in ('alpha', 'beta', 'gamma', 4, 5, 6): + for i in ("alpha", "beta", "gamma", 4, 5, 6): self.assertEqual(90, pf.getvar(pf.lat(i))) return def test_xyz(self): - """check PdfFit.x() PdfFit.y(), PdfFit.z() - """ + """check PdfFit.x() PdfFit.y(), PdfFit.z()""" pf = self.P - pf.read_struct(datafile('Ni.stru')) + pf.read_struct(datafile("Ni.stru")) self.assertEqual(0.5, pf.getvar(pf.x(3))) self.assertEqual(0, pf.getvar(pf.y(3))) self.assertEqual(0.5, pf.getvar(pf.z(3))) return def test_uij(self): - """check PdfFit.uij() - """ - ni = loadStructure(datafile('Ni.stru')) + """check PdfFit.uij()""" + ni = loadStructure(datafile("Ni.stru")) ni[2].anisotropy = True ni[2].U11, ni[2].U22, ni[2].U33 = 1, 2, 3 ni[2].U12, ni[2].U13, ni[2].U23 = 4, 5, 6 @@ -716,14 +694,14 @@ def test_uij(self): return def test_occ(self): - """check PdfFit.occ() - """ + """check PdfFit.occ()""" pf = self.P - pf.read_struct(datafile('Ni.stru')) + pf.read_struct(datafile("Ni.stru")) for i in range(1, 5): self.assertEqual(1, pf.getvar(pf.occ(i))) return + # def test_pscale(self): # """check PdfFit.pscale() # """ @@ -781,7 +759,7 @@ def test_occ(self): # End of class TestPdfFit -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/diffpy/pdffit2/tests/TestPhaseFractions.py b/diffpy/pdffit2/tests/TestPhaseFractions.py index aa3b27e6..2bbebf76 100644 --- a/diffpy/pdffit2/tests/TestPhaseFractions.py +++ b/diffpy/pdffit2/tests/TestPhaseFractions.py @@ -16,10 +16,10 @@ class TestPhaseFractions(unittest.TestCase): def setUp(self): self.P = PdfFit() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.alloc('N', 0.0, 0.05, 0.1, 10, 200) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.alloc("N", 0.0, 0.05, 0.1, 10, 200) return def tearDown(self): @@ -27,83 +27,70 @@ def tearDown(self): return def test_xray_fractions(self): - """test_xray_fractions -- check phase fractions in x-ray dataset. - """ + """test_xray_fractions -- check phase fractions in x-ray dataset.""" self.P.setdata(1) ph = self.P.phase_fractions() - bb1 = 28**2 - bb2 = ((8*82 + 24*8 + 4*21 + 2*74 + 2*22) / 40.0)**2 - self.assertAlmostEqual(1.0, sum(ph['atom']), self.places) - self.assertAlmostEqual(1.0, sum(ph['cell']), self.places) - self.assertAlmostEqual(1.0, sum(ph['mass']), self.places) - self.assertAlmostEqual(bb2/bb1, - ph['atom'][0]/ph['atom'][1], self.places) - self.assertAlmostEqual(bb2/bb1 * 40.0/4.0, - ph['cell'][0]/ph['cell'][1], self.places) + bb1 = 28 ** 2 + bb2 = ((8 * 82 + 24 * 8 + 4 * 21 + 2 * 74 + 2 * 22) / 40.0) ** 2 + self.assertAlmostEqual(1.0, sum(ph["atom"]), self.places) + self.assertAlmostEqual(1.0, sum(ph["cell"]), self.places) + self.assertAlmostEqual(1.0, sum(ph["mass"]), self.places) + self.assertAlmostEqual(bb2 / bb1, ph["atom"][0] / ph["atom"][1], self.places) + self.assertAlmostEqual(bb2 / bb1 * 40.0 / 4.0, ph["cell"][0] / ph["cell"][1], self.places) mavg1 = 58.69 - mavg2 = (8*207.19 + 24*15.994 + 4*44.956 + 2*183.85 + 2*47.90)/40.0 - self.assertAlmostEqual(bb2/bb1 * mavg1/mavg2, - ph['mass'][0]/ph['mass'][1], self.places) - self.assertEqual(0.0, sum(ph['stdatom'])) - self.assertEqual(0.0, sum(ph['stdcell'])) - self.assertEqual(0.0, sum(ph['stdmass'])) + mavg2 = (8 * 207.19 + 24 * 15.994 + 4 * 44.956 + 2 * 183.85 + 2 * 47.90) / 40.0 + self.assertAlmostEqual(bb2 / bb1 * mavg1 / mavg2, ph["mass"][0] / ph["mass"][1], self.places) + self.assertEqual(0.0, sum(ph["stdatom"])) + self.assertEqual(0.0, sum(ph["stdcell"])) + self.assertEqual(0.0, sum(ph["stdmass"])) self.P.setphase(1) - self.P.setvar('pscale', 2.0) + self.P.setvar("pscale", 2.0) ph2 = self.P.phase_fractions() - self.assertAlmostEqual(1.0, sum(ph2['atom']), self.places) - self.assertAlmostEqual(1.0, sum(ph2['cell']), self.places) - self.assertAlmostEqual(1.0, sum(ph2['mass']), self.places) - self.assertAlmostEqual(2.0, ph2['atom'][0]/ph2['atom'][1] / - (ph['atom'][0]/ph['atom'][1]), self.places) - self.assertAlmostEqual(2.0, ph2['cell'][0]/ph2['cell'][1] / - (ph['cell'][0]/ph['cell'][1]), self.places) - self.assertAlmostEqual(2.0, ph2['mass'][0]/ph2['mass'][1] / - (ph['mass'][0]/ph['mass'][1]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["atom"]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["cell"]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["mass"]), self.places) + self.assertAlmostEqual(2.0, ph2["atom"][0] / ph2["atom"][1] / (ph["atom"][0] / ph["atom"][1]), self.places) + self.assertAlmostEqual(2.0, ph2["cell"][0] / ph2["cell"][1] / (ph["cell"][0] / ph["cell"][1]), self.places) + self.assertAlmostEqual(2.0, ph2["mass"][0] / ph2["mass"][1] / (ph["mass"][0] / ph["mass"][1]), self.places) return def test_neutron_fractions(self): - """test_neutron_fractions -- check phase fractions in neutron dataset. - """ + """test_neutron_fractions -- check phase fractions in neutron dataset.""" self.P.setdata(2) ph = self.P.phase_fractions() - bb1 = 10.31**2 + bb1 = 10.31 ** 2 bPb = 9.4012 bO = 5.8054 bSc = 12.11 bW = 4.75518 bTi = -3.37013 - bb2 = ((8*bPb + 24*bO + 4*bSc + 2*bW + 2*bTi) / 40.0)**2 - self.assertAlmostEqual(1.0, sum(ph['atom']), self.places) - self.assertAlmostEqual(1.0, sum(ph['cell']), self.places) - self.assertAlmostEqual(1.0, sum(ph['mass']), self.places) - self.assertAlmostEqual(bb2/bb1, - ph['atom'][0]/ph['atom'][1], self.places) - self.assertAlmostEqual(bb2/bb1 * 40.0/4.0, - ph['cell'][0]/ph['cell'][1], self.places) + bb2 = ((8 * bPb + 24 * bO + 4 * bSc + 2 * bW + 2 * bTi) / 40.0) ** 2 + self.assertAlmostEqual(1.0, sum(ph["atom"]), self.places) + self.assertAlmostEqual(1.0, sum(ph["cell"]), self.places) + self.assertAlmostEqual(1.0, sum(ph["mass"]), self.places) + self.assertAlmostEqual(bb2 / bb1, ph["atom"][0] / ph["atom"][1], self.places) + self.assertAlmostEqual(bb2 / bb1 * 40.0 / 4.0, ph["cell"][0] / ph["cell"][1], self.places) mavg1 = 58.69 - mavg2 = (8*207.19 + 24*15.994 + 4*44.956 + 2*183.85 + 2*47.90)/40.0 - self.assertAlmostEqual(bb2/bb1 * mavg1/mavg2, - ph['mass'][0]/ph['mass'][1], self.places) - self.assertEqual(0.0, sum(ph['stdatom'])) - self.assertEqual(0.0, sum(ph['stdcell'])) - self.assertEqual(0.0, sum(ph['stdmass'])) + mavg2 = (8 * 207.19 + 24 * 15.994 + 4 * 44.956 + 2 * 183.85 + 2 * 47.90) / 40.0 + self.assertAlmostEqual(bb2 / bb1 * mavg1 / mavg2, ph["mass"][0] / ph["mass"][1], self.places) + self.assertEqual(0.0, sum(ph["stdatom"])) + self.assertEqual(0.0, sum(ph["stdcell"])) + self.assertEqual(0.0, sum(ph["stdmass"])) self.P.setphase(1) - self.P.setvar('pscale', 2.0) + self.P.setvar("pscale", 2.0) ph2 = self.P.phase_fractions() - self.assertAlmostEqual(1.0, sum(ph2['atom']), self.places) - self.assertAlmostEqual(1.0, sum(ph2['cell']), self.places) - self.assertAlmostEqual(1.0, sum(ph2['mass']), self.places) - self.assertAlmostEqual(2.0, ph2['atom'][0]/ph2['atom'][1] / - (ph['atom'][0]/ph['atom'][1]), self.places) - self.assertAlmostEqual(2.0, ph2['cell'][0]/ph2['cell'][1] / - (ph['cell'][0]/ph['cell'][1]), self.places) - self.assertAlmostEqual(2.0, ph2['mass'][0]/ph2['mass'][1] / - (ph['mass'][0]/ph['mass'][1]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["atom"]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["cell"]), self.places) + self.assertAlmostEqual(1.0, sum(ph2["mass"]), self.places) + self.assertAlmostEqual(2.0, ph2["atom"][0] / ph2["atom"][1] / (ph["atom"][0] / ph["atom"][1]), self.places) + self.assertAlmostEqual(2.0, ph2["cell"][0] / ph2["cell"][1] / (ph["cell"][0] / ph["cell"][1]), self.places) + self.assertAlmostEqual(2.0, ph2["mass"][0] / ph2["mass"][1] / (ph["mass"][0] / ph["mass"][1]), self.places) return + # End of class TestSphereEnvelope -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/diffpy/pdffit2/tests/TestShapeFactors.py b/diffpy/pdffit2/tests/TestShapeFactors.py index 26e5bb46..9c870c4a 100644 --- a/diffpy/pdffit2/tests/TestShapeFactors.py +++ b/diffpy/pdffit2/tests/TestShapeFactors.py @@ -21,7 +21,7 @@ def spherefactor(r, d): Return numpy array of shape correction envelope. """ r1 = numpy.array(r) - fsph = 1.0 - 1.5*r1/d + 0.5*(r1/d)**3 + fsph = 1.0 - 1.5 * r1 / d + 0.5 * (r1 / d) ** 3 fsph[r1 > d] = 0.0 return fsph @@ -39,33 +39,29 @@ def tearDown(self): self.P = None return - def test_calculation(self): - """check calculation of sphere envelope factor - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) + """check calculation of sphere envelope factor""" + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) self.P.calc() d = 8.0 r = numpy.array(self.P.getR()) G0 = numpy.array(self.P.getpdf_fit()) - self.P.setvar('spdiameter', d) + self.P.setvar("spdiameter", d) self.P.calc() G1 = numpy.array(self.P.getpdf_fit()) - dG = (G0*spherefactor(r, d) - G1) - msd = numpy.dot(dG, dG)/len(r) + dG = G0 * spherefactor(r, d) - G1 + msd = numpy.dot(dG, dG) / len(r) self.assertAlmostEqual(0.0, numpy.sqrt(msd), self.places) return - def test_refinement(self): - """check refinement of sphere envelope factor - """ + """check refinement of sphere envelope factor""" dcheck = 8.0 dstart = 12.0 - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('spdiameter', dcheck) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("spdiameter", dcheck) self.P.calc() r = numpy.array(self.P.getR()) Gd8 = numpy.array(self.P.getpdf_fit()) @@ -73,65 +69,61 @@ def test_refinement(self): Gd8noise[::2] += 0.01 Gd8noise[1::2] -= 0.01 self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_data_lists('X', 0.0, 0.05, list(r), list(Gd8noise)) - self.P.constrain('spdiameter', '@8') + self.P.read_struct(datafile("Ni.stru")) + self.P.read_data_lists("X", 0.0, 0.05, list(r), list(Gd8noise)) + self.P.constrain("spdiameter", "@8") self.P.setpar(8, dstart) self.P.refine() - dfinal = self.P.getvar('spdiameter') + dfinal = self.P.getvar("spdiameter") self.assertAlmostEqual(dcheck, dfinal, 3) return - def test_twophase_calculation(self): - """check PDF calculation for 2 phases with different spdiameters - """ + """check PDF calculation for 2 phases with different spdiameters""" d1 = 6 d2 = 9 - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('spdiameter', d1) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("spdiameter", d1) self.P.calc() G1 = numpy.array(self.P.getpdf_fit()) self.P.reset() - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('spdiameter', d2) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("spdiameter", d2) self.P.calc() G2 = numpy.array(self.P.getpdf_fit()) self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) self.P.setphase(1) - self.P.setvar('spdiameter', d1) + self.P.setvar("spdiameter", d1) self.P.setphase(2) - self.P.setvar('spdiameter', d2) + self.P.setvar("spdiameter", d2) self.P.calc() Gtot = numpy.array(self.P.getpdf_fit()) - dG = (G1 + G2 - Gtot) + dG = G1 + G2 - Gtot r = numpy.array(self.P.getR()) - msd = numpy.dot(dG, dG)/len(r) + msd = numpy.dot(dG, dG) / len(r) self.assertAlmostEqual(0.0, numpy.sqrt(msd), self.places) return - def test_twophase_refinement(self): - """check PDF refinement of 2 phases that have different spdiameter. - """ + """check PDF refinement of 2 phases that have different spdiameter.""" dcheck1 = 8.0 dstart1 = 8.2 dcheck2 = 6.0 dstart2 = 5.5 - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('spdiameter', dcheck1) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("spdiameter", dcheck1) self.P.calc() G1 = numpy.array(self.P.getpdf_fit()) self.P.reset() - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('spdiameter', dcheck2) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("spdiameter", dcheck2) self.P.calc() G2 = numpy.array(self.P.getpdf_fit()) r = numpy.array(self.P.getR()) @@ -139,48 +131,46 @@ def test_twophase_refinement(self): Gnoise[::2] += 0.01 Gnoise[1::2] -= 0.01 self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.read_data_lists('X', 0.0, 0.05, list(r), list(Gnoise)) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.read_data_lists("X", 0.0, 0.05, list(r), list(Gnoise)) self.P.setphase(1) - self.P.constrain('spdiameter', '@11') + self.P.constrain("spdiameter", "@11") self.P.setphase(2) - self.P.constrain('spdiameter', '@12') + self.P.constrain("spdiameter", "@12") self.P.setpar(11, dstart1) self.P.setpar(12, dstart2) self.P.refine() - dfinal2 = self.P.getvar('spdiameter') + dfinal2 = self.P.getvar("spdiameter") self.P.setphase(1) - dfinal1 = self.P.getvar('spdiameter') + dfinal1 = self.P.getvar("spdiameter") self.assertAlmostEqual(dcheck1, dfinal1, 3) self.assertAlmostEqual(dcheck2, dfinal2, 3) return - def test_spdiameter_io(self): - """Check reading and writing of spdiameter from structure file. - """ + """Check reading and writing of spdiameter from structure file.""" import re - self.P.read_struct(datafile('Ni.stru')) - self.assertEqual(0.0, self.P.getvar('spdiameter')) + + self.P.read_struct(datafile("Ni.stru")) + self.assertEqual(0.0, self.P.getvar("spdiameter")) # engine should not write shape factor when not defined spdnone = self.P.save_struct_string(1) - self.assertTrue(not re.search('(?m)^shape +sphere,', spdnone)) - self.P.setvar('spdiameter', 7) + self.assertTrue(not re.search("(?m)^shape +sphere,", spdnone)) + self.P.setvar("spdiameter", 7) spd7 = self.P.save_struct_string(1) # spd7 should contain shape factor data - self.assertTrue(re.search('(?m)^shape +sphere,', spd7)) + self.assertTrue(re.search("(?m)^shape +sphere,", spd7)) self.P.reset() self.P.read_struct_string(spd7) - self.assertEqual(7.0, self.P.getvar('spdiameter')) + self.assertEqual(7.0, self.P.getvar("spdiameter")) # try to read without comma - spd14 = re.sub('(?m)^shape +sphere.*$', 'shape sphere 14.00', spd7) + spd14 = re.sub("(?m)^shape +sphere.*$", "shape sphere 14.00", spd7) self.P.read_struct_string(spd14) - self.assertEqual(14.0, self.P.getvar('spdiameter')) + self.assertEqual(14.0, self.P.getvar("spdiameter")) # try to read invalid shape data - sinvalid = re.sub('(?m)^shape .*', 'shape invalid, 1', spd7) - self.assertRaises(pdffit2.structureError, - self.P.read_struct_string, sinvalid) + sinvalid = re.sub("(?m)^shape .*", "shape invalid, 1", spd7) + self.assertRaises(pdffit2.structureError, self.P.read_struct_string, sinvalid) return @@ -200,91 +190,85 @@ def tearDown(self): self.P = None return - def test_stepcut_calculation(self): - """check calculation of sphere envelope factor - """ - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) + """check calculation of sphere envelope factor""" + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) self.P.calc() stepcut = 8.0 r = numpy.array(self.P.getR()) G0 = numpy.array(self.P.getpdf_fit()) G0[r > stepcut] = 0.0 - self.P.setvar('stepcut', stepcut) + self.P.setvar("stepcut", stepcut) self.P.calc() G1 = numpy.array(self.P.getpdf_fit()) - dG = (G0 - G1) - msd = numpy.dot(dG, dG)/len(r) + dG = G0 - G1 + msd = numpy.dot(dG, dG) / len(r) self.assertAlmostEqual(0.0, numpy.sqrt(msd), self.places) return - def test_twophase_stepcut_calculation(self): - """check PDF calculation for 2 phases with different spdiameters - """ + """check PDF calculation for 2 phases with different spdiameters""" d1 = 6 d2 = 9 - self.P.read_struct(datafile('Ni.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('stepcut', d1) + self.P.read_struct(datafile("Ni.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("stepcut", d1) self.P.calc() G1 = numpy.array(self.P.getpdf_fit()) self.P.reset() - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) - self.P.setvar('stepcut', d2) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) + self.P.setvar("stepcut", d2) self.P.calc() G2 = numpy.array(self.P.getpdf_fit()) self.P.reset() - self.P.read_struct(datafile('Ni.stru')) - self.P.read_struct(datafile('PbScW25TiO3.stru')) - self.P.alloc('X', 0.0, 0.05, 0.1, 10, 200) + self.P.read_struct(datafile("Ni.stru")) + self.P.read_struct(datafile("PbScW25TiO3.stru")) + self.P.alloc("X", 0.0, 0.05, 0.1, 10, 200) self.P.setphase(1) - self.P.setvar('stepcut', d1) + self.P.setvar("stepcut", d1) self.P.setphase(2) - self.P.setvar('stepcut', d2) + self.P.setvar("stepcut", d2) self.P.calc() Gtot = numpy.array(self.P.getpdf_fit()) - dG = (G1 + G2 - Gtot) + dG = G1 + G2 - Gtot r = numpy.array(self.P.getR()) - msd = numpy.dot(dG, dG)/len(r) + msd = numpy.dot(dG, dG) / len(r) self.assertAlmostEqual(0.0, numpy.sqrt(msd), self.places) # G after step should be zero self.assertTrue(numpy.all(0 == Gtot[r > max(d1, d2)])) return - def test_stepcut_io(self): - """Check reading and writing of stepcut from structure file. - """ + """Check reading and writing of stepcut from structure file.""" import re - self.P.read_struct(datafile('Ni.stru')) - self.assertEqual(0.0, self.P.getvar('stepcut')) + + self.P.read_struct(datafile("Ni.stru")) + self.assertEqual(0.0, self.P.getvar("stepcut")) # engine should not write shape factor when not defined sscnone = self.P.save_struct_string(1) - self.assertTrue(not re.search('(?m)^shape +stepcut,', sscnone)) - self.P.setvar('stepcut', 7) + self.assertTrue(not re.search("(?m)^shape +stepcut,", sscnone)) + self.P.setvar("stepcut", 7) ssc7 = self.P.save_struct_string(1) # ssc7 should contain shape factor data - self.assertTrue(re.search('(?m)^shape +stepcut,', ssc7)) + self.assertTrue(re.search("(?m)^shape +stepcut,", ssc7)) self.P.reset() self.P.read_struct_string(ssc7) - self.assertEqual(7.0, self.P.getvar('stepcut')) + self.assertEqual(7.0, self.P.getvar("stepcut")) # try to read without comma - ssc14 = re.sub('(?m)^shape +stepcut.*$', 'shape stepcut 14.00', ssc7) + ssc14 = re.sub("(?m)^shape +stepcut.*$", "shape stepcut 14.00", ssc7) self.P.read_struct_string(ssc14) - self.assertEqual(14.0, self.P.getvar('stepcut')) + self.assertEqual(14.0, self.P.getvar("stepcut")) # try to read invalid shape data - sinvalid = re.sub('(?m)^shape .*', 'shape invalid, 1', ssc7) - self.assertRaises(pdffit2.structureError, - self.P.read_struct_string, sinvalid) + sinvalid = re.sub("(?m)^shape .*", "shape invalid, 1", ssc7) + self.assertRaises(pdffit2.structureError, self.P.read_struct_string, sinvalid) return # End of class TestStepCutEnvelope -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/diffpy/pdffit2/tests/__init__.py b/diffpy/pdffit2/tests/__init__.py index 4a21417c..8eca524f 100644 --- a/diffpy/pdffit2/tests/__init__.py +++ b/diffpy/pdffit2/tests/__init__.py @@ -18,8 +18,9 @@ import unittest -def testsuite(pattern=''): - '''Create a unit tests suite for the diffpy.pdffit2 package. + +def testsuite(pattern=""): + """Create a unit tests suite for the diffpy.pdffit2 package. Parameters ---------- @@ -32,30 +33,30 @@ def testsuite(pattern=''): ------- suite : `unittest.TestSuite` The TestSuite object containing the matching tests. - ''' + """ import re from os.path import dirname from itertools import chain from pkg_resources import resource_filename + loader = unittest.defaultTestLoader - thisdir = resource_filename(__name__, '') - depth = __name__.count('.') + 1 + thisdir = resource_filename(__name__, "") + depth = __name__.count(".") + 1 topdir = thisdir for i in range(depth): topdir = dirname(topdir) - suite_all = loader.discover(thisdir, pattern='*Test*.py', - top_level_dir=topdir) + suite_all = loader.discover(thisdir, pattern="*Test*.py", top_level_dir=topdir) # always filter the suite by pattern to test-cover the selection code. suite = unittest.TestSuite() rx = re.compile(pattern) tsuites = list(chain.from_iterable(suite_all)) tsok = all(isinstance(ts, unittest.TestSuite) for ts in tsuites) - if not tsok: # pragma: no cover + if not tsok: # pragma: no cover return suite_all tcases = chain.from_iterable(tsuites) for tc in tcases: - tcwords = tc.id().split('.') - shortname = '.'.join(tcwords[-3:]) + tcwords = tc.id().split(".") + shortname = ".".join(tcwords[-3:]) if rx.search(shortname): suite.addTest(tc) # verify all tests are found for an empty pattern. @@ -64,12 +65,12 @@ def testsuite(pattern=''): def test(): - '''Execute all unit tests for the diffpy.pdffit2 package. + """Execute all unit tests for the diffpy.pdffit2 package. Returns ------- result : `unittest.TestResult` - ''' + """ suite = testsuite() runner = unittest.TextTestRunner() result = runner.run(suite) @@ -77,17 +78,18 @@ def test(): def testdeps(): - '''Execute all unit tests for diffpy.pdffit2 and its dependencies. + """Execute all unit tests for diffpy.pdffit2 and its dependencies. Returns ------- result : `unittest.TestResult` - ''' + """ from importlib import import_module - modulenames = ''' + + modulenames = """ diffpy.pdffit2.tests diffpy.structure.tests - '''.split() + """.split() suite = unittest.TestSuite() for mname in modulenames: mod = import_module(mname) diff --git a/diffpy/pdffit2/tests/debug.py b/diffpy/pdffit2/tests/debug.py index be6e48e4..b99602d4 100644 --- a/diffpy/pdffit2/tests/debug.py +++ b/diffpy/pdffit2/tests/debug.py @@ -23,10 +23,11 @@ """ -if __name__ == '__main__': +if __name__ == "__main__": import sys from diffpy.pdffit2.tests import testsuite - pattern = sys.argv[1] if len(sys.argv) > 1 else '' + + pattern = sys.argv[1] if len(sys.argv) > 1 else "" suite = testsuite(pattern) suite.debug() diff --git a/diffpy/pdffit2/tests/pdffit2testutils.py b/diffpy/pdffit2/tests/pdffit2testutils.py index 18dabf11..c2d82948 100644 --- a/diffpy/pdffit2/tests/pdffit2testutils.py +++ b/diffpy/pdffit2/tests/pdffit2testutils.py @@ -23,22 +23,21 @@ import diffpy.pdffit2 # silence the C++ engine output -diffpy.pdffit2.redirect_stdout(open(os.path.devnull, 'w')) +diffpy.pdffit2.redirect_stdout(open(os.path.devnull, "w")) # path variables -thisfile = locals().get('__file__', 'file.py') +thisfile = locals().get("__file__", "file.py") tests_dir = os.path.dirname(os.path.abspath(thisfile)) -testdata_dir = os.path.join(tests_dir, 'testdata') +testdata_dir = os.path.join(tests_dir, "testdata") + def datafile(filename): - """prepend testdata_dir to filename. - """ + """prepend testdata_dir to filename.""" return os.path.join(testdata_dir, filename) def capture_output(f, *args, **kwargs): - """Capture output from pdffit2 engine produced in function call. - """ + """Capture output from pdffit2 engine produced in function call.""" savestdout = diffpy.pdffit2.output.stdout fp = six.StringIO() diffpy.pdffit2.redirect_stdout(fp) @@ -48,4 +47,5 @@ def capture_output(f, *args, **kwargs): diffpy.pdffit2.redirect_stdout(savestdout) return fp.getvalue() + # End of file diff --git a/diffpy/pdffit2/tests/run.py b/diffpy/pdffit2/tests/run.py index 8519454c..7eb6aadd 100644 --- a/diffpy/pdffit2/tests/run.py +++ b/diffpy/pdffit2/tests/run.py @@ -19,15 +19,18 @@ """ -if __name__ == '__main__': +if __name__ == "__main__": import sys + # show warnings by default if not sys.warnoptions: import os, warnings + warnings.simplefilter("default") # also affect subprocesses os.environ["PYTHONWARNINGS"] = "default" from diffpy.pdffit2.tests import test + # produce zero exit code for a successful test sys.exit(not test().wasSuccessful()) diff --git a/diffpy/pdffit2/tests/rundeps.py b/diffpy/pdffit2/tests/rundeps.py index 9e3c5ee9..420c4d6f 100644 --- a/diffpy/pdffit2/tests/rundeps.py +++ b/diffpy/pdffit2/tests/rundeps.py @@ -19,9 +19,10 @@ """ -if __name__ == '__main__': +if __name__ == "__main__": import sys from diffpy.pdffit2.tests import testdeps + # produce zero exit code for a successful test sys.exit(not testdeps().wasSuccessful()) diff --git a/diffpy/pdffit2/version.py b/diffpy/pdffit2/version.py index e77b09d0..098dcde1 100644 --- a/diffpy/pdffit2/version.py +++ b/diffpy/pdffit2/version.py @@ -22,7 +22,7 @@ Use `__git_commit__` instead. """ -__all__ = ['__date__', '__git_commit__', '__timestamp__', '__version__'] +__all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__"] import os.path @@ -30,22 +30,22 @@ # obtain version information from the version.cfg file -cp = dict(version='', date='', commit='', timestamp='0') -fcfg = resource_filename(__name__, 'version.cfg') -if not os.path.isfile(fcfg): # pragma: no cover +cp = dict(version="", date="", commit="", timestamp="0") +fcfg = resource_filename(__name__, "version.cfg") +if not os.path.isfile(fcfg): # pragma: no cover from warnings import warn + warn('Package metadata not found, execute "./setup.py egg_info".') fcfg = os.devnull with open(fcfg) as fp: - kwords = [[w.strip() for w in line.split(' = ', 1)] - for line in fp if line[:1].isalpha() and ' = ' in line] + kwords = [[w.strip() for w in line.split(" = ", 1)] for line in fp if line[:1].isalpha() and " = " in line] assert all(w[0] in cp for w in kwords), "received unrecognized keyword" cp.update(kwords) -__version__ = cp['version'] -__date__ = cp['date'] -__git_commit__ = cp['commit'] -__timestamp__ = int(cp['timestamp']) +__version__ = cp["version"] +__date__ = cp["date"] +__git_commit__ = cp["commit"] +__timestamp__ = int(cp["timestamp"]) # TODO remove deprecated __gitsha__ in version 1.3. __gitsha__ = __git_commit__ From 18944da4b3cfd8db81e1b73d3951696805a5fb5a Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 11:44:05 -0400 Subject: [PATCH 5/8] Run black on full package --- conda-recipe/run_test.py | 1 + examples/Ni_calculation.py | 8 +- examples/Ni_plot_pdf.py | 15 ++- examples/Ni_refinement.py | 32 ++--- setup.py | 256 +++++++++++++++++++------------------ 5 files changed, 158 insertions(+), 154 deletions(-) diff --git a/conda-recipe/run_test.py b/conda-recipe/run_test.py index f7099645..1432eed6 100644 --- a/conda-recipe/run_test.py +++ b/conda-recipe/run_test.py @@ -1,4 +1,5 @@ #!/usr/bin/env python import diffpy.pdffit2.tests + assert diffpy.pdffit2.tests.test().wasSuccessful() diff --git a/examples/Ni_calculation.py b/examples/Ni_calculation.py index bfe1e941..fd789c56 100755 --- a/examples/Ni_calculation.py +++ b/examples/Ni_calculation.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -'''Calculate PDF of FCC nickel. Save data to Ni_calculation.cgr. -''' +"""Calculate PDF of FCC nickel. Save data to Ni_calculation.cgr. +""" from diffpy.pdffit2 import PdfFit @@ -11,9 +11,9 @@ # load structure file in PDFFIT or DISCUS format P.read_struct("Ni.stru") -radiation_type = 'X' # x-rays +radiation_type = "X" # x-rays qmax = 30.0 # Q-cutoff used in PDF calculation in 1/A -qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay +qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay rmin = 0.01 # minimum r-value rmax = 30.0 # maximum r-value npts = 3000 # number of points in the r-grid diff --git a/examples/Ni_plot_pdf.py b/examples/Ni_plot_pdf.py index f6019d2a..9b1fd4ad 100755 --- a/examples/Ni_plot_pdf.py +++ b/examples/Ni_plot_pdf.py @@ -1,8 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -'''Calculate PDF of FCC nickel and plot it using matplotlib. -''' +"""Calculate PDF of FCC nickel and plot it using matplotlib. +""" from diffpy.pdffit2 import PdfFit @@ -12,9 +12,9 @@ # load structure file in PDFFIT or DISCUS format P.read_struct("Ni.stru") -radiation_type = 'X' # x-rays +radiation_type = "X" # x-rays qmax = 30.0 # Q-cutoff used in PDF calculation in 1/A -qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay +qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay rmin = 0.01 # minimum r-value rmax = 30.0 # maximum r-value npts = 3000 # number of points in the r-grid @@ -29,10 +29,11 @@ # pylab is matplotlib interface with MATLAB-like plotting commands import pylab + pylab.plot(r, G) -pylab.xlabel(u'r (Å)') -pylab.ylabel(u'G (Å$^{-2}$)') -pylab.title('x-ray PDF of nickel simulated at Qmax = %g' % qmax) +pylab.xlabel(u"r (Å)") +pylab.ylabel(u"G (Å$^{-2}$)") +pylab.title("x-ray PDF of nickel simulated at Qmax = %g" % qmax) # display plot window, this must be the last command in the script pylab.show() diff --git a/examples/Ni_refinement.py b/examples/Ni_refinement.py index 177659d2..2a467cde 100755 --- a/examples/Ni_refinement.py +++ b/examples/Ni_refinement.py @@ -1,9 +1,9 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -'''Perform simple refinement of Ni structure to the experimental x-ray PDF. +"""Perform simple refinement of Ni structure to the experimental x-ray PDF. Save fitted curve, refined structure and results summary. -''' +""" from diffpy.pdffit2 import PdfFit @@ -14,11 +14,11 @@ # Load experimental x-ray PDF data qmax = 30.0 # Q-cutoff used in PDF calculation in 1/A -qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay -pf.read_data('Ni-xray.gr', 'X', qmax, qdamp) +qdamp = 0.01 # instrument Q-resolution factor, responsible for PDF decay +pf.read_data("Ni-xray.gr", "X", qmax, qdamp) # Load nickel structure, must be in PDFFIT or DISCUS format -pf.read_struct('Ni.stru') +pf.read_struct("Ni.stru") # Configure Refinement ------------------------------------------------------- @@ -31,12 +31,12 @@ pf.setpar(1, pf.lat(1)) # Refine phase scale factor. Right side can have formulas. -pf.constrain('pscale', '@20 * 2') +pf.constrain("pscale", "@20 * 2") pf.setpar(20, pf.getvar(pf.pscale) / 2.0) # Refine PDF damping due to instrument Q-resolution. # Left side can be also passed as a reference to PdfFit object -pf.constrain(pf.qdamp, '@21') +pf.constrain(pf.qdamp, "@21") pf.setpar(21, 0.03) # Refine sharpening factor for correlated motion of close atoms. @@ -45,9 +45,9 @@ # Set all temperature factors isotropic and equal to @4 for idx in range(1, 5): - pf.constrain(pf.u11(idx), '@4') - pf.constrain(pf.u22(idx), '@4') - pf.constrain(pf.u33(idx), '@4') + pf.constrain(pf.u11(idx), "@4") + pf.constrain(pf.u22(idx), "@4") + pf.constrain(pf.u33(idx), "@4") pf.setpar(4, pf.u11(1)) # Refine --------------------------------------------------------------------- @@ -76,13 +76,13 @@ Gdiff = pylab.array(Gobs) - pylab.array(Gfit) Gdiff_baseline = -10 -pylab.plot(r, Gobs, 'ko') -pylab.plot(r, Gfit, 'b-') -pylab.plot(r, Gdiff + Gdiff_baseline, 'r-') +pylab.plot(r, Gobs, "ko") +pylab.plot(r, Gfit, "b-") +pylab.plot(r, Gdiff + Gdiff_baseline, "r-") -pylab.xlabel(u'r (Å)') -pylab.ylabel(u'G (Å$^{-2}$)') -pylab.title('Fit of nickel to x-ray experimental PDF') +pylab.xlabel(u"r (Å)") +pylab.ylabel(u"G (Å$^{-2}$)") +pylab.title("Fit of nickel to x-ray experimental PDF") # display plot window, this must be the last command in the script pylab.show() diff --git a/setup.py b/setup.py index bb6bb72a..70e6c6d5 100755 --- a/setup.py +++ b/setup.py @@ -18,29 +18,30 @@ # Use this version when git data are not available, like in git zip archive. # Update when tagging a new release. -FALLBACK_VERSION = '1.4.2' +FALLBACK_VERSION = "1.4.2" # determine if we run with Python 3. -PY3 = (sys.version_info[0] == 3) +PY3 = sys.version_info[0] == 3 # versioncfgfile holds version data for git commit hash and date. # It must reside in the same directory as version.py. MYDIR = os.path.dirname(os.path.abspath(__file__)) -versioncfgfile = os.path.join(MYDIR, 'diffpy/pdffit2/version.cfg') -gitarchivecfgfile = os.path.join(MYDIR, '.gitarchive.cfg') +versioncfgfile = os.path.join(MYDIR, "diffpy/pdffit2/version.cfg") +gitarchivecfgfile = os.path.join(MYDIR, ".gitarchive.cfg") def gitinfo(): from subprocess import Popen, PIPE, check_output + kw = dict(stdout=PIPE, cwd=MYDIR, universal_newlines=True) - proc = Popen(['git', 'describe', '--tags', '--match=[v,V,[:digit:]]*'], **kw) + proc = Popen(["git", "describe", "--tags", "--match=[v,V,[:digit:]]*"], **kw) desc = proc.stdout.read() - proc = Popen(['git', 'log', '-1', '--format=%H %ct %ci'], **kw) + proc = Popen(["git", "log", "-1", "--format=%H %ct %ci"], **kw) glog = proc.stdout.read() rv = {} - rv['commit'], rv['timestamp'], rv['date'] = glog.strip().split(None, 2) - version = '.post'.join(desc.strip().split('-')[:2]).lstrip('vV') - rv['version'] = version + rv["commit"], rv["timestamp"], rv["date"] = glog.strip().split(None, 2) + version = ".post".join(desc.strip().split("-")[:2]).lstrip("vV") + rv["version"] = version return rv @@ -49,19 +50,19 @@ def getversioncfg(): from configparser import RawConfigParser else: from ConfigParser import RawConfigParser - vd0 = dict(version=FALLBACK_VERSION, commit='', date='', timestamp=0) + vd0 = dict(version=FALLBACK_VERSION, commit="", date="", timestamp=0) # first fetch data from gitarchivecfgfile, ignore if it is unexpanded g = vd0.copy() cp0 = RawConfigParser(vd0) cp0.read(gitarchivecfgfile) - if len(cp0.get('DEFAULT', 'commit')) > 20: + if len(cp0.get("DEFAULT", "commit")) > 20: g = cp0.defaults() - mx = re.search(r'\btag: [vV]?(\d[^,]*)', g.pop('refnames')) + mx = re.search(r"\btag: [vV]?(\d[^,]*)", g.pop("refnames")) if mx: - g['version'] = mx.group(1) + g["version"] = mx.group(1) # then try to obtain version data from git. - gitdir = os.path.join(MYDIR, '.git') - if os.path.exists(gitdir) or 'GIT_DIR' in os.environ: + gitdir = os.path.join(MYDIR, ".git") + if os.path.exists(gitdir) or "GIT_DIR" in os.environ: try: g = gitinfo() except OSError: @@ -71,40 +72,39 @@ def getversioncfg(): cp = RawConfigParser() cp.read(versioncfgfile) d = cp.defaults() - rewrite = not d or (g['commit'] and ( - g['version'] != d.get('version') or g['commit'] != d.get('commit'))) + rewrite = not d or (g["commit"] and (g["version"] != d.get("version") or g["commit"] != d.get("commit"))) if rewrite: - cp.set('DEFAULT', 'version', g['version']) - cp.set('DEFAULT', 'commit', g['commit']) - cp.set('DEFAULT', 'date', g['date']) - cp.set('DEFAULT', 'timestamp', g['timestamp']) - with open(versioncfgfile, 'w') as fp: + cp.set("DEFAULT", "version", g["version"]) + cp.set("DEFAULT", "commit", g["commit"]) + cp.set("DEFAULT", "date", g["date"]) + cp.set("DEFAULT", "timestamp", g["timestamp"]) + with open(versioncfgfile, "w") as fp: cp.write(fp) return cp + versiondata = getversioncfg() # Helper functions ----------------------------------------------------------- + def get_compiler_type(): - """find compiler used for building extensions. - """ - cc_arg = [a for a in sys.argv if a.startswith('--compiler=')] + """find compiler used for building extensions.""" + cc_arg = [a for a in sys.argv if a.startswith("--compiler=")] if cc_arg: - compiler_type = cc_arg[-1].split('=', 1)[1] + compiler_type = cc_arg[-1].split("=", 1)[1] else: from distutils.ccompiler import new_compiler + compiler_type = new_compiler().compiler_type return compiler_type def get_gsl_config(): - '''Return dictionary with paths to GSL library. - ''' - gslcfgpaths = [os.path.join(p, 'gsl-config') - for p in ([MYDIR] + os.environ['PATH'].split(os.pathsep))] + """Return dictionary with paths to GSL library.""" + gslcfgpaths = [os.path.join(p, "gsl-config") for p in ([MYDIR] + os.environ["PATH"].split(os.pathsep))] gslcfgpaths = [p for p in gslcfgpaths if os.path.isfile(p)] - rv = {'include_dirs': [], 'library_dirs': []} + rv = {"include_dirs": [], "library_dirs": []} if not gslcfgpaths: wmsg = "Cannot find gsl-config in {!r} nor in system PATH." warnings.warn(wmsg.format(MYDIR)) @@ -112,41 +112,43 @@ def get_gsl_config(): gslcfg = gslcfgpaths[0] with open(gslcfg) as fp: txt = fp.read() - mprefix = re.search('(?m)^prefix=(.+)', txt) - minclude = re.search(r'(?m)^[^#]*\s-I(\S+)', txt) - mlibpath = re.search(r'(?m)^[^#]*\s-L(\S+)', txt) + mprefix = re.search("(?m)^prefix=(.+)", txt) + minclude = re.search(r"(?m)^[^#]*\s-I(\S+)", txt) + mlibpath = re.search(r"(?m)^[^#]*\s-L(\S+)", txt) if not mprefix: emsg = "Cannot find 'prefix=' line in {}." raise RuntimeError(emsg.format(gslcfg)) p = mprefix.group(1) - inc = minclude.group(1) if minclude else (p + '/include') - lib = mlibpath.group(1) if mlibpath else (p + '/lib') - rv['include_dirs'] += [inc] - rv['library_dirs'] += [lib] + inc = minclude.group(1) if minclude else (p + "/include") + lib = mlibpath.group(1) if mlibpath else (p + "/lib") + rv["include_dirs"] += [inc] + rv["library_dirs"] += [lib] return rv + def get_gsl_config_win(): - '''Return dictionary with paths to GSL library, windwows version. - This version is installed with conda. - ''' - conda_prefix = os.environ['CONDA_PREFIX'] - inc = os.path.join(conda_prefix, 'Library', 'include') - lib = os.path.join(conda_prefix, 'Library', 'lib') - rv = {'include_dirs': [], 'library_dirs': []} - rv['include_dirs'] += [inc] - rv['library_dirs'] += [lib] + """Return dictionary with paths to GSL library, windwows version. + This version is installed with conda. + """ + conda_prefix = os.environ["CONDA_PREFIX"] + inc = os.path.join(conda_prefix, "Library", "include") + lib = os.path.join(conda_prefix, "Library", "lib") + rv = {"include_dirs": [], "library_dirs": []} + rv["include_dirs"] += [inc] + rv["library_dirs"] += [lib] return rv + # ---------------------------------------------------------------------------- # compile and link options define_macros = [] os_name = os.name -if os_name == 'nt': +if os_name == "nt": gcfg = get_gsl_config_win() else: gcfg = get_gsl_config() -include_dirs = [MYDIR] + gcfg['include_dirs'] +include_dirs = [MYDIR] + gcfg["include_dirs"] library_dirs = [] libraries = [] extra_objects = [] @@ -155,102 +157,102 @@ def get_gsl_config_win(): compiler_type = get_compiler_type() if compiler_type in ("unix", "cygwin", "mingw32"): - extra_compile_args = ['-std=c++11', '-Wall', '-Wno-write-strings', - '-O3', '-funroll-loops', '-ffast-math'] - extra_objects += ((p + '/libgsl.a') for p in gcfg['library_dirs']) + extra_compile_args = ["-std=c++11", "-Wall", "-Wno-write-strings", "-O3", "-funroll-loops", "-ffast-math"] + extra_objects += ((p + "/libgsl.a") for p in gcfg["library_dirs"]) elif compiler_type == "msvc": - define_macros += [('_USE_MATH_DEFINES', None)] - extra_compile_args = ['/EHs'] - libraries += ['gsl'] - library_dirs += gcfg['library_dirs'] + define_macros += [("_USE_MATH_DEFINES", None)] + extra_compile_args = ["/EHs"] + libraries += ["gsl"] + library_dirs += gcfg["library_dirs"] # add optimization flags for other compilers if needed # define extension here -pdffit2module = Extension('diffpy.pdffit2.pdffit2', [ - 'pdffit2module/bindings.cc', - 'pdffit2module/misc.cc', - 'pdffit2module/pdffit2module.cc', - 'pdffit2module/pyexceptions.cc', - 'libpdffit2/Atom.cc', - 'libpdffit2/LocalPeriodicTable.cc', - 'libpdffit2/OutputStreams.cc', - 'libpdffit2/PeriodicTable.cc', - 'libpdffit2/PointsInSphere.cc', - 'libpdffit2/StringUtils.cc', - 'libpdffit2/fit.cc', - 'libpdffit2/gaussj.cc', - 'libpdffit2/metric.cc', - 'libpdffit2/nrutil.cc', - 'libpdffit2/output.cc', - 'libpdffit2/parser.cc', - 'libpdffit2/pdf.cc', - 'libpdffit2/pdffit.cc', - 'libpdffit2/pdflsmin.cc', - 'libpdffit2/scatlen.cc', - 'libpdffit2/stru.cc', - ], - include_dirs = include_dirs, - libraries = libraries, - library_dirs = library_dirs, - define_macros = define_macros, - extra_compile_args = extra_compile_args, - extra_link_args = extra_link_args, - extra_objects = extra_objects, +pdffit2module = Extension( + "diffpy.pdffit2.pdffit2", + [ + "pdffit2module/bindings.cc", + "pdffit2module/misc.cc", + "pdffit2module/pdffit2module.cc", + "pdffit2module/pyexceptions.cc", + "libpdffit2/Atom.cc", + "libpdffit2/LocalPeriodicTable.cc", + "libpdffit2/OutputStreams.cc", + "libpdffit2/PeriodicTable.cc", + "libpdffit2/PointsInSphere.cc", + "libpdffit2/StringUtils.cc", + "libpdffit2/fit.cc", + "libpdffit2/gaussj.cc", + "libpdffit2/metric.cc", + "libpdffit2/nrutil.cc", + "libpdffit2/output.cc", + "libpdffit2/parser.cc", + "libpdffit2/pdf.cc", + "libpdffit2/pdffit.cc", + "libpdffit2/pdflsmin.cc", + "libpdffit2/scatlen.cc", + "libpdffit2/stru.cc", + ], + include_dirs=include_dirs, + libraries=libraries, + library_dirs=library_dirs, + define_macros=define_macros, + extra_compile_args=extra_compile_args, + extra_link_args=extra_link_args, + extra_objects=extra_objects, ) -with open(os.path.join(MYDIR, 'README.rst')) as fp: +with open(os.path.join(MYDIR, "README.rst")) as fp: long_description = fp.read() # define distribution setup_args = dict( - name = 'diffpy.pdffit2', - version = versiondata.get('DEFAULT', 'version'), - packages = find_packages(), - test_suite = 'diffpy.pdffit2.tests', - ext_modules = [pdffit2module], - include_package_data = True, - install_requires = [ - 'six', - 'diffpy.structure>=3', + name="diffpy.pdffit2", + version=versiondata.get("DEFAULT", "version"), + packages=find_packages(), + test_suite="diffpy.pdffit2.tests", + ext_modules=[pdffit2module], + include_package_data=True, + install_requires=[ + "six", + "diffpy.structure>=3", ], - zip_safe = False, - - author = 'Simon J.L. Billinge', - author_email = 'sb2896@columbia.edu', - maintainer = 'Pavol Juhas', - maintainer_email = 'pavol.juhas@gmail.com', - url = 'https://github.com/diffpy/diffpy.pdffit2', - description = 'PDFfit2 - real space structure refinement program.', - long_description = long_description, - long_description_content_type = 'text/x-rst', - license = 'BSD', - keywords = 'PDF structure refinement', - classifiers = [ + zip_safe=False, + author="Simon J.L. Billinge", + author_email="sb2896@columbia.edu", + maintainer="Pavol Juhas", + maintainer_email="pavol.juhas@gmail.com", + url="https://github.com/diffpy/diffpy.pdffit2", + description="PDFfit2 - real space structure refinement program.", + long_description=long_description, + long_description_content_type="text/x-rst", + license="BSD", + keywords="PDF structure refinement", + classifiers=[ # List of possible values at # http://pypi.python.org/pypi?:action=list_classifiers - 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: BSD License', - 'Operating System :: MacOS', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: POSIX', - 'Programming Language :: C++', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'Topic :: Scientific/Engineering :: Chemistry', - 'Topic :: Scientific/Engineering :: Physics', + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: BSD License", + "Operating System :: MacOS", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Programming Language :: C++", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering :: Chemistry", + "Topic :: Scientific/Engineering :: Physics", ], ) -if __name__ == '__main__': +if __name__ == "__main__": setup(**setup_args) # End of file From ff5140df48b4b5873555200143e1ac42eb53e5e7 Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 11:45:18 -0400 Subject: [PATCH 6/8] Add flake8 config --- .flake8 | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .flake8 diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..076b9924 --- /dev/null +++ b/.flake8 @@ -0,0 +1,11 @@ +[flake8] +exclude = + .git, + __pycache__, + build, + dist, + doc/source/conf.py +max-line-length = 115 +# Ignore some style 'errors' produced while formatting by 'black' +# https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#labels-why-pycodestyle-warnings +extend-ignore = E203 \ No newline at end of file From 7d76d7dac6c324f70bc038151fbe17a37daf3e08 Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 11:56:13 -0400 Subject: [PATCH 7/8] flake8 fixes --- diffpy/pdffit2/pdffit.py | 4 ++-- diffpy/pdffit2/tests/TestPdfFit.py | 5 ++--- diffpy/pdffit2/tests/TestPhaseFractions.py | 3 +-- diffpy/pdffit2/tests/run.py | 3 ++- examples/Ni_plot_pdf.py | 3 +-- examples/Ni_refinement.py | 4 ++-- setup.py | 2 +- 7 files changed, 11 insertions(+), 13 deletions(-) diff --git a/diffpy/pdffit2/pdffit.py b/diffpy/pdffit2/pdffit.py index e39b6694..cb4f82c9 100644 --- a/diffpy/pdffit2/pdffit.py +++ b/diffpy/pdffit2/pdffit.py @@ -29,6 +29,7 @@ from diffpy.pdffit2 import pdffit2 from diffpy.pdffit2 import output + # helper routines @@ -147,7 +148,7 @@ def intro(): date = __date__[:10] d = {"version": __version__, "date": date, "year": date[:4] or "2019"} msg = __intro_message__ % d - filler = lambda mx: (mx.group(0).rstrip(" *").ljust(77) + "*") + def filler(mx): return mx.group(0).rstrip(" *").ljust(77) + "*" msg_ljust = re.sub("(?m)^(.{1,77}|.{79}.*)$", filler, msg) print(msg_ljust, file=output.stdout) return @@ -1287,7 +1288,6 @@ def __getRef(self, var_string): retval = f(self._handle, arg_int) return retval - # End of class PdfFit diff --git a/diffpy/pdffit2/tests/TestPdfFit.py b/diffpy/pdffit2/tests/TestPdfFit.py index 8102b8b9..43dd2085 100644 --- a/diffpy/pdffit2/tests/TestPdfFit.py +++ b/diffpy/pdffit2/tests/TestPdfFit.py @@ -3,7 +3,6 @@ """Unit tests for PdfFit.py """ - import unittest from diffpy.structure import loadStructure @@ -12,11 +11,11 @@ from diffpy.pdffit2 import pdffit2 from diffpy.pdffit2.tests.pdffit2testutils import datafile, capture_output + # ---------------------------------------------------------------------------- class TestPdfFit(unittest.TestCase): - places = 6 def setUp(self): @@ -291,7 +290,7 @@ def test_num_datasets(self): # failed data should not increase num_datasets try: self.P.read_data(datafile("badNi.dat")) - except: + except (ValueError, IOError): pass self.assertEqual(1, self.P.num_datasets()) # alloc should increase number of datasets diff --git a/diffpy/pdffit2/tests/TestPhaseFractions.py b/diffpy/pdffit2/tests/TestPhaseFractions.py index 2bbebf76..0b90a703 100644 --- a/diffpy/pdffit2/tests/TestPhaseFractions.py +++ b/diffpy/pdffit2/tests/TestPhaseFractions.py @@ -3,15 +3,14 @@ """Unit tests for phase fraction calculations. """ - import unittest from diffpy.pdffit2 import PdfFit from diffpy.pdffit2.tests.pdffit2testutils import datafile + ############################################################################## class TestPhaseFractions(unittest.TestCase): - places = 4 def setUp(self): diff --git a/diffpy/pdffit2/tests/run.py b/diffpy/pdffit2/tests/run.py index 7eb6aadd..790e018d 100644 --- a/diffpy/pdffit2/tests/run.py +++ b/diffpy/pdffit2/tests/run.py @@ -24,7 +24,8 @@ # show warnings by default if not sys.warnoptions: - import os, warnings + import os + import warnings warnings.simplefilter("default") # also affect subprocesses diff --git a/examples/Ni_plot_pdf.py b/examples/Ni_plot_pdf.py index 9b1fd4ad..1f8cb97d 100755 --- a/examples/Ni_plot_pdf.py +++ b/examples/Ni_plot_pdf.py @@ -5,6 +5,7 @@ """ from diffpy.pdffit2 import PdfFit +import pylab # create new PDF calculator object P = PdfFit() @@ -28,8 +29,6 @@ G = P.getpdf_fit() # pylab is matplotlib interface with MATLAB-like plotting commands -import pylab - pylab.plot(r, G) pylab.xlabel(u"r (Å)") pylab.ylabel(u"G (Å$^{-2}$)") diff --git a/examples/Ni_refinement.py b/examples/Ni_refinement.py index 2a467cde..11f6f1ec 100755 --- a/examples/Ni_refinement.py +++ b/examples/Ni_refinement.py @@ -6,6 +6,8 @@ """ from diffpy.pdffit2 import PdfFit +import pylab + # Create new PDF calculator object. pf = PdfFit() @@ -64,8 +66,6 @@ # Plot results --------------------------------------------------------------- # pylab is matplotlib interface with MATLAB-like plotting commands -import pylab - # obtain data from PdfFit calculator object r = pf.getR() Gobs = pf.getpdf_obs() diff --git a/setup.py b/setup.py index 70e6c6d5..6a32d3b1 100755 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ def gitinfo(): - from subprocess import Popen, PIPE, check_output + from subprocess import Popen, PIPE kw = dict(stdout=PIPE, cwd=MYDIR, universal_newlines=True) proc = Popen(["git", "describe", "--tags", "--match=[v,V,[:digit:]]*"], **kw) From db1e93630a83e20ea276803988792150fd24c798 Mon Sep 17 00:00:00 2001 From: Sam Andrello Date: Tue, 16 Jul 2024 12:14:06 -0400 Subject: [PATCH 8/8] add further error catching to test_num_datasets --- diffpy/pdffit2/tests/TestPdfFit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diffpy/pdffit2/tests/TestPdfFit.py b/diffpy/pdffit2/tests/TestPdfFit.py index 43dd2085..0a7e944c 100644 --- a/diffpy/pdffit2/tests/TestPdfFit.py +++ b/diffpy/pdffit2/tests/TestPdfFit.py @@ -290,7 +290,7 @@ def test_num_datasets(self): # failed data should not increase num_datasets try: self.P.read_data(datafile("badNi.dat")) - except (ValueError, IOError): + except (RuntimeError, TypeError, NameError, ValueError, IOError): pass self.assertEqual(1, self.P.num_datasets()) # alloc should increase number of datasets