Debian Codegraph @

dicompylercore/util.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # util.py
4 """Several utility functions that don't really belong anywhere."""
5 # Copyright (c) 2009-2016 Aditya Panchal
6 # This file is part of dicompyler, released under a BSD license.
7 # See the file license.txt included with this distribution, also
8 # available at http://code.google.com/p/dicompyler/
9
10 import numpy as np
11 import collections
12 import sys
13
14
15 def piecewise(x, condlist, funclist, *args, **kw):
16 """
17 Evaluate a piecewise-defined function.
18 (Borrowed from numpy 1.11 for compatibility for numpy 1.9-1.10)
19
20 Given a set of conditions and corresponding functions, evaluate each
21 function on the input data wherever its condition is true.
22
23 Parameters
24 ----------
25 x : ndarray
26 The input domain.
27 condlist : list of bool arrays
28 Each boolean array corresponds to a function in `funclist`. Wherever
29 `condlist[i]` is True, `funclist[i](x)` is used as the output value.
30
31 Each boolean array in `condlist` selects a piece of `x`,
32 and should therefore be of the same shape as `x`.
33
34 The length of `condlist` must correspond to that of `funclist`.
35 If one extra function is given, i.e. if
36 ``len(funclist) - len(condlist) == 1``, then that extra function
37 is the default value, used wherever all conditions are false.
38 funclist : list of callables, f(x,*args,**kw), or scalars
39 Each function is evaluated over `x` wherever its corresponding
40 condition is True. It should take an array as input and give an array
41 or a scalar value as output. If, instead of a callable,
42 a scalar is provided then a constant function (``lambda x: scalar``) is
43 assumed.
44 args : tuple, optional
45 Any further arguments given to `piecewise` are passed to the functions
46 upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then
47 each function is called as ``f(x, 1, 'a')``.
48 kw : dict, optional
49 Keyword arguments used in calling `piecewise` are passed to the
50 functions upon execution, i.e., if called
51 ``piecewise(..., ..., lambda=1)``, then each function is called as
52 ``f(x, lambda=1)``.
53
54 Returns
55 -------
56 out : ndarray
57 The output is the same shape and type as x and is found by
58 calling the functions in `funclist` on the appropriate portions of `x`,
59 as defined by the boolean arrays in `condlist`. Portions not covered
60 by any condition have a default value of 0.
61
62
63 See Also
64 --------
65 choose, select, where
66
67 Notes
68 -----
69 This is similar to choose or select, except that functions are
70 evaluated on elements of `x` that satisfy the corresponding condition from
71 `condlist`.
72
73 The result is::
74
75 |--
76 |funclist[0](x[condlist[0]])
77 out = |funclist[1](x[condlist[1]])
78 |...
79 |funclist[n2](x[condlist[n2]])
80 |--
81
82 Examples
83 --------
84 Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
85
86 >>> x = np.linspace(-2.5, 2.5, 6)
87 >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
88 array([-1., -1., -1., 1., 1., 1.])
89
90 Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
91 ``x >= 0``.
92
93 >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
94 array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
95
96 """
97
98 # Use the built-in numpy piecewise function if not on numpy 1.9-1.10
99 version = np.version.version.split('.')
100 if (version[0] == '1') and (version[1] not in ['9', '10']):
101 return np.piecewise(x, condlist, funclist, *args, **kw)
102
103 x = np.asanyarray(x)
104 n2 = len(funclist)
105 if (np.isscalar(condlist) or not (isinstance(condlist[0], list) or
106 isinstance(condlist[0], np.ndarray))):
107 condlist = [condlist]
108 condlist = np.array(condlist, dtype=bool)
109 n = len(condlist)
110 # This is a hack to work around problems with NumPy's
111 # handling of 0-d arrays and boolean indexing with
112 # numpy.bool_ scalars
113 zerod = False
114 if x.ndim == 0:
115 x = x[None]
116 zerod = True
117 if condlist.shape[-1] != 1:
118 condlist = condlist.T
119 if n == n2 - 1: # compute the "otherwise" condition.
120 totlist = np.logical_or.reduce(condlist, axis=0)
121 # Only able to stack vertically if the array is 1d or less
122 if x.ndim <= 1:
123 condlist = np.vstack([condlist, ~totlist])
124 else:
125 condlist = [np.asarray(c, dtype=bool) for c in condlist]
126 totlist = condlist[0]
127 for k in range(1, n):
128 totlist |= condlist[k]
129 condlist.append(~totlist)
130 n += 1
131
132 y = np.zeros(x.shape, x.dtype)
133 for k in range(n):
134 item = funclist[k]
135 if not isinstance(item, collections.Callable):
136 y[condlist[k]] = item
137 else:
138 vals = x[condlist[k]]
139 if vals.size > 0:
140 y[condlist[k]] = item(vals, *args, **kw)
141 if zerod:
142 y = y.squeeze()
143 return y
144
145
146 def platform():
147 if sys.platform.startswith('win'):
148 return 'windows'
149 elif sys.platform.startswith('darwin'):
150 return 'mac'
151 return 'linux'