Changes in / [61f8638:56b2687] in sasmodels
- Files:
-
- 4 added
- 4 deleted
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
README.rst
r9fb92a0 r84bc3c1 53 53 in the same data set. 54 54 55 `Travis-CI Build Status <https://travis-ci.org/SasView/sasmodels.svg?branch=master)](https://travis-ci.org/SasView/sasmodels>`_ 55 |TravisStatus|_ 56 57 .. |TravisStatus| image:: https://travis-ci.org/SasView/sasmodels.svg?branch=master 58 .. _TravisStatus: https://travis-ci.org/SasView/sasmodels -
sascomp
ra78bebc r6708a6a 4 4 import os 5 5 import glob 6 import logging 7 logging.basicConfig(level=logging.INFO) 6 8 7 9 def main(): 8 10 sasmodels = os.path.dirname(os.path.realpath(__file__)) 9 11 root = os.path.dirname(sasmodels) 10 sasview=glob.glob(os.path.join(root, 'sasview', 'build', 'lib .*' ))12 sasview=glob.glob(os.path.join(root, 'sasview', 'build', 'lib*' )) 11 13 sys.path.insert(0, os.path.join(root, 'bumps')) 12 14 sys.path.insert(0, os.path.join(root, 'periodictable')) 15 sys.path.insert(0, os.path.join(root, 'tinycc', 'build', 'lib')) 13 16 if sasview: # glob returns a list 14 17 sys.path.insert(0, sasview[0]) -
sasmodels/__init__.py
rc2c51a2 r59d94b3 24 24 """ 25 25 from os.path import join as joinpath 26 from .generate import SIBLING_DIR, DATA_PATH 27 data_files = {} 28 def add_patterns(path, patterns): 29 data_files[joinpath(SIBLING_DIR, *path)] \ 30 = [joinpath(DATA_PATH, *(path+[p])) for p in patterns] 31 add_patterns([], ['*.c', '*.cl', 'convert.json']) 32 add_patterns(['models'], ['*.c']) 33 add_patterns(['models', 'lib'], ['*.c']) 26 import glob 34 27 35 return data_files28 from .generate import EXTERNAL_DIR, DATA_PATH 36 29 30 def expand_patterns(path, patterns): 31 target_path = joinpath(EXTERNAL_DIR, *path) 32 source_path = joinpath(DATA_PATH, *path) 33 files = [] 34 for p in patterns: 35 files.extend(glob.glob(joinpath(source_path, p))) 36 return target_path, files 37 38 # Place the source for the model tree in the distribution. Minimally we 39 # need the c and cl files for running on OpenCL. Need the py files so 40 # users can easily copy existing models. Need the img files so that we 41 # can build model docs on the fly, including images. 42 return_list = [ 43 expand_patterns([], ['*.c', '*.cl', 'convert.json']), 44 expand_patterns(['models'], ['*.py', '*.c']), 45 expand_patterns(['models', 'lib'], ['*.c']), 46 expand_patterns(['models', 'img'], ['*.*']), 47 ] 48 return return_list 49 50 -
sasmodels/core.py
r7bf4757 rf5dde3f 34 34 pass 35 35 36 try: 37 np.meshgrid([]) 38 meshgrid = np.meshgrid 39 except Exception: 40 # CRUFT: np.meshgrid requires multiple vectors 41 def meshgrid(*args): 42 if len(args) > 1: 43 return np.meshgrid(*args) 44 else: 45 return [np.asarray(v) for v in args] 36 46 37 47 # TODO: refactor composite model support -
sasmodels/custom/__init__.py
r7ae2b7f r4bfbca2 25 25 def load_module_from_path(fullname, path): 26 26 module = imp.load_source(fullname, path) 27 os.unlink(path+"c") # remove the automatic pyc file27 #os.unlink(path+"c") # remove the automatic pyc file 28 28 return module 29 29 -
sasmodels/data.py
re78edc4 r4e00c13 62 62 Add a beam stop of the given *radius*. If *outer*, make an annulus. 63 63 """ 64 from sas. dataloader.manipulations import Ringcut # type: ignore64 from sas.sascalc.dataloader.manipulations import Ringcut 65 65 if hasattr(data, 'qx_data'): 66 66 data.mask = Ringcut(0, radius)(data) … … 78 78 Select half of the data, either "right" or "left". 79 79 """ 80 from sas. dataloader.manipulations import Boxcut # type: ignore80 from sas.sascalc.dataloader.manipulations import Boxcut 81 81 if half == 'right': 82 82 data.mask += \ … … 92 92 Chop the top off the data, above *cutoff*. 93 93 """ 94 from sas. dataloader.manipulations import Boxcut # type: ignore94 from sas.sascalc.dataloader.manipulations import Boxcut 95 95 data.mask += \ 96 96 Boxcut(x_min=-np.inf, x_max=np.inf, y_min=-np.inf, y_max=cutoff)(data) -
sasmodels/direct_model.py
r0ff62d4 r4d8e0bb 133 133 134 134 if self.data_type == 'sesans': 135 136 135 q = sesans.make_q(data.sample.zacceptance, data.Rmax) 137 136 index = slice(None, None) … … 180 179 and getattr(data, 'dxw', None) is not None): 181 180 res = resolution.Slit1D(data.x[index], 182 qx_width=data.dx w[index],183 qy_width=data.dx l[index])181 qx_width=data.dxl[index], 182 qy_width=data.dxw[index]) 184 183 else: 185 184 res = resolution.Perfect1D(data.x[index]) -
sasmodels/generate.py
rc2c51a2 r001d9f5 179 179 pass 180 180 181 SIBLING_DIR = 'sasmodels-data' 182 PACKAGE_PATH = abspath(dirname(__file__)) 183 SIBLING_PATH = abspath(joinpath(PACKAGE_PATH, '..', 'sasmodels-data')) 184 DATA_PATH = SIBLING_PATH if isdir(SIBLING_PATH) else PACKAGE_PATH 181 def get_data_path(external_dir, target_file): 182 path = abspath(dirname(__file__)) 183 if exists(joinpath(path, target_file)): 184 return path 185 186 # check next to exe/zip file 187 exepath = dirname(sys.executable) 188 path = joinpath(exepath, external_dir) 189 if exists(joinpath(path, target_file)): 190 return path 191 192 # check in py2app Contents/Resources 193 path = joinpath(exepath, '..', 'Resources', external_dir) 194 if exists(joinpath(path, target_file)): 195 return abspath(path) 196 197 raise RuntimeError('Could not find '+joinpath(external_dir, target_file)) 198 199 EXTERNAL_DIR = 'sasmodels-data' 200 DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_template.c') 185 201 MODEL_PATH = joinpath(DATA_PATH, 'models') 186 202 … … 657 673 658 674 675 def make_html(model_info): 676 """ 677 Convert model docs directly to html. 678 """ 679 from . import rst2html 680 return rst2html.convert(make_doc(model_info), title=model_info['name']) 681 659 682 def demo_time(): 660 683 # type: () -> None -
sasmodels/kernel_template.c
r3832f27 r5efe850 12 12 // Note: if using a C++ compiler, then define kernel as extern "C" 13 13 #ifndef USE_OPENCL 14 // Use SAS_DOUBLE to force the use of double even for float kernels 15 # define SAS_DOUBLE dou ## ble 14 16 # ifdef __cplusplus 15 17 #include <cstdio> … … 38 40 #if defined(__TINYC__) 39 41 #include <math.h> 40 inline double trunc(double x) { return x>=0?floor(x):-floor(-x); }41 inline double fmin(double x, double y) { return x>y ? y : x; }42 inline double fmax(double x, double y) { return x<y ? y : x; }43 42 // TODO: test isnan 44 43 inline double _isnan(double x) { return x != x; } // hope this doesn't optimize away! 45 44 #undef isnan 46 45 #define isnan(x) _isnan(x) 46 // Defeat the double->float conversion since we don't have tgmath 47 inline SAS_DOUBLE trunc(SAS_DOUBLE x) { return x>=0?floor(x):-floor(-x); } 48 inline SAS_DOUBLE fmin(SAS_DOUBLE x, SAS_DOUBLE y) { return x>y ? y : x; } 49 inline SAS_DOUBLE fmax(SAS_DOUBLE x, SAS_DOUBLE y) { return x<y ? y : x; } 47 50 #define NEED_EXPM1 48 51 #define NEED_TGAMMA … … 70 73 71 74 #if defined(NEED_EXPM1) 72 static double expm1(double x) { 75 static SAS_DOUBLE expm1(SAS_DOUBLE x_in) { 76 double x = (double)x_in; // go back to float for single precision kernels 73 77 // Adapted from the cephes math library. 74 78 // Copyright 1984 - 1992 by Stephen L. Moshier -
sasmodels/kernelcl.py
rae2b6b5 r197e41d 52 52 import os 53 53 import warnings 54 import logging 54 55 55 56 import numpy as np # type: ignore … … 60 61 # Ask OpenCL for the default context so that we know that one exists 61 62 cl.create_some_context(interactive=False) 62 except Exception as ocl_exc: 63 warnings.warn(str(ocl_exc)) 64 del ocl_exc 63 except Exception as exc: 64 warnings.warn("OpenCL startup failed with ***"+str(exc)+"***; using C compiler instead") 65 65 raise RuntimeError("OpenCL not available") 66 66 67 67 from pyopencl import mem_flags as mf # type: ignore 68 68 from pyopencl.characterize import get_fast_inaccurate_build_options # type: ignore 69 # CRUFT: pyopencl < 2017.1 (as of June 2016 needs quotes around include path) 70 def _quote_path(v): 71 """ 72 Quote the path if it is not already quoted. 73 74 If v starts with '-', then assume that it is a -I option or similar 75 and do not quote it. This is fragile: -Ipath with space needs to 76 be quoted. 77 """ 78 return '"'+v+'"' if v and ' ' in v and not v[0] in "\"'-" else v 79 80 if hasattr(cl, '_DEFAULT_INCLUDE_OPTIONS'): 81 cl._DEFAULT_INCLUDE_OPTIONS = [_quote_path(v) for v in cl._DEFAULT_INCLUDE_OPTIONS] 82 83 from pyopencl import mem_flags as mf 84 from pyopencl.characterize import get_fast_inaccurate_build_options 69 85 70 86 from . import generate … … 188 204 source = "\n".join(source_list) 189 205 program = cl.Program(context, source).build(options=options) 206 #print("done with "+program) 190 207 return program 191 208 … … 262 279 Compile the program for the device in the given context. 263 280 """ 264 key = "%s-%s -%s"%(name, dtype, fast)281 key = "%s-%s%s"%(name, dtype, ("-fast" if fast else "")) 265 282 if key not in self.compiled: 283 context = self.get_context(dtype) 284 logging.info("building %s for OpenCL %s" 285 % (key, context.devices[0].name.strip())) 286 program = compile_model(context, source, np.dtype(dtype), fast) 266 287 #print("OpenCL compile",name) 267 288 dtype = np.dtype(dtype) -
sasmodels/kerneldll.py
r5a91c6b r15e74ad 49 49 import os 50 50 from os.path import join as joinpath, split as splitpath, splitext 51 import subprocess 51 52 import tempfile 52 53 import ctypes as ct # type: ignore 53 54 from ctypes import c_void_p, c_int32, c_longdouble, c_double, c_float # type: ignore 55 import logging 54 56 55 57 import numpy as np # type: ignore … … 68 70 pass 69 71 70 # Compiler platform details 71 if sys.platform == 'darwin': 72 #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" 73 COMPILE = "gcc -shared -fPIC -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" 74 elif os.name == 'nt': 72 if os.name == 'nt': 73 ARCH = "" if sys.maxint > 2**32 else "x86" # maxint=2**31-1 on 32 bit 74 # Windows compiler; check if TinyCC is available 75 try: 76 import tinycc 77 except ImportError: 78 tinycc = None 75 79 # call vcvarsall.bat before compiling to set path, headers, libs, etc. 76 80 if "VCINSTALLDIR" in os.environ: … … 81 85 # TODO: remove intermediate OBJ file created in the directory 82 86 # TODO: maybe don't use randomized name for the c file 83 CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG /Tp%(source)s "84 LN = "/link /DLL /INCREMENTAL:NO /MANIFEST /OUT:%(output)s"87 # TODO: maybe ask distutils to find MSVC 88 CC = "cl /nologo /Ox /MD /W3 /GS- /DNDEBUG".split() 85 89 if "SAS_OPENMP" in os.environ: 86 COMPILE = " ".join((CC, "/openmp", LN)) 87 else: 88 COMPILE = " ".join((CC, LN)) 89 elif True: 90 # If MSVC compiler is not available, try using mingw 91 # fPIC is not needed on windows 92 COMPILE = "gcc -shared -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" 90 CC.append("/openmp") 91 LN = "/link /DLL /INCREMENTAL:NO /MANIFEST".split() 92 def compile_command(source, output): 93 return CC + ["/Tp%s"%source] + LN + ["/OUT:%s"%output] 94 elif tinycc: 95 # TinyCC compiler. 96 CC = [tinycc.TCC] + "-shared -rdynamic -Wall".split() 97 def compile_command(source, output): 98 return CC + [source, "-o", output] 99 else: 100 # MinGW compiler. 101 CC = "gcc -shared -std=c99 -O2 -Wall".split() 93 102 if "SAS_OPENMP" in os.environ: 94 COMPILE += " -fopenmp" 95 else: 96 # If MSVC compiler is not available, try using tinycc 97 from tinycc import TCC 98 COMPILE = TCC + " -shared -rdynamic -Wall %(source)s -o %(output)s" 103 CC.append("-fopenmp") 104 def compile_command(source, output): 105 return CC + [source, "-o", output, "-lm"] 99 106 else: 100 COMPILE = "cc -shared -fPIC -fopenmp -std=c99 -O2 -Wall %(source)s -o %(output)s -lm" 107 ARCH = "" 108 # Generic unix compile 109 # On mac users will need the X code command line tools installed 110 #COMPILE = "gcc-mp-4.7 -shared -fPIC -std=c99 -fopenmp -O2 -Wall %s -o %s -lm -lgomp" 111 CC = "cc -shared -fPIC -std=c99 -O2 -Wall".split() 112 # add openmp support if not running on a mac 113 if sys.platform != "darwin": 114 CC.append("-fopenmp") 115 def compile_command(source, output): 116 return CC + [source, "-o", output, "-lm"] 101 117 102 118 # Windows-specific solution … … 112 128 ALLOW_SINGLE_PRECISION_DLLS = True 113 129 130 def compile(source, output): 131 command = compile_command(source=source, output=output) 132 command_str = " ".join('"%s"'%p if ' ' in p else p for p in command) 133 logging.info(command_str) 134 try: 135 # need shell=True on windows to keep console box from popping up 136 shell = (os.name == 'nt') 137 subprocess.check_output(command, shell=shell, stderr=subprocess.STDOUT) 138 except subprocess.CalledProcessError as exc: 139 raise RuntimeError("compile failed.\n%s\n%s"%(command_str, exc.output)) 140 if not os.path.exists(output): 141 raise RuntimeError("compile failed. File is in %r"%source) 114 142 115 143 def dll_name(model_info, dtype): … … 120 148 """ 121 149 bits = 8*dtype.itemsize 122 return "sas%d_%s"%(bits, model_info.id) 150 basename = "sas%d_%s"%(bits, model_info.id) 151 basename += ARCH + ".so" 152 153 # Hack to find precompiled dlls 154 path = joinpath(generate.DATA_PATH, '..', 'compiled_models', basename) 155 if os.path.exists(path): 156 return path 157 158 return joinpath(DLL_PATH, basename) 123 159 124 160 … … 161 197 if not os.path.exists(dll): 162 198 need_recompile = True 163 elif getattr(sys, 'frozen', False):199 elif getattr(sys, 'frozen', None) is not None: 164 200 # TODO: don't suppress time stamp 165 201 # Currently suppressing recompile when running in a frozen environment … … 173 209 fid, filename = tempfile.mkstemp(suffix=".c", prefix=basename) 174 210 source = generate.convert_type(source, dtype) 175 os.fdopen(fid, "w").write(source)176 command = COMPILE%{"source":filename, "output":dll}177 status = os.system(command)178 if status != 0 or not os.path.exists(dll):179 raise RuntimeError("compile failed. File is in %r"%filename)180 else:181 ## comment the following to keep the generated c file182 183 211 fd, filename = tempfile.mkstemp(suffix=".c", prefix=tempfile_prefix) 212 with os.fdopen(fd, "w") as file: 213 file.write(source) 214 compile(source=filename, output=dll) 215 # comment the following to keep the generated c file 216 # Note: if there is a syntax error then compile raises an error 217 # and the source file will not be deleted. 218 os.unlink(filename) 219 #print("saving compiled file in %r"%filename) 184 220 return dll 185 221 -
sasmodels/models/core_shell_parallelepiped.py
rec45c4f r500128b 6 6 can be different on all three (pairs) of faces.** 7 7 8 The form factor is normalized by the particle volume *V*such that8 The form factor is normalized by the particle volume $V$ such that 9 9 10 *I(q)* = *scale* \* <*f*\ :sup:`2`> / *V* + *background* 10 .. math:: 11 11 12 where < > is an average over all possible orientations of the rectangular solid. 12 I(q) = \text{scale}\frac{\langle f^2 \rangle}{V} + \text{background} 13 14 where $\langle \ldots \rangle$ is an average over all possible orientations 15 of the rectangular solid. 13 16 14 17 An instrument resolution smeared version of the model is also provided. … … 19 22 20 23 The function calculated is the form factor of the rectangular solid below. 21 The core of the solid is defined by the dimensions *A*, *B*, *C*such that22 *A* < *B* < *C*.24 The core of the solid is defined by the dimensions $A$, $B$, $C$ such that 25 $A < B < C$. 23 26 24 27 .. image:: img/core_shell_parallelepiped_geometry.jpg 25 28 26 There are rectangular "slabs" of thickness $t_A$ that add to the *A*dimension27 (on the *BC* faces). There are similar slabs on the *AC* $(=t_B)$ and *AB*28 $(=t_C)$ faces. The projection in the *AB*plane is then29 There are rectangular "slabs" of thickness $t_A$ that add to the $A$ dimension 30 (on the $BC$ faces). There are similar slabs on the $AC$ $(=t_B)$ and $AB$ 31 $(=t_C)$ faces. The projection in the $AB$ plane is then 29 32 30 33 .. image:: img/core_shell_parallelepiped_projection.jpg … … 43 46 44 47 **For the calculation of the form factor to be valid, the sides of the solid 45 MUST be chosen such that** *A* < *B* < *C*.48 MUST be chosen such that** $A < B < C$. 46 49 **If this inequality is not satisfied, the model will not report an error, 47 50 and the calculation will not be correct.** … … 49 52 FITTING NOTES 50 53 If the scale is set equal to the particle volume fraction, |phi|, the returned 51 value is the scattered intensity per unit volume ; ie, *I(q)* = |phi| *P(q)*.54 value is the scattered intensity per unit volume, $I(q) = \phi P(q)$. 52 55 However, **no interparticle interference effects are included in this calculation.** 53 56 … … 56 59 57 60 Constraints must be applied during fitting to ensure that the inequality 58 *A* < *B* < *C*is not violated. The calculation will not report an error,61 $A < B < C$ is not violated. The calculation will not report an error, 59 62 but the results will not be correct. 60 63 … … 64 67 based on the the averaged effective radius $(=\sqrt{(A+2t_A)(B+2t_B)/\pi})$ 65 68 and length $(C+2t_C)$ values, and used as the effective radius 66 for *S(Q)* when *P(Q)* \* *S(Q)*is applied.69 for $S(Q)$ when $P(Q) * S(Q)$ is applied. 67 70 68 71 .. Comment by Miguel Gonzalez: … … 71 74 72 75 To provide easy access to the orientation of the parallelepiped, we define the 73 axis of the cylinder using three angles |theta|, |phi| and |bigpsi|.76 axis of the cylinder using three angles $\theta$, $\phi$ and $\Psi$. 74 77 (see :ref:`cylinder orientation <cylinder-angle-definition>`). 75 The angle |bigpsi|is the rotational angle around the *long_c* axis against the76 *q* plane. For example, |bigpsi| = 0when the *short_b* axis is parallel to the78 The angle $\Psi$ is the rotational angle around the *long_c* axis against the 79 $q$ plane. For example, $\Psi = 0$ when the *short_b* axis is parallel to the 77 80 *x*-axis of the detector. 78 81 -
sasmodels/models/hollow_rectangular_prism.py
rec45c4f r117090a 3 3 r""" 4 4 5 This model provides the form factor, *P(q)*, for a hollow rectangular6 parallelepiped with a wall of thickness |bigdelta|.5 This model provides the form factor, $P(q)$, for a hollow rectangular 6 parallelepiped with a wall of thickness $\Delta$. 7 7 It computes only the 1D scattering, not the 2D. 8 8 … … 24 24 \int_0^{\frac{\pi}{2}} A_{P\Delta}^2(q) \, \sin\theta \, d\theta \, d\phi 25 25 26 where |theta| is the angle between the *z*axis and the longest axis27 of the parallelepiped, |phi|is the angle between the scattering vector28 (lying in the *xy* plane) and the *y*axis, and26 where $\theta$ is the angle between the $z$ axis and the longest axis 27 of the parallelepiped, $\phi$ is the angle between the scattering vector 28 (lying in the $xy$ plane) and the $y$ axis, and 29 29 30 30 .. math:: … … 49 49 \end{align} 50 50 51 where *A*, *B* and *C*are the external sides of the parallelepiped fulfilling52 :math:`A \le B \le C`, and the volume *V*of the parallelepiped is51 where $A$, $B$ and $C$ are the external sides of the parallelepiped fulfilling 52 $A \le B \le C$, and the volume $V$ of the parallelepiped is 53 53 54 54 .. math:: … … 58 58 59 59 .. math:: 60 I(q) = \ mbox{scale} \times V \times (\rho_{\mbox{p}} -61 \rho_{\ mbox{solvent}})^2 \times P(q)60 I(q) = \text{scale} \times V \times (\rho_{\text{p}} - 61 \rho_{\text{solvent}})^2 \times P(q) + \text{background} 62 62 63 where :math:`\rho_{\mbox{p}}`is the scattering length of the parallelepiped,64 :math:`\rho_{\mbox{solvent}}`is the scattering length of the solvent,63 where $\rho_{\text{p}}$ is the scattering length of the parallelepiped, 64 $\rho_{\text{solvent}}$ is the scattering length of the solvent, 65 65 and (if the data are in absolute units) *scale* represents the volume fraction 66 66 (which is unitless). -
sasmodels/models/lamellar.py
rd2bb604 r500128b 9 9 .. math:: 10 10 11 I(q) = scale*\frac{2\pi P(q)}{q^2\delta}11 I(q) = \text{scale}\frac{2\pi P(q)}{q^2\delta} + \text{background} 12 12 13 13 … … 16 16 .. math:: 17 17 18 P(q) = \frac{2\Delta\rho^2}{q^2}(1-cos(q\delta)) = \frac{4\Delta\rho^2}{q^2}sin^2(\frac{q\delta}{2}) 18 P(q) = \frac{2\Delta\rho^2}{q^2}(1-\cos(q\delta)) 19 = \frac{4\Delta\rho^2}{q^2}\sin^2\left(\frac{q\delta}{2}\right) 19 20 20 21 where $\delta$ is the total layer thickness and $\Delta\rho$ is the scattering length density difference. -
sasmodels/models/sc_paracrystal.py
rec45c4f r500128b 13 13 .. math:: 14 14 15 I(q) = \ frac{scale}{V_p}V_{lattice}P(q)Z(q)15 I(q) = \text{scale}\frac{V_\text{lattice}P(q)Z(q)}{V_p} + \text{background} 16 16 17 17 where scale is the volume fraction of spheres, $V_p$ is the volume of 18 the primary particle, $V_ {lattice}$ is a volume correction for the crystal18 the primary particle, $V_\text{lattice}$ is a volume correction for the crystal 19 19 structure, $P(q)$ is the form factor of the sphere (normalized), and 20 20 $Z(q)$ is the paracrystalline structure factor for a simple cubic structure. … … 28 28 .. math:: 29 29 30 V_ {lattice}=\frac{4\pi}{3}\frac{R^3}{D^3}30 V_\text{lattice}=\frac{4\pi}{3}\frac{R^3}{D^3} 31 31 32 32 The distortion factor (one standard deviation) of the paracrystal is included -
sasmodels/models/squarewell.py
rd2bb604 raa9e4e3 14 14 The interaction potential is: 15 15 16 .. image:: img \squarewell.png16 .. image:: img/squarewell.png 17 17 18 18 .. math:: -
sasmodels/sasview_model.py
rf36c1b7 rfa800e72 5 5 create a sasview model class to run that kernel as follows:: 6 6 7 from sasmodels.sasview_model import make_class 8 from sasmodels.models import cylinder 9 CylinderModel = make_class(cylinder, dtype='single') 10 11 The model parameters for sasmodels are different from those in sasview. 12 When reloading previously saved models, the parameters should be converted 13 using :func:`sasmodels.convert.convert`. 7 from sasmodels.sasview_model import load_custom_model 8 CylinderModel = load_custom_model('sasmodels/models/cylinder.py') 14 9 """ 15 10 from __future__ import print_function … … 49 44 ) 50 45 46 MODELS = {} 47 def find_model(modelname): 48 # TODO: used by sum/product model to load an existing model 49 # TODO: doesn't handle custom models properly 50 if modelname.endswith('.py'): 51 return load_custom_model(modelname) 52 elif modelname in MODELS: 53 return MODELS[modelname] 54 else: 55 raise ValueError("unknown model %r"%modelname) 56 57 51 58 # TODO: figure out how to say that the return type is a subclass 52 59 def load_standard_models(): … … 61 68 for name in core.list_models(): 62 69 try: 63 models.append(_make_standard_model(name)) 70 MODELS[name] = _make_standard_model(name) 71 models.append(MODELS[name]) 64 72 except Exception: 65 73 logging.error(traceback.format_exc()) … … 72 80 Load a custom model given the model path. 73 81 """ 82 #print("load custom model", path) 74 83 kernel_module = custom.load_custom_kernel_module(path) 75 model_info = modelinfo.make_model_info(kernel_module) 76 return _make_model_from_info(model_info) 84 try: 85 model = kernel_module.Model 86 except AttributeError: 87 model_info = modelinfo.make_model_info(kernel_module) 88 model = _make_model_from_info(model_info) 89 MODELS[model.name] = model 90 return model 77 91 78 92 … … 254 268 self._persistency_dict = {} 255 269 self.params = collections.OrderedDict() 256 self.dispersion = {}270 self.dispersion = collections.OrderedDict() 257 271 self.details = {} 258 272 for p in self._model_info.parameters.user_parameters(): … … 300 314 :param par_name: the parameter name to check 301 315 """ 302 return par_name .lower()in self.fixed316 return par_name in self.fixed 303 317 #For the future 304 318 #return self.params[str(par_name)].is_fittable() … … 337 351 if len(toks) == 2: 338 352 for item in self.dispersion.keys(): 339 if item .lower() == toks[0].lower():353 if item == toks[0]: 340 354 for par in self.dispersion[item]: 341 if par .lower() == toks[1].lower():355 if par == toks[1]: 342 356 self.dispersion[item][par] = value 343 357 return … … 345 359 # Look for standard parameter 346 360 for item in self.params.keys(): 347 if item .lower() == name.lower():361 if item == name: 348 362 self.params[item] = value 349 363 return … … 363 377 if len(toks) == 2: 364 378 for item in self.dispersion.keys(): 365 if item .lower() == toks[0].lower():379 if item == toks[0]: 366 380 for par in self.dispersion[item]: 367 if par .lower() == toks[1].lower():381 if par == toks[1]: 368 382 return self.dispersion[item][par] 369 383 else: 370 384 # Look for standard parameter 371 385 for item in self.params.keys(): 372 if item .lower() == name.lower():386 if item == name: 373 387 return self.params[item] 374 388 … … 391 405 """ 392 406 # TODO: fix test so that parameter order doesn't matter 393 ret = ['%s.%s' % (p.name .lower(), ext)407 ret = ['%s.%s' % (p.name, ext) 394 408 for p in self._model_info.parameters.user_parameters() 395 409 for ext in ('npts', 'nsigmas', 'width') … … 544 558 :param dispersion: dispersion object of type Dispersion 545 559 """ 546 if parameter .lower() in (s.lower() for s in self.params.keys()):560 if parameter in self.params: 547 561 # TODO: Store the disperser object directly in the model. 548 # The current method of creating one on the fly whenever it is549 # neededis kind of funky.562 # The current method of relying on the sasview GUI to 563 # remember them is kind of funky. 550 564 # Note: can't seem to get disperser parameters from sasview 551 565 # (1) Could create a sasview model that has not yet # been -
sasmodels/weights.py
ra936688 rfa800e72 205 205 v, w = obj.get_weights(value, limits[0], limits[1], relative) 206 206 return v, w 207 208 # Hack to allow sasview dispersion objects to interoperate with sasmodels209 dispersers = dict((v.__name__, k) for k, v in MODELS.items())210 dispersers['DispersionModel'] = RectangleDispersion.type211 -
setup.py
re9d10a6 r3a161d0 21 21 version=find_version('sasmodels'), 22 22 description="sasmodels package", 23 long_description=open('README. md').read(),23 long_description=open('README.rst').read(), 24 24 author="SasView Collaboration", 25 25 author_email="management@sasview.org",
Note: See TracChangeset
for help on using the changeset viewer.