Changeset 5a81885 in sasview
- Timestamp:
-
Sep 26, 2017 5:18:30 PM
(7 years ago)
- Author:
- Paul Kienzle <pkienzle@…>
- Branches:
- master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
- Children:
- b916afa
- Parents:
- 0a3c740 (diff), 69a6897 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
- Message:
-
Merge branch 'ticket-853-fit-gui-to-calc' into py3
-
Files:
-
Legend:
- Unmodified
- Added
- Removed
-
r463e7ffc
|
r69a6897
|
|
13 | 13 | if sys.platform == "win32": |
14 | 14 | _STATICBOX_WIDTH = 450 |
15 | | PANEL_WIDTH = 500 |
| 15 | PANEL_WIDTH = 500 |
16 | 16 | PANEL_HEIGHT = 700 |
17 | 17 | FONT_VARIANT = 0 |
… |
… |
|
26 | 26 | |
27 | 27 | class BaseReportDialog(wx.Dialog): |
28 | | |
| 28 | |
29 | 29 | def __init__(self, report_list, *args, **kwds): |
30 | 30 | """ |
31 | 31 | Initialization. The parameters added to Dialog are: |
32 | | |
| 32 | |
33 | 33 | :param report_list: list of html_str, text_str, image for report |
34 | 34 | """ |
… |
… |
|
48 | 48 | self.report_list = report_list |
49 | 49 | # wild card |
50 | | # pdf supporting only on MAC |
51 | | if self.is_pdf: |
52 | | self.wild_card = ' PDF files (*.pdf)|*.pdf|' |
| 50 | if self.is_pdf: # pdf writer is available |
| 51 | self.wild_card = 'PDF files (*.pdf)|*.pdf|' |
53 | 52 | self.index_offset = 0 |
54 | 53 | else: |
… |
… |
|
63 | 62 | """ |
64 | 63 | hbox = wx.BoxSizer(wx.HORIZONTAL) |
65 | | |
| 64 | |
66 | 65 | # buttons |
67 | 66 | button_close = wx.Button(self, wx.ID_OK, "Close") |
… |
… |
|
75 | 74 | id=button_print.GetId()) |
76 | 75 | hbox.Add(button_print) |
77 | | |
| 76 | |
78 | 77 | button_save = wx.Button(self, wx.NewId(), "Save") |
79 | 78 | button_save.SetToolTipString("Save this report.") |
80 | 79 | button_save.Bind(wx.EVT_BUTTON, self.onSave, id=button_save.GetId()) |
81 | 80 | hbox.Add(button_save) |
82 | | |
| 81 | |
83 | 82 | # panel for report page |
84 | 83 | vbox = wx.BoxSizer(wx.VERTICAL) |
… |
… |
|
87 | 86 | # set the html page with the report string |
88 | 87 | self.hwindow.SetPage(self.report_html) |
89 | | |
| 88 | |
90 | 89 | # add panels to boxsizers |
91 | 90 | vbox.Add(hbox) |
… |
… |
|
103 | 102 | previewh = html.HtmlEasyPrinting(name="Printing", parentWindow=self) |
104 | 103 | previewh.PreviewText(self.report_html) |
105 | | |
| 104 | |
106 | 105 | def onPrint(self, event=None): |
107 | 106 | """ |
… |
… |
|
118 | 117 | """ |
119 | 118 | self.Close() |
120 | | |
| 119 | |
121 | 120 | def HTML2PDF(self, data, filename): |
122 | 121 | """ |
123 | 122 | Create a PDF file from html source string. |
124 | | Returns True is the file creation was successful. |
| 123 | Returns True is the file creation was successful. |
125 | 124 | : data: html string |
126 | 125 | : filename: name of file to be saved |
… |
… |
|
136 | 135 | self.Update() |
137 | 136 | return pisaStatus.err |
138 | | except: |
| 137 | except Exception: |
139 | 138 | logger.error("Error creating pdf: %s" % sys.exc_value) |
140 | 139 | return False |
141 | | |
-
r78312f7
|
r69a6897
|
|
57 | 57 | |
58 | 58 | fName = dlg.GetPath() |
| 59 | basename = os.path.splitext(fName)[0] |
59 | 60 | ext_num = dlg.GetFilterIndex() |
| 61 | dlg.Destroy() |
| 62 | |
| 63 | if ext_num == 0 and self.index_offset == 0: # has pdf |
| 64 | ext = ".pdf" |
| 65 | elif ext_num == 1 - self.index_offset: |
| 66 | ext = ".html" |
| 67 | elif ext_num == 2 - self.index_offset: |
| 68 | ext = ".txt" |
| 69 | else: |
| 70 | logger.warn("unknown export format in report dialog") |
| 71 | return |
| 72 | filename = basename + ext |
| 73 | |
| 74 | # save figures |
| 75 | pictures = [] |
| 76 | for num in range(self.nimages): |
| 77 | pic_name = basename + '_img%s.png' % num |
| 78 | # save the image for use with pdf writer |
| 79 | self.report_list[2][num].savefig(pic_name) |
| 80 | pictures.append(pic_name) |
| 81 | |
| 82 | # translate png references int html from in-memory name to on-disk name |
| 83 | html = self.report_html.replace("memory:img_fit", basename+'_img') |
60 | 84 | |
61 | 85 | #set file extensions |
62 | 86 | img_ext = [] |
63 | | pic_fname = [] |
64 | | #PDF |
65 | | if ext_num == (0 + 2 * self.index_offset): |
66 | | # TODO: Sort this case out |
67 | | ext = '.pdf' |
| 87 | if ext == ".pdf": |
| 88 | # write pdf as a pdf file |
| 89 | pdf = self.HTML2PDF(data=html, filename=filename) |
68 | 90 | |
69 | | fName = os.path.splitext(fName)[0] + ext |
70 | | dlg.Destroy() |
71 | | #pic (png) file path/name |
72 | | for num in range(self.nimages): |
73 | | im_ext = '_img%s.png' % num |
74 | | #img_ext.append(im_ext) |
75 | | pic_name = os.path.splitext(fName)[0] + im_ext |
76 | | pic_fname.append(pic_name) |
77 | | # save the image for use with pdf writer |
78 | | self.report_list[2][num].savefig(pic_name) |
| 91 | # delete images used to create the pdf |
| 92 | for pic_name in pictures: |
| 93 | os.remove(pic_name) |
79 | 94 | |
80 | | #put the image path in html string |
81 | | report_frame = self.report_list[0] |
82 | | #put image name strings into the html file |
83 | | #Note:The str for pic_fname shouldn't be removed. |
84 | | if self.nimages == 1: |
85 | | html = report_frame % str(pic_fname[0]) |
86 | | elif self.nimages == 2: |
87 | | html = report_frame % (str(pic_fname[0]), str(pic_fname[1])) |
88 | | elif self.nimages == 3: |
89 | | html = report_frame % (str(pic_fname[0]), str(pic_fname[1]), |
90 | | str(pic_fname[2])) |
91 | | |
92 | | # make/open file in case of absence |
93 | | f = open(fName, 'w') |
94 | | f.close() |
95 | | # write pdf as a pdf file |
96 | | pdf = self.HTML2PDF(data=html, filename=fName) |
97 | | |
98 | | #open pdf |
| 95 | #open pdf viewer |
99 | 96 | if pdf: |
100 | 97 | try: |
101 | | #Windows |
102 | | os.startfile(str(fName)) |
103 | | except Exception: |
104 | | try: |
105 | | #Mac |
| 98 | if os.name == 'nt': # Windows |
| 99 | os.startfile(fName) |
| 100 | elif sys.platform == "darwin": # Mac |
106 | 101 | os.system("open %s" % fName) |
107 | | except Exception: |
108 | | #DO not open |
109 | | pass |
110 | | #delete image file |
111 | | for num in range(self.nimages): |
112 | | os.remove(pic_fname[num]) |
113 | | return |
114 | | #HTML + png(graph) |
115 | | elif ext_num == (1 - self.index_offset): |
116 | | ext = '.html' |
117 | | for num in range(self.nimages): |
118 | | img_ext.append('_img4html%s.png' % num) |
119 | | report_frame = self.report_list[0] |
120 | | #TEXT + pdf(graph) |
121 | | elif ext_num == (2 - self.index_offset): |
122 | | ext = '.txt' |
123 | | # changing the image extension actually changes the image |
124 | | # format on saving |
125 | | for num in range(self.nimages): |
126 | | img_ext.append('_img4txt%s.pdf' % num) |
127 | | report = self.report_list[1] |
128 | | else: |
129 | | return |
| 102 | except Exception as exc: |
| 103 | # cannot open pdf |
| 104 | logging.error(str(exc)) |
130 | 105 | |
131 | | #file name |
132 | | fName = os.path.splitext(fName)[0] + ext |
133 | | dlg.Destroy() |
| 106 | elif ext == ".html": |
| 107 | with open(filename, 'w') as f: |
| 108 | f.write(html) |
134 | 109 | |
135 | | #pic (png) file path/name |
136 | | for num in range(self.nimages): |
137 | | pic_name = os.path.splitext(fName)[0] + img_ext[num] |
138 | | pic_fname.append(pic_name) |
139 | | #put the image path in html string |
140 | | if ext_num == (1 - self.index_offset): |
141 | | if self.nimages == 1: |
142 | | report = report_frame % os.path.basename(pic_fname[0]) |
143 | | elif self.nimages == 2: |
144 | | report = report_frame % (os.path.basename(pic_fname[0]), |
145 | | os.path.basename(pic_fname[1])) |
146 | | elif self.nimages == 3: |
147 | | report = report_frame % (os.path.basename(pic_fname[0]), |
148 | | os.path.basename(pic_fname[1]), |
149 | | os.path.basename(pic_fname[2])) |
150 | | f = open(fName, 'w') |
151 | | f.write(report) |
152 | | f.close() |
| 110 | elif ext == ".txt": |
| 111 | with open(filename, 'w') as f: |
| 112 | f.write(self.report_list[1]) |
| 113 | |
153 | 114 | self.Update() |
154 | | #save png file using pic_fname |
155 | | for num in range(self.nimages): |
156 | | self.report_list[2][num].savefig(pic_fname[num]) |
-
r55bde35
|
r36ca21e
|
|
1 | 1 | package: |
2 | 2 | name: periodictable |
3 | | version: !!str 1.4.1 |
| 3 | version: !!str 1.5.0 |
4 | 4 | |
5 | 5 | source: |
6 | | fn: periodictable-1.4.1.tar.gz |
7 | | url: https://pypi.python.org/packages/source/p/periodictable/periodictable-1.4.1.tar.gz |
8 | | md5: 7246b63cc0b6b1be6e86b6616f9e866e |
| 6 | fn: periodictable-1.5.0.tar.gz |
| 7 | url: https://pypi.python.org/packages/source/p/periodictable/periodictable-1.5.0.tar.gz |
| 8 | md5: f7e0d8199b0fe829868d24a0a734398e |
9 | 9 | # patches: |
10 | 10 | # List any patch files here |
-
r243fbc0
|
r36ca21e
|
|
29 | 29 | "$EASY_INSTALL" -d "$WORKSPACE/utils" pyparsing==1.5.5 |
30 | 30 | "$EASY_INSTALL" -d "$WORKSPACE/utils" bumps==0.7.5.9 |
31 | | "$EASY_INSTALL" -d "$WORKSPACE/utils" periodictable==1.3.0 |
| 31 | "$EASY_INSTALL" -d "$WORKSPACE/utils" periodictable==1.5.0 |
32 | 32 | python deps.py |
33 | 33 | |
… |
… |
|
44 | 44 | # Build SasView ########################################################### |
45 | 45 | export PYTHONPATH=$PYTHONPATH:$WORKSPACE/$SASVIEW_INSTALL:$WORKSPACE/utils |
46 | | python setup.py bdist_egg |
| 46 | python setup.py bdist_egg |
47 | 47 | |
48 | 48 | |
-
r131d94b
|
r36ca21e
|
|
8 | 8 | lxml==2.3 |
9 | 9 | #PIL==1.1.7 |
10 | | periodictable==1.3.0 |
| 10 | periodictable==1.5.0 |
11 | 11 | bumps==0.7.5.9 |
12 | 12 | numpy>=1.7.1 |
-
r3e1f417
|
r36ca21e
|
|
27 | 27 | 'PIL': {'version': '1.1.7', 'import_name': 'Image', 'test': 'VERSION'}, |
28 | 28 | 'pylint': {'version': None, 'import_name': 'pylint', 'test': None}, |
29 | | 'periodictable': {'version': '1.3.0', 'import_name': 'periodictable', 'test': '__version__'}, |
| 29 | 'periodictable': {'version': '1.5.0', 'import_name': 'periodictable', 'test': '__version__'}, |
30 | 30 | 'bumps': {'version': '0.7.5.9', 'import_name': 'bumps', 'test': '__version__'}, |
31 | 31 | 'numpy': {'version': '1.7.1', 'import_name': 'numpy', 'test': '__version__'}, |
-
r2ecb0a5
|
r0225a3f
|
|
| 1 | #!/usr/bin/env python |
1 | 2 | # -*- coding: utf-8 -*- |
2 | | #!/usr/bin/env python |
3 | 3 | """ |
4 | 4 | Run sasview in place. This allows sasview to use the python |
-
r7152c82
|
r36ca21e
|
|
66 | 66 | # os.remove(file_path) |
67 | 67 | |
68 | | if os.path.exists(SASVIEW_BUILD): |
| 68 | |
| 69 | # Optionally clean before build. |
| 70 | dont_clean = 'update' in sys.argv |
| 71 | if dont_clean: |
| 72 | sys.argv.remove('update') |
| 73 | elif os.path.exists(SASVIEW_BUILD): |
69 | 74 | print("Removing existing build directory", SASVIEW_BUILD, "for a clean build") |
70 | 75 | shutil.rmtree(SASVIEW_BUILD) |
… |
… |
|
387 | 392 | |
388 | 393 | required = [ |
389 | | 'bumps>=0.7.5.9', 'periodictable>=1.3.1', 'pyparsing<2.0.0', |
| 394 | 'bumps>=0.7.5.9', 'periodictable>=1.5.0', 'pyparsing<2.0.0', |
390 | 395 | |
391 | 396 | # 'lxml>=2.2.2', |
-
r9a5097c
|
r574adc7
|
|
143 | 143 | qdist[1].__class__.__name__ != 'ndarray': |
144 | 144 | msg = "evalDistribution expects a list of 2 ndarrays" |
145 | | raise RuntimeError, msg |
| 145 | raise RuntimeError(msg) |
146 | 146 | |
147 | 147 | # Extract qx and qy for code clarity |
… |
… |
|
167 | 167 | mesg = "evalDistribution is expecting an ndarray of scalar q-values" |
168 | 168 | mesg += " or a list [qx,qy] where qx,qy are 2D ndarrays." |
169 | | raise RuntimeError, mesg |
| 169 | raise RuntimeError(mesg) |
170 | 170 | |
171 | 171 | |
… |
… |
|
228 | 228 | return |
229 | 229 | |
230 | | raise ValueError, "Model does not contain parameter %s" % name |
| 230 | raise ValueError("Model does not contain parameter %s" % name) |
231 | 231 | |
232 | 232 | def getParam(self, name): |
… |
… |
|
250 | 250 | return self.params[item] |
251 | 251 | |
252 | | raise ValueError, "Model does not contain parameter %s" % name |
| 252 | raise ValueError("Model does not contain parameter %s" % name) |
253 | 253 | |
254 | 254 | def getParamList(self): |
… |
… |
|
294 | 294 | add |
295 | 295 | """ |
296 | | raise ValueError, "Model operation are no longer supported" |
| 296 | raise ValueError("Model operation are no longer supported") |
297 | 297 | def __sub__(self, other): |
298 | 298 | """ |
299 | 299 | sub |
300 | 300 | """ |
301 | | raise ValueError, "Model operation are no longer supported" |
| 301 | raise ValueError("Model operation are no longer supported") |
302 | 302 | def __mul__(self, other): |
303 | 303 | """ |
304 | 304 | mul |
305 | 305 | """ |
306 | | raise ValueError, "Model operation are no longer supported" |
| 306 | raise ValueError("Model operation are no longer supported") |
307 | 307 | def __div__(self, other): |
308 | 308 | """ |
309 | 309 | div |
310 | 310 | """ |
311 | | raise ValueError, "Model operation are no longer supported" |
| 311 | raise ValueError("Model operation are no longer supported") |
312 | 312 | |
313 | 313 | |
-
rb523c0e
|
r1d014cb
|
|
5 | 5 | #include <stdio.h> |
6 | 6 | #include <sld2i.hh> |
| 7 | |
| 8 | #if PY_MAJOR_VERSION < 3 |
| 9 | typedef void (*PyCapsule_Destructor)(PyObject *); |
| 10 | typedef void (*PyCObject_Destructor)(void *); |
| 11 | #define PyCapsule_New(pointer, name, destructor) (PyCObject_FromVoidPtr(pointer, (PyCObject_Destructor)destructor)) |
| 12 | #define PyCapsule_GetPointer(capsule, name) (PyCObject_AsVoidPtr(capsule)) |
| 13 | #endif |
| 14 | |
7 | 15 | |
8 | 16 | // Utilities |
… |
… |
|
25 | 33 | * Delete a GenI object |
26 | 34 | */ |
27 | | void del_sld2i(void *ptr){ |
28 | | GenI* sld2i = static_cast<GenI *>(ptr); |
| 35 | void |
| 36 | del_sld2i(PyObject *obj){ |
| 37 | GenI* sld2i = static_cast<GenI *>(PyCapsule_GetPointer(obj, "GenI")); |
29 | 38 | delete sld2i; |
30 | 39 | return; |
… |
… |
|
71 | 80 | OUTVECTOR(vol_pix_obj, vol_pix, n_x); |
72 | 81 | GenI* sld2i = new GenI(n_pix,x_val,y_val,z_val,sldn_val,mx_val,my_val,mz_val,vol_pix,inspin,outspin,stheta); |
73 | | return PyCObject_FromVoidPtr(sld2i, del_sld2i); |
| 82 | return PyCapsule_New(sld2i, "GenI", del_sld2i); |
74 | 83 | } |
75 | 84 | |
… |
… |
|
97 | 106 | |
98 | 107 | // Set the array pointers |
99 | | void *temp = PyCObject_AsVoidPtr(gen_obj); |
| 108 | void *temp = PyCapsule_GetPointer(gen_obj, "GenI"); |
100 | 109 | GenI* s = static_cast<GenI *>(temp); |
101 | 110 | |
… |
… |
|
125 | 134 | |
126 | 135 | // Set the array pointers |
127 | | void *temp = PyCObject_AsVoidPtr(gen_obj); |
| 136 | void *temp = PyCapsule_GetPointer(gen_obj, "GenI"); |
128 | 137 | GenI* s = static_cast<GenI *>(temp); |
129 | 138 | |
… |
… |
|
146 | 155 | }; |
147 | 156 | |
148 | | |
149 | | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ |
150 | | #define PyMODINIT_FUNC void |
| 157 | #define MODULE_DOC "Sld2i C Library" |
| 158 | #define MODULE_NAME "sld2i" |
| 159 | #define MODULE_INIT2 initsld2i |
| 160 | #define MODULE_INIT3 PyInit_sld2i |
| 161 | #define MODULE_METHODS module_methods |
| 162 | |
| 163 | /* ==== boilerplate python 2/3 interface bootstrap ==== */ |
| 164 | |
| 165 | |
| 166 | #if defined(WIN32) && !defined(__MINGW32__) |
| 167 | #define DLL_EXPORT __declspec(dllexport) |
| 168 | #else |
| 169 | #define DLL_EXPORT |
151 | 170 | #endif |
152 | | PyMODINIT_FUNC |
153 | | initsld2i(void) |
154 | | { |
155 | | Py_InitModule3("sld2i", module_methods, "Sld2i module"); |
156 | | } |
| 171 | |
| 172 | #if PY_MAJOR_VERSION >= 3 |
| 173 | |
| 174 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) |
| 175 | { |
| 176 | static struct PyModuleDef moduledef = { |
| 177 | PyModuleDef_HEAD_INIT, |
| 178 | MODULE_NAME, /* m_name */ |
| 179 | MODULE_DOC, /* m_doc */ |
| 180 | -1, /* m_size */ |
| 181 | MODULE_METHODS, /* m_methods */ |
| 182 | NULL, /* m_reload */ |
| 183 | NULL, /* m_traverse */ |
| 184 | NULL, /* m_clear */ |
| 185 | NULL, /* m_free */ |
| 186 | }; |
| 187 | return PyModule_Create(&moduledef); |
| 188 | } |
| 189 | |
| 190 | #else /* !PY_MAJOR_VERSION >= 3 */ |
| 191 | |
| 192 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) |
| 193 | { |
| 194 | Py_InitModule4(MODULE_NAME, |
| 195 | MODULE_METHODS, |
| 196 | MODULE_DOC, |
| 197 | 0, |
| 198 | PYTHON_API_VERSION |
| 199 | ); |
| 200 | } |
| 201 | |
| 202 | #endif /* !PY_MAJOR_VERSION >= 3 */ |
-
r9a5097c
|
r574adc7
|
|
222 | 222 | """ |
223 | 223 | # check if the wavelength is in range |
224 | | if min(band) < self.min or\ |
225 | | max(band) > self.max: |
226 | | raise |
| 224 | if min(band) < self.min or max(band) > self.max: |
| 225 | raise ValueError("band out of range") |
227 | 226 | self.band = band |
228 | 227 | |
… |
… |
|
239 | 238 | """ |
240 | 239 | # check if the wavelength is in range |
241 | | if wavelength < min(self.band) or\ |
242 | | wavelength > max(self.band): |
243 | | raise |
| 240 | if wavelength < min(self.band) or wavelength > max(self.band): |
| 241 | raise ValueError("wavelength out of range") |
244 | 242 | self.wavelength = wavelength |
245 | 243 | validate(wavelength) |
… |
… |
|
324 | 322 | plt.show() |
325 | 323 | except: |
326 | | raise RuntimeError, "Can't import matplotlib required to plot..." |
| 324 | raise RuntimeError("Can't import matplotlib required to plot...") |
327 | 325 | |
328 | 326 | |
-
r7432acb
|
r574adc7
|
|
4 | 4 | instrumental parameters. |
5 | 5 | """ |
6 | | from instrument import Sample |
7 | | from instrument import Detector |
8 | | from instrument import TOF as Neutron |
9 | | from instrument import Aperture |
10 | | # import math stuffs |
11 | | from math import pi |
12 | | from math import sqrt |
| 6 | import sys |
| 7 | from math import pi, sqrt |
13 | 8 | import math |
| 9 | import logging |
| 10 | |
14 | 11 | import numpy as np |
15 | | import sys |
16 | | import logging |
| 12 | |
| 13 | from .instrument import Sample |
| 14 | from .instrument import Detector |
| 15 | from .instrument import TOF as Neutron |
| 16 | from .instrument import Aperture |
17 | 17 | |
18 | 18 | logger = logging.getLogger(__name__) |
… |
… |
|
208 | 208 | if wavelength == 0: |
209 | 209 | msg = "Can't compute the resolution: the wavelength is zero..." |
210 | | raise RuntimeError, msg |
| 210 | raise RuntimeError(msg) |
211 | 211 | return self.intensity |
212 | 212 | |
… |
… |
|
379 | 379 | if qx_min < self.qx_min: |
380 | 380 | self.qx_min = qx_min |
381 | | #raise ValueError, msg |
| 381 | #raise ValueError(msg) |
382 | 382 | if qx_max > self.qx_max: |
383 | 383 | self.qx_max = qx_max |
384 | | #raise ValueError, msg |
| 384 | #raise ValueError(msg) |
385 | 385 | if qy_min < self.qy_min: |
386 | 386 | self.qy_min = qy_min |
387 | | #raise ValueError, msg |
| 387 | #raise ValueError(msg) |
388 | 388 | if qy_max > self.qy_max: |
389 | 389 | self.qy_max = qy_max |
390 | | #raise ValueError, msg |
| 390 | #raise ValueError(msg) |
391 | 391 | if not full_cal: |
392 | 392 | return None |
… |
… |
|
503 | 503 | # otherwise |
504 | 504 | else: |
505 | | raise ValueError, " Improper input..." |
| 505 | raise ValueError(" Improper input...") |
506 | 506 | # get them squared |
507 | 507 | sigma = x_comp * x_comp |
… |
… |
|
706 | 706 | #self.set_wavelength(wavelength) |
707 | 707 | else: |
708 | | raise |
| 708 | raise TypeError("invalid wavlength---should be list or float") |
709 | 709 | |
710 | 710 | def set_wave_spread(self, wavelength_spread): |
… |
… |
|
717 | 717 | self.wave.set_wave_spread_list([wavelength_spread]) |
718 | 718 | else: |
719 | | raise |
| 719 | raise TypeError("invalid wavelength spread---should be list or float") |
720 | 720 | |
721 | 721 | def set_wavelength(self, wavelength): |
… |
… |
|
766 | 766 | """ |
767 | 767 | if len(size) < 1 or len(size) > 2: |
768 | | raise RuntimeError, "The length of the size must be one or two." |
| 768 | raise RuntimeError("The length of the size must be one or two.") |
769 | 769 | self.aperture.set_source_size(size) |
770 | 770 | |
… |
… |
|
783 | 783 | """ |
784 | 784 | if len(size) < 1 or len(size) > 2: |
785 | | raise RuntimeError, "The length of the size must be one or two." |
| 785 | raise RuntimeError("The length of the size must be one or two.") |
786 | 786 | self.aperture.set_sample_size(size) |
787 | 787 | |
… |
… |
|
806 | 806 | """ |
807 | 807 | if len(distance) < 1 or len(distance) > 2: |
808 | | raise RuntimeError, "The length of the size must be one or two." |
| 808 | raise RuntimeError("The length of the size must be one or two.") |
809 | 809 | self.aperture.set_sample_distance(distance) |
810 | 810 | |
… |
… |
|
816 | 816 | """ |
817 | 817 | if len(distance) < 1 or len(distance) > 2: |
818 | | raise RuntimeError, "The length of the size must be one or two." |
| 818 | raise RuntimeError("The length of the size must be one or two.") |
819 | 819 | self.sample.set_distance(distance) |
820 | 820 | |
… |
… |
|
826 | 826 | """ |
827 | 827 | if len(distance) < 1 or len(distance) > 2: |
828 | | raise RuntimeError, "The length of the size must be one or two." |
| 828 | raise RuntimeError("The length of the size must be one or two.") |
829 | 829 | self.detector.set_distance(distance) |
830 | 830 | |
… |
… |
|
998 | 998 | pix_y_size = detector_pix_size[1] |
999 | 999 | else: |
1000 | | raise ValueError, " Input value format error..." |
| 1000 | raise ValueError(" Input value format error...") |
1001 | 1001 | # Sample to detector distance = sample slit to detector |
1002 | 1002 | # minus sample offset |
-
rf2ea95a
|
rb58265c3
|
|
5 | 5 | from __future__ import print_function |
6 | 6 | |
7 | | import sas.sascalc.calculator.core.sld2i as mod |
8 | | from sas.sascalc.calculator.BaseComponent import BaseComponent |
| 7 | import os |
| 8 | import sys |
| 9 | import copy |
| 10 | import logging |
| 11 | |
9 | 12 | from periodictable import formula |
10 | 13 | from periodictable import nsf |
11 | 14 | import numpy as np |
12 | | import os |
13 | | import copy |
14 | | import sys |
15 | | import logging |
| 15 | |
| 16 | from .core import sld2i as mod |
| 17 | from .BaseComponent import BaseComponent |
16 | 18 | |
17 | 19 | logger = logging.getLogger(__name__) |
| 20 | |
| 21 | if sys.version_info[0] < 3: |
| 22 | def decode(s): |
| 23 | return s |
| 24 | else: |
| 25 | def decode(s): |
| 26 | return s.decode() if isinstance(s, bytes) else s |
18 | 27 | |
19 | 28 | MFACTOR_AM = 2.853E-12 |
… |
… |
|
34 | 43 | factor = MFACTOR_MT |
35 | 44 | else: |
36 | | raise ValueError, "Invalid valueunit" |
| 45 | raise ValueError("Invalid valueunit") |
37 | 46 | sld_m = factor * mag |
38 | 47 | return sld_m |
… |
… |
|
100 | 109 | """ |
101 | 110 | if self.data_vol is None: |
102 | | raise |
| 111 | raise TypeError("data_vol is missing") |
103 | 112 | self.data_vol = volume |
104 | 113 | |
… |
… |
|
174 | 183 | if len(x[1]) > 0: |
175 | 184 | msg = "Not a 1D." |
176 | | raise ValueError, msg |
| 185 | raise ValueError(msg) |
177 | 186 | i_out = np.zeros_like(x[0]) |
178 | 187 | # 1D I is found at y =0 in the 2D pattern |
… |
… |
|
181 | 190 | else: |
182 | 191 | msg = "Q must be given as list of qx's and qy's" |
183 | | raise ValueError, msg |
| 192 | raise ValueError(msg) |
184 | 193 | |
185 | 194 | def runXY(self, x=0.0): |
… |
… |
|
196 | 205 | else: |
197 | 206 | msg = "Q must be given as list of qx's and qy's" |
198 | | raise ValueError, msg |
| 207 | raise ValueError(msg) |
199 | 208 | |
200 | 209 | def evalDistribution(self, qdist): |
… |
… |
|
214 | 223 | mesg = "evalDistribution is expecting an ndarray of " |
215 | 224 | mesg += "a list [qx,qy] where qx,qy are arrays." |
216 | | raise RuntimeError, mesg |
| 225 | raise RuntimeError(mesg) |
217 | 226 | |
218 | 227 | class OMF2SLD(object): |
… |
… |
|
288 | 297 | z_dir2 *= z_dir2 |
289 | 298 | mask = (x_dir2 + y_dir2 + z_dir2) <= 1.0 |
290 | | except: |
| 299 | except Exception: |
291 | 300 | logger.error(sys.exc_value) |
292 | 301 | self.output = MagSLD(self.pos_x[mask], self.pos_y[mask], |
… |
… |
|
313 | 322 | :Params length: data length |
314 | 323 | """ |
315 | | msg = "Error: Inconsistent data length." |
316 | | if len(self.pos_x) != length: |
317 | | raise ValueError, msg |
318 | | if len(self.pos_y) != length: |
319 | | raise ValueError, msg |
320 | | if len(self.pos_z) != length: |
321 | | raise ValueError, msg |
322 | | if len(self.mx) != length: |
323 | | raise ValueError, msg |
324 | | if len(self.my) != length: |
325 | | raise ValueError, msg |
326 | | if len(self.mz) != length: |
327 | | raise ValueError, msg |
| 324 | parts = (self.pos_x, self.pos_y, self.pos_z, self.mx, self.my, self.mz) |
| 325 | if any(len(v) != length for v in parts): |
| 326 | raise ValueError("Error: Inconsistent data length.") |
328 | 327 | |
329 | 328 | def remove_null_points(self, remove=False, recenter=False): |
… |
… |
|
378 | 377 | try: |
379 | 378 | input_f = open(path, 'rb') |
380 | | buff = input_f.read() |
| 379 | buff = decode(input_f.read()) |
381 | 380 | lines = buff.split('\n') |
382 | 381 | input_f.close() |
… |
… |
|
384 | 383 | valueunit = None |
385 | 384 | for line in lines: |
386 | | toks = line.split() |
| 385 | line = line.strip() |
387 | 386 | # Read data |
388 | | try: |
389 | | _mx = float(toks[0]) |
390 | | _my = float(toks[1]) |
391 | | _mz = float(toks[2]) |
392 | | _mx = mag2sld(_mx, valueunit) |
393 | | _my = mag2sld(_my, valueunit) |
394 | | _mz = mag2sld(_mz, valueunit) |
395 | | mx = np.append(mx, _mx) |
396 | | my = np.append(my, _my) |
397 | | mz = np.append(mz, _mz) |
398 | | except: |
399 | | # Skip non-data lines |
400 | | logger.error(sys.exc_value) |
| 387 | if line and not line.startswith('#'): |
| 388 | try: |
| 389 | toks = line.split() |
| 390 | _mx = float(toks[0]) |
| 391 | _my = float(toks[1]) |
| 392 | _mz = float(toks[2]) |
| 393 | _mx = mag2sld(_mx, valueunit) |
| 394 | _my = mag2sld(_my, valueunit) |
| 395 | _mz = mag2sld(_mz, valueunit) |
| 396 | mx = np.append(mx, _mx) |
| 397 | my = np.append(my, _my) |
| 398 | mz = np.append(mz, _mz) |
| 399 | except Exception as exc: |
| 400 | # Skip non-data lines |
| 401 | logger.error(str(exc)+" when processing %r"%line) |
401 | 402 | #Reading Header; Segment count ignored |
402 | 403 | s_line = line.split(":", 1) |
… |
… |
|
415 | 416 | msg = "Error: \n" |
416 | 417 | msg += "We accept only m as meshunit" |
417 | | raise ValueError, msg |
| 418 | raise ValueError(msg) |
418 | 419 | if s_line[0].lower().count("xbase") > 0: |
419 | 420 | xbase = s_line[1].lstrip() |
… |
… |
|
482 | 483 | output.set_m(mx, my, mz) |
483 | 484 | return output |
484 | | except: |
| 485 | except Exception: |
485 | 486 | msg = "%s is not supported: \n" % path |
486 | 487 | msg += "We accept only Text format OMF file." |
487 | | raise RuntimeError, msg |
| 488 | raise RuntimeError(msg) |
488 | 489 | |
489 | 490 | class PDBReader(object): |
… |
… |
|
522 | 523 | try: |
523 | 524 | input_f = open(path, 'rb') |
524 | | buff = input_f.read() |
| 525 | buff = decode(input_f.read()) |
525 | 526 | lines = buff.split('\n') |
526 | 527 | input_f.close() |
… |
… |
|
536 | 537 | float(line[12]) |
537 | 538 | atom_name = atom_name[1].upper() |
538 | | except: |
| 539 | except Exception: |
539 | 540 | if len(atom_name) == 4: |
540 | 541 | atom_name = atom_name[0].upper() |
… |
… |
|
559 | 560 | vol = 1.0e+24 * atom.mass / atom.density / NA |
560 | 561 | vol_pix = np.append(vol_pix, vol) |
561 | | except: |
562 | | print("Error: set the sld of %s to zero"% atom_name) |
| 562 | except Exception: |
| 563 | logger.error("Error: set the sld of %s to zero"% atom_name) |
563 | 564 | sld_n = np.append(sld_n, 0.0) |
564 | 565 | sld_mx = np.append(sld_mx, 0) |
… |
… |
|
573 | 574 | try: |
574 | 575 | int_val = int(val) |
575 | | except: |
| 576 | except Exception: |
576 | 577 | break |
577 | 578 | if int_val == 0: |
… |
… |
|
592 | 593 | y_lines.append(y_line) |
593 | 594 | z_lines.append(z_line) |
594 | | except: |
| 595 | except Exception: |
595 | 596 | logger.error(sys.exc_value) |
596 | 597 | |
… |
… |
|
604 | 605 | output.sld_unit = '1/A^(2)' |
605 | 606 | return output |
606 | | except: |
607 | | raise RuntimeError, "%s is not a sld file" % path |
| 607 | except Exception: |
| 608 | raise RuntimeError("%s is not a sld file" % path) |
608 | 609 | |
609 | 610 | def write(self, path, data): |
… |
… |
|
657 | 658 | elif ncols == 7: |
658 | 659 | vol_pix = None |
659 | | except: |
| 660 | except Exception: |
660 | 661 | # For older version of numpy |
661 | 662 | input_f = open(path, 'rb') |
662 | | buff = input_f.read() |
| 663 | buff = decode(input_f.read()) |
663 | 664 | lines = buff.split('\n') |
664 | 665 | input_f.close() |
… |
… |
|
683 | 684 | _vol_pix = float(toks[7]) |
684 | 685 | vol_pix = np.append(vol_pix, _vol_pix) |
685 | | except: |
| 686 | except Exception: |
686 | 687 | vol_pix = None |
687 | | except: |
| 688 | except Exception: |
688 | 689 | # Skip non-data lines |
689 | 690 | logger.error(sys.exc_value) |
… |
… |
|
696 | 697 | output.set_pixel_volumes(vol_pix) |
697 | 698 | return output |
698 | | except: |
699 | | raise RuntimeError, "%s is not a sld file" % path |
| 699 | except Exception: |
| 700 | raise RuntimeError("%s is not a sld file" % path) |
700 | 701 | |
701 | 702 | def write(self, path, data): |
… |
… |
|
706 | 707 | """ |
707 | 708 | if path is None: |
708 | | raise ValueError, "Missing the file path." |
| 709 | raise ValueError("Missing the file path.") |
709 | 710 | if data is None: |
710 | | raise ValueError, "Missing the data to save." |
| 711 | raise ValueError("Missing the data to save.") |
711 | 712 | x_val = data.pos_x |
712 | 713 | y_val = data.pos_y |
… |
… |
|
977 | 978 | self.ynodes = int(ydist) + 1 |
978 | 979 | self.znodes = int(zdist) + 1 |
979 | | except: |
| 980 | except Exception: |
980 | 981 | self.xnodes = None |
981 | 982 | self.ynodes = None |
… |
… |
|
1012 | 1013 | self.set_pixel_volumes(vol) |
1013 | 1014 | self.has_stepsize = True |
1014 | | except: |
| 1015 | except Exception: |
1015 | 1016 | self.xstepsize = None |
1016 | 1017 | self.ystepsize = None |
… |
… |
|
1057 | 1058 | reader = SLDReader() |
1058 | 1059 | oreader = OMFReader() |
1059 | | output = reader.read(tfpath) |
1060 | | ooutput = oreader.read(ofpath) |
| 1060 | output = decode(reader.read(tfpath)) |
| 1061 | ooutput = decode(oreader.read(ofpath)) |
1061 | 1062 | foutput = OMF2SLD() |
1062 | 1063 | foutput.set_data(ooutput) |
… |
… |
|
1099 | 1100 | break |
1100 | 1101 | oreader = OMFReader() |
1101 | | ooutput = oreader.read(ofpath) |
| 1102 | ooutput = decode(oreader.read(ofpath)) |
1102 | 1103 | foutput = OMF2SLD() |
1103 | 1104 | foutput.set_data(ooutput) |
-
ra859f99
|
r574adc7
|
|
88 | 88 | # Only process data of the class Data1D |
89 | 89 | if not issubclass(data.__class__, Data1D): |
90 | | raise ValueError, "Data must be of the type DataLoader.Data1D" |
| 90 | raise ValueError("Data must be of the type DataLoader.Data1D") |
91 | 91 | |
92 | 92 | # Prepare the data |
… |
… |
|
161 | 161 | err = ("Incorrect transform type supplied, must be 'fourier'", |
162 | 162 | " or 'hilbert'") |
163 | | raise ValueError, err |
| 163 | raise ValueError(err) |
164 | 164 | |
165 | 165 | self._transform_thread.queue() |
-
ra1b8fee
|
r574adc7
|
|
6 | 6 | from __future__ import print_function |
7 | 7 | |
8 | | import thread |
9 | 8 | import traceback |
10 | 9 | import sys |
11 | 10 | import logging |
| 11 | try: |
| 12 | import _thread as thread |
| 13 | except ImportError: # CRUFT: python 2 support |
| 14 | import thread |
12 | 15 | |
13 | 16 | if sys.platform.count("darwin") > 0: |
14 | 17 | import time |
15 | 18 | stime = time.time() |
16 | | |
| 19 | |
17 | 20 | def clock(): |
18 | 21 | return time.time() - stime |
19 | | |
| 22 | |
20 | 23 | def sleep(t): |
21 | 24 | return time.sleep(t) |
… |
… |
|
35 | 38 | CalcThread.__init__, passing it the keyword arguments for |
36 | 39 | yieldtime, worktime, update and complete. |
37 | | |
| 40 | |
38 | 41 | When defining the compute() method you need to include code which |
39 | 42 | allows the GUI to run. They are as follows: :: |
… |
… |
|
211 | 214 | self._lock.release() |
212 | 215 | self._time_for_update += 1e6 # No more updates |
213 | | |
| 216 | |
214 | 217 | self.updatefn(**kwargs) |
215 | 218 | sleep(self.yieldtime) |
-
r8e9536f
|
r574adc7
|
|
13 | 13 | in the NeXus definition files. |
14 | 14 | |
15 | | Unlike other units packages, this package does not carry the units along with |
| 15 | Unlike other units packages, this package does not carry the units along with |
16 | 16 | the value but merely provides a conversion function for transforming values. |
17 | 17 | |
… |
… |
|
68 | 68 | Ack! Allows, e.g., Coulomb and coulomb even though Coulomb is not |
69 | 69 | a unit because some NeXus files store it that way! |
70 | | |
| 70 | |
71 | 71 | Returns a dictionary of names and scales. |
72 | 72 | """ |
… |
… |
|
78 | 78 | n=1e-9,p=1e-12,f=1e-15) |
79 | 79 | map = {abbr:1} |
80 | | map.update([(P+abbr,scale) for (P,scale) in short_prefix.iteritems()]) |
| 80 | map.update([(P+abbr,scale) for (P,scale) in short_prefix.items()]) |
81 | 81 | for name in [unit,unit.capitalize()]: |
82 | 82 | map.update({name:1,name+'s':1}) |
83 | | map.update([(P+name,scale) for (P,scale) in prefix.iteritems()]) |
84 | | map.update([(P+'*'+name,scale) for (P,scale) in prefix.iteritems()]) |
85 | | map.update([(P+name+'s',scale) for (P,scale) in prefix.iteritems()]) |
| 83 | map.update([(P+name,scale) for (P,scale) in prefix.items()]) |
| 84 | map.update([(P+'*'+name,scale) for (P,scale) in prefix.items()]) |
| 85 | map.update([(P+name+'s',scale) for (P,scale) in prefix.items()]) |
86 | 86 | return map |
87 | 87 | |
… |
… |
|
91 | 91 | """ |
92 | 92 | map = {} |
93 | | map.update([(name,scale) for name,scale in kw.iteritems()]) |
94 | | map.update([(name+'s',scale) for name,scale in kw.iteritems()]) |
| 93 | map.update([(name,scale) for name,scale in kw.items()]) |
| 94 | map.update([(name+'s',scale) for name,scale in kw.items()]) |
95 | 95 | return map |
96 | 96 | |
… |
… |
|
101 | 101 | * WARNING * this will incorrect transform 10^3 to 103. |
102 | 102 | """ |
103 | | s.update((k.replace('^',''),v) |
104 | | for k,v in s.items() |
| 103 | s.update((k.replace('^',''),v) |
| 104 | for k, v in list(s.items()) |
105 | 105 | if '^' in k) |
106 | 106 | |
… |
… |
|
130 | 130 | temperature.update(_build_metric_units('Celcius', 'C')) |
131 | 131 | temperature.update(_build_metric_units('celcius', 'C')) |
132 | | |
| 132 | |
133 | 133 | charge = _build_metric_units('coulomb','C') |
134 | 134 | charge.update({'microAmp*hour':0.0036}) |
135 | 135 | |
136 | 136 | sld = { '10^-6 Angstrom^-2': 1e-6, 'Angstrom^-2': 1 } |
137 | | Q = { 'invA': 1, 'invAng': 1, 'invAngstroms': 1, '1/A': 1, |
| 137 | Q = { 'invA': 1, 'invAng': 1, 'invAngstroms': 1, '1/A': 1, |
138 | 138 | '10^-3 Angstrom^-1': 1e-3, '1/cm': 1e-8, '1/m': 1e-10, |
139 | 139 | 'nm^-1': 0.1, '1/nm': 0.1, 'n_m^-1': 0.1 } |
… |
… |
|
189 | 189 | |
190 | 190 | def _check(expect,get): |
191 | | if expect != get: raise ValueError, "Expected %s but got %s"%(expect,get) |
| 191 | if expect != get: |
| 192 | raise ValueError("Expected %s but got %s"%(expect, get)) |
192 | 193 | #print expect,"==",get |
193 | 194 | |
… |
… |
|
202 | 203 | _check(123,Converter('a.u.')(123,units='s')) # arbitrary units always returns the same value |
203 | 204 | _check(123,Converter('a.u.')(123,units='')) # arbitrary units always returns the same value |
204 | | try: Converter('help') |
205 | | except KeyError: pass |
206 | | else: raise Exception("unknown unit did not raise an error") |
| 205 | try: |
| 206 | Converter('help') |
| 207 | except KeyError: |
| 208 | pass |
| 209 | else: |
| 210 | raise Exception("unknown unit did not raise an error") |
207 | 211 | |
208 | 212 | # TODO: more tests |
-
rb699768
|
r574adc7
|
|
39 | 39 | """ |
40 | 40 | A class of dictionary that keeps the insertion order of keys. |
41 | | |
| 41 | |
42 | 42 | All appropriate methods return keys, items, or values in an ordered way. |
43 | | |
| 43 | |
44 | 44 | All normal dictionary methods are available. Update and comparison is |
45 | 45 | restricted to other OrderedDict objects. |
46 | | |
| 46 | |
47 | 47 | Various sequence methods are available, including the ability to explicitly |
48 | 48 | mutate the key ordering. |
49 | | |
| 49 | |
50 | 50 | __contains__ tests: |
51 | | |
| 51 | |
52 | 52 | >>> d = OrderedDict(((1, 3),)) |
53 | 53 | >>> 1 in d |
… |
… |
|
55 | 55 | >>> 4 in d |
56 | 56 | 0 |
57 | | |
| 57 | |
58 | 58 | __getitem__ tests: |
59 | | |
| 59 | |
60 | 60 | >>> OrderedDict(((1, 3), (3, 2), (2, 1)))[2] |
61 | 61 | 1 |
… |
… |
|
63 | 63 | Traceback (most recent call last): |
64 | 64 | KeyError: 4 |
65 | | |
| 65 | |
66 | 66 | __len__ tests: |
67 | | |
| 67 | |
68 | 68 | >>> len(OrderedDict()) |
69 | 69 | 0 |
70 | 70 | >>> len(OrderedDict(((1, 3), (3, 2), (2, 1)))) |
71 | 71 | 3 |
72 | | |
| 72 | |
73 | 73 | get tests: |
74 | | |
| 74 | |
75 | 75 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
76 | 76 | >>> d.get(1) |
… |
… |
|
82 | 82 | >>> d |
83 | 83 | OrderedDict([(1, 3), (3, 2), (2, 1)]) |
84 | | |
| 84 | |
85 | 85 | has_key tests: |
86 | | |
| 86 | |
87 | 87 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
88 | 88 | >>> d.has_key(1) |
… |
… |
|
96 | 96 | Create a new ordered dictionary. Cannot init from a normal dict, |
97 | 97 | nor from kwargs, since items order is undefined in those cases. |
98 | | |
| 98 | |
99 | 99 | If the ``strict`` keyword argument is ``True`` (``False`` is the |
100 | 100 | default) then when doing slice assignment - the ``OrderedDict`` you are |
101 | 101 | assigning from *must not* contain any keys in the remaining dict. |
102 | | |
| 102 | |
103 | 103 | >>> OrderedDict() |
104 | 104 | OrderedDict([]) |
… |
… |
|
283 | 283 | """ |
284 | 284 | Used for __repr__ and __str__ |
285 | | |
| 285 | |
286 | 286 | >>> r1 = repr(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f')))) |
287 | 287 | >>> r1 |
… |
… |
|
321 | 321 | >>> d |
322 | 322 | OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)]) |
323 | | |
| 323 | |
324 | 324 | >>> a = OrderedDict(((0, 1), (1, 2), (2, 3)), strict=True) |
325 | 325 | >>> a[3] = 4 |
… |
… |
|
345 | 345 | >>> a |
346 | 346 | OrderedDict([(3, 4), (2, 3), (1, 2), (0, 1)]) |
347 | | |
| 347 | |
348 | 348 | >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) |
349 | 349 | >>> d[:1] = 3 |
350 | 350 | Traceback (most recent call last): |
351 | 351 | TypeError: slice assignment requires an OrderedDict |
352 | | |
| 352 | |
353 | 353 | >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) |
354 | 354 | >>> d[:1] = OrderedDict([(9, 8)]) |
… |
… |
|
444 | 444 | """ |
445 | 445 | Implemented so that access to ``sequence`` raises a warning. |
446 | | |
| 446 | |
447 | 447 | >>> d = OrderedDict() |
448 | 448 | >>> d.sequence |
… |
… |
|
463 | 463 | """ |
464 | 464 | To allow deepcopy to work with OrderedDict. |
465 | | |
| 465 | |
466 | 466 | >>> from copy import deepcopy |
467 | 467 | >>> a = OrderedDict([(1, 1), (2, 2), (3, 3)]) |
… |
… |
|
490 | 490 | def items(self): |
491 | 491 | """ |
492 | | ``items`` returns a list of tuples representing all the |
| 492 | ``items`` returns a list of tuples representing all the |
493 | 493 | ``(key, value)`` pairs in the dictionary. |
494 | | |
| 494 | |
495 | 495 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
496 | 496 | >>> d.items() |
… |
… |
|
505 | 505 | """ |
506 | 506 | Return a list of keys in the ``OrderedDict``. |
507 | | |
| 507 | |
508 | 508 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
509 | 509 | >>> d.keys() |
… |
… |
|
515 | 515 | """ |
516 | 516 | Return a list of all the values in the OrderedDict. |
517 | | |
| 517 | |
518 | 518 | Optionally you can pass in a list of values, which will replace the |
519 | 519 | current list. The value list must be the same len as the OrderedDict. |
520 | | |
| 520 | |
521 | 521 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
522 | 522 | >>> d.values() |
… |
… |
|
596 | 596 | """ |
597 | 597 | No dict.pop in Python 2.2, gotta reimplement it |
598 | | |
| 598 | |
599 | 599 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
600 | 600 | >>> d.pop(3) |
… |
… |
|
612 | 612 | """ |
613 | 613 | if len(args) > 1: |
614 | | raise TypeError, ('pop expected at most 2 arguments, got %s' % |
| 614 | raise TypeError('pop expected at most 2 arguments, got %s' % |
615 | 615 | (len(args) + 1)) |
616 | 616 | if key in self: |
… |
… |
|
628 | 628 | Delete and return an item specified by index, not a random one as in |
629 | 629 | dict. The index is -1 by default (the last item). |
630 | | |
| 630 | |
631 | 631 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
632 | 632 | >>> d.popitem() |
… |
… |
|
674 | 674 | """ |
675 | 675 | Update from another OrderedDict or sequence of (key, value) pairs |
676 | | |
| 676 | |
677 | 677 | >>> d = OrderedDict(((1, 0), (0, 1))) |
678 | 678 | >>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1)))) |
… |
… |
|
706 | 706 | """ |
707 | 707 | Rename the key for a given value, without modifying sequence order. |
708 | | |
| 708 | |
709 | 709 | For the case where new_key already exists this raise an exception, |
710 | 710 | since if new_key exists, it is ambiguous as to what happens to the |
711 | 711 | associated values, and the position of new_key in the sequence. |
712 | | |
| 712 | |
713 | 713 | >>> od = OrderedDict() |
714 | 714 | >>> od['a'] = 1 |
… |
… |
|
732 | 732 | raise ValueError("New key already exists: %r" % new_key) |
733 | 733 | # rename sequence entry |
734 | | value = self[old_key] |
| 734 | value = self[old_key] |
735 | 735 | old_idx = self._sequence.index(old_key) |
736 | 736 | self._sequence[old_idx] = new_key |
… |
… |
|
742 | 742 | """ |
743 | 743 | This method allows you to set the items in the dict. |
744 | | |
| 744 | |
745 | 745 | It takes a list of tuples - of the same sort returned by the ``items`` |
746 | 746 | method. |
747 | | |
| 747 | |
748 | 748 | >>> d = OrderedDict() |
749 | 749 | >>> d.setitems(((3, 1), (2, 3), (1, 2))) |
… |
… |
|
760 | 760 | replace the current set. This must contain the same set of keys, but |
761 | 761 | need not be in the same order. |
762 | | |
| 762 | |
763 | 763 | If you pass in new keys that don't match, a ``KeyError`` will be |
764 | 764 | raised. |
765 | | |
| 765 | |
766 | 766 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
767 | 767 | >>> d.keys() |
… |
… |
|
791 | 791 | You can pass in a list of values, which will replace the |
792 | 792 | current list. The value list must be the same len as the OrderedDict. |
793 | | |
| 793 | |
794 | 794 | (Or a ``ValueError`` is raised.) |
795 | | |
| 795 | |
796 | 796 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
797 | 797 | >>> d.setvalues((1, 2, 3)) |
… |
… |
|
813 | 813 | """ |
814 | 814 | Return the position of the specified key in the OrderedDict. |
815 | | |
| 815 | |
816 | 816 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
817 | 817 | >>> d.index(3) |
… |
… |
|
826 | 826 | """ |
827 | 827 | Takes ``index``, ``key``, and ``value`` as arguments. |
828 | | |
| 828 | |
829 | 829 | Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in |
830 | 830 | the OrderedDict. |
831 | | |
| 831 | |
832 | 832 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
833 | 833 | >>> d.insert(0, 4, 0) |
… |
… |
|
850 | 850 | """ |
851 | 851 | Reverse the order of the OrderedDict. |
852 | | |
| 852 | |
853 | 853 | >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) |
854 | 854 | >>> d.reverse() |
… |
… |
|
861 | 861 | """ |
862 | 862 | Sort the key order in the OrderedDict. |
863 | | |
| 863 | |
864 | 864 | This method takes the same arguments as the ``list.sort`` method on |
865 | 865 | your version of Python. |
866 | | |
| 866 | |
867 | 867 | >>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4))) |
868 | 868 | >>> d.sort() |
… |
… |
|
876 | 876 | """ |
877 | 877 | Custom object for accessing the keys of an OrderedDict. |
878 | | |
| 878 | |
879 | 879 | Can be called like the normal ``OrderedDict.keys`` method, but also |
880 | 880 | supports indexing and sequence methods. |
… |
… |
|
897 | 897 | You cannot assign to keys, but you can do slice assignment to re-order |
898 | 898 | them. |
899 | | |
| 899 | |
900 | 900 | You can only do slice assignment if the new set of keys is a reordering |
901 | 901 | of the original set. |
… |
… |
|
967 | 967 | """ |
968 | 968 | Custom object for accessing the items of an OrderedDict. |
969 | | |
| 969 | |
970 | 970 | Can be called like the normal ``OrderedDict.items`` method, but also |
971 | 971 | supports indexing and sequence methods. |
… |
… |
|
1077 | 1077 | """ |
1078 | 1078 | Custom object for accessing the values of an OrderedDict. |
1079 | | |
| 1079 | |
1080 | 1080 | Can be called like the normal ``OrderedDict.values`` method, but also |
1081 | 1081 | supports indexing and sequence methods. |
… |
… |
|
1099 | 1099 | """ |
1100 | 1100 | Set the value at position i to value. |
1101 | | |
| 1101 | |
1102 | 1102 | You can only do slice assignment to values if you supply a sequence of |
1103 | 1103 | equal length to the slice you are replacing. |
… |
… |
|
1168 | 1168 | Experimental version of OrderedDict that has a custom object for ``keys``, |
1169 | 1169 | ``values``, and ``items``. |
1170 | | |
| 1170 | |
1171 | 1171 | These are callable sequence objects that work as methods, or can be |
1172 | 1172 | manipulated directly as sequences. |
1173 | | |
| 1173 | |
1174 | 1174 | Test for ``keys``, ``items`` and ``values``. |
1175 | | |
| 1175 | |
1176 | 1176 | >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) |
1177 | 1177 | >>> d |
… |
… |
|
1293 | 1293 | >>> d |
1294 | 1294 | SequenceOrderedDict([(1, 1), (2, 2), (3, 3)]) |
1295 | | |
| 1295 | |
1296 | 1296 | >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) |
1297 | 1297 | >>> d |
-
r5a8cdbb
|
rdc8d1c2
|
|
101 | 101 | extlist = [ext for ext in self.extensions() if path.endswith(ext)] |
102 | 102 | # Sort matching extensions by decreasing order of length |
103 | | extlist.sort(lambda a,b: len(a)<len(b)) |
| 103 | extlist.sort(key=len) |
104 | 104 | # Combine loaders for matching extensions into one big list |
105 | 105 | loaders = [] |
-
r9a5097c
|
r574adc7
|
|
2 | 2 | Uncertainty propagation class for arithmetic, log and exp. |
3 | 3 | |
4 | | Based on scalars or numpy vectors, this class allows you to store and |
| 4 | Based on scalars or numpy vectors, this class allows you to store and |
5 | 5 | manipulate values+uncertainties, with propagation of gaussian error for |
6 | 6 | addition, subtraction, multiplication, division, power, exp and log. |
7 | 7 | |
8 | 8 | Storage properties are determined by the numbers used to set the value |
9 | | and uncertainty. Be sure to use floating point uncertainty vectors |
| 9 | and uncertainty. Be sure to use floating point uncertainty vectors |
10 | 10 | for inplace operations since numpy does not do automatic type conversion. |
11 | 11 | Normal operations can use mixed integer and floating point. In place |
… |
… |
|
18 | 18 | |
19 | 19 | import numpy as np |
20 | | import err1d |
21 | | from formatnum import format_uncertainty |
| 20 | |
| 21 | from .import err1d |
| 22 | from .formatnum import format_uncertainty |
22 | 23 | |
23 | 24 | __all__ = ['Uncertainty'] |
… |
… |
|
28 | 29 | # Make standard deviation available |
29 | 30 | def _getdx(self): return np.sqrt(self.variance) |
30 | | def _setdx(self,dx): |
| 31 | def _setdx(self,dx): |
31 | 32 | # Direct operation |
32 | 33 | # variance = dx**2 |
… |
… |
|
38 | 39 | # Constructor |
39 | 40 | def __init__(self, x, variance=None): |
40 | | self.x, self.variance = x, variance |
41 | | |
| 41 | self.x, self.variance = x, variance |
| 42 | |
42 | 43 | # Numpy array slicing operations |
43 | | def __len__(self): |
| 44 | def __len__(self): |
44 | 45 | return len(self.x) |
45 | | def __getitem__(self,key): |
| 46 | def __getitem__(self,key): |
46 | 47 | return Uncertainty(self.x[key],self.variance[key]) |
47 | 48 | def __setitem__(self,key,value): |
… |
… |
|
137 | 138 | def __idiv__(self, other): return self.__itruediv__(other) |
138 | 139 | |
139 | | |
| 140 | |
140 | 141 | # Unary ops |
141 | 142 | def __neg__(self): |
… |
… |
|
151 | 152 | return format_uncertainty(self.x,np.sqrt(self.variance)) |
152 | 153 | else: |
153 | | return [format_uncertainty(v,dv) |
| 154 | return [format_uncertainty(v,dv) |
154 | 155 | for v,dv in zip(self.x,np.sqrt(self.variance))] |
155 | 156 | def __repr__(self): |
… |
… |
|
219 | 220 | z = a/4 |
220 | 221 | assert z.x == 5./4 and z.variance == 3./4**2 |
221 | | |
| 222 | |
222 | 223 | # Reverse scalar operations |
223 | 224 | z = 4+a |
… |
… |
|
229 | 230 | z = 4/a |
230 | 231 | assert z.x == 4./5 and abs(z.variance - 3./5**4 * 4**2) < 1e-15 |
231 | | |
| 232 | |
232 | 233 | # Power operations |
233 | 234 | z = a**2 |
… |
… |
|
250 | 251 | assert z.x == 5./4 and abs(z.variance - (3./5**2 + 2./4**2)*(5./4)**2) < 1e-15 |
251 | 252 | |
252 | | # ===== Inplace operations ===== |
| 253 | # ===== Inplace operations ===== |
253 | 254 | # Scalar operations |
254 | 255 | y = a+0; y += 4 |
… |
… |
|
308 | 309 | assert (z.x == 5./4).all() |
309 | 310 | assert (abs(z.variance - (3./5**2 + 2./4**2)*(5./4)**2) < 1e-15).all() |
310 | | |
| 311 | |
311 | 312 | # printing; note that sqrt(3) ~ 1.7 |
312 | 313 | assert str(Uncertainty(5,3)) == "5.0(17)" |
-
rb699768
|
r574adc7
|
|
1 | | from data_info import * |
2 | | from manipulations import * |
3 | | from readers import * |
| 1 | from .data_info import * |
| 2 | from .manipulations import * |
| 3 | from .readers import * |
-
rdeaa0c6
|
r9e6aeaf
|
|
716 | 716 | self.y_unit = '1/cm' |
717 | 717 | except: # the data is not recognized/supported, and the user is notified |
718 | | raise(TypeError, 'data not recognized, check documentation for supported 1D data formats') |
| 718 | raise TypeError('data not recognized, check documentation for supported 1D data formats') |
719 | 719 | |
720 | 720 | def __str__(self): |
… |
… |
|
796 | 796 | len(self.y) != len(other.y): |
797 | 797 | msg = "Unable to perform operation: data length are not equal" |
798 | | raise ValueError, msg |
| 798 | raise ValueError(msg) |
799 | 799 | # Here we could also extrapolate between data points |
800 | 800 | TOLERANCE = 0.01 |
… |
… |
|
802 | 802 | if math.fabs((self.x[i] - other.x[i])/self.x[i]) > TOLERANCE: |
803 | 803 | msg = "Incompatible data sets: x-values do not match" |
804 | | raise ValueError, msg |
| 804 | raise ValueError(msg) |
805 | 805 | |
806 | 806 | # Check that the other data set has errors, otherwise |
… |
… |
|
876 | 876 | if not isinstance(other, Data1D): |
877 | 877 | msg = "Unable to perform operation: different types of data set" |
878 | | raise ValueError, msg |
| 878 | raise ValueError(msg) |
879 | 879 | return True |
880 | 880 | |
… |
… |
|
948 | 948 | |
949 | 949 | if len(self.detector) > 0: |
950 | | raise RuntimeError, "Data2D: Detector bank already filled at init" |
| 950 | raise RuntimeError("Data2D: Detector bank already filled at init") |
951 | 951 | |
952 | 952 | def __str__(self): |
… |
… |
|
1020 | 1020 | len(self.qy_data) != len(other.qy_data): |
1021 | 1021 | msg = "Unable to perform operation: data length are not equal" |
1022 | | raise ValueError, msg |
| 1022 | raise ValueError(msg) |
1023 | 1023 | for ind in range(len(self.data)): |
1024 | 1024 | if math.fabs((self.qx_data[ind] - other.qx_data[ind])/self.qx_data[ind]) > TOLERANCE: |
1025 | 1025 | msg = "Incompatible data sets: qx-values do not match: %s %s" % (self.qx_data[ind], other.qx_data[ind]) |
1026 | | raise ValueError, msg |
| 1026 | raise ValueError(msg) |
1027 | 1027 | if math.fabs((self.qy_data[ind] - other.qy_data[ind])/self.qy_data[ind]) > TOLERANCE: |
1028 | 1028 | msg = "Incompatible data sets: qy-values do not match: %s %s" % (self.qy_data[ind], other.qy_data[ind]) |
1029 | | raise ValueError, msg |
| 1029 | raise ValueError(msg) |
1030 | 1030 | |
1031 | 1031 | # Check that the scales match |
… |
… |
|
1108 | 1108 | if not isinstance(other, Data2D): |
1109 | 1109 | msg = "Unable to perform operation: different types of data set" |
1110 | | raise ValueError, msg |
| 1110 | raise ValueError(msg) |
1111 | 1111 | return True |
1112 | 1112 | |
-
rdeaa0c6
|
r9e6aeaf
|
|
6 | 6 | |
7 | 7 | import os |
| 8 | import sys |
8 | 9 | import re |
9 | 10 | import logging |
| 11 | from abc import abstractmethod |
| 12 | |
10 | 13 | import numpy as np |
11 | | from abc import abstractmethod |
12 | | from loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
| 14 | from .loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
13 | 15 | DataReaderException, DefaultReaderException |
14 | | from data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\ |
| 16 | from .data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\ |
15 | 17 | combine_data_info_with_plottable |
16 | 18 | |
17 | 19 | logger = logging.getLogger(__name__) |
18 | 20 | |
| 21 | if sys.version_info[0] < 3: |
| 22 | def decode(s): |
| 23 | return s |
| 24 | else: |
| 25 | def decode(s): |
| 26 | return s.decode() if isinstance(s, bytes) else s |
19 | 27 | |
20 | 28 | class FileReader(object): |
… |
… |
|
78 | 86 | # Return a list of parsed entries that data_loader can manage |
79 | 87 | return self.output |
| 88 | |
| 89 | def nextline(self): |
| 90 | """ |
| 91 | Returns the next line in the file as a string. |
| 92 | """ |
| 93 | #return self.f_open.readline() |
| 94 | return decode(self.f_open.readline()) |
| 95 | |
| 96 | def nextlines(self): |
| 97 | """ |
| 98 | Returns the next line in the file as a string. |
| 99 | """ |
| 100 | for line in self.f_open: |
| 101 | #yield line |
| 102 | yield decode(line) |
| 103 | |
| 104 | def readall(self): |
| 105 | """ |
| 106 | Returns the entire file as a string. |
| 107 | """ |
| 108 | #return self.f_open.read() |
| 109 | return decode(self.f_open.read()) |
80 | 110 | |
81 | 111 | def handle_error_message(self, msg): |
-
rdcb91cf
|
rdc8d1c2
|
|
26 | 26 | import time |
27 | 27 | from zipfile import ZipFile |
| 28 | |
28 | 29 | from sas.sascalc.data_util.registry import ExtensionRegistry |
| 30 | |
29 | 31 | # Default readers are defined in the readers sub-module |
30 | | import readers |
31 | | from loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
| 32 | from . import readers |
| 33 | from .loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
32 | 34 | DefaultReaderException |
33 | | from readers import ascii_reader |
34 | | from readers import cansas_reader |
35 | | from readers import cansas_reader_HDF5 |
| 35 | from .readers import ascii_reader |
| 36 | from .readers import cansas_reader |
| 37 | from .readers import cansas_reader_HDF5 |
36 | 38 | |
37 | 39 | logger = logging.getLogger(__name__) |
… |
… |
|
73 | 75 | try: |
74 | 76 | return super(Registry, self).load(path, format=format) |
| 77 | #except Exception: raise # for debugging, don't use fallback loader |
75 | 78 | except NoKnownLoaderException as nkl_e: |
76 | 79 | pass # Try the ASCII reader |
… |
… |
|
327 | 330 | extlist = [ext for ext in self.extensions() if path.endswith(ext)] |
328 | 331 | # Sort matching extensions by decreasing order of length |
329 | | extlist.sort(lambda a, b: len(a) < len(b)) |
| 332 | extlist.sort(key=len) |
330 | 333 | # Combine loaders for matching extensions into one big list |
331 | 334 | writers = [] |
… |
… |
|
341 | 344 | # Raise an error if there are no matching extensions |
342 | 345 | if len(writers) == 0: |
343 | | raise ValueError, "Unknown file type for " + path |
| 346 | raise ValueError("Unknown file type for " + path) |
344 | 347 | # All done |
345 | 348 | return writers |
… |
… |
|
360 | 363 | try: |
361 | 364 | return fn(path, data) |
362 | | except: |
| 365 | except Exception: |
363 | 366 | pass # give other loaders a chance to succeed |
364 | 367 | # If we get here it is because all loaders failed |
-
r324e0bf
|
r574adc7
|
|
26 | 26 | |
27 | 27 | #from data_info import plottable_2D |
28 | | from data_info import Data1D |
| 28 | from .data_info import Data1D |
29 | 29 | |
30 | 30 | |
-
r488f3a5
|
raaa801e
|
|
1 | 1 | # Method to associate extensions to default readers |
2 | | from associations import read_associations |
| 2 | from .associations import read_associations |
-
rffb6474
|
r1efbc190
|
|
11 | 11 | |
12 | 12 | import logging |
| 13 | |
13 | 14 | import numpy as np |
14 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
15 | | from sas.sascalc.dataloader.data_info import DataInfo, plottable_1D, Data1D,\ |
16 | | Detector |
17 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException,\ |
18 | | DefaultReaderException |
| 15 | |
| 16 | from sas.sascalc.data_util.nxsunit import Converter |
| 17 | from ..file_reader_base_class import FileReader |
| 18 | from ..data_info import DataInfo, plottable_1D, Data1D, Detector |
| 19 | from ..loader_exceptions import FileContentsException, DefaultReaderException |
19 | 20 | |
20 | 21 | logger = logging.getLogger(__name__) |
… |
… |
|
31 | 32 | # List of allowed extensions |
32 | 33 | ext = ['.abs'] |
33 | | |
| 34 | |
34 | 35 | def get_file_contents(self): |
35 | | """ |
| 36 | """ |
36 | 37 | Get the contents of the file |
37 | | |
| 38 | |
38 | 39 | :raise RuntimeError: when the file can't be opened |
39 | 40 | :raise ValueError: when the length of the data vectors are inconsistent |
40 | 41 | """ |
41 | | buff = self.f_open.read() |
| 42 | buff = self.readall() |
42 | 43 | filepath = self.f_open.name |
43 | 44 | lines = buff.splitlines() |
44 | | self.has_converter = True |
45 | | try: |
46 | | from sas.sascalc.data_util.nxsunit import Converter |
47 | | except: |
48 | | self.has_converter = False |
49 | 45 | self.output = [] |
50 | 46 | self.current_datainfo = DataInfo() |
… |
… |
|
75 | 71 | try: |
76 | 72 | value = float(line_toks[1]) |
77 | | if self.has_converter and \ |
78 | | self.current_datainfo.source.wavelength_unit != 'A': |
| 73 | if self.current_datainfo.source.wavelength_unit != 'A': |
79 | 74 | conv = Converter('A') |
80 | 75 | self.current_datainfo.source.wavelength = conv(value, |
… |
… |
|
89 | 84 | try: |
90 | 85 | value = float(line_toks[3]) |
91 | | if self.has_converter and detector.distance_unit != 'm': |
| 86 | if detector.distance_unit != 'm': |
92 | 87 | conv = Converter('m') |
93 | 88 | detector.distance = conv(value, |
… |
… |
|
95 | 90 | else: |
96 | 91 | detector.distance = value |
97 | | except: |
| 92 | except Exception: |
98 | 93 | msg = "ABSReader cannot read SDD from %s" % filepath |
99 | 94 | self.current_datainfo.errors.append(msg) |
… |
… |
|
109 | 104 | # Sample thickness in mm |
110 | 105 | try: |
111 | | value = float(line_toks[5][:-1]) |
112 | | if self.has_converter and \ |
113 | | self.current_datainfo.sample.thickness_unit != 'cm': |
| 106 | # ABS writer adds 'C' with no space to the end of the |
| 107 | # thickness column. Remove it if it is there before |
| 108 | # converting the thickness. |
| 109 | if line_toks[5][-1] not in '012345679.': |
| 110 | value = float(line_toks[5][:-1]) |
| 111 | else: |
| 112 | value = float(line_toks[5]) |
| 113 | if self.current_datainfo.sample.thickness_unit != 'cm': |
114 | 114 | conv = Converter('cm') |
115 | 115 | self.current_datainfo.sample.thickness = conv(value, |
… |
… |
|
134 | 134 | |
135 | 135 | # Bin size |
136 | | if self.has_converter and detector.pixel_size_unit != 'mm': |
| 136 | if detector.pixel_size_unit != 'mm': |
137 | 137 | conv = Converter('mm') |
138 | 138 | detector.pixel_size.x = conv(5.08, |
… |
… |
|
146 | 146 | # Store beam center in distance units |
147 | 147 | # Det 640 x 640 mm |
148 | | if self.has_converter and detector.beam_center_unit != 'mm': |
| 148 | if detector.beam_center_unit != 'mm': |
149 | 149 | conv = Converter('mm') |
150 | 150 | detector.beam_center.x = conv(center_x * 5.08, |
151 | 151 | units=detector.beam_center_unit) |
152 | 152 | detector.beam_center.y = conv(center_y * 5.08, |
153 | | units=detector.beam_center_unit) |
| 153 | units=detector.beam_center_unit) |
154 | 154 | else: |
155 | 155 | detector.beam_center.x = center_x * 5.08 |
-
rfafe52a
|
ra5bd87a
|
|
63 | 63 | ## Reinitialize the class when loading a new data file to reset all class variables |
64 | 64 | self.reset_state() |
65 | | buff = self.f_open.read() |
| 65 | buff = self.readall() |
66 | 66 | self.raw_data = buff.splitlines() |
67 | 67 | self.read_data() |
-
r7b07fbe
|
r9e6aeaf
|
|
45 | 45 | """ |
46 | 46 | |
47 | | buff = self.f_open.read() |
| 47 | buff = self.readall() |
48 | 48 | filepath = self.f_open.name |
49 | 49 | lines = buff.splitlines() |
… |
… |
|
130 | 130 | # Reset # of lines of data candidates |
131 | 131 | candidate_lines = 0 |
132 | | |
| 132 | |
133 | 133 | if not is_data: |
134 | 134 | self.set_all_to_none() |
-
rce8c7bd
|
r574adc7
|
|
40 | 40 | """ |
41 | 41 | # For each FileType entry, get the associated reader and extension |
42 | | for ext, reader in settings.iteritems(): |
| 42 | for ext, reader in settings.items(): |
43 | 43 | if reader is not None and ext is not None: |
44 | 44 | # Associate the extension with a particular reader |
… |
… |
|
47 | 47 | # and remove the extra line below. |
48 | 48 | try: |
49 | | exec "import %s" % reader |
50 | | exec "loader.associate_file_type('%s', %s)" % (ext.lower(), |
51 | | reader) |
52 | | exec "loader.associate_file_type('%s', %s)" % (ext.upper(), |
53 | | reader) |
| 49 | exec("from . import %s" % reader) |
| 50 | exec("loader.associate_file_type('%s', %s)" |
| 51 | % (ext.lower(), reader)) |
| 52 | exec("loader.associate_file_type('%s', %s)" |
| 53 | % (ext.upper(), reader)) |
54 | 54 | except: |
55 | 55 | msg = "read_associations: skipping association" |
-
r62160509
|
r9e6aeaf
|
|
1 | 1 | import logging |
2 | | import numpy as np |
3 | 2 | import os |
4 | 3 | import sys |
5 | 4 | import datetime |
6 | 5 | import inspect |
7 | | # For saving individual sections of data |
8 | | from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \ |
9 | | plottable_1D, plottable_2D |
10 | | from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \ |
11 | | Detector, Process, Aperture |
12 | | from sas.sascalc.dataloader.data_info import \ |
13 | | combine_data_info_with_plottable as combine_data |
14 | | import sas.sascalc.dataloader.readers.xml_reader as xml_reader |
15 | | from sas.sascalc.dataloader.readers.xml_reader import XMLreader |
16 | | from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel |
17 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException, \ |
18 | | DefaultReaderException, DataReaderException |
| 6 | |
| 7 | import numpy as np |
19 | 8 | |
20 | 9 | # The following 2 imports *ARE* used. Do not remove either. |
… |
… |
|
23 | 12 | |
24 | 13 | from lxml import etree |
| 14 | |
| 15 | from sas.sascalc.data_util.nxsunit import Converter |
| 16 | |
| 17 | # For saving individual sections of data |
| 18 | from ..data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D, \ |
| 19 | Collimation, TransmissionSpectrum, Detector, Process, Aperture, \ |
| 20 | combine_data_info_with_plottable as combine_data |
| 21 | from ..loader_exceptions import FileContentsException, DefaultReaderException, \ |
| 22 | DataReaderException |
| 23 | from . import xml_reader |
| 24 | from .xml_reader import XMLreader |
| 25 | from .cansas_constants import CansasConstants, CurrentLevel |
25 | 26 | |
26 | 27 | logger = logging.getLogger(__name__) |
… |
… |
|
33 | 34 | INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \ |
34 | 35 | "as much of the data as possible.\n\n" |
35 | | HAS_CONVERTER = True |
36 | | try: |
37 | | from sas.sascalc.data_util.nxsunit import Converter |
38 | | except ImportError: |
39 | | HAS_CONVERTER = False |
40 | 36 | |
41 | 37 | CONSTANTS = CansasConstants() |
… |
… |
|
152 | 148 | raise fc_exc |
153 | 149 | except Exception as e: # Convert all other exceptions to FileContentsExceptions |
154 | | raise FileContentsException(e.message) |
| 150 | raise FileContentsException(str(e)) |
155 | 151 | finally: |
156 | 152 | if not self.f_open.closed: |
… |
… |
|
622 | 618 | else: |
623 | 619 | save_in = "current_datainfo" |
624 | | exec "default_unit = self.{0}.{1}".format(save_in, unitname) |
625 | | if local_unit and default_unit and local_unit.lower() != default_unit.lower() \ |
626 | | and local_unit.lower() != "none": |
627 | | if HAS_CONVERTER == True: |
628 | | # Check local units - bad units raise KeyError |
629 | | data_conv_q = Converter(local_unit) |
630 | | value_unit = default_unit |
631 | | node_value = data_conv_q(node_value, units=default_unit) |
632 | | else: |
633 | | value_unit = local_unit |
634 | | err_msg = "Unit converter is not available.\n" |
| 620 | default_unit = getattrchain(self, '.'.join((save_in, unitname))) |
| 621 | if (local_unit and default_unit |
| 622 | and local_unit.lower() != default_unit.lower() |
| 623 | and local_unit.lower() != "none"): |
| 624 | # Check local units - bad units raise KeyError |
| 625 | #print("loading", tagname, node_value, local_unit, default_unit) |
| 626 | data_conv_q = Converter(local_unit) |
| 627 | value_unit = default_unit |
| 628 | node_value = data_conv_q(node_value, units=default_unit) |
635 | 629 | else: |
636 | 630 | value_unit = local_unit |
… |
… |
|
644 | 638 | err_msg += "expecting [{0}]".format(default_unit) |
645 | 639 | value_unit = local_unit |
646 | | except: |
| 640 | except Exception: |
647 | 641 | err_msg = "CanSAS reader: unknown error converting " |
648 | 642 | err_msg += "\"{0}\" unit [{1}]" |
… |
… |
|
676 | 670 | doc, _ = self._to_xml_doc(datainfo) |
677 | 671 | # Write the file |
678 | | file_ref = open(filename, 'w') |
| 672 | file_ref = open(filename, 'wb') |
679 | 673 | if self.encoding is None: |
680 | 674 | self.encoding = "UTF-8" |
… |
… |
|
867 | 861 | point = self.create_element("Idata") |
868 | 862 | node.append(point) |
869 | | qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))]) |
870 | | qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))]) |
871 | | intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))]) |
| 863 | qx = ','.join(str(v) for v in datainfo.qx_data) |
| 864 | qy = ','.join(str(v) for v in datainfo.qy_data) |
| 865 | intensity = ','.join(str(v) for v in datainfo.data) |
872 | 866 | |
873 | 867 | self.write_node(point, "Qx", qx, |
… |
… |
|
878 | 872 | {'unit': datainfo._zunit}) |
879 | 873 | if datainfo.err_data is not None: |
880 | | err = ','.join([str(datainfo.err_data[i]) for i in |
881 | | xrange(len(datainfo.err_data))]) |
| 874 | err = ','.join(str(v) for v in datainfo.err_data) |
882 | 875 | self.write_node(point, "Idev", err, |
883 | 876 | {'unit': datainfo._zunit}) |
884 | 877 | if datainfo.dqy_data is not None: |
885 | | dqy = ','.join([str(datainfo.dqy_data[i]) for i in |
886 | | xrange(len(datainfo.dqy_data))]) |
| 878 | dqy = ','.join(str(v) for v in datainfo.dqy_data) |
887 | 879 | self.write_node(point, "Qydev", dqy, |
888 | 880 | {'unit': datainfo._yunit}) |
889 | 881 | if datainfo.dqx_data is not None: |
890 | | dqx = ','.join([str(datainfo.dqx_data[i]) for i in |
891 | | xrange(len(datainfo.dqx_data))]) |
| 882 | dqx = ','.join(str(v) for v in datainfo.dqx_data) |
892 | 883 | self.write_node(point, "Qxdev", dqx, |
893 | 884 | {'unit': datainfo._xunit}) |
894 | 885 | if datainfo.mask is not None: |
895 | | mask = ','.join( |
896 | | ["1" if datainfo.mask[i] else "0" |
897 | | for i in xrange(len(datainfo.mask))]) |
| 886 | mask = ','.join("1" if v else "0" for v in datainfo.mask) |
898 | 887 | self.write_node(point, "Mask", mask) |
899 | 888 | |
… |
… |
|
1239 | 1228 | try: |
1240 | 1229 | value = float(entry.text) |
1241 | | except: |
| 1230 | except ValueError: |
1242 | 1231 | value = None |
1243 | 1232 | |
… |
… |
|
1248 | 1237 | if units is not None: |
1249 | 1238 | toks = variable.split('.') |
1250 | | local_unit = None |
1251 | | exec "local_unit = storage.%s_unit" % toks[0] |
| 1239 | # TODO: why split() when accessing unit, but not when setting value? |
| 1240 | local_unit = getattr(storage, toks[0]+"_unit") |
1252 | 1241 | if local_unit is not None and units.lower() != local_unit.lower(): |
1253 | | if HAS_CONVERTER == True: |
1254 | | try: |
1255 | | conv = Converter(units) |
1256 | | exec "storage.%s = %g" % \ |
1257 | | (variable, conv(value, units=local_unit)) |
1258 | | except: |
1259 | | _, exc_value, _ = sys.exc_info() |
1260 | | err_mess = "CanSAS reader: could not convert" |
1261 | | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
1262 | | % (variable, units, local_unit, exc_value) |
1263 | | self.errors.add(err_mess) |
1264 | | if optional: |
1265 | | logger.info(err_mess) |
1266 | | else: |
1267 | | raise ValueError, err_mess |
1268 | | else: |
1269 | | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
1270 | | % (variable, units) |
1271 | | err_mess += " expecting [%s]" % local_unit |
| 1242 | try: |
| 1243 | conv = Converter(units) |
| 1244 | setattrchain(storage, variable, conv(value, units=local_unit)) |
| 1245 | except Exception: |
| 1246 | _, exc_value, _ = sys.exc_info() |
| 1247 | err_mess = "CanSAS reader: could not convert" |
| 1248 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
| 1249 | % (variable, units, local_unit, exc_value) |
1272 | 1250 | self.errors.add(err_mess) |
1273 | 1251 | if optional: |
1274 | 1252 | logger.info(err_mess) |
1275 | 1253 | else: |
1276 | | raise ValueError, err_mess |
| 1254 | raise ValueError(err_mess) |
1277 | 1255 | else: |
1278 | | exec "storage.%s = value" % variable |
| 1256 | setattrchain(storage, variable, value) |
1279 | 1257 | else: |
1280 | | exec "storage.%s = value" % variable |
| 1258 | setattrchain(storage, variable, value) |
1281 | 1259 | |
1282 | 1260 | # DO NOT REMOVE - used in saving and loading panel states. |
… |
… |
|
1298 | 1276 | entry = get_content(location, node) |
1299 | 1277 | if entry is not None and entry.text is not None: |
1300 | | exec "storage.%s = entry.text.strip()" % variable |
| 1278 | setattrchain(storage, variable, entry.text.strip()) |
1301 | 1279 | |
1302 | 1280 | # DO NOT REMOVE Called by outside packages: |
… |
… |
|
1341 | 1319 | return True |
1342 | 1320 | return False |
| 1321 | |
| 1322 | def getattrchain(obj, chain, default=None): |
| 1323 | """Like getattr, but the attr may contain multiple parts separated by '.'""" |
| 1324 | for part in chain.split('.'): |
| 1325 | if hasattr(obj, part): |
| 1326 | obj = getattr(obj, part, None) |
| 1327 | else: |
| 1328 | return default |
| 1329 | return obj |
| 1330 | |
| 1331 | def setattrchain(obj, chain, value): |
| 1332 | """Like setattr, but the attr may contain multiple parts separated by '.'""" |
| 1333 | parts = list(chain.split('.')) |
| 1334 | for part in parts[-1]: |
| 1335 | obj = getattr(obj, part, None) |
| 1336 | if obj is None: |
| 1337 | raise ValueError("missing parent object "+part) |
| 1338 | setattr(obj, value) |
-
rcd57c7d4
|
r7b50f14
|
|
9 | 9 | import sys |
10 | 10 | |
11 | | from sas.sascalc.dataloader.data_info import plottable_1D, plottable_2D,\ |
| 11 | from ..data_info import plottable_1D, plottable_2D,\ |
12 | 12 | Data1D, Data2D, DataInfo, Process, Aperture, Collimation, \ |
13 | 13 | TransmissionSpectrum, Detector |
14 | | from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable |
15 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DefaultReaderException |
16 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
17 | | |
| 14 | from ..data_info import combine_data_info_with_plottable |
| 15 | from ..loader_exceptions import FileContentsException, DefaultReaderException |
| 16 | from ..file_reader_base_class import FileReader, decode |
| 17 | |
| 18 | def h5attr(node, key, default=None): |
| 19 | return decode(node.attrs.get(key, default)) |
18 | 20 | |
19 | 21 | class Reader(FileReader): |
… |
… |
|
130 | 132 | # Get all information for the current key |
131 | 133 | value = data.get(key) |
132 | | if value.attrs.get(u'canSAS_class') is not None: |
133 | | class_name = value.attrs.get(u'canSAS_class') |
134 | | else: |
135 | | class_name = value.attrs.get(u'NX_class') |
| 134 | class_name = h5attr(value, u'canSAS_class') |
| 135 | if class_name is None: |
| 136 | class_name = h5attr(value, u'NX_class') |
136 | 137 | if class_name is not None: |
137 | 138 | class_prog = re.compile(class_name) |
… |
… |
|
225 | 226 | |
226 | 227 | for data_point in data_set: |
| 228 | if data_point.dtype.char == 'S': |
| 229 | data_point = decode(bytes(data_point)) |
227 | 230 | # Top Level Meta Data |
228 | 231 | if key == u'definition': |
… |
… |
|
231 | 234 | self.current_datainfo.run.append(data_point) |
232 | 235 | try: |
233 | | run_name = value.attrs['name'] |
| 236 | run_name = h5attr(value, 'name') |
234 | 237 | run_dict = {data_point: run_name} |
235 | 238 | self.current_datainfo.run_name = run_dict |
236 | | except: |
| 239 | except Exception: |
237 | 240 | pass |
238 | 241 | elif key == u'title': |
… |
… |
|
576 | 579 | :return: unit for the value passed to the method |
577 | 580 | """ |
578 | | unit = value.attrs.get(u'units') |
| 581 | unit = h5attr(value, u'units') |
579 | 582 | if unit is None: |
580 | | unit = value.attrs.get(u'unit') |
| 583 | unit = h5attr(value, u'unit') |
581 | 584 | # Convert the unit formats |
582 | 585 | if unit == "1/A": |
-
ra78a02f
|
raf3e9f5
|
|
14 | 14 | import math |
15 | 15 | import os |
| 16 | import logging |
| 17 | |
16 | 18 | import numpy as np |
17 | | import logging |
18 | | from sas.sascalc.dataloader.data_info import plottable_2D, DataInfo, Detector |
19 | | from sas.sascalc.dataloader.manipulations import reader2D_converter |
20 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
21 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DataReaderException |
| 19 | |
| 20 | from ..data_info import plottable_2D, DataInfo, Detector |
| 21 | from ..manipulations import reader2D_converter |
| 22 | from ..file_reader_base_class import FileReader |
| 23 | from ..loader_exceptions import FileContentsException, DataReaderException |
22 | 24 | |
23 | 25 | logger = logging.getLogger(__name__) |
… |
… |
|
78 | 80 | data_start_line = 1 |
79 | 81 | while read_on: |
80 | | line = self.f_open.readline() |
| 82 | line = self.nextline() |
81 | 83 | data_start_line += 1 |
82 | 84 | if line.find("DATA:") >= 0: |
… |
… |
|
112 | 114 | raise FileContentsException(msg) |
113 | 115 | |
114 | | for line_num, data_str in enumerate(self.f_open.readlines()): |
| 116 | for line_num, data_str in enumerate(self.nextlines()): |
115 | 117 | toks = data_str.split() |
116 | 118 | try: |
-
r2f85af7
|
rc8321cfc
|
|
10 | 10 | ###################################################################### |
11 | 11 | import os |
| 12 | import math |
| 13 | import time |
| 14 | |
12 | 15 | import numpy as np |
13 | | import math |
14 | | from sas.sascalc.dataloader.data_info import plottable_2D, DataInfo, Detector |
15 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
16 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException |
17 | | |
18 | | # Look for unit converter |
19 | | has_converter = True |
20 | | try: |
21 | | from sas.sascalc.data_util.nxsunit import Converter |
22 | | except: |
23 | | has_converter = False |
| 16 | |
| 17 | from sas.sascalc.data_util.nxsunit import Converter |
| 18 | |
| 19 | from ..data_info import plottable_2D, DataInfo, Detector |
| 20 | from ..file_reader_base_class import FileReader |
| 21 | from ..loader_exceptions import FileContentsException |
24 | 22 | |
25 | 23 | |
… |
… |
|
31 | 29 | try: |
32 | 30 | return float(x_point) |
33 | | except: |
| 31 | except Exception: |
34 | 32 | return 0 |
35 | 33 | |
… |
… |
|
51 | 49 | :param data: data2D |
52 | 50 | """ |
53 | | import time |
54 | 51 | # Write the file |
55 | 52 | try: |
… |
… |
|
72 | 69 | def get_file_contents(self): |
73 | 70 | # Read file |
74 | | buf = self.f_open.read() |
| 71 | buf = self.readall() |
75 | 72 | self.f_open.close() |
76 | 73 | # Instantiate data object |
… |
… |
|
119 | 116 | try: |
120 | 117 | wavelength = float(line_toks[1]) |
121 | | # Units |
122 | | if has_converter == True and \ |
123 | | self.current_datainfo.source.wavelength_unit != 'A': |
| 118 | # Wavelength is stored in angstroms; convert if necessary |
| 119 | if self.current_datainfo.source.wavelength_unit != 'A': |
124 | 120 | conv = Converter('A') |
125 | 121 | wavelength = conv(wavelength, |
126 | 122 | units=self.current_datainfo.source.wavelength_unit) |
127 | | except: |
128 | | #Not required |
129 | | pass |
130 | | # Distance in mm |
| 123 | except Exception: |
| 124 | pass # Not required |
131 | 125 | try: |
132 | 126 | distance = float(line_toks[3]) |
133 | | # Units |
134 | | if has_converter == True and self.current_datainfo.detector[0].distance_unit != 'm': |
| 127 | # Distance is stored in meters; convert if necessary |
| 128 | if self.current_datainfo.detector[0].distance_unit != 'm': |
135 | 129 | conv = Converter('m') |
136 | 130 | distance = conv(distance, |
137 | 131 | units=self.current_datainfo.detector[0].distance_unit) |
138 | | except: |
139 | | #Not required |
140 | | pass |
141 | | |
142 | | # Distance in meters |
| 132 | except Exception: |
| 133 | pass # Not required |
| 134 | |
143 | 135 | try: |
144 | 136 | transmission = float(line_toks[4]) |
145 | | except: |
146 | | #Not required |
147 | | pass |
| 137 | except Exception: |
| 138 | pass # Not required |
148 | 139 | |
149 | 140 | if line.count("LAMBDA") > 0: |
… |
… |
|
170 | 161 | |
171 | 162 | ## Read and get data. |
172 | | if data_started == True: |
| 163 | if data_started: |
173 | 164 | line_toks = line.split() |
174 | 165 | if len(line_toks) == 0: |
… |
… |
|
178 | 169 | col_num = len(line_toks) |
179 | 170 | break |
| 171 | |
180 | 172 | # Make numpy array to remove header lines using index |
181 | 173 | lines_array = np.array(lines) |
… |
… |
|
203 | 195 | # Change it(string) into float |
204 | 196 | #data_list = map(float,data_list) |
205 | | data_list1 = map(check_point, data_list) |
| 197 | data_list1 = list(map(check_point, data_list)) |
206 | 198 | |
207 | 199 | # numpy array form |
… |
… |
|
211 | 203 | try: |
212 | 204 | data_point = data_array.reshape(row_num, col_num).transpose() |
213 | | except: |
| 205 | except Exception: |
214 | 206 | msg = "red2d_reader can't read this file: Incorrect number of data points provided." |
215 | 207 | raise FileContentsException(msg) |
… |
… |
|
325 | 317 | |
326 | 318 | # Units of axes |
327 | | self.current_dataset.xaxis("\\rm{Q_{x}}", 'A^{-1}') |
328 | | self.current_dataset.yaxis("\\rm{Q_{y}}", 'A^{-1}') |
329 | | self.current_dataset.zaxis("\\rm{Intensity}", "cm^{-1}") |
| 319 | self.current_dataset.xaxis(r"\rm{Q_{x}}", 'A^{-1}') |
| 320 | self.current_dataset.yaxis(r"\rm{Q_{y}}", 'A^{-1}') |
| 321 | self.current_dataset.zaxis(r"\rm{Intensity}", "cm^{-1}") |
330 | 322 | |
331 | 323 | # Store loading process information |
-
rbe43448
|
r849094a
|
|
6 | 6 | Jurrian Bakker |
7 | 7 | """ |
| 8 | import os |
| 9 | |
8 | 10 | import numpy as np |
9 | | import os |
10 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
11 | | from sas.sascalc.dataloader.data_info import plottable_1D, DataInfo |
12 | | from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DataReaderException |
| 11 | |
| 12 | from ..file_reader_base_class import FileReader |
| 13 | from ..data_info import plottable_1D, DataInfo |
| 14 | from ..loader_exceptions import FileContentsException, DataReaderException |
13 | 15 | |
14 | 16 | # Check whether we have a converter available |
… |
… |
|
42 | 44 | self.output = [] |
43 | 45 | |
44 | | line = self.f_open.readline() |
| 46 | line = self.nextline() |
45 | 47 | params = {} |
46 | 48 | while not line.startswith("BEGIN_DATA"): |
… |
… |
|
48 | 50 | if len(terms) >= 2: |
49 | 51 | params[terms[0]] = " ".join(terms[1:]) |
50 | | line = self.f_open.readline() |
| 52 | line = self.nextline() |
51 | 53 | self.params = params |
52 | 54 | |
… |
… |
|
68 | 70 | "handled by other software.") |
69 | 71 | |
70 | | headers = self.f_open.readline().split() |
| 72 | headers = self.nextline().split() |
71 | 73 | |
72 | 74 | self._insist_header(headers, "SpinEchoLength") |
-
r959eb01
|
r574adc7
|
|
2 | 2 | #This software was developed by the University of Tennessee as part of the |
3 | 3 | #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) |
4 | | #project funded by the US National Science Foundation. |
| 4 | #project funded by the US National Science Foundation. |
5 | 5 | #See the license text in license.txt |
6 | 6 | #copyright 2008, University of Tennessee |
… |
… |
|
31 | 31 | ## Extension |
32 | 32 | ext = ['.tif', '.tiff'] |
33 | | |
| 33 | |
34 | 34 | def read(self, filename=None): |
35 | 35 | """ |
36 | 36 | Open and read the data in a file |
37 | | |
| 37 | |
38 | 38 | :param file: path of the file |
39 | 39 | """ |
… |
… |
|
44 | 44 | except: |
45 | 45 | msg = "tiff_reader: could not load file. Missing Image module." |
46 | | raise RuntimeError, msg |
47 | | |
| 46 | raise RuntimeError(msg) |
| 47 | |
48 | 48 | # Instantiate data object |
49 | 49 | output = Data2D() |
50 | 50 | output.filename = os.path.basename(filename) |
51 | | |
| 51 | |
52 | 52 | # Read in the image |
53 | 53 | try: |
54 | 54 | im = Image.open(filename) |
55 | 55 | except: |
56 | | raise RuntimeError, "cannot open %s"%(filename) |
| 56 | raise RuntimeError("cannot open %s"%(filename)) |
57 | 57 | data = im.getdata() |
58 | 58 | |
… |
… |
|
61 | 61 | output.err_data = np.zeros([im.size[0], im.size[1]]) |
62 | 62 | output.mask = np.ones([im.size[0], im.size[1]], dtype=bool) |
63 | | |
| 63 | |
64 | 64 | # Initialize |
65 | 65 | x_vals = [] |
… |
… |
|
69 | 69 | for i_x in range(im.size[0]): |
70 | 70 | x_vals.append(i_x) |
71 | | |
| 71 | |
72 | 72 | itot = 0 |
73 | 73 | for i_y in range(im.size[1]): |
… |
… |
|
80 | 80 | logger.error("tiff_reader: had to skip a non-float point") |
81 | 81 | continue |
82 | | |
| 82 | |
83 | 83 | # Get bin number |
84 | 84 | if math.fmod(itot, im.size[0]) == 0: |
… |
… |
|
87 | 87 | else: |
88 | 88 | i_x += 1 |
89 | | |
| 89 | |
90 | 90 | output.data[im.size[1] - 1 - i_y][i_x] = value |
91 | | |
| 91 | |
92 | 92 | itot += 1 |
93 | | |
| 93 | |
94 | 94 | output.xbins = im.size[0] |
95 | 95 | output.ybins = im.size[1] |
… |
… |
|
102 | 102 | output.ymin = 0 |
103 | 103 | output.ymax = im.size[0] - 1 |
104 | | |
| 104 | |
105 | 105 | # Store loading process information |
106 | 106 | output.meta_data['loader'] = self.type_name |
-
rcd57c7d4
|
r7b50f14
|
|
16 | 16 | |
17 | 17 | import logging |
| 18 | |
18 | 19 | from lxml import etree |
19 | 20 | from lxml.builder import E |
20 | | from sas.sascalc.dataloader.file_reader_base_class import FileReader |
| 21 | |
| 22 | from ..file_reader_base_class import FileReader, decode |
21 | 23 | |
22 | 24 | logger = logging.getLogger(__name__) |
… |
… |
|
151 | 153 | Converts an etree element into a string |
152 | 154 | """ |
153 | | return etree.tostring(elem, pretty_print=pretty_print, \ |
154 | | encoding=encoding) |
| 155 | return decode(etree.tostring(elem, pretty_print=pretty_print, |
| 156 | encoding=encoding)) |
155 | 157 | |
156 | 158 | def break_processing_instructions(self, string, dic): |
-
r2ab9c432
|
rd5aeaa3
|
|
1 | 1 | #include <Python.h> |
2 | | //#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION |
| 2 | #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION |
3 | 3 | #include <numpy/arrayobject.h> |
4 | 4 | #include <stdio.h> |
… |
… |
|
44 | 44 | static void CLoader_dealloc(CLoader *self) { |
45 | 45 | free(self->params.filename); |
46 | | self->ob_type->tp_free((PyObject *)self); |
| 46 | Py_TYPE(self)->tp_free((PyObject *)self); |
47 | 47 | } |
48 | 48 | |
… |
… |
|
237 | 237 | |
238 | 238 | static PyTypeObject CLoaderType = { |
239 | | PyObject_HEAD_INIT(NULL) |
240 | | 0, /*ob_size*/ |
| 239 | //PyObject_HEAD_INIT(NULL) |
| 240 | //0, /*ob_size*/ |
| 241 | PyVarObject_HEAD_INIT(NULL, 0) |
241 | 242 | "CLoader", /*tp_name*/ |
242 | 243 | sizeof(CLoader), /*tp_basicsize*/ |
… |
… |
|
278 | 279 | }; |
279 | 280 | |
280 | | PyMODINIT_FUNC |
281 | | initbsl_loader(void) |
| 281 | /** |
| 282 | * Function used to add the model class to a module |
| 283 | * @param module: module to add the class to |
| 284 | */ |
| 285 | void addCLoader(PyObject *module) |
282 | 286 | { |
283 | | PyObject *module; |
284 | | module = Py_InitModule("bsl_loader", NULL); |
285 | | import_array(); |
286 | | |
287 | 287 | if (PyType_Ready(&CLoaderType) < 0) |
288 | 288 | return; |
289 | | |
290 | 289 | Py_INCREF(&CLoaderType); |
291 | 290 | PyModule_AddObject(module, "CLoader", (PyObject *)&CLoaderType); |
292 | 291 | } |
| 292 | |
| 293 | #define MODULE_DOC "C module for loading bsl." |
| 294 | #define MODULE_NAME "bsl_loader" |
| 295 | #define MODULE_INIT2 initbsl_loader |
| 296 | #define MODULE_INIT3 PyInit_bsl_loader |
| 297 | #define MODULE_METHODS module_methods |
| 298 | |
| 299 | /* ==== boilerplate python 2/3 interface bootstrap ==== */ |
| 300 | |
| 301 | |
| 302 | #if defined(WIN32) && !defined(__MINGW32__) |
| 303 | #define DLL_EXPORT __declspec(dllexport) |
| 304 | #else |
| 305 | #define DLL_EXPORT |
| 306 | #endif |
| 307 | |
| 308 | #if PY_MAJOR_VERSION >= 3 |
| 309 | |
| 310 | static PyMethodDef module_methods[] = { |
| 311 | {NULL} |
| 312 | }; |
| 313 | |
| 314 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) |
| 315 | { |
| 316 | static struct PyModuleDef moduledef = { |
| 317 | PyModuleDef_HEAD_INIT, |
| 318 | MODULE_NAME, /* m_name */ |
| 319 | MODULE_DOC, /* m_doc */ |
| 320 | -1, /* m_size */ |
| 321 | MODULE_METHODS, /* m_methods */ |
| 322 | NULL, /* m_reload */ |
| 323 | NULL, /* m_traverse */ |
| 324 | NULL, /* m_clear */ |
| 325 | NULL, /* m_free */ |
| 326 | }; |
| 327 | PyObject* m = PyModule_Create(&moduledef); |
| 328 | import_array(); |
| 329 | addCLoader(m); |
| 330 | return m; |
| 331 | } |
| 332 | |
| 333 | #else /* !PY_MAJOR_VERSION >= 3 */ |
| 334 | |
| 335 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) |
| 336 | { |
| 337 | PyObject* m = Py_InitModule(MODULE_NAME, NULL); |
| 338 | import_array(); |
| 339 | addCLoader(m); |
| 340 | } |
| 341 | |
| 342 | #endif /* !PY_MAJOR_VERSION >= 3 */ |
-
r7432acb
|
r574adc7
|
|
32 | 32 | valid_class = all([issubclass(data.__class__, Data1D) for data in frame_data]) |
33 | 33 | if not valid_class: |
34 | | raise RuntimeError, ("The cansas writer expects an array of " |
| 34 | raise RuntimeError("The cansas writer expects an array of " |
35 | 35 | "Data1D instances") |
36 | 36 | |
-
r5e906207
|
r574adc7
|
|
166 | 166 | 'wavelength_max': 'wavelength_max', |
167 | 167 | 'wavelength_spread': 'incident_wavelength_spread' } |
168 | | for sasname, nxname in wavelength_keys.iteritems(): |
| 168 | for sasname, nxname in wavelength_keys.items(): |
169 | 169 | value = getattr(data_info.source, sasname) |
170 | 170 | units = getattr(data_info.source, sasname + '_unit') |
-
r50fcb09
|
r574adc7
|
|
251 | 251 | msg = "FitData1D: invalid error array " |
252 | 252 | msg += "%d <> %d" % (np.shape(self.dy), np.size(fx)) |
253 | | raise RuntimeError, msg |
| 253 | raise RuntimeError(msg) |
254 | 254 | return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx], fx[self.idx] |
255 | 255 | |
-
ra1b8fee
|
r574adc7
|
|
18 | 18 | self.dy = dy |
19 | 19 | self.filename = None |
20 | | |
| 20 | |
21 | 21 | def set_filename(self, path=None): |
22 | 22 | """ |
23 | | Store path into a variable.If the user doesn't give |
| 23 | Store path into a variable.If the user doesn't give |
24 | 24 | a path as a parameter a pop-up |
25 | 25 | window appears to select the file. |
26 | | |
| 26 | |
27 | 27 | :param path: the path given by the user |
28 | | |
| 28 | |
29 | 29 | """ |
30 | 30 | self.filename = path |
31 | | |
| 31 | |
32 | 32 | def get_filename(self): |
33 | 33 | """ return the file's path""" |
34 | 34 | return self.filename |
35 | | |
| 35 | |
36 | 36 | def set_values(self): |
37 | 37 | """ Store the values loaded from file in local variables""" |
… |
… |
|
42 | 42 | self.x = [] |
43 | 43 | self.y = [] |
44 | | self.dx = [] |
| 44 | self.dx = [] |
45 | 45 | self.dy = [] |
46 | 46 | for line in lines: |
… |
… |
|
50 | 50 | y = float(toks[1]) |
51 | 51 | dy = float(toks[2]) |
52 | | |
| 52 | |
53 | 53 | self.x.append(x) |
54 | 54 | self.y.append(y) |
… |
… |
|
59 | 59 | # Sanity check |
60 | 60 | if not len(self.x) == len(self.dx): |
61 | | raise ValueError, "x and dx have different length" |
| 61 | raise ValueError("x and dx have different length") |
62 | 62 | if not len(self.y) == len(self.dy): |
63 | | raise ValueError, "y and dy have different length" |
64 | | |
65 | | |
| 63 | raise ValueError("y and dy have different length") |
| 64 | |
| 65 | |
66 | 66 | def get_values(self): |
67 | 67 | """ Return x, y, dx, dy""" |
68 | 68 | return self.x, self.y, self.dx, self.dy |
69 | | |
| 69 | |
70 | 70 | def load_data(self, data): |
71 | 71 | """ Return plottable""" |
… |
… |
|
77 | 77 | #Load its View class |
78 | 78 | #plottable.reset_view() |
79 | | |
80 | | |
81 | | if __name__ == "__main__": |
| 79 | |
| 80 | |
| 81 | if __name__ == "__main__": |
82 | 82 | load = Load() |
83 | 83 | load.set_filename("testdata_line.txt") |
84 | | print(load.get_filename()) |
| 84 | print(load.get_filename()) |
85 | 85 | load.set_values() |
86 | 86 | print(load.get_values()) |
87 | | |
88 | | |
| 87 | |
-
r7432acb
|
r574adc7
|
|
109 | 109 | """ |
110 | 110 | ##set dispersion only from p_model |
111 | | for name , value in self.p_model.dispersion.iteritems(): |
| 111 | for name , value in self.p_model.dispersion.items(): |
112 | 112 | self.dispersion[name] = value |
113 | 113 | |
… |
… |
|
135 | 135 | """ |
136 | 136 | |
137 | | for name , value in self.p_model.params.iteritems(): |
| 137 | for name , value in self.p_model.params.items(): |
138 | 138 | if not name in self.params.keys() and name not in self.excluded_params: |
139 | 139 | self.params[name] = value |
140 | 140 | |
141 | | for name , value in self.s_model.params.iteritems(): |
| 141 | for name , value in self.s_model.params.items(): |
142 | 142 | #Remove the radius_effective from the (P*S) model parameters. |
143 | 143 | if not name in self.params.keys() and name not in self.excluded_params: |
… |
… |
|
155 | 155 | this model's details |
156 | 156 | """ |
157 | | for name, detail in self.p_model.details.iteritems(): |
| 157 | for name, detail in self.p_model.details.items(): |
158 | 158 | if name not in self.excluded_params: |
159 | 159 | self.details[name] = detail |
160 | 160 | |
161 | | for name , detail in self.s_model.details.iteritems(): |
| 161 | for name , detail in self.s_model.details.items(): |
162 | 162 | if not name in self.details.keys() or name not in self.exluded_params: |
163 | 163 | self.details[name] = detail |
… |
… |
|
245 | 245 | return |
246 | 246 | |
247 | | raise ValueError, "Model does not contain parameter %s" % name |
| 247 | raise ValueError("Model does not contain parameter %s" % name) |
248 | 248 | |
249 | 249 | |
-
ra1b8fee
|
r574adc7
|
|
59 | 59 | occur multiple times. The return value is a set with the elements in |
60 | 60 | no particular order. |
61 | | |
| 61 | |
62 | 62 | This is the first step in computing a dependency graph. |
63 | 63 | """ |
… |
… |
|
81 | 81 | offset = end |
82 | 82 | pieces.append(expr[offset:]) |
83 | | |
| 83 | |
84 | 84 | # Join the pieces and return them |
85 | 85 | return "".join(pieces) |
… |
… |
|
88 | 88 | """ |
89 | 89 | Returns a list of pair-wise dependencies from the parameter expressions. |
90 | | |
| 90 | |
91 | 91 | For example, if p3 = p1+p2, then find_dependencies([p1,p2,p3]) will |
92 | 92 | return [(p3,p1),(p3,p2)]. For base expressions without dependencies, |
… |
… |
|
110 | 110 | """ |
111 | 111 | Find the parameter substitution we need so that expressions can |
112 | | be evaluated without having to traverse a chain of |
| 112 | be evaluated without having to traverse a chain of |
113 | 113 | model.layer.parameter.value |
114 | 114 | """ |
… |
… |
|
122 | 122 | return definition, substitution |
123 | 123 | |
124 | | def no_constraints(): |
| 124 | def no_constraints(): |
125 | 125 | """ |
126 | 126 | This parameter set has no constraints between the parameters. |
… |
… |
|
163 | 163 | |
164 | 164 | Parameter names are assumed to contain only _.a-zA-Z0-9#[] |
165 | | |
| 165 | |
166 | 166 | Both names are provided for inverse functions, e.g., acos and arccos. |
167 | 167 | |
168 | 168 | Should try running the function to identify syntax errors before |
169 | 169 | running it in a fit. |
170 | | |
| 170 | |
171 | 171 | Use help(fn) to see the code generated for the returned function fn. |
172 | 172 | dis.dis(fn) will show the corresponding python vm instructions. |
… |
… |
|
239 | 239 | if independent == emptyset: |
240 | 240 | cycleset = ", ".join(str(s) for s in left) |
241 | | raise ValueError,"Cyclic dependencies amongst %s"%cycleset |
| 241 | raise ValueError("Cyclic dependencies amongst %s"%cycleset) |
242 | 242 | |
243 | 243 | # The possibly resolvable items are those that depend on the independents |
… |
… |
|
267 | 267 | n.sort() |
268 | 268 | items = list(items); items.sort() |
269 | | raise Exception,"%s expect %s to contain %s for %s"%(msg,n,items,pairs) |
| 269 | raise ValueError("%s expect %s to contain %s for %s"%(msg,n,items,pairs)) |
270 | 270 | for lo,hi in pairs: |
271 | 271 | if lo in n and hi in n and n.index(lo) >= n.index(hi): |
272 | | raise Exception,"%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs) |
| 272 | raise ValueError("%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs)) |
273 | 273 | |
274 | 274 | def test_deps(): |
… |
… |
|
288 | 288 | # Cycle test |
289 | 289 | pairs = [(1,4),(4,3),(4,5),(5,1)] |
290 | | try: n = order_dependencies(pairs) |
291 | | except ValueError: pass |
292 | | else: raise Exception,"test3 expect ValueError exception for %s"%(pairs,) |
| 290 | try: |
| 291 | n = order_dependencies(pairs) |
| 292 | except ValueError: |
| 293 | pass |
| 294 | else: |
| 295 | raise ValueError("test3 expect ValueError exception for %s"%(pairs,)) |
293 | 296 | |
294 | 297 | # large test for gross speed check |
… |
… |
|
308 | 311 | import inspect, dis |
309 | 312 | import math |
310 | | |
| 313 | |
311 | 314 | symtab = {'a.b.x':1, 'a.c':2, 'a.b':3, 'b.x':4} |
312 | 315 | expr = 'a.b.x + sin(4*pi*a.c) + a.b.x/a.b' |
313 | | |
| 316 | |
314 | 317 | # Check symbol lookup |
315 | 318 | assert _symbols(expr, symtab) == set([1,2,3]) |
… |
… |
|
357 | 360 | expected = 2*math.pi*math.sin(5/.1875) + 6 |
358 | 361 | assert p2.value == expected,"Value was %s, not %s"%(p2.value,expected) |
359 | | |
| 362 | |
360 | 363 | # Check empty dependency set doesn't crash |
361 | 364 | fn = compile_constraints(*world(p1,p3)) |
… |
… |
|
381 | 384 | fn() |
382 | 385 | assert p5.value == 2.07,"Value for %s was %s"%(p5.expression,p5.value) |
383 | | |
| 386 | |
384 | 387 | |
385 | 388 | # Verify that we capture invalid expressions |
386 | | for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', |
| 389 | for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', |
387 | 390 | 'piddle', |
388 | 391 | '5; import sys; print "p0wned"', |
-
r0315b63
|
r9e6aeaf
|
|
313 | 313 | |
314 | 314 | if len(self.disp_obj_dict) > 0: |
315 | | for k, v in self.disp_obj_dict.iteritems(): |
| 315 | for k, v in self.disp_obj_dict.items(): |
316 | 316 | obj.disp_obj_dict[k] = v |
317 | 317 | if len(self.disp_cb_dict) > 0: |
318 | | for k, v in self.disp_cb_dict.iteritems(): |
| 318 | for k, v in self.disp_cb_dict.items(): |
319 | 319 | obj.disp_cb_dict[k] = v |
320 | 320 | if len(self.values) > 0: |
321 | | for k, v in self.values.iteritems(): |
| 321 | for k, v in self.values.items(): |
322 | 322 | obj.values[k] = v |
323 | 323 | if len(self.weights) > 0: |
324 | | for k, v in self.weights.iteritems(): |
| 324 | for k, v in self.weights.items(): |
325 | 325 | obj.weights[k] = v |
326 | 326 | obj.enable_smearer = copy.deepcopy(self.enable_smearer) |
… |
… |
|
347 | 347 | obj.version = copy.deepcopy(self.version) |
348 | 348 | |
349 | | for name, state in self.saved_states.iteritems(): |
| 349 | for name, state in self.saved_states.items(): |
350 | 350 | copy_name = copy.deepcopy(name) |
351 | 351 | copy_state = state.clone() |
… |
… |
|
430 | 430 | """ |
431 | 431 | p_map = [] |
432 | | for name, info in params.iteritems(): |
| 432 | for name, info in params.items(): |
433 | 433 | if ".fittable" in name or ".std" in name or ".upper" in name or \ |
434 | 434 | ".lower" in name or ".units" in name: |
… |
… |
|
475 | 475 | formfactor, str_params = convert.convert_model( |
476 | 476 | self.formfactorcombobox, str_pars, False, self.version) |
477 | | for key, value in str_params.iteritems(): |
| 477 | for key, value in str_params.items(): |
478 | 478 | params[key] = value |
479 | 479 | |
… |
… |
|
835 | 835 | element = newdoc.createElement(item[0]) |
836 | 836 | value_list = getattr(self, item[1]) |
837 | | for key, value in value_list.iteritems(): |
| 837 | for key, value in value_list.items(): |
838 | 838 | sub_element = newdoc.createElement(key) |
839 | 839 | sub_element.setAttribute('name', str(key)) |
… |
… |
|
848 | 848 | element = newdoc.createElement(tagname) |
849 | 849 | value_list = getattr(self, varname) |
850 | | for key, value in value_list.iteritems(): |
| 850 | for key, value in value_list.items(): |
851 | 851 | sub_element = newdoc.createElement(key) |
852 | 852 | sub_element.setAttribute('name', str(key)) |
… |
… |
|
950 | 950 | msg = "PageState no longer supports non-CanSAS" |
951 | 951 | msg += " format for fitting files" |
952 | | raise RuntimeError, msg |
| 952 | raise RuntimeError(msg) |
953 | 953 | |
954 | 954 | if node.get('version'): |
… |
… |
|
1241 | 1241 | else: |
1242 | 1242 | self.call_back(format=ext) |
1243 | | raise RuntimeError, "%s is not a file" % path |
| 1243 | raise RuntimeError("%s is not a file" % path) |
1244 | 1244 | |
1245 | 1245 | # Return output consistent with the loader's api |
-
r5213d22
|
r574adc7
|
|
35 | 35 | return self.function(x_val)*self.function(y_val) |
36 | 36 | elif x.__class__.__name__ == 'tuple': |
37 | | raise ValueError, "Tuples are not allowed as input to BaseComponent models" |
| 37 | raise ValueError("Tuples are not allowed as input to BaseComponent models") |
38 | 38 | else: |
39 | 39 | return self.function(x) |
… |
… |
|
52 | 52 | return self.function(x[0])*self.function(x[1]) |
53 | 53 | elif x.__class__.__name__ == 'tuple': |
54 | | raise ValueError, "Tuples are not allowed as input to BaseComponent models" |
| 54 | raise ValueError("Tuples are not allowed as input to BaseComponent models") |
55 | 55 | else: |
56 | 56 | return self.function(x) |
-
rb1f20d1
|
r574adc7
|
|
424 | 424 | if not issubclass(data.__class__, LoaderData1D): |
425 | 425 | #Process only data that inherited from DataLoader.Data_info.Data1D |
426 | | raise ValueError, "Data must be of type DataLoader.Data1D" |
| 426 | raise ValueError("Data must be of type DataLoader.Data1D") |
427 | 427 | #from copy import deepcopy |
428 | 428 | new_data = (self._scale * data) - self._background |
… |
… |
|
484 | 484 | msg = "Length x and y must be equal" |
485 | 485 | msg += " and greater than 1; got x=%s, y=%s" % (len(data.x), len(data.y)) |
486 | | raise ValueError, msg |
| 486 | raise ValueError(msg) |
487 | 487 | else: |
488 | 488 | # Take care of smeared data |
… |
… |
|
507 | 507 | #iterate between for element different |
508 | 508 | #from the first and the last |
509 | | for i in xrange(1, n - 1): |
| 509 | for i in range(1, n - 1): |
510 | 510 | dxi = (data.x[i + 1] - data.x[i - 1]) / 2 |
511 | 511 | total += gx[i] * data.y[i] * dxi |
… |
… |
|
533 | 533 | msg = "Length of data.x and data.y must be equal" |
534 | 534 | msg += " and greater than 1; got x=%s, y=%s" % (len(data.x), len(data.y)) |
535 | | raise ValueError, msg |
| 535 | raise ValueError(msg) |
536 | 536 | else: |
537 | 537 | #Create error for data without dy error |
… |
… |
|
560 | 560 | #iterate between for element different |
561 | 561 | #from the first and the last |
562 | | for i in xrange(1, n - 1): |
| 562 | for i in range(1, n - 1): |
563 | 563 | dxi = (data.x[i + 1] - data.x[i - 1]) / 2 |
564 | 564 | total += (gx[i] * dy[i] * dxi) ** 2 |
… |
… |
|
742 | 742 | range = range.lower() |
743 | 743 | if range not in ['high', 'low']: |
744 | | raise ValueError, "Extrapolation range should be 'high' or 'low'" |
| 744 | raise ValueError("Extrapolation range should be 'high' or 'low'") |
745 | 745 | function = function.lower() |
746 | 746 | if function not in ['power_law', 'guinier']: |
747 | 747 | msg = "Extrapolation function should be 'guinier' or 'power_law'" |
748 | | raise ValueError, msg |
| 748 | raise ValueError(msg) |
749 | 749 | |
750 | 750 | if range == 'high': |
751 | 751 | if function != 'power_law': |
752 | 752 | msg = "Extrapolation only allows a power law at high Q" |
753 | | raise ValueError, msg |
| 753 | raise ValueError(msg) |
754 | 754 | self._high_extrapolation_npts = npts |
755 | 755 | self._high_extrapolation_power = power |
… |
… |
|
852 | 852 | """ |
853 | 853 | if contrast <= 0: |
854 | | raise ValueError, "The contrast parameter must be greater than zero" |
| 854 | raise ValueError("The contrast parameter must be greater than zero") |
855 | 855 | |
856 | 856 | # Make sure Q star is up to date |
… |
… |
|
859 | 859 | if self._qstar <= 0: |
860 | 860 | msg = "Invalid invariant: Invariant Q* must be greater than zero" |
861 | | raise RuntimeError, msg |
| 861 | raise RuntimeError(msg) |
862 | 862 | |
863 | 863 | # Compute intermediate constant |
… |
… |
|
869 | 869 | if discrim < 0: |
870 | 870 | msg = "Could not compute the volume fraction: negative discriminant" |
871 | | raise RuntimeError, msg |
| 871 | raise RuntimeError(msg) |
872 | 872 | elif discrim == 0: |
873 | 873 | return 1 / 2 |
… |
… |
|
881 | 881 | return volume2 |
882 | 882 | msg = "Could not compute the volume fraction: inconsistent results" |
883 | | raise RuntimeError, msg |
| 883 | raise RuntimeError(msg) |
884 | 884 | |
885 | 885 | def get_qstar_with_error(self, extrapolation=None): |
-
rcb62bd5
|
rd04ac05
|
|
52 | 52 | invertor_dealloc(&(self->params)); |
53 | 53 | |
54 | | self->ob_type->tp_free((PyObject*)self); |
| 54 | Py_TYPE(self)->tp_free((PyObject*)self); |
55 | 55 | |
56 | 56 | } |
… |
… |
|
1054 | 1054 | |
1055 | 1055 | static PyTypeObject CinvertorType = { |
1056 | | PyObject_HEAD_INIT(NULL) |
1057 | | 0, /*ob_size*/ |
| 1056 | //PyObject_HEAD_INIT(NULL) |
| 1057 | //0, /*ob_size*/ |
| 1058 | PyVarObject_HEAD_INIT(NULL, 0) |
1058 | 1059 | "Cinvertor", /*tp_name*/ |
1059 | 1060 | sizeof(Cinvertor), /*tp_basicsize*/ |
… |
… |
|
1119 | 1120 | |
1120 | 1121 | |
1121 | | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ |
1122 | | #define PyMODINIT_FUNC void |
| 1122 | #define MODULE_DOC "C extension module for inversion to P(r)." |
| 1123 | #define MODULE_NAME "pr_inversion" |
| 1124 | #define MODULE_INIT2 initpr_inversion |
| 1125 | #define MODULE_INIT3 PyInit_pr_inversion |
| 1126 | #define MODULE_METHODS module_methods |
| 1127 | |
| 1128 | /* ==== boilerplate python 2/3 interface bootstrap ==== */ |
| 1129 | |
| 1130 | |
| 1131 | #if defined(WIN32) && !defined(__MINGW32__) |
| 1132 | #define DLL_EXPORT __declspec(dllexport) |
| 1133 | #else |
| 1134 | #define DLL_EXPORT |
1123 | 1135 | #endif |
1124 | | PyMODINIT_FUNC |
1125 | | initpr_inversion(void) |
1126 | | { |
1127 | | PyObject* m; |
1128 | | |
1129 | | m = Py_InitModule3("pr_inversion", module_methods, |
1130 | | "C extension module for inversion to P(r)."); |
1131 | | |
1132 | | addCinvertor(m); |
1133 | | } |
| 1136 | |
| 1137 | #if PY_MAJOR_VERSION >= 3 |
| 1138 | |
| 1139 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) |
| 1140 | { |
| 1141 | static struct PyModuleDef moduledef = { |
| 1142 | PyModuleDef_HEAD_INIT, |
| 1143 | MODULE_NAME, /* m_name */ |
| 1144 | MODULE_DOC, /* m_doc */ |
| 1145 | -1, /* m_size */ |
| 1146 | MODULE_METHODS, /* m_methods */ |
| 1147 | NULL, /* m_reload */ |
| 1148 | NULL, /* m_traverse */ |
| 1149 | NULL, /* m_clear */ |
| 1150 | NULL, /* m_free */ |
| 1151 | }; |
| 1152 | PyObject* m = PyModule_Create(&moduledef); |
| 1153 | addCinvertor(m); |
| 1154 | return m; |
| 1155 | } |
| 1156 | |
| 1157 | #else /* !PY_MAJOR_VERSION >= 3 */ |
| 1158 | |
| 1159 | DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) |
| 1160 | { |
| 1161 | PyObject* m = Py_InitModule4(MODULE_NAME, |
| 1162 | MODULE_METHODS, |
| 1163 | MODULE_DOC, |
| 1164 | 0, |
| 1165 | PYTHON_API_VERSION |
| 1166 | ); |
| 1167 | addCinvertor(m); |
| 1168 | } |
| 1169 | |
| 1170 | #endif /* !PY_MAJOR_VERSION >= 3 */ |
-
r50fcb09
|
r574adc7
|
|
251 | 251 | msg = "FitData1D: invalid error array " |
252 | 252 | msg += "%d <> %d" % (np.shape(self.dy), np.size(fx)) |
253 | | raise RuntimeError, msg |
| 253 | raise RuntimeError(msg) |
254 | 254 | return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx], fx[self.idx] |
255 | 255 | |
-
ra1b8fee
|
r574adc7
|
|
18 | 18 | self.dy = dy |
19 | 19 | self.filename = None |
20 | | |
| 20 | |
21 | 21 | def set_filename(self, path=None): |
22 | 22 | """ |
23 | | Store path into a variable.If the user doesn't give |
| 23 | Store path into a variable.If the user doesn't give |
24 | 24 | a path as a parameter a pop-up |
25 | 25 | window appears to select the file. |
26 | | |
| 26 | |
27 | 27 | :param path: the path given by the user |
28 | | |
| 28 | |
29 | 29 | """ |
30 | 30 | self.filename = path |
31 | | |
| 31 | |
32 | 32 | def get_filename(self): |
33 | 33 | """ return the file's path""" |
34 | 34 | return self.filename |
35 | | |
| 35 | |
36 | 36 | def set_values(self): |
37 | 37 | """ Store the values loaded from file in local variables""" |
… |
… |
|
42 | 42 | self.x = [] |
43 | 43 | self.y = [] |
44 | | self.dx = [] |
| 44 | self.dx = [] |
45 | 45 | self.dy = [] |
46 | 46 | for line in lines: |
… |
… |
|
50 | 50 | y = float(toks[1]) |
51 | 51 | dy = float(toks[2]) |
52 | | |
| 52 | |
53 | 53 | self.x.append(x) |
54 | 54 | self.y.append(y) |
… |
… |
|
59 | 59 | # Sanity check |
60 | 60 | if not len(self.x) == len(self.dx): |
61 | | raise ValueError, "x and dx have different length" |
| 61 | raise ValueError("x and dx have different length") |
62 | 62 | if not len(self.y) == len(self.dy): |
63 | | raise ValueError, "y and dy have different length" |
64 | | |
65 | | |
| 63 | raise ValueError("y and dy have different length") |
| 64 | |
| 65 | |
66 | 66 | def get_values(self): |
67 | 67 | """ Return x, y, dx, dy""" |
68 | 68 | return self.x, self.y, self.dx, self.dy |
69 | | |
| 69 | |
70 | 70 | def load_data(self, data): |
71 | 71 | """ Return plottable""" |
… |
… |
|
77 | 77 | #Load its View class |
78 | 78 | #plottable.reset_view() |
79 | | |
80 | | |
81 | | if __name__ == "__main__": |
| 79 | |
| 80 | |
| 81 | if __name__ == "__main__": |
82 | 82 | load = Load() |
83 | 83 | load.set_filename("testdata_line.txt") |
84 | | print(load.get_filename()) |
| 84 | print(load.get_filename()) |
85 | 85 | load.set_values() |
86 | 86 | print(load.get_values()) |
87 | | |
88 | | |
| 87 | |
-
ra1b8fee
|
r574adc7
|
|
59 | 59 | occur multiple times. The return value is a set with the elements in |
60 | 60 | no particular order. |
61 | | |
| 61 | |
62 | 62 | This is the first step in computing a dependency graph. |
63 | 63 | """ |
… |
… |
|
81 | 81 | offset = end |
82 | 82 | pieces.append(expr[offset:]) |
83 | | |
| 83 | |
84 | 84 | # Join the pieces and return them |
85 | 85 | return "".join(pieces) |
… |
… |
|
88 | 88 | """ |
89 | 89 | Returns a list of pair-wise dependencies from the parameter expressions. |
90 | | |
| 90 | |
91 | 91 | For example, if p3 = p1+p2, then find_dependencies([p1,p2,p3]) will |
92 | 92 | return [(p3,p1),(p3,p2)]. For base expressions without dependencies, |
… |
… |
|
110 | 110 | """ |
111 | 111 | Find the parameter substitution we need so that expressions can |
112 | | be evaluated without having to traverse a chain of |
| 112 | be evaluated without having to traverse a chain of |
113 | 113 | model.layer.parameter.value |
114 | 114 | """ |
… |
… |
|
122 | 122 | return definition, substitution |
123 | 123 | |
124 | | def no_constraints(): |
| 124 | def no_constraints(): |
125 | 125 | """ |
126 | 126 | This parameter set has no constraints between the parameters. |
… |
… |
|
163 | 163 | |
164 | 164 | Parameter names are assumed to contain only _.a-zA-Z0-9#[] |
165 | | |
| 165 | |
166 | 166 | Both names are provided for inverse functions, e.g., acos and arccos. |
167 | 167 | |
168 | 168 | Should try running the function to identify syntax errors before |
169 | 169 | running it in a fit. |
170 | | |
| 170 | |
171 | 171 | Use help(fn) to see the code generated for the returned function fn. |
172 | 172 | dis.dis(fn) will show the corresponding python vm instructions. |
… |
… |
|
239 | 239 | if independent == emptyset: |
240 | 240 | cycleset = ", ".join(str(s) for s in left) |
241 | | raise ValueError,"Cyclic dependencies amongst %s"%cycleset |
| 241 | raise ValueError("Cyclic dependencies amongst %s"%cycleset) |
242 | 242 | |
243 | 243 | # The possibly resolvable items are those that depend on the independents |
… |
… |
|
267 | 267 | n.sort() |
268 | 268 | items = list(items); items.sort() |
269 | | raise Exception,"%s expect %s to contain %s for %s"%(msg,n,items,pairs) |
| 269 | raise ValueError("%s expect %s to contain %s for %s"%(msg,n,items,pairs)) |
270 | 270 | for lo,hi in pairs: |
271 | 271 | if lo in n and hi in n and n.index(lo) >= n.index(hi): |
272 | | raise Exception,"%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs) |
| 272 | raise ValueError("%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs)) |
273 | 273 | |
274 | 274 | def test_deps(): |
… |
… |
|
288 | 288 | # Cycle test |
289 | 289 | pairs = [(1,4),(4,3),(4,5),(5,1)] |
290 | | try: n = order_dependencies(pairs) |
291 | | except ValueError: pass |
292 | | else: raise Exception,"test3 expect ValueError exception for %s"%(pairs,) |
| 290 | try: |
| 291 | n = order_dependencies(pairs) |
| 292 | except ValueError: |
| 293 | pass |
| 294 | else: |
| 295 | raise Exception("test3 expect ValueError exception for %s"%(pairs,)) |
293 | 296 | |
294 | 297 | # large test for gross speed check |
… |
… |
|
308 | 311 | import inspect, dis |
309 | 312 | import math |
310 | | |
| 313 | |
311 | 314 | symtab = {'a.b.x':1, 'a.c':2, 'a.b':3, 'b.x':4} |
312 | 315 | expr = 'a.b.x + sin(4*pi*a.c) + a.b.x/a.b' |
313 | | |
| 316 | |
314 | 317 | # Check symbol lookup |
315 | 318 | assert _symbols(expr, symtab) == set([1,2,3]) |
… |
… |
|
357 | 360 | expected = 2*math.pi*math.sin(5/.1875) + 6 |
358 | 361 | assert p2.value == expected,"Value was %s, not %s"%(p2.value,expected) |
359 | | |
| 362 | |
360 | 363 | # Check empty dependency set doesn't crash |
361 | 364 | fn = compile_constraints(*world(p1,p3)) |
… |
… |
|
381 | 384 | fn() |
382 | 385 | assert p5.value == 2.07,"Value for %s was %s"%(p5.expression,p5.value) |
383 | | |
| 386 | |
384 | 387 | |
385 | 388 | # Verify that we capture invalid expressions |
386 | | for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', |
| 389 | for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', |
387 | 390 | 'piddle', |
388 | 391 | '5; import sys; print "p0wned"', |
-
rcb62bd5
|
rd04ac05
|
|
148 | 148 | msg = "Invertor: one of your q-values is zero. " |
149 | 149 | msg += "Delete that entry before proceeding" |
150 | | raise ValueError, msg |
| 150 | raise ValueError(msg) |
151 | 151 | return self.set_x(value) |
152 | 152 | elif name == 'y': |
… |
… |
|
159 | 159 | msg = "Invertor: d_max must be greater than zero." |
160 | 160 | msg += "Correct that entry before proceeding" |
161 | | raise ValueError, msg |
| 161 | raise ValueError(msg) |
162 | 162 | return self.set_dmax(value) |
163 | 163 | elif name == 'q_min': |
… |
… |
|
181 | 181 | return self.set_est_bck(0) |
182 | 182 | else: |
183 | | raise ValueError, "Invertor: est_bck can only be True or False" |
| 183 | raise ValueError("Invertor: est_bck can only be True or False") |
184 | 184 | |
185 | 185 | return Cinvertor.__setattr__(self, name, value) |
… |
… |
|
331 | 331 | if self.is_valid() <= 0: |
332 | 332 | msg = "Invertor.invert: Data array are of different length" |
333 | | raise RuntimeError, msg |
| 333 | raise RuntimeError(msg) |
334 | 334 | |
335 | 335 | p = np.ones(nfunc) |
… |
… |
|
364 | 364 | if self.is_valid() <= 0: |
365 | 365 | msg = "Invertor.invert: Data arrays are of different length" |
366 | | raise RuntimeError, msg |
| 366 | raise RuntimeError(msg) |
367 | 367 | |
368 | 368 | p = np.ones(nfunc) |
… |
… |
|
448 | 448 | if self.is_valid() < 0: |
449 | 449 | msg = "Invertor: invalid data; incompatible data lengths." |
450 | | raise RuntimeError, msg |
| 450 | raise RuntimeError(msg) |
451 | 451 | |
452 | 452 | self.nfunc = nfunc |
… |
… |
|
472 | 472 | try: |
473 | 473 | self._get_matrix(nfunc, nq, a, b) |
474 | | except: |
475 | | raise RuntimeError, "Invertor: could not invert I(Q)\n %s" % sys.exc_value |
| 474 | except Exception as exc: |
| 475 | raise RuntimeError("Invertor: could not invert I(Q)\n %s" % str(exc)) |
476 | 476 | |
477 | 477 | # Perform the inversion (least square fit) |
… |
… |
|
756 | 756 | except: |
757 | 757 | msg = "Invertor.from_file: corrupted file\n%s" % sys.exc_value |
758 | | raise RuntimeError, msg |
| 758 | raise RuntimeError(msg) |
759 | 759 | else: |
760 | 760 | msg = "Invertor.from_file: '%s' is not a file" % str(path) |
761 | | raise RuntimeError, msg |
| 761 | raise RuntimeError(msg) |
-
rb963b20
|
r1efbc190
|
|
145 | 145 | UPDATE_TIMEOUT = 2 |
146 | 146 | |
147 | | # Time out for updating sasview |
148 | | UPDATE_TIMEOUT = 2 |
149 | | |
150 | 147 | def printEVT(message): |
151 | 148 | if __EVT_DEBUG__: |
-
r24d9e84
|
r0a3c740
|
|
174 | 174 | save_id = self._format_id(save_id) |
175 | 175 | if save_id == model_id: |
176 | | model_map[saved_model.pop('fit_page_source')] = \ |
177 | | model[3].name |
178 | | check = bool(saved_model.pop('checked')) |
179 | | self.model_list[i][0].SetValue(check) |
180 | 176 | inter_id = str(i)*5 |
181 | 177 | init_map[saved_model.pop('fit_page_source')] = inter_id |
-
rb277220
|
r0225a3f
|
|
18 | 18 | import logging |
19 | 19 | |
20 | | reload(sys) |
21 | | sys.setdefaultencoding("iso-8859-1") |
| 20 | try: |
| 21 | reload(sys) |
| 22 | sys.setdefaultencoding("iso-8859-1") |
| 23 | except NameError: |
| 24 | # On python 3 sys.setdefaultencoding does nothing, so pass. |
| 25 | # We know we are in python 3 at this point since reload is no longer in |
| 26 | # builtins, but instead has been moved to importlib, hence the NameError. |
| 27 | pass |
22 | 28 | |
23 | 29 | import sas |
… |
… |
|
224 | 230 | setup_mpl(backend='WXAgg' if os.name == 'nt' else None) |
225 | 231 | setup_sasmodels() |
226 | | if len(sys.argv) == 1: |
| 232 | if len(sys.argv) == 1 or sys.argv[1] == '-i': |
227 | 233 | # Run sasview as an interactive python interpreter |
228 | 234 | try: |
… |
… |
|
233 | 239 | import code |
234 | 240 | code.interact(local={'exit': sys.exit}) |
| 241 | elif sys.argv[1] == '-c': |
| 242 | exec(sys.argv[2]) |
235 | 243 | else: |
236 | | # Run sasview as a python script interpreter |
237 | | ## Run sasview as an interactive python interpreter |
238 | | # if sys.argv[1] == "-i": |
239 | | # sys.argv = ["ipython", "--pylab"] |
240 | | # from IPython import start_ipython |
241 | | # sys.exit(start_ipython()) |
242 | 244 | thing_to_run = sys.argv[1] |
243 | 245 | sys.argv = sys.argv[1:] |
-
-
Property
mode
changed from
100644
to
100755
-
r959eb01
|
r1d014cb
|
|
10 | 10 | |
11 | 11 | class sas_gen_test(unittest.TestCase): |
12 | | |
| 12 | |
13 | 13 | def setUp(self): |
14 | 14 | self.sldloader = sas_gen.SLDReader() |
15 | 15 | self.pdbloader = sas_gen.PDBReader() |
16 | 16 | self.omfloader = sas_gen.OMFReader() |
17 | | |
| 17 | |
18 | 18 | def test_sldreader(self): |
19 | 19 | """ |
20 | | Test .sld file loaded |
| 20 | Test .sld file loaded |
21 | 21 | """ |
22 | 22 | f = self.sldloader.read("sld_file.sld") |
… |
… |
|
24 | 24 | self.assertEqual(f.pos_y[0], -13.5) |
25 | 25 | self.assertEqual(f.pos_z[0], -13.5) |
26 | | |
| 26 | |
27 | 27 | def test_pdbreader(self): |
28 | 28 | """ |
29 | | Test .pdb file loaded |
| 29 | Test .pdb file loaded |
30 | 30 | """ |
31 | 31 | f = self.pdbloader.read("c60.pdb") |
… |
… |
|
33 | 33 | self.assertEqual(f.pos_y[0], -1.008) |
34 | 34 | self.assertEqual(f.pos_z[0], 3.326) |
35 | | |
| 35 | |
36 | 36 | def test_omfreader(self): |
37 | 37 | """ |
38 | | Test .omf file loaded |
| 38 | Test .omf file loaded |
39 | 39 | """ |
40 | 40 | f = self.omfloader.read("A_Raw_Example-1.omf") |
-
r959eb01
|
ra50da82
|
|
10 | 10 | from periodictable.constants import avogadro_number |
11 | 11 | from periodictable.nsf import neutron_scattering, neutron_sld |
12 | | |
| 12 | |
13 | 13 | |
14 | 14 | def calculate_xray_sld(element, density, molecule_formula): |
… |
… |
|
19 | 19 | element_formula = formula(str(element)) |
20 | 20 | if len(element_formula.atoms) != 1: |
21 | | return |
22 | | element = element_formula.atoms.keys()[0] |
| 21 | return |
| 22 | element = next(iter(element_formula.atoms)) # only one element... |
23 | 23 | energy = xray_energy(element.K_alpha) |
24 | 24 | atom = molecule_formula.atoms |
… |
… |
|
30 | 30 | Sld calculator test for H2O |
31 | 31 | """ |
32 | | |
| 32 | |
33 | 33 | def setUp(self): |
34 | 34 | """Inititialze variables""" |
35 | | |
| 35 | |
36 | 36 | self.compound = "H2O" |
37 | 37 | self.density = 1.0 |
38 | 38 | self.wavelength = 6.0 |
39 | 39 | self.sld_formula = formula(self.compound, density=self.density) |
40 | | |
| 40 | |
41 | 41 | def test_neutron_sld(self): |
42 | 42 | """ |
43 | | test sld |
| 43 | test sld |
44 | 44 | """ |
45 | 45 | #Compute incoherence , absorption, and incoherence |
46 | 46 | (sld_real,sld_im,sld_inc), (coh,abs,incoh), length = neutron_scattering(self.compound, |
47 | | density=self.density, wavelength=self.wavelength) |
| 47 | density=self.density, wavelength=self.wavelength) |
48 | 48 | cu_real, cu_im = calculate_xray_sld(element="Cu", density=self.density, |
49 | 49 | molecule_formula=self.sld_formula) |
50 | 50 | mo_real, mo_im = calculate_xray_sld(element="Mo", density=self.density, |
51 | 51 | molecule_formula=self.sld_formula) |
52 | | #test sld |
| 52 | #test sld |
53 | 53 | self.assertAlmostEquals(sld_real * _SCALE, -5.6e-7, 1) |
54 | 54 | self.assertAlmostEquals(sld_im * _SCALE, 0) |
… |
… |
|
64 | 64 | self.assertAlmostEquals(mo_real * _SCALE, 9.43e-6) |
65 | 65 | self.assertAlmostEquals(mo_im * _SCALE, 5.65e-7,1) |
66 | | |
67 | | |
| 66 | |
| 67 | |
68 | 68 | class TestD2O(unittest.TestCase): |
69 | 69 | """ |
70 | 70 | Sld calculator test for D2O |
71 | 71 | """ |
72 | | |
| 72 | |
73 | 73 | def setUp(self): |
74 | 74 | """Inititialze variables""" |
75 | | |
| 75 | |
76 | 76 | self.compound = "D2O" |
77 | 77 | self.density = 1.1 |
78 | 78 | self.wavelength = 6.0 |
79 | 79 | self.sld_formula = formula(self.compound, density=self.density) |
80 | | |
| 80 | |
81 | 81 | def test_neutron_sld(self): |
82 | 82 | """ |
83 | | test sld |
| 83 | test sld |
84 | 84 | """ |
85 | 85 | #Compute incoherence , absorption, and incoherence |
86 | 86 | (sld_real,sld_im,sld_inc), (coh,abs,incoh), length = neutron_scattering(self.compound, |
87 | | density=self.density, wavelength=self.wavelength) |
| 87 | density=self.density, wavelength=self.wavelength) |
88 | 88 | cu_real, cu_im = calculate_xray_sld(element="Cu", density=self.density, |
89 | 89 | molecule_formula=self.sld_formula) |
90 | 90 | mo_real, mo_im = calculate_xray_sld(element="Mo", density=self.density, |
91 | 91 | molecule_formula=self.sld_formula) |
92 | | #test sld |
| 92 | #test sld |
93 | 93 | self.assertAlmostEquals(sld_real * _SCALE, 6.33e-6, 1) |
94 | 94 | self.assertAlmostEquals(sld_im * _SCALE, 0) |
… |
… |
|
104 | 104 | self.assertAlmostEquals(mo_real * _SCALE, 9.33e-6) |
105 | 105 | self.assertAlmostEquals(mo_im * _SCALE, 5.59e-9,1) |
106 | | |
107 | | |
| 106 | |
| 107 | |
108 | 108 | class TestCd(unittest.TestCase): |
109 | 109 | """ |
110 | 110 | Sld calculator test for Cd |
111 | 111 | """ |
112 | | |
| 112 | |
113 | 113 | def setUp(self): |
114 | 114 | """Inititialze variables""" |
… |
… |
|
118 | 118 | self.wavelength = 6.0 |
119 | 119 | self.sld_formula = formula(self.compound, density=self.density) |
120 | | |
| 120 | |
121 | 121 | def test_neutron_sld(self): |
122 | 122 | """ |
123 | | test sld |
| 123 | test sld |
124 | 124 | """ |
125 | 125 | #Compute incoherence , absorption, and incoherence |
126 | 126 | (sld_real,sld_im,sld_inc), (coh,abs,incoh), length = neutron_scattering(self.compound, |
127 | | density=self.density, wavelength=self.wavelength) |
| 127 | density=self.density, wavelength=self.wavelength) |
128 | 128 | cu_real, cu_im = calculate_xray_sld(element="Cu", density=self.density, |
129 | 129 | molecule_formula=self.sld_formula) |
130 | 130 | mo_real, mo_im = calculate_xray_sld(element="Mo", density=self.density, |
131 | 131 | molecule_formula=self.sld_formula) |
132 | | #test sld |
| 132 | #test sld |
133 | 133 | self.assertAlmostEquals(sld_real * _SCALE, 1.04e-6, 1) |
134 | 134 | self.assertAlmostEquals(sld_im * _SCALE, -1.5e-7, 1) |
… |
… |
|
144 | 144 | self.assertAlmostEquals(mo_real * _SCALE, 2.84e-5, 1) |
145 | 145 | self.assertAlmostEquals(mo_im * _SCALE, 7.26e-7,1) |
146 | | |
| 146 | |
147 | 147 | if __name__ == '__main__': |
148 | 148 | unittest.main() |
-
rae69c690
|
r574adc7
|
|
224 | 224 | _found2 = True |
225 | 225 | |
226 | | if _found1 == False or _found2 == False: |
227 | | raise RuntimeError, "Could not find all data %s %s" % (_found1, _found2) |
| 226 | if not _found1 or not _found2: |
| 227 | raise RuntimeError("Could not find all data %s %s" |
| 228 | % (_found1, _found2)) |
228 | 229 | |
229 | 230 | # Detector |
… |
… |
|
269 | 270 | _found_term1 = True |
270 | 271 | |
271 | | if _found_term1 == False or _found_term2 == False: |
272 | | raise RuntimeError, "Could not find all process terms %s %s" % (_found_term1, _found_term2) |
| 272 | if not _found_term1 or not _found_term2: |
| 273 | raise RuntimeError("Could not find all process terms %s %s" |
| 274 | % (_found_term1, _found_term2)) |
273 | 275 | |
274 | 276 | def test_writer(self): |
-
r17e257b5
|
rf00072f
|
|
2 | 2 | Unit tests for the new recursive cansas reader |
3 | 3 | """ |
| 4 | import os |
| 5 | import sys |
| 6 | import unittest |
| 7 | import logging |
| 8 | import warnings |
| 9 | if sys.version_info[0] >= 3: |
| 10 | from io import StringIO |
| 11 | else: |
| 12 | from StringIO import StringIO |
| 13 | |
| 14 | from lxml import etree |
| 15 | from lxml.etree import XMLSyntaxError |
| 16 | from xml.dom import minidom |
| 17 | |
4 | 18 | import sas.sascalc.dataloader.readers.cansas_reader as cansas |
| 19 | from sas.sascalc.dataloader.file_reader_base_class import decode |
5 | 20 | from sas.sascalc.dataloader.loader import Loader |
6 | 21 | from sas.sascalc.dataloader.data_info import Data1D, Data2D |
… |
… |
|
8 | 23 | from sas.sascalc.dataloader.readers.cansas_reader import Reader |
9 | 24 | from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants |
10 | | |
11 | | import os |
12 | | import sys |
13 | | import urllib2 |
14 | | import StringIO |
15 | | import pylint as pylint |
16 | | import unittest |
17 | | import numpy as np |
18 | | import logging |
19 | | import warnings |
20 | | |
21 | | from lxml import etree |
22 | | from lxml.etree import XMLSyntaxError |
23 | | from xml.dom import minidom |
24 | 25 | |
25 | 26 | logger = logging.getLogger(__name__) |
… |
… |
|
62 | 63 | Should fail gracefully and send a message to logger.info() |
63 | 64 | """ |
64 | | invalid = StringIO.StringIO('<a><c></b></a>') |
| 65 | invalid = StringIO('<a><c></b></a>') |
65 | 66 | self.assertRaises(XMLSyntaxError, lambda: XMLreader(invalid)) |
66 | 67 | |
… |
… |
|
74 | 75 | string += "\t</xsd:complexType>\n" |
75 | 76 | string += "</xsd:schema>" |
76 | | f = StringIO.StringIO(string) |
| 77 | f = StringIO(string) |
77 | 78 | xmlschema_doc = etree.parse(f) |
78 | 79 | xmlschema = etree.XMLSchema(xmlschema_doc) |
79 | | valid = etree.parse(StringIO.StringIO('<a><b></b></a>')) |
80 | | invalid = etree.parse(StringIO.StringIO('<a><c></c></a>')) |
| 80 | valid = etree.parse(StringIO('<a><b></b></a>')) |
| 81 | invalid = etree.parse(StringIO('<a><c></c></a>')) |
81 | 82 | self.assertTrue(xmlschema.validate(valid)) |
82 | 83 | self.assertFalse(xmlschema.validate(invalid)) |
… |
… |
|
214 | 215 | # find the processing instructions and make into a dictionary |
215 | 216 | dic = self.get_processing_instructions(reader) |
216 | | self.assertTrue(dic == {'xml-stylesheet': \ |
217 | | 'type="text/xsl" href="cansas1d.xsl" '}) |
| 217 | self.assertEqual(dic, {'xml-stylesheet': |
| 218 | 'type="text/xsl" href="cansas1d.xsl" '}) |
218 | 219 | |
219 | 220 | xml = "<test><a><b><c></c></b></a></test>" |
… |
… |
|
238 | 239 | attr = {} |
239 | 240 | pi_name = "" |
240 | | pi_string = etree.tostring(pi) |
| 241 | pi_string = decode(etree.tostring(pi)) |
241 | 242 | if isinstance(pi_string, str): |
242 | 243 | pi_string = pi_string.replace("<?", "").replace("?>", "") |
… |
… |
|
309 | 310 | |
310 | 311 | if __name__ == '__main__': |
311 | | unittest.main() |
| 312 | unittest.main() |
-
raaf5e49
|
r1cdbcd8
|
|
9 | 9 | # Disable "missing docstring" complaint |
10 | 10 | # pylint: disable-msg=C0111 |
11 | | # Disable "too many methods" complaint |
12 | | # pylint: disable-msg=R0904 |
13 | | # Disable "could be a function" complaint |
| 11 | # Disable "too many methods" complaint |
| 12 | # pylint: disable-msg=R0904 |
| 13 | # Disable "could be a function" complaint |
14 | 14 | # pylint: disable-msg=R0201 |
15 | 15 | # pylint: disable-msg=W0702 |
16 | 16 | |
17 | | try: |
18 | | import VolumeCanvas |
19 | | print("Testing local version") |
20 | | except: |
21 | | print(sys.exc_value) |
22 | | #testing the version that is working on |
23 | | print("Testing installed version") |
24 | | import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas |
25 | | |
| 17 | from sasmodels.sasview_model import _make_standard_model |
| 18 | EllipsoidModel = _make_standard_model('ellipsoid') |
| 19 | SphereModel = _make_standard_model('sphere') |
| 20 | CylinderModel = _make_standard_model('cylinder') |
| 21 | CoreShellModel = _make_standard_model('core_shell_sphere') |
| 22 | |
| 23 | import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas |
| 24 | |
| 25 | |
26 | 26 | |
27 | 27 | class TestSphere(unittest.TestCase): |
28 | 28 | """ Tests for oriented (2D) systems """ |
29 | | |
| 29 | |
30 | 30 | def setUp(self): |
31 | 31 | """ |
32 | 32 | Set up canvas |
33 | 33 | """ |
34 | | from sas.models.SphereModel import SphereModel |
35 | 34 | self.model = VolumeCanvas.VolumeCanvas() |
36 | | |
| 35 | |
37 | 36 | handle = self.model.add('sphere') |
38 | | |
| 37 | |
39 | 38 | radius = 10 |
40 | 39 | density = .1 |
41 | | |
| 40 | |
42 | 41 | ana = SphereModel() |
43 | 42 | ana.setParam('scale', 1.0) |
44 | | ana.setParam('contrast', 1.0) |
45 | 43 | ana.setParam('background', 0.0) |
| 44 | ana.setParam('sld', 1.0) |
| 45 | ana.setParam('sld_solvent', 0.0) |
46 | 46 | ana.setParam('radius', radius) |
47 | 47 | self.ana = ana |
48 | | |
| 48 | |
49 | 49 | self.model.setParam('lores_density', density) |
| 50 | self.model.setParam('scale' , 1.0) |
| 51 | self.model.setParam('background' , 0.0) |
| 52 | self.model.setParam('%s.contrast' % handle, 1.0) |
50 | 53 | self.model.setParam('%s.radius' % handle, radius) |
51 | | self.model.setParam('scale' , 1.0) |
52 | | self.model.setParam('%s.contrast' % handle, 1.0) |
53 | | self.model.setParam('background' , 0.0) |
54 | | |
55 | | |
| 54 | |
| 55 | |
56 | 56 | def testdefault(self): |
57 | 57 | """ Testing sphere """ |
… |
… |
|
60 | 60 | sim_val = self.model.getIq2D(0.1, 0.1) |
61 | 61 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.1 ) |
62 | | |
| 62 | |
63 | 63 | class TestCylinderAddObject(unittest.TestCase): |
64 | 64 | """ Tests for oriented (2D) systems """ |
65 | | |
| 65 | |
66 | 66 | def setUp(self): |
67 | 67 | """ Set up cylinder model """ |
68 | | from sas.models.CylinderModel import CylinderModel |
69 | 68 | radius = 5 |
70 | 69 | length = 40 |
71 | 70 | density = 20 |
72 | | |
| 71 | |
73 | 72 | # Analytical model |
74 | 73 | self.ana = CylinderModel() |
75 | 74 | self.ana.setParam('scale', 1.0) |
76 | | self.ana.setParam('contrast', 1.0) |
77 | 75 | self.ana.setParam('background', 0.0) |
| 76 | self.ana.setParam('sld', 1.0) |
| 77 | self.ana.setParam('sld_solvent', 0.0) |
78 | 78 | self.ana.setParam('radius', radius) |
79 | 79 | self.ana.setParam('length', length) |
80 | | |
| 80 | |
81 | 81 | # Simulation model |
82 | 82 | self.model = VolumeCanvas.VolumeCanvas() |
… |
… |
|
84 | 84 | self.handle = self.model.addObject(cyl) |
85 | 85 | self.model.setParam('lores_density', density) |
| 86 | self.model.setParam('scale' , 1.0) |
| 87 | self.model.setParam('background' , 0.0) |
| 88 | self.model.setParam('%s.contrast' % self.handle, 1.0) |
86 | 89 | self.model.setParam('%s.radius' % self.handle, radius) |
87 | 90 | self.model.setParam('%s.length' % self.handle, length) |
88 | | self.model.setParam('scale' , 1.0) |
89 | | self.model.setParam('%s.contrast' % self.handle, 1.0) |
90 | | self.model.setParam('background' , 0.0) |
91 | | |
| 91 | |
92 | 92 | def testalongY(self): |
93 | 93 | """ Testing cylinder along Y axis """ |
94 | | self.ana.setParam('cyl_theta', math.pi/2.0) |
95 | | self.ana.setParam('cyl_phi', math.pi/2.0) |
96 | | |
| 94 | self.ana.setParam('theta', math.pi/2.0) |
| 95 | self.ana.setParam('phi', math.pi/2.0) |
| 96 | |
97 | 97 | self.model.setParam('%s.orientation' % self.handle, [0,0,0]) |
98 | | |
99 | | ana_val = self.ana.runXY([0.1, 0.2]) |
100 | | sim_val = self.model.getIq2D(0.1, 0.2) |
101 | | #print ana_val, sim_val, sim_val/ana_val |
102 | | |
103 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
104 | | |
105 | | |
| 98 | |
| 99 | ana_val = self.ana.runXY([0.1, 0.2]) |
| 100 | sim_val = self.model.getIq2D(0.1, 0.2) |
| 101 | #print ana_val, sim_val, sim_val/ana_val |
| 102 | |
| 103 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 104 | |
| 105 | |
106 | 106 | class TestCylinder(unittest.TestCase): |
107 | 107 | """ Tests for oriented (2D) systems """ |
108 | | |
| 108 | |
109 | 109 | def setUp(self): |
110 | 110 | """ Set up cylinder model """ |
111 | | from sas.models.CylinderModel import CylinderModel |
112 | 111 | radius = 5 |
113 | 112 | length = 40 |
114 | 113 | density = 20 |
115 | | |
| 114 | |
116 | 115 | # Analytical model |
117 | 116 | self.ana = CylinderModel() |
118 | 117 | self.ana.setParam('scale', 1.0) |
119 | | self.ana.setParam('contrast', 1.0) |
120 | 118 | self.ana.setParam('background', 0.0) |
| 119 | self.ana.setParam('sld', 1.0) |
| 120 | self.ana.setParam('sld_solvent', 0.0) |
121 | 121 | self.ana.setParam('radius', radius) |
122 | 122 | self.ana.setParam('length', length) |
123 | | |
| 123 | |
124 | 124 | # Simulation model |
125 | 125 | self.model = VolumeCanvas.VolumeCanvas() |
126 | 126 | self.handle = self.model.add('cylinder') |
127 | 127 | self.model.setParam('lores_density', density) |
| 128 | self.model.setParam('scale' , 1.0) |
| 129 | self.model.setParam('background' , 0.0) |
128 | 130 | self.model.setParam('%s.radius' % self.handle, radius) |
129 | 131 | self.model.setParam('%s.length' % self.handle, length) |
130 | | self.model.setParam('scale' , 1.0) |
131 | 132 | self.model.setParam('%s.contrast' % self.handle, 1.0) |
132 | | self.model.setParam('background' , 0.0) |
133 | | |
| 133 | |
134 | 134 | def testalongY(self): |
135 | 135 | """ Testing cylinder along Y axis """ |
136 | | self.ana.setParam('cyl_theta', math.pi/2.0) |
137 | | self.ana.setParam('cyl_phi', math.pi/2.0) |
138 | | |
| 136 | self.ana.setParam('theta', math.pi/2.0) |
| 137 | self.ana.setParam('phi', math.pi/2.0) |
| 138 | |
139 | 139 | self.model.setParam('%s.orientation' % self.handle, [0,0,0]) |
140 | | |
141 | | ana_val = self.ana.runXY([0.1, 0.2]) |
142 | | sim_val = self.model.getIq2D(0.1, 0.2) |
143 | | #print ana_val, sim_val, sim_val/ana_val |
144 | | |
145 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
146 | | |
| 140 | |
| 141 | ana_val = self.ana.runXY([0.1, 0.2]) |
| 142 | sim_val = self.model.getIq2D(0.1, 0.2) |
| 143 | #print ana_val, sim_val, sim_val/ana_val |
| 144 | |
| 145 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 146 | |
147 | 147 | def testalongZ(self): |
148 | 148 | """ Testing cylinder along Z axis """ |
149 | | self.ana.setParam('cyl_theta', 0) |
150 | | self.ana.setParam('cyl_phi', 0) |
151 | | |
| 149 | self.ana.setParam('theta', 0) |
| 150 | self.ana.setParam('phi', 0) |
| 151 | |
152 | 152 | self.model.setParam('%s.orientation' % self.handle, [90,0,0]) |
153 | | |
154 | | ana_val = self.ana.runXY([0.1, 0.2]) |
155 | | sim_val = self.model.getIq2D(0.1, 0.2) |
156 | | #print ana_val, sim_val, sim_val/ana_val |
157 | | |
158 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
159 | | |
| 153 | |
| 154 | ana_val = self.ana.runXY([0.1, 0.2]) |
| 155 | sim_val = self.model.getIq2D(0.1, 0.2) |
| 156 | #print ana_val, sim_val, sim_val/ana_val |
| 157 | |
| 158 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 159 | |
160 | 160 | def testalongX(self): |
161 | 161 | """ Testing cylinder along X axis """ |
162 | | self.ana.setParam('cyl_theta', 1.57) |
163 | | self.ana.setParam('cyl_phi', 0) |
164 | | |
| 162 | self.ana.setParam('theta', 1.57) |
| 163 | self.ana.setParam('phi', 0) |
| 164 | |
165 | 165 | self.model.setParam('%s.orientation' % self.handle, [0,0,90]) |
166 | | |
167 | | ana_val = self.ana.runXY([0.1, 0.2]) |
168 | | sim_val = self.model.getIq2D(0.1, 0.2) |
169 | | #print ana_val, sim_val, sim_val/ana_val |
170 | | |
171 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
172 | | |
| 166 | |
| 167 | ana_val = self.ana.runXY([0.1, 0.2]) |
| 168 | sim_val = self.model.getIq2D(0.1, 0.2) |
| 169 | #print ana_val, sim_val, sim_val/ana_val |
| 170 | |
| 171 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 172 | |
173 | 173 | class TestEllipsoid(unittest.TestCase): |
174 | 174 | """ Tests for oriented (2D) systems """ |
175 | | |
| 175 | |
176 | 176 | def setUp(self): |
177 | 177 | """ Set up ellipsoid """ |
178 | | from sas.models.EllipsoidModel import EllipsoidModel |
179 | | |
| 178 | |
180 | 179 | radius_a = 60 |
181 | 180 | radius_b = 10 |
182 | 181 | density = 30 |
183 | | |
| 182 | |
184 | 183 | self.ana = EllipsoidModel() |
185 | 184 | self.ana.setParam('scale', 1.0) |
186 | | self.ana.setParam('contrast', 1.0) |
187 | 185 | self.ana.setParam('background', 0.0) |
188 | | self.ana.setParam('radius_a', radius_a) |
189 | | self.ana.setParam('radius_b', radius_b) |
| 186 | self.ana.setParam('sld', 1.0) |
| 187 | self.ana.setParam('sld_solvent', 0.0) |
| 188 | self.ana.setParam('radius_polar', radius_a) |
| 189 | self.ana.setParam('radius_equatorial', radius_b) |
190 | 190 | # Default orientation is there=1.57, phi=0 |
191 | 191 | # Radius_a is along the x direction |
192 | | |
| 192 | |
193 | 193 | canvas = VolumeCanvas.VolumeCanvas() |
| 194 | self.handle = canvas.add('ellipsoid') |
194 | 195 | canvas.setParam('lores_density', density) |
195 | | self.handle = canvas.add('ellipsoid') |
| 196 | canvas.setParam('scale' , 1.0) |
| 197 | canvas.setParam('background' , 0.0) |
196 | 198 | canvas.setParam('%s.radius_x' % self.handle, radius_a) |
197 | 199 | canvas.setParam('%s.radius_y' % self.handle, radius_b) |
198 | 200 | canvas.setParam('%s.radius_z' % self.handle, radius_b) |
199 | | canvas.setParam('scale' , 1.0) |
200 | 201 | canvas.setParam('%s.contrast' % self.handle, 1.0) |
201 | | canvas.setParam('background' , 0.0) |
202 | | self.canvas = canvas |
| 202 | self.canvas = canvas |
203 | 203 | |
204 | 204 | def testalongX(self): |
205 | 205 | """ Testing ellipsoid along X """ |
206 | | self.ana.setParam('axis_theta', 1.57) |
207 | | self.ana.setParam('axis_phi', 0) |
208 | | |
| 206 | self.ana.setParam('theta', 1.57) |
| 207 | self.ana.setParam('phi', 0) |
| 208 | |
209 | 209 | self.canvas.setParam('%s.orientation' % self.handle, [0,0,0]) |
210 | | |
| 210 | |
211 | 211 | ana_val = self.ana.runXY([0.1, 0.2]) |
212 | 212 | sim_val = self.canvas.getIq2D(0.1, 0.2) |
213 | 213 | #print ana_val, sim_val, sim_val/ana_val |
214 | | |
| 214 | |
215 | 215 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
216 | 216 | |
217 | 217 | def testalongZ(self): |
218 | 218 | """ Testing ellipsoid along Z """ |
219 | | self.ana.setParam('axis_theta', 0) |
220 | | self.ana.setParam('axis_phi', 0) |
221 | | |
| 219 | self.ana.setParam('theta', 0) |
| 220 | self.ana.setParam('phi', 0) |
| 221 | |
222 | 222 | self.canvas.setParam('%s.orientation' % self.handle, [0,90,0]) |
223 | | |
| 223 | |
224 | 224 | ana_val = self.ana.runXY([0.1, 0.2]) |
225 | 225 | sim_val = self.canvas.getIq2D(0.1, 0.2) |
226 | 226 | #print ana_val, sim_val, sim_val/ana_val |
227 | | |
| 227 | |
228 | 228 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
229 | 229 | |
230 | 230 | def testalongY(self): |
231 | 231 | """ Testing ellipsoid along Y """ |
232 | | self.ana.setParam('axis_theta', math.pi/2.0) |
233 | | self.ana.setParam('axis_phi', math.pi/2.0) |
234 | | |
| 232 | self.ana.setParam('theta', math.pi/2.0) |
| 233 | self.ana.setParam('phi', math.pi/2.0) |
| 234 | |
235 | 235 | self.canvas.setParam('%s.orientation' % self.handle, [0,0,90]) |
236 | | |
| 236 | |
237 | 237 | ana_val = self.ana.runXY([0.05, 0.15]) |
238 | 238 | sim_val = self.canvas.getIq2D(0.05, 0.15) |
239 | 239 | #print ana_val, sim_val, sim_val/ana_val |
240 | | |
| 240 | |
241 | 241 | try: |
242 | 242 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
243 | | except: |
| 243 | except Exception: |
244 | 244 | print("Error", ana_val, sim_val, sim_val/ana_val) |
245 | | raise sys.exc_type, sys.exc_value |
| 245 | raise |
246 | 246 | |
247 | 247 | class TestCoreShell(unittest.TestCase): |
248 | 248 | """ Tests for oriented (2D) systems """ |
249 | | |
| 249 | |
250 | 250 | def setUp(self): |
251 | 251 | """ Set up zero-SLD-average core-shell model """ |
252 | | from sas.models.CoreShellModel import CoreShellModel |
253 | | |
| 252 | |
254 | 253 | radius = 15 |
255 | 254 | thickness = 5 |
256 | 255 | density = 20 |
257 | | |
| 256 | |
258 | 257 | core_vol = 4.0/3.0*math.pi*radius*radius*radius |
259 | 258 | self.outer_radius = radius+thickness |
… |
… |
|
262 | 261 | |
263 | 262 | self.density = density |
264 | | |
| 263 | |
265 | 264 | # Core-shell |
266 | 265 | sphere = CoreShellModel() |
| 266 | sphere.setParam('scale', 1.0) |
| 267 | sphere.setParam('background', 0.0) |
267 | 268 | # Core radius |
268 | 269 | sphere.setParam('radius', radius) |
269 | 270 | # Shell thickness |
270 | 271 | sphere.setParam('thickness', thickness) |
271 | | sphere.setParam('core_sld', 1.0) |
272 | | sphere.setParam('shell_sld', self.shell_sld) |
273 | | sphere.setParam('solvent_sld', 0.0) |
274 | | sphere.setParam('background', 0.0) |
275 | | sphere.setParam('scale', 1.0) |
| 272 | sphere.setParam('sld_core', 1.0) |
| 273 | sphere.setParam('sld_shell', self.shell_sld) |
| 274 | sphere.setParam('sld_solvent', 0.0) |
276 | 275 | self.ana = sphere |
277 | | |
278 | | canvas = VolumeCanvas.VolumeCanvas() |
| 276 | |
| 277 | canvas = VolumeCanvas.VolumeCanvas() |
279 | 278 | canvas.setParam('lores_density', self.density) |
280 | | |
| 279 | canvas.setParam('scale' , 1.0) |
| 280 | canvas.setParam('background' , 0.0) |
| 281 | |
281 | 282 | handle = canvas.add('sphere') |
282 | 283 | canvas.setParam('%s.radius' % handle, self.outer_radius) |
283 | 284 | canvas.setParam('%s.contrast' % handle, self.shell_sld) |
284 | | |
| 285 | |
285 | 286 | handle2 = canvas.add('sphere') |
286 | 287 | canvas.setParam('%s.radius' % handle2, radius) |
287 | 288 | canvas.setParam('%s.contrast' % handle2, 1.0) |
288 | | |
289 | | canvas.setParam('scale' , 1.0) |
290 | | canvas.setParam('background' , 0.0) |
291 | | self.canvas = canvas |
292 | | |
| 289 | |
| 290 | self.canvas = canvas |
| 291 | |
293 | 292 | def testdefault(self): |
294 | 293 | """ Testing default core-shell orientation """ |
295 | 294 | ana_val = self.ana.runXY([0.1, 0.2]) |
296 | 295 | sim_val, err = self.canvas.getIq2DError(0.1, 0.2) |
297 | | |
298 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
299 | | |
| 296 | |
| 297 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 298 | |
300 | 299 | class TestCoreShellError(unittest.TestCase): |
301 | 300 | """ Tests for oriented (2D) systems """ |
302 | | |
| 301 | |
303 | 302 | def setUp(self): |
304 | 303 | """ Set up zero-SLD-average core-shell model """ |
305 | | from sas.models.CoreShellModel import CoreShellModel |
306 | | |
| 304 | |
307 | 305 | radius = 15 |
308 | 306 | thickness = 5 |
309 | 307 | density = 5 |
310 | | |
| 308 | |
311 | 309 | core_vol = 4.0/3.0*math.pi*radius*radius*radius |
312 | 310 | self.outer_radius = radius+thickness |
… |
… |
|
315 | 313 | |
316 | 314 | self.density = density |
317 | | |
| 315 | |
318 | 316 | # Core-shell |
319 | 317 | sphere = CoreShellModel() |
| 318 | sphere.setParam('scale', 1.0) |
| 319 | sphere.setParam('background', 0.0) |
320 | 320 | # Core radius |
321 | 321 | sphere.setParam('radius', radius) |
322 | 322 | # Shell thickness |
323 | 323 | sphere.setParam('thickness', thickness) |
324 | | sphere.setParam('core_sld', 1.0) |
325 | | sphere.setParam('shell_sld', self.shell_sld) |
326 | | sphere.setParam('solvent_sld', 0.0) |
327 | | sphere.setParam('background', 0.0) |
328 | | sphere.setParam('scale', 1.0) |
| 324 | sphere.setParam('sld_core', 1.0) |
| 325 | sphere.setParam('sld_shell', self.shell_sld) |
| 326 | sphere.setParam('sld_solvent', 0.0) |
329 | 327 | self.ana = sphere |
330 | | |
331 | | canvas = VolumeCanvas.VolumeCanvas() |
| 328 | |
| 329 | canvas = VolumeCanvas.VolumeCanvas() |
332 | 330 | canvas.setParam('lores_density', self.density) |
333 | | |
| 331 | canvas.setParam('scale' , 1.0) |
| 332 | canvas.setParam('background' , 0.0) |
| 333 | |
334 | 334 | handle = canvas.add('sphere') |
335 | 335 | canvas.setParam('%s.radius' % handle, self.outer_radius) |
336 | 336 | canvas.setParam('%s.contrast' % handle, self.shell_sld) |
337 | | |
| 337 | |
338 | 338 | handle2 = canvas.add('sphere') |
339 | 339 | canvas.setParam('%s.radius' % handle2, radius) |
340 | 340 | canvas.setParam('%s.contrast' % handle2, 1.0) |
341 | | |
342 | | canvas.setParam('scale' , 1.0) |
343 | | canvas.setParam('background' , 0.0) |
344 | | self.canvas = canvas |
345 | | |
| 341 | |
| 342 | self.canvas = canvas |
| 343 | |
346 | 344 | def testdefault(self): |
347 | 345 | """ Testing default core-shell orientation """ |
348 | 346 | ana_val = self.ana.runXY([0.1, 0.2]) |
349 | 347 | sim_val, err = self.canvas.getIq2DError(0.1, 0.2) |
350 | | |
| 348 | |
351 | 349 | self.assert_( math.fabs(sim_val-ana_val) < 3.0 * err ) |
352 | 350 | |
… |
… |
|
356 | 354 | def setUp(self): |
357 | 355 | """ Set up ellipsoid """ |
358 | | from sas.models.EllipsoidModel import EllipsoidModel |
359 | | |
| 356 | |
360 | 357 | radius_a = 10 |
361 | 358 | radius_b = 15 |
362 | 359 | density = 5 |
363 | | |
| 360 | |
364 | 361 | self.ana = EllipsoidModel() |
365 | 362 | self.ana.setParam('scale', 1.0) |
366 | | self.ana.setParam('contrast', 1.0) |
367 | 363 | self.ana.setParam('background', 0.0) |
368 | | self.ana.setParam('radius_a', radius_a) |
369 | | self.ana.setParam('radius_b', radius_b) |
370 | | |
371 | | |
| 364 | self.ana.setParam('sld', 1.0) |
| 365 | self.ana.setParam('sld_solvent', 1.0) |
| 366 | self.ana.setParam('radius_polar', radius_a) |
| 367 | self.ana.setParam('radius_equatorial', radius_b) |
| 368 | |
| 369 | |
372 | 370 | canvas = VolumeCanvas.VolumeCanvas() |
| 371 | self.handle = canvas.add('ellipsoid') |
373 | 372 | canvas.setParam('lores_density', density) |
374 | | self.handle = canvas.add('ellipsoid') |
| 373 | canvas.setParam('scale' , 1.0) |
| 374 | canvas.setParam('background' , 0.0) |
375 | 375 | canvas.setParam('%s.radius_x' % self.handle, radius_a) |
376 | 376 | canvas.setParam('%s.radius_y' % self.handle, radius_b) |
377 | 377 | canvas.setParam('%s.radius_z' % self.handle, radius_b) |
378 | | canvas.setParam('scale' , 1.0) |
379 | 378 | canvas.setParam('%s.contrast' % self.handle, 1.0) |
380 | | canvas.setParam('background' , 0.0) |
381 | | self.canvas = canvas |
382 | | |
383 | | self.ana.setParam('axis_theta', 1.57) |
384 | | self.ana.setParam('axis_phi', 0) |
385 | | |
| 379 | self.canvas = canvas |
| 380 | |
| 381 | self.ana.setParam('theta', 1.57) |
| 382 | self.ana.setParam('phi', 0) |
| 383 | |
386 | 384 | self.canvas.setParam('%s.orientation' % self.handle, [0,0,0]) |
387 | | |
| 385 | |
388 | 386 | |
389 | 387 | def testRunXY_List(self): |
… |
… |
|
392 | 390 | sim_val = self.canvas.runXY([0.1, 0.2]) |
393 | 391 | #print ana_val, sim_val, sim_val/ana_val |
394 | | |
| 392 | |
395 | 393 | try: |
396 | 394 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
397 | | except: |
| 395 | except Exception: |
398 | 396 | print("Error", ana_val, sim_val, sim_val/ana_val) |
399 | | raise sys.exc_type, sys.exc_value |
| 397 | raise |
400 | 398 | |
401 | 399 | def testRunXY_float(self): |
… |
… |
|
404 | 402 | sim_val = self.canvas.runXY(0.1) |
405 | 403 | #print ana_val, sim_val, sim_val/ana_val |
406 | | |
| 404 | |
407 | 405 | try: |
408 | 406 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
409 | | except: |
| 407 | except Exception: |
410 | 408 | print("Error", ana_val, sim_val, sim_val/ana_val) |
411 | | raise sys.exc_type, sys.exc_value |
| 409 | raise |
412 | 410 | |
413 | 411 | def testRun_float(self): |
… |
… |
|
416 | 414 | sim_val = self.canvas.run(0.1) |
417 | 415 | #print ana_val, sim_val, sim_val/ana_val |
418 | | |
| 416 | |
419 | 417 | try: |
420 | 418 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
421 | | except: |
| 419 | except Exception: |
422 | 420 | print("Error", ana_val, sim_val, sim_val/ana_val) |
423 | | raise sys.exc_type, sys.exc_value |
| 421 | raise |
424 | 422 | |
425 | 423 | def testRun_list(self): |
… |
… |
|
428 | 426 | sim_val = self.canvas.run([0.1, 33.0]) |
429 | 427 | #print ana_val, sim_val, sim_val/ana_val |
430 | | |
| 428 | |
431 | 429 | try: |
432 | 430 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
433 | | except: |
| 431 | except Exception: |
434 | 432 | print("Error", ana_val, sim_val, sim_val/ana_val) |
435 | | raise sys.exc_type, sys.exc_value |
| 433 | raise |
436 | 434 | |
437 | 435 | class TestParamChange(unittest.TestCase): |
438 | 436 | """ Tests for oriented (2D) systems """ |
439 | | |
| 437 | |
440 | 438 | def setUp(self): |
441 | 439 | """ Set up cylinder model """ |
442 | | from sas.models.CylinderModel import CylinderModel |
443 | 440 | radius = 5 |
444 | 441 | length = 40 |
445 | 442 | density = 20 |
446 | | |
| 443 | |
447 | 444 | # Analytical model |
448 | 445 | self.ana = CylinderModel() |
449 | 446 | self.ana.setParam('scale', 1.0) |
450 | | self.ana.setParam('contrast', 1.0) |
451 | 447 | self.ana.setParam('background', 0.0) |
| 448 | self.ana.setParam('sld', 1.0) |
| 449 | self.ana.setParam('sld_solvent', 0.0) |
452 | 450 | self.ana.setParam('radius', radius) |
453 | 451 | self.ana.setParam('length', length) |
454 | | self.ana.setParam('cyl_theta', math.pi/2.0) |
455 | | self.ana.setParam('cyl_phi', math.pi/2.0) |
456 | | |
| 452 | self.ana.setParam('theta', math.pi/2.0) |
| 453 | self.ana.setParam('phi', math.pi/2.0) |
| 454 | |
457 | 455 | # Simulation model |
458 | 456 | self.model = VolumeCanvas.VolumeCanvas() |
459 | 457 | self.handle = self.model.add('cylinder') |
460 | 458 | self.model.setParam('lores_density', density) |
| 459 | self.model.setParam('scale' , 1.0) |
| 460 | self.model.setParam('background' , 0.0) |
461 | 461 | self.model.setParam('%s.radius' % self.handle, radius) |
462 | 462 | self.model.setParam('%s.length' % self.handle, length) |
463 | | self.model.setParam('scale' , 1.0) |
464 | 463 | self.model.setParam('%s.contrast' % self.handle, 1.0) |
465 | | self.model.setParam('background' , 0.0) |
466 | 464 | self.model.setParam('%s.orientation' % self.handle, [0,0,0]) |
467 | | |
| 465 | |
468 | 466 | def testalongY(self): |
469 | 467 | """ Test that a parameter change forces the generation |
… |
… |
|
472 | 470 | ana_val = self.ana.runXY([0.1, 0.2]) |
473 | 471 | sim_val = self.model.getIq2D(0.1, 0.2) |
474 | | |
475 | | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
476 | | |
| 472 | |
| 473 | self.assert_( math.fabs(sim_val/ana_val-1.0)<0.05 ) |
| 474 | |
477 | 475 | # Change the radius a re-evaluate |
478 | 476 | self.ana.setParam('radius', 10) |
479 | 477 | self.model.setParam('%s.radius' % self.handle, 10) |
480 | | |
| 478 | |
481 | 479 | ana_val = self.ana.runXY([0.1, 0.2]) |
482 | 480 | sim_val = self.model.getIq2D(0.1, 0.2) |
… |
… |
|
485 | 483 | |
486 | 484 | if __name__ == '__main__': |
487 | | unittest.main() |
| 485 | unittest.main() |
-
raaf5e49
|
r1cdbcd8
|
|
9 | 9 | # Disable "missing docstring" complaint |
10 | 10 | # pylint: disable-msg=C0111 |
11 | | # Disable "too many methods" complaint |
12 | | # pylint: disable-msg=R0904 |
13 | | # Disable "could be a function" complaint |
| 11 | # Disable "too many methods" complaint |
| 12 | # pylint: disable-msg=R0904 |
| 13 | # Disable "could be a function" complaint |
14 | 14 | # pylint: disable-msg=R0201 |
15 | 15 | |
16 | | try: |
17 | | import VolumeCanvas |
18 | | print("Testing local version") |
19 | | except: |
20 | | import sys |
21 | | print(sys.exc_value) |
22 | | #testing the version that is working on |
23 | | print("Testing installed version") |
24 | | import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas |
25 | | |
| 16 | from sasmodels.sasview_model import _make_standard_model |
| 17 | EllipsoidModel = _make_standard_model('ellipsoid') |
| 18 | SphereModel = _make_standard_model('sphere') |
| 19 | CylinderModel = _make_standard_model('cylinder') |
| 20 | CoreShellModel = _make_standard_model('core_shell_sphere') |
| 21 | |
| 22 | import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas |
| 23 | |
26 | 24 | class TestRealSpaceModel(unittest.TestCase): |
27 | 25 | """ Unit tests for sphere model """ |
28 | | |
| 26 | |
29 | 27 | def setUp(self): |
30 | 28 | self.model = VolumeCanvas.VolumeCanvas() |
… |
… |
|
33 | 31 | self.model.add('ellipsoid', 'elli') |
34 | 32 | self.model.add('singlehelix', 'shelix') |
35 | | |
| 33 | |
36 | 34 | def testAdding(self): |
37 | | self.assertEqual('cyl', self.model.add('cylinder', 'cyl')) |
| 35 | self.assertEqual('cyl', self.model.add('cylinder', 'cyl')) |
38 | 36 | |
39 | 37 | def testDeleting(self): |
… |
… |
|
55 | 53 | #print "pr is calculated", self.model.hasPr |
56 | 54 | result = self.model.getIq(0.1) |
57 | | #print "I(0.1) is calculated: ", result |
| 55 | #print "I(0.1) is calculated: ", result |
58 | 56 | |
59 | 57 | class TestSphere(unittest.TestCase): |
… |
… |
|
62 | 60 | def setUp(self): |
63 | 61 | self.canvas = VolumeCanvas.VolumeCanvas() |
64 | | |
65 | | |
| 62 | |
| 63 | |
66 | 64 | def testSetQmax(self): |
67 | 65 | old_value = self.canvas.getParam('q_max') |
68 | 66 | new_value = old_value + 0.1 |
69 | 67 | self.canvas.setParam('q_max', new_value) |
70 | | self.assertEqual(self.canvas.getParam("Q_MAx"), new_value) |
71 | | |
72 | | def testSetDensity(self): |
| 68 | self.assertEqual(self.canvas.getParam("Q_MAx"), new_value) |
| 69 | |
| 70 | def testSetDensity(self): |
73 | 71 | self.canvas.setParam('lores_density', 0.1) |
74 | 72 | handle = self.canvas.add('sphere') |
… |
… |
|
77 | 75 | npts_1 = vol/0.1 |
78 | 76 | value_1 = self.canvas.getIq(0.001) |
79 | | |
| 77 | |
80 | 78 | # Change density, the answer should be the same |
81 | 79 | self.canvas.setParam('lores_density', 0.2) |
82 | 80 | npts_2 = vol/0.2 |
83 | 81 | value_2 = self.canvas.getIq(0.001) |
84 | | |
85 | | self.assert_( (value_1-value_2)/value_1 < 0.1) |
86 | | |
87 | | def testSetDensityTiming(self): |
| 82 | |
| 83 | self.assert_( (value_1-value_2)/value_1 < 0.1) |
| 84 | |
| 85 | def testSetDensityTiming(self): |
88 | 86 | """Testing change in computation time with density""" |
89 | 87 | handle = self.canvas.add('sphere') |
90 | 88 | self.canvas.setParam("%s.radius" % handle, 15.0) |
91 | | |
| 89 | |
92 | 90 | self.canvas.setParam('lores_density', 0.6) |
93 | 91 | t_0 = time.time() |
94 | 92 | self.canvas.getIq(0.001) |
95 | 93 | t_1 = time.time()-t_0 |
96 | | |
| 94 | |
97 | 95 | # Change density, the answer should be the same |
98 | 96 | self.canvas.setParam('lores_density', 0.1) |
… |
… |
|
100 | 98 | self.canvas.getIq(0.001) |
101 | 99 | t_2 = time.time()-t_0 |
102 | | |
103 | | self.assert_( t_2 < t_1 and (t_1-t_2)/t_2 > 2) |
104 | | |
| 100 | |
| 101 | self.assert_( t_2 < t_1 and (t_1-t_2)/t_2 > 2) |
| 102 | |
105 | 103 | def testGetParamList(self): |
106 | 104 | """ Test GetParamList on empty canvas""" |
107 | 105 | self.assert_('lores_density' in self.canvas.getParamList()) |
108 | 106 | handle = self.canvas.add('sphere') |
109 | | |
| 107 | |
110 | 108 | def testGetParamListWithShape(self): |
111 | 109 | """ Test GetParamList on filled canvas""" |
112 | 110 | self.canvas.add('sphere') |
113 | 111 | self.assert_('lores_density' in self.canvas.getParamList()) |
114 | | |
| 112 | |
115 | 113 | def testAdd(self): |
116 | 114 | handle = "s1" |
117 | 115 | self.assertEqual(handle, self.canvas.add('sphere', handle)) |
118 | | |
| 116 | |
119 | 117 | #TODO: test for current list of shape |
120 | 118 | self.assertEqual( [handle] , self.canvas.getShapeList()) |
121 | | |
| 119 | |
122 | 120 | def testSetRadius(self): |
123 | 121 | handle = self.canvas.add('sphere') |
124 | | self.canvas.setParam("%s.rAdius" % handle, 24.0) |
125 | | self.assertEqual(self.canvas.getParam("%s.rAdius" % handle), 24.0) |
| 122 | self.canvas.setParam("%s.radius" % handle, 24.0) |
| 123 | self.assertEqual(self.canvas.getParam("%s.radius" % handle), 24.0) |
126 | 124 | |
127 | 125 | def testGetIq(self): |
128 | 126 | """ Test the output of I(q) to the analytical solution |
129 | 127 | If the normalization is wrong, we will have to fix it. |
130 | | |
| 128 | |
131 | 129 | getIq() should call getPr() behind the scenes so that |
132 | 130 | the user doesnt have to do it if he doesn't need to. |
133 | 131 | """ |
134 | | from sas.models.SphereModel import SphereModel |
135 | 132 | sphere = SphereModel() |
| 133 | sphere.setParam('scale', 1.0) |
| 134 | sphere.setParam('background', 0.0) |
| 135 | sphere.setParam('sld', 1.0) |
| 136 | sphere.setParam('sld_solvent', 0.0) |
136 | 137 | sphere.setParam('radius', 10.0) |
137 | | sphere.setParam('contrast', 1.0) |
138 | | sphere.setParam('background', 0.0) |
139 | | sphere.setParam('scale', 1.0) |
140 | | |
| 138 | |
141 | 139 | handle = self.canvas.add('sphere') |
142 | 140 | self.canvas.setParam('%s.radius' % handle, 10.0) |
143 | 141 | self.canvas.setParam('%s.contrast' % handle, 1.0) |
144 | | |
145 | | |
| 142 | |
| 143 | |
146 | 144 | sim_1 = self.canvas.getIq(0.001) |
147 | 145 | ana_1 = sphere.run(0.001) |
148 | 146 | sim_2 = self.canvas.getIq(0.01) |
149 | 147 | ana_2 = sphere.run(0.01) |
150 | | |
151 | | # test the shape of the curve (calculate relative error |
| 148 | |
| 149 | # test the shape of the curve (calculate relative error |
152 | 150 | # on the output and it should be compatible with zero |
153 | 151 | # THIS WILL DEPEND ON THE NUMBER OF SPACE POINTS: |
154 | 152 | # that why we need some error analysis. |
155 | 153 | self.assert_( (sim_2*ana_1/sim_1 - ana_2)/ana_2 < 0.1) |
156 | | |
| 154 | |
157 | 155 | # test the absolute amplitude |
158 | 156 | self.assert_( math.fabs(sim_2-ana_2)/ana_2 < 0.1) |
159 | | |
| 157 | |
160 | 158 | def testGetIq2(self): |
161 | 159 | """ Test two different q values |
… |
… |
|
163 | 161 | handle = self.canvas.add('sphere') |
164 | 162 | self.canvas.setParam('%s.radius' % handle, 10.0) |
165 | | |
| 163 | |
166 | 164 | sim_1 = self.canvas.getIq(0.001) |
167 | 165 | sim_2 = self.canvas.getIq(0.01) |
168 | | |
| 166 | |
169 | 167 | self.assertNotAlmostEqual(sim_2, sim_1, 3) |
170 | | |
| 168 | |
171 | 169 | def testGetIq_Identical(self): |
172 | 170 | """ Test for identical model / no param change |
… |
… |
|
174 | 172 | handle = self.canvas.add('sphere') |
175 | 173 | self.canvas.setParam('%s.radius' % handle, 10.0) |
176 | | |
| 174 | |
177 | 175 | sim_1 = self.canvas.getIq(0.01) |
178 | 176 | sim_2 = self.canvas.getIq(0.01) |
179 | | |
| 177 | |
180 | 178 | self.assertEqual(sim_2, sim_1) |
181 | | |
| 179 | |
182 | 180 | def testGetIq_Identical2(self): |
183 | 181 | """ Test for identical model after a parameter change |
… |
… |
|
187 | 185 | handle = self.canvas.add('sphere') |
188 | 186 | self.canvas.setParam('%s.radius' % handle, 10.0) |
189 | | |
| 187 | |
190 | 188 | self.canvas.setParam('lores_density', 0.1) |
191 | 189 | sim_1 = self.canvas.getIq(0.01) |
192 | | |
| 190 | |
193 | 191 | # Try to fool the code by changing to a different value |
194 | 192 | self.canvas.setParam('lores_density', 0.2) |
195 | 193 | self.canvas.getIq(0.01) |
196 | | |
197 | | self.canvas.setParam('lores_density', 0.1) |
198 | | sim_2 = self.canvas.getIq(0.01) |
199 | | |
| 194 | |
| 195 | self.canvas.setParam('lores_density', 0.1) |
| 196 | sim_2 = self.canvas.getIq(0.01) |
| 197 | |
200 | 198 | self.assert_((sim_2-sim_1)/sim_1<0.05) |
201 | | |
| 199 | |
202 | 200 | def testGetIq_time(self): |
203 | 201 | """ Time profile |
… |
… |
|
205 | 203 | handle = self.canvas.add('sphere') |
206 | 204 | self.canvas.setParam('%s.radius' % handle, 15.0) |
207 | | |
208 | | |
| 205 | |
| 206 | |
209 | 207 | self.canvas.setParam('lores_density', 0.1) |
210 | 208 | t_0 = time.time() |
211 | 209 | sim_1 = self.canvas.getIq(0.01) |
212 | 210 | delta_1 = time.time()-t_0 |
213 | | |
214 | | self.canvas.setParam('lores_density', 0.1) |
215 | | |
| 211 | |
| 212 | self.canvas.setParam('lores_density', 0.1) |
| 213 | |
216 | 214 | t_0 = time.time() |
217 | 215 | sim_2 = self.canvas.getIq(0.01) |
218 | 216 | delta_2 = time.time()-t_0 |
219 | | |
| 217 | |
220 | 218 | self.assert_((delta_2-delta_1)/delta_1<0.05) |
221 | | |
222 | | |
| 219 | |
| 220 | |
223 | 221 | def testGetPr(self): |
224 | 222 | """Compare the output of P(r) to the theoretical value""" |
… |
… |
|
231 | 229 | get the right output after changing a parameter |
232 | 230 | """ |
233 | | |
| 231 | |
234 | 232 | handle = self.canvas.add('sphere') |
235 | 233 | self.canvas.setParam('%s.radius' % handle, 10.0) |
… |
… |
|