28. 1-D resolution functions¶
sasmodels.resolution¶
Define the resolution functions for the data.
This defines classes for 1D and 2D resolution calculations.
- class sasmodels.resolution.IgorComparisonTest(methodName='runTest')¶
Bases:
TestCaseTest resolution calculations against those returned by Igor.
- __call__(*args, **kwds)¶
Call self as a function.
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Test resolution calculations against those returned by Igor.\n ', 'setUp': <function IgorComparisonTest.setUp>, '_eval_sphere': <function IgorComparisonTest._eval_sphere>, '_compare': <function IgorComparisonTest._compare>, 'test_perfect': <function IgorComparisonTest.test_perfect>, 'test_pinhole': <function IgorComparisonTest.test_pinhole>, 'test_pinhole_scipy': <function IgorComparisonTest.test_pinhole_scipy>, 'test_slit': <function IgorComparisonTest.test_slit>, 'test_slit_scipy': <function IgorComparisonTest.test_slit_scipy>, 'test_slit_ellipsoid_scipy': <function IgorComparisonTest.test_slit_ellipsoid_scipy>, 'test_pinhole_sparse': <function IgorComparisonTest.test_pinhole_sparse>, '_classSetupFailed': False, '_class_cleanups': [], '__annotations__': {}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Test resolution calculations against those returned by Igor.\n '¶
- __eq__(other)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(methodName='runTest')¶
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- classmethod __init_subclass__(*args, **kwargs)¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- _addExpectedFailure(result, exc_info)¶
- _addUnexpectedSuccess(result)¶
- _baseAssertEqual(first, second, msg=None)¶
The default assertEqual implementation, not type specific.
- _callCleanup(function, /, *args, **kwargs)¶
- _callSetUp()¶
- _callTearDown()¶
- _callTestMethod(method)¶
- _classSetupFailed = False¶
- _class_cleanups = []¶
- _compare(q, output, answer, tolerance)¶
- _deprecate()¶
- _diffThreshold = 65536¶
- _eval_sphere(pars, resolution)¶
- _formatMessage(msg, standardMsg)¶
Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert
If longMessage is True: * Use the standard message * If an explicit message is provided, plus ‘ : ‘ and the explicit message
- _getAssertEqualityFunc(first, second)¶
Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types.
- _truncateMessage(message, diff)¶
- classmethod addClassCleanup(function, /, *args, **kwargs)¶
Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).
- addCleanup(function, /, *args, **kwargs)¶
Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
- addTypeEqualityFunc(typeobj, function)¶
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.
- Args:
- typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
- function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.
- assertAlmostEqual(first, second, places=None, msg=None, delta=None)¶
Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically compare almost equal.
- assertAlmostEquals(**kwargs)¶
- assertCountEqual(first, second, msg=None)¶
Asserts that two iterables have the same elements, the same number of times, without regard to order.
- self.assertEqual(Counter(list(first)),
Counter(list(second)))
- Example:
[0, 1, 1] and [1, 0, 1] compare equal.
[0, 0, 1] and [0, 1] compare unequal.
- assertDictContainsSubset(subset, dictionary, msg=None)¶
Checks whether dictionary is a superset of subset.
- assertDictEqual(d1, d2, msg=None)¶
- assertEqual(first, second, msg=None)¶
Fail if the two objects are unequal as determined by the ‘==’ operator.
- assertEquals(**kwargs)¶
- assertFalse(expr, msg=None)¶
Check that the expression is false.
- assertGreater(a, b, msg=None)¶
Just like self.assertTrue(a > b), but with a nicer default message.
- assertGreaterEqual(a, b, msg=None)¶
Just like self.assertTrue(a >= b), but with a nicer default message.
- assertIn(member, container, msg=None)¶
Just like self.assertTrue(a in b), but with a nicer default message.
- assertIs(expr1, expr2, msg=None)¶
Just like self.assertTrue(a is b), but with a nicer default message.
- assertIsInstance(obj, cls, msg=None)¶
Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.
- assertIsNone(obj, msg=None)¶
Same as self.assertTrue(obj is None), with a nicer default message.
- assertIsNot(expr1, expr2, msg=None)¶
Just like self.assertTrue(a is not b), but with a nicer default message.
- assertIsNotNone(obj, msg=None)¶
Included for symmetry with assertIsNone.
- assertLess(a, b, msg=None)¶
Just like self.assertTrue(a < b), but with a nicer default message.
- assertLessEqual(a, b, msg=None)¶
Just like self.assertTrue(a <= b), but with a nicer default message.
- assertListEqual(list1, list2, msg=None)¶
A list-specific equality assertion.
- Args:
list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of
differences.
- assertLogs(logger=None, level=None)¶
Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.
This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.
Example:
with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message'])
- assertMultiLineEqual(first, second, msg=None)¶
Assert that two multi-line strings are equal.
- assertNoLogs(logger=None, level=None)¶
Fail unless no log messages of level level or higher are emitted on logger_name or its children.
This method must be used as a context manager.
- assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)¶
Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
- assertNotAlmostEquals(**kwargs)¶
- assertNotEqual(first, second, msg=None)¶
Fail if the two objects are equal as determined by the ‘!=’ operator.
- assertNotEquals(**kwargs)¶
- assertNotIn(member, container, msg=None)¶
Just like self.assertTrue(a not in b), but with a nicer default message.
- assertNotIsInstance(obj, cls, msg=None)¶
Included for symmetry with assertIsInstance.
- assertNotRegex(text, unexpected_regex, msg=None)¶
Fail the test if the text matches the regular expression.
- assertNotRegexpMatches(**kwargs)¶
- assertRaises(expected_exception, *args, **kwargs)¶
Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
If called with the callable and arguments omitted, will return a context object used like this:
with self.assertRaises(SomeException): do_something()
An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.
The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:
with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3)
- assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)¶
Asserts that the message in a raised exception matches a regex.
- Args:
expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
- assertRaisesRegexp(**kwargs)¶
- assertRegex(text, expected_regex, msg=None)¶
Fail the test unless the text matches the regular expression.
- assertRegexpMatches(**kwargs)¶
- assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)¶
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.
- Args:
seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
- msg: Optional message to use on failure instead of a list of
differences.
- assertSetEqual(set1, set2, msg=None)¶
A set-specific equality assertion.
- Args:
set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).
- assertTrue(expr, msg=None)¶
Check that the expression is true.
- assertTupleEqual(tuple1, tuple2, msg=None)¶
A tuple-specific equality assertion.
- Args:
tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of
differences.
- assertWarns(expected_warning, *args, **kwargs)¶
Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.
If called with the callable and arguments omitted, will return a context object used like this:
with self.assertWarns(SomeWarning): do_something()
An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.
The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:
with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147)
- assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)¶
Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.
- Args:
expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
- assert_(**kwargs)¶
- countTestCases()¶
- debug()¶
Run the test without collecting errors in a TestResult
- defaultTestResult()¶
- classmethod doClassCleanups()¶
Execute all class cleanup functions. Normally called for you after tearDownClass.
- doCleanups()¶
Execute all cleanup functions. Normally called for you after tearDown.
- classmethod enterClassContext(cm)¶
Same as enterContext, but class-wide.
- enterContext(cm)¶
Enters the supplied context manager.
If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.
- fail(msg=None)¶
Fail immediately, with the given message.
- failIf(**kwargs)¶
- failIfAlmostEqual(**kwargs)¶
- failIfEqual(**kwargs)¶
- failUnless(**kwargs)¶
- failUnlessAlmostEqual(**kwargs)¶
- failUnlessEqual(**kwargs)¶
- failUnlessRaises(**kwargs)¶
- failureException¶
alias of
AssertionError
- id()¶
- longMessage = True¶
- maxDiff = 640¶
- run(result=None)¶
- setUp()¶
Hook method for setting up the test fixture before exercising it.
- classmethod setUpClass()¶
Hook method for setting up class fixture before running tests in the class.
- shortDescription()¶
Returns a one-line description of the test, or None if no description has been provided.
The default implementation of this method returns the first line of the specified test method’s docstring.
- skipTest(reason)¶
Skip this test.
- subTest(msg=<object object>, **params)¶
Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.
- tearDown()¶
Hook method for deconstructing the test fixture after testing it.
- classmethod tearDownClass()¶
Hook method for deconstructing the class fixture after running all tests in the class.
- test_perfect()¶
Compare sphere model with NIST Igor SANS, no resolution smearing.
- test_pinhole()¶
Compare pinhole resolution smearing with NIST Igor SANS
- test_pinhole_scipy()¶
Compare pinhole resolution smearing with scipy integration result.
- test_pinhole_sparse()¶
Compare pinhole resolution smearing with NIST Igor SANS on sparse data
- test_slit()¶
Compare slit resolution smearing with NIST Igor SANS
- test_slit_ellipsoid_scipy()¶
Compare slit resolution with scipy integration for ellipsoid model.
- test_slit_scipy()¶
Compare slit resolution with scipy integration for sphere.
- class sasmodels.resolution.Perfect1D(q)¶
Bases:
ResolutionResolution function to use when there is no actual resolution smearing to be applied. It has the same interface as the other resolution functions, but returns the identity function.
- __annotations__ = {}¶
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Resolution function to use when there is no actual resolution smearing\n to be applied. It has the same interface as the other resolution\n functions, but returns the identity function.\n ', '__init__': <function Perfect1D.__init__>, 'apply': <function Perfect1D.apply>, '__annotations__': {'q': 'np.ndarray', 'q_calc': 'np.ndarray'}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Resolution function to use when there is no actual resolution smearing\n to be applied. It has the same interface as the other resolution\n functions, but returns the identity function.\n '¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(q)¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- apply(theory)¶
Smear theory by the resolution function, returning Iq.
- q: ndarray = None¶
- q_calc: ndarray = None¶
- class sasmodels.resolution.Pinhole1D(q, q_width, q_calc=None, nsigma=(2.5, 3.0))¶
Bases:
ResolutionPinhole aperture with q-dependent gaussian resolution.
q points at which the data is measured.
q_width gaussian 1-sigma resolution at each data point.
q_calc is the list of points to calculate, or None if this should be estimated from the q and q_width.
nsigma is the width of the resolution function. Should be 2.5. See
pinhole_resolution()for details.- __annotations__ = {}¶
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Pinhole aperture with q-dependent gaussian resolution.\n\n *q* points at which the data is measured.\n\n *q_width* gaussian 1-sigma resolution at each data point.\n\n *q_calc* is the list of points to calculate, or None if this should\n be estimated from the *q* and *q_width*.\n\n *nsigma* is the width of the resolution function. Should be 2.5.\n See :func:`pinhole_resolution` for details.\n ', '__init__': <function Pinhole1D.__init__>, 'apply': <function Pinhole1D.apply>, '__annotations__': {'q': 'np.ndarray', 'q_calc': 'np.ndarray'}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Pinhole aperture with q-dependent gaussian resolution.\n\n *q* points at which the data is measured.\n\n *q_width* gaussian 1-sigma resolution at each data point.\n\n *q_calc* is the list of points to calculate, or None if this should\n be estimated from the *q* and *q_width*.\n\n *nsigma* is the width of the resolution function. Should be 2.5.\n See :func:`pinhole_resolution` for details.\n '¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(q, q_width, q_calc=None, nsigma=(2.5, 3.0))¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- apply(theory)¶
Smear theory by the resolution function, returning Iq.
- q: ndarray = None¶
- q_calc: ndarray = None¶
- class sasmodels.resolution.Resolution¶
Bases:
objectAbstract base class defining a 1D resolution function.
q is the set of q values at which the data is measured.
q_calc is the set of q values at which the theory needs to be evaluated. This may extend and interpolate the q values.
apply is the method to call with I(q_calc) to compute the resolution smeared theory I(q).
- __annotations__ = {'q': 'np.ndarray', 'q_calc': 'np.ndarray'}¶
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Abstract base class defining a 1D resolution function.\n\n *q* is the set of q values at which the data is measured.\n\n *q_calc* is the set of q values at which the theory needs to be evaluated.\n This may extend and interpolate the q values.\n\n *apply* is the method to call with I(q_calc) to compute the resolution\n smeared theory I(q).\n\n ', 'q': None, 'q_calc': None, 'apply': <function Resolution.apply>, '__dict__': <attribute '__dict__' of 'Resolution' objects>, '__weakref__': <attribute '__weakref__' of 'Resolution' objects>, '__annotations__': {'q': 'np.ndarray', 'q_calc': 'np.ndarray'}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Abstract base class defining a 1D resolution function.\n\n *q* is the set of q values at which the data is measured.\n\n *q_calc* is the set of q values at which the theory needs to be evaluated.\n This may extend and interpolate the q values.\n\n *apply* is the method to call with I(q_calc) to compute the resolution\n smeared theory I(q).\n\n '¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__()¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- apply(theory)¶
Smear theory by the resolution function, returning Iq.
- q: ndarray = None¶
- q_calc: ndarray = None¶
- class sasmodels.resolution.ResolutionTest(methodName='runTest')¶
Bases:
TestCaseTest the resolution calculations.
- Iq(q)¶
Linear function for resolution unit test
- __annotations__ = {}¶
- __call__(*args, **kwds)¶
Call self as a function.
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Test the resolution calculations.\n ', 'setUp': <function ResolutionTest.setUp>, 'Iq': <function ResolutionTest.Iq>, 'test_perfect': <function ResolutionTest.test_perfect>, 'test_slit_zero': <function ResolutionTest.test_slit_zero>, 'test_slit_long': <function ResolutionTest.test_slit_long>, 'test_slit_both_high': <function ResolutionTest.test_slit_both_high>, 'test_slit_wide': <function ResolutionTest.test_slit_wide>, 'test_slit_both_wide': <function ResolutionTest.test_slit_both_wide>, 'test_pinhole_zero': <function ResolutionTest.test_pinhole_zero>, 'test_pinhole': <function ResolutionTest.test_pinhole>, '_classSetupFailed': False, '_class_cleanups': [], '__annotations__': {}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Test the resolution calculations.\n '¶
- __eq__(other)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(methodName='runTest')¶
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- classmethod __init_subclass__(*args, **kwargs)¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- _addExpectedFailure(result, exc_info)¶
- _addUnexpectedSuccess(result)¶
- _baseAssertEqual(first, second, msg=None)¶
The default assertEqual implementation, not type specific.
- _callCleanup(function, /, *args, **kwargs)¶
- _callSetUp()¶
- _callTearDown()¶
- _callTestMethod(method)¶
- _classSetupFailed = False¶
- _class_cleanups = []¶
- _deprecate()¶
- _diffThreshold = 65536¶
- _formatMessage(msg, standardMsg)¶
Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert
If longMessage is True: * Use the standard message * If an explicit message is provided, plus ‘ : ‘ and the explicit message
- _getAssertEqualityFunc(first, second)¶
Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types.
- _truncateMessage(message, diff)¶
- classmethod addClassCleanup(function, /, *args, **kwargs)¶
Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).
- addCleanup(function, /, *args, **kwargs)¶
Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
- addTypeEqualityFunc(typeobj, function)¶
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.
- Args:
- typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
- function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.
- assertAlmostEqual(first, second, places=None, msg=None, delta=None)¶
Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically compare almost equal.
- assertAlmostEquals(**kwargs)¶
- assertCountEqual(first, second, msg=None)¶
Asserts that two iterables have the same elements, the same number of times, without regard to order.
- self.assertEqual(Counter(list(first)),
Counter(list(second)))
- Example:
[0, 1, 1] and [1, 0, 1] compare equal.
[0, 0, 1] and [0, 1] compare unequal.
- assertDictContainsSubset(subset, dictionary, msg=None)¶
Checks whether dictionary is a superset of subset.
- assertDictEqual(d1, d2, msg=None)¶
- assertEqual(first, second, msg=None)¶
Fail if the two objects are unequal as determined by the ‘==’ operator.
- assertEquals(**kwargs)¶
- assertFalse(expr, msg=None)¶
Check that the expression is false.
- assertGreater(a, b, msg=None)¶
Just like self.assertTrue(a > b), but with a nicer default message.
- assertGreaterEqual(a, b, msg=None)¶
Just like self.assertTrue(a >= b), but with a nicer default message.
- assertIn(member, container, msg=None)¶
Just like self.assertTrue(a in b), but with a nicer default message.
- assertIs(expr1, expr2, msg=None)¶
Just like self.assertTrue(a is b), but with a nicer default message.
- assertIsInstance(obj, cls, msg=None)¶
Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.
- assertIsNone(obj, msg=None)¶
Same as self.assertTrue(obj is None), with a nicer default message.
- assertIsNot(expr1, expr2, msg=None)¶
Just like self.assertTrue(a is not b), but with a nicer default message.
- assertIsNotNone(obj, msg=None)¶
Included for symmetry with assertIsNone.
- assertLess(a, b, msg=None)¶
Just like self.assertTrue(a < b), but with a nicer default message.
- assertLessEqual(a, b, msg=None)¶
Just like self.assertTrue(a <= b), but with a nicer default message.
- assertListEqual(list1, list2, msg=None)¶
A list-specific equality assertion.
- Args:
list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of
differences.
- assertLogs(logger=None, level=None)¶
Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.
This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.
Example:
with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message'])
- assertMultiLineEqual(first, second, msg=None)¶
Assert that two multi-line strings are equal.
- assertNoLogs(logger=None, level=None)¶
Fail unless no log messages of level level or higher are emitted on logger_name or its children.
This method must be used as a context manager.
- assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)¶
Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
- assertNotAlmostEquals(**kwargs)¶
- assertNotEqual(first, second, msg=None)¶
Fail if the two objects are equal as determined by the ‘!=’ operator.
- assertNotEquals(**kwargs)¶
- assertNotIn(member, container, msg=None)¶
Just like self.assertTrue(a not in b), but with a nicer default message.
- assertNotIsInstance(obj, cls, msg=None)¶
Included for symmetry with assertIsInstance.
- assertNotRegex(text, unexpected_regex, msg=None)¶
Fail the test if the text matches the regular expression.
- assertNotRegexpMatches(**kwargs)¶
- assertRaises(expected_exception, *args, **kwargs)¶
Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
If called with the callable and arguments omitted, will return a context object used like this:
with self.assertRaises(SomeException): do_something()
An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.
The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:
with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3)
- assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)¶
Asserts that the message in a raised exception matches a regex.
- Args:
expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
- assertRaisesRegexp(**kwargs)¶
- assertRegex(text, expected_regex, msg=None)¶
Fail the test unless the text matches the regular expression.
- assertRegexpMatches(**kwargs)¶
- assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)¶
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.
- Args:
seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
- msg: Optional message to use on failure instead of a list of
differences.
- assertSetEqual(set1, set2, msg=None)¶
A set-specific equality assertion.
- Args:
set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).
- assertTrue(expr, msg=None)¶
Check that the expression is true.
- assertTupleEqual(tuple1, tuple2, msg=None)¶
A tuple-specific equality assertion.
- Args:
tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of
differences.
- assertWarns(expected_warning, *args, **kwargs)¶
Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.
If called with the callable and arguments omitted, will return a context object used like this:
with self.assertWarns(SomeWarning): do_something()
An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.
The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:
with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147)
- assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)¶
Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.
- Args:
expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
- assert_(**kwargs)¶
- countTestCases()¶
- debug()¶
Run the test without collecting errors in a TestResult
- defaultTestResult()¶
- classmethod doClassCleanups()¶
Execute all class cleanup functions. Normally called for you after tearDownClass.
- doCleanups()¶
Execute all cleanup functions. Normally called for you after tearDown.
- classmethod enterClassContext(cm)¶
Same as enterContext, but class-wide.
- enterContext(cm)¶
Enters the supplied context manager.
If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.
- fail(msg=None)¶
Fail immediately, with the given message.
- failIf(**kwargs)¶
- failIfAlmostEqual(**kwargs)¶
- failIfEqual(**kwargs)¶
- failUnless(**kwargs)¶
- failUnlessAlmostEqual(**kwargs)¶
- failUnlessEqual(**kwargs)¶
- failUnlessRaises(**kwargs)¶
- failureException¶
alias of
AssertionError
- id()¶
- longMessage = True¶
- maxDiff = 640¶
- run(result=None)¶
- setUp()¶
Hook method for setting up the test fixture before exercising it.
- classmethod setUpClass()¶
Hook method for setting up class fixture before running tests in the class.
- shortDescription()¶
Returns a one-line description of the test, or None if no description has been provided.
The default implementation of this method returns the first line of the specified test method’s docstring.
- skipTest(reason)¶
Skip this test.
- subTest(msg=<object object>, **params)¶
Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.
- tearDown()¶
Hook method for deconstructing the test fixture after testing it.
- classmethod tearDownClass()¶
Hook method for deconstructing the class fixture after running all tests in the class.
- test_perfect()¶
Perfect resolution and no smearing.
- test_pinhole()¶
Pinhole smearing with dQ = 0.001 [Note: not dQ/Q = 0.001]
- test_pinhole_zero()¶
Pinhole smearing with perfect resolution
- test_slit_both_high()¶
Slit smearing with width < 100*length.
- test_slit_both_wide()¶
Slit smearing with width > 100*length.
- test_slit_long()¶
Slit smearing with length 0.005
- test_slit_wide()¶
Slit smearing with width 0.0002
- test_slit_zero()¶
Slit smearing with perfect resolution.
- class sasmodels.resolution.Slit1D(q, q_length=None, q_width=None, q_calc=None)¶
Bases:
ResolutionSlit aperture with resolution function.
q points at which the data is measured.
q_width slit width (short axis); deprecated nomenclature qy
q_length slit length (long axis); deprecated nomenclature qx
q_calc is the list of points to calculate, or None if this should be estimated from the q and q_width.
The weight_matrix is computed by
slit_resolution()- __annotations__ = {}¶
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.resolution', '__doc__': '\n Slit aperture with resolution function.\n\n *q* points at which the data is measured.\n\n *q_width* slit width (short axis); deprecated nomenclature qy\n\n *q_length* slit length (long axis); deprecated nomenclature qx\n\n *q_calc* is the list of points to calculate, or None if this should\n be estimated from the *q* and *q_width*.\n\n The *weight_matrix* is computed by :func:`slit_resolution`\n\n ', '__init__': <function Slit1D.__init__>, 'apply': <function Slit1D.apply>, '__annotations__': {'q': 'np.ndarray', 'q_calc': 'np.ndarray'}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Slit aperture with resolution function.\n\n *q* points at which the data is measured.\n\n *q_width* slit width (short axis); deprecated nomenclature qy\n\n *q_length* slit length (long axis); deprecated nomenclature qx\n\n *q_calc* is the list of points to calculate, or None if this should\n be estimated from the *q* and *q_width*.\n\n The *weight_matrix* is computed by :func:`slit_resolution`\n\n '¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(q, q_length=None, q_width=None, q_calc=None)¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.resolution'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- apply(theory)¶
Smear theory by the resolution function, returning Iq.
- q: ndarray = None¶
- q_calc: ndarray = None¶
- sasmodels.resolution._eval_demo_1d(resolution, title)¶
- sasmodels.resolution._q_perp_weights(q_edges, qi, w)¶
- sasmodels.resolution._quad_pinhole_1d(q, q_width, form, pars, nsigma=2.5)¶
Scipy integration for pinhole resolution.
This is an adaptive integration technique. It is called with settings that make it slow to evaluate but give it good accuracy.
- sasmodels.resolution._quad_slit_1d(q, width, length, form, pars)¶
Scipy integration for slit resolution.
This is an adaptive integration technique. It is called with settings that make it slow to evaluate but give it good accuracy.
- sasmodels.resolution.apply_resolution_matrix(weight_matrix, theory)¶
Apply the resolution weight matrix to the computed theory function.
- sasmodels.resolution.bin_edges(x)¶
Determine bin edges from bin centers, assuming that edges are centered between the bins.
Note: this uses the arithmetic mean, which may not be appropriate for log-scaled data.
- sasmodels.resolution.demo()¶
Run the resolution demos.
- sasmodels.resolution.demo_pinhole_1d()¶
Show example of pinhole smearing.
- sasmodels.resolution.demo_slit_1d()¶
Show example of slit smearing.
- sasmodels.resolution.eval_form(q, form, pars)¶
Return the SAS model evaluated at q.
form is the SAS model returned from
core.load_model().pars are the parameter values to use when evaluating.
- sasmodels.resolution.gaussian(q, q0, dq, nsigma=2.5)¶
Return the truncated Gaussian resolution function.
q0 is the center, dq is the width and q are the points to evaluate.
- sasmodels.resolution.geometric_extrapolation(q, q_min, q_max, points_per_decade=None)¶
Extrapolate q to [q_min, q_max] using geometric steps, with the average geometric step size in q as the step size.
if q_min is zero or less then q[0]/10 is used instead.
points_per_decade sets the ratio between consecutive steps such that there will be \(n\) points used for every factor of 10 increase in q.
If points_per_decade is not given, it will be estimated as follows. Starting at \(q_1\) and stepping geometrically by \(\Delta q\) to \(q_n\) in \(n\) points gives a geometric average of:
\[\log \Delta q = (\log q_n - \log q_1) / (n - 1)\]From this we can compute the number of steps required to extend \(q\) from \(q_n\) to \(q_\text{max}\) by \(\Delta q\) as:
\[n_\text{extend} = (\log q_\text{max} - \log q_n) / \log \Delta q\]Substituting:
\[n_\text{extend} = (n-1) (\log q_\text{max} - \log q_n) / (\log q_n - \log q_1)\]
- sasmodels.resolution.interpolate(q, max_step)¶
Returns q_calc with points spaced at most max_step apart.
- sasmodels.resolution.linear_extrapolation(q, q_min, q_max)¶
Extrapolate q out to [q_min, q_max] using the step size in q as a guide. Extrapolation below uses about the same size as the first interval. Extrapolation above uses about the same size as the final interval.
Note that extrapolated values may be negative.
- sasmodels.resolution.main()¶
Run tests given is sys.argv.
Returns 0 if success or 1 if any tests fail.
- sasmodels.resolution.pinhole_extend_q(q, q_width, nsigma=(2.5, 3.0))¶
Given q and q_width, find a set of sampling points q_calc so that each point \(I(q)\) has sufficient support from the underlying function.
- sasmodels.resolution.pinhole_resolution(q_calc, q, q_width, nsigma=(2.5, 3.0))¶
Compute the convolution matrix W for pinhole resolution 1-D data.
Each row W[i] determines the normalized weight that the corresponding points q_calc contribute to the resolution smeared point q[i]. Given W, the resolution smearing can be computed using dot(W,q).
Note that resolution is limited to \(\pm 2.5 \sigma\).[1] The true resolution function is a broadened triangle, and does not extend over the entire range \((-\infty, +\infty)\). It is important to impose this limitation since some models fall so steeply that the weighted value in gaussian tails would otherwise dominate the integral.
q_calc must be increasing. q_width must be greater than zero.
[1] Barker, J. G., and J. S. Pedersen. 1995. Instrumental Smearing Effects in Radially Symmetric Small-Angle Neutron Scattering by Numerical and Analytical Methods. Journal of Applied Crystallography 28 (2): 105–14. https://doi.org/10.1107/S0021889894010095.
- sasmodels.resolution.slit_extend_q(q, width, length)¶
Given q, width and length, find a set of sampling points q_calc so that each point I(q) has sufficient support from the underlying function.
- sasmodels.resolution.slit_resolution(q_calc, q, width, length, n_length=30)¶
Build a weight matrix to compute I_s(q) from I(q_calc), given \(q_\perp\) = width (in the high-resolution axis) and \(q_\parallel\) = length (in the low resolution axis). n_length is the number of steps to use in the integration over \(q_\parallel\) when both \(q_\perp\) and \(q_\parallel\) are non-zero.
Each \(q\) can have an independent width and length value even though current instruments use the same slit setting for all measured points.
If slit length is large relative to width, use:
\[I_s(q_i) = \frac{1}{\Delta q_\perp} \int_0^{\Delta q_\perp} I\left(\sqrt{q_i^2 + q_\perp^2}\right) \,dq_\perp\]If slit width is large relative to length, use:
\[I_s(q_i) = \frac{1}{2 \Delta q_\parallel} \int_{-\Delta q_\parallel}^{\Delta q_\parallel} I\left(|q_i + q_\parallel|\right) \,dq_\parallel\]For a mixture of slit width and length use:
\[I_s(q_i) = \frac{1}{2 \Delta q_\parallel \Delta q_\perp} \int_{-\Delta q_\parallel}^{\Delta q_\parallel} \int_0^{\Delta q_\perp} I\left(\sqrt{(q_i + q_\parallel)^2 + q_\perp^2}\right) \,dq_\perp dq_\parallel\]Definition
We are using the mid-point integration rule to assign weights to each element of a weight matrix \(W\) so that
\[I_s(q) = W\,I(q_\text{calc})\]If q_calc is at the mid-point, we can infer the bin edges from the pairwise averages of q_calc, adding the missing edges before q_calc[0] and after q_calc[-1].
For \(q_\parallel = 0\), the smeared value can be computed numerically using the \(u\) substitution
\[u_j = \sqrt{q_j^2 - q^2}\]This gives
\[I_s(q) \approx \sum_j I(u_j) \Delta u_j\]where \(I(u_j)\) is the value at the mid-point, and \(\Delta u_j\) is the difference between consecutive edges which have been first converted to \(u\). Only \(u_j \in [0, \Delta q_\perp]\) are used, which corresponds to \(q_j \in \left[q, \sqrt{q^2 + \Delta q_\perp}\right]\), so
\[W_{ij} = \frac{1}{\Delta q_\perp} \Delta u_j = \frac{1}{\Delta q_\perp} \left( \sqrt{q_{j+1}^2 - q_i^2} - \sqrt{q_j^2 - q_i^2} \right) \ \text{if}\ q_j \in \left[q_i, \sqrt{q_i^2 + q_\perp^2}\right]\]where \(I_s(q_i)\) is the theory function being computed and \(q_j\) are the mid-points between the calculated values in q_calc. We tweak the edges of the initial and final intervals so that they lie on integration limits.
(To be precise, the transformed midpoint \(u(q_j)\) is not necessarily the midpoint of the edges \(u((q_{j-1}+q_j)/2)\) and \(u((q_j + q_{j+1})/2)\), but it is at least in the interval, so the approximation is going to be a little better than the left or right Riemann sum, and should be good enough for our purposes.)
For \(q_\perp = 0\), the \(u\) substitution is simpler:
\[u_j = \left|q_j - q\right|\]so
\[W_{ij} = \frac{1}{2 \Delta q_\parallel} \Delta u_j = \frac{1}{2 \Delta q_\parallel} (q_{j+1} - q_j) \ \text{if}\ q_j \in \left[q-\Delta q_\parallel, q+\Delta q_\parallel\right]\]However, we need to support cases were \(u_j < 0\), which means using \(2 (q_{j+1} - q_j)\) when \(q_j \in \left[0, q_\parallel-q_i\right]\). This is not an issue for \(q_i > q_\parallel\).
For both \(q_\perp > 0\) and \(q_\parallel > 0\) we perform a 2 dimensional integration with
\[u_{jk} = \sqrt{q_j^2 - (q + (k\Delta q_\parallel/L))^2} \ \text{for}\ k = -L \ldots L\]for \(L\) = n_length. This gives
\[W_{ij} = \frac{1}{2 \Delta q_\perp q_\parallel} \sum_{k=-L}^L \Delta u_{jk} \left(\frac{\Delta q_\parallel}{2 L + 1}\right)\]