Chris@87
|
1 """ Basic functions for manipulating 2d arrays
|
Chris@87
|
2
|
Chris@87
|
3 """
|
Chris@87
|
4 from __future__ import division, absolute_import, print_function
|
Chris@87
|
5
|
Chris@87
|
6 from numpy.core.numeric import (
|
Chris@87
|
7 asanyarray, arange, zeros, greater_equal, multiply, ones, asarray,
|
Chris@87
|
8 where, int8, int16, int32, int64, empty, promote_types
|
Chris@87
|
9 )
|
Chris@87
|
10 from numpy.core import iinfo
|
Chris@87
|
11
|
Chris@87
|
12
|
Chris@87
|
13 __all__ = [
|
Chris@87
|
14 'diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'rot90', 'tri', 'triu',
|
Chris@87
|
15 'tril', 'vander', 'histogram2d', 'mask_indices', 'tril_indices',
|
Chris@87
|
16 'tril_indices_from', 'triu_indices', 'triu_indices_from', ]
|
Chris@87
|
17
|
Chris@87
|
18
|
Chris@87
|
19 i1 = iinfo(int8)
|
Chris@87
|
20 i2 = iinfo(int16)
|
Chris@87
|
21 i4 = iinfo(int32)
|
Chris@87
|
22 def _min_int(low, high):
|
Chris@87
|
23 """ get small int that fits the range """
|
Chris@87
|
24 if high <= i1.max and low >= i1.min:
|
Chris@87
|
25 return int8
|
Chris@87
|
26 if high <= i2.max and low >= i2.min:
|
Chris@87
|
27 return int16
|
Chris@87
|
28 if high <= i4.max and low >= i4.min:
|
Chris@87
|
29 return int32
|
Chris@87
|
30 return int64
|
Chris@87
|
31
|
Chris@87
|
32
|
Chris@87
|
33 def fliplr(m):
|
Chris@87
|
34 """
|
Chris@87
|
35 Flip array in the left/right direction.
|
Chris@87
|
36
|
Chris@87
|
37 Flip the entries in each row in the left/right direction.
|
Chris@87
|
38 Columns are preserved, but appear in a different order than before.
|
Chris@87
|
39
|
Chris@87
|
40 Parameters
|
Chris@87
|
41 ----------
|
Chris@87
|
42 m : array_like
|
Chris@87
|
43 Input array, must be at least 2-D.
|
Chris@87
|
44
|
Chris@87
|
45 Returns
|
Chris@87
|
46 -------
|
Chris@87
|
47 f : ndarray
|
Chris@87
|
48 A view of `m` with the columns reversed. Since a view
|
Chris@87
|
49 is returned, this operation is :math:`\\mathcal O(1)`.
|
Chris@87
|
50
|
Chris@87
|
51 See Also
|
Chris@87
|
52 --------
|
Chris@87
|
53 flipud : Flip array in the up/down direction.
|
Chris@87
|
54 rot90 : Rotate array counterclockwise.
|
Chris@87
|
55
|
Chris@87
|
56 Notes
|
Chris@87
|
57 -----
|
Chris@87
|
58 Equivalent to A[:,::-1]. Requires the array to be at least 2-D.
|
Chris@87
|
59
|
Chris@87
|
60 Examples
|
Chris@87
|
61 --------
|
Chris@87
|
62 >>> A = np.diag([1.,2.,3.])
|
Chris@87
|
63 >>> A
|
Chris@87
|
64 array([[ 1., 0., 0.],
|
Chris@87
|
65 [ 0., 2., 0.],
|
Chris@87
|
66 [ 0., 0., 3.]])
|
Chris@87
|
67 >>> np.fliplr(A)
|
Chris@87
|
68 array([[ 0., 0., 1.],
|
Chris@87
|
69 [ 0., 2., 0.],
|
Chris@87
|
70 [ 3., 0., 0.]])
|
Chris@87
|
71
|
Chris@87
|
72 >>> A = np.random.randn(2,3,5)
|
Chris@87
|
73 >>> np.all(np.fliplr(A)==A[:,::-1,...])
|
Chris@87
|
74 True
|
Chris@87
|
75
|
Chris@87
|
76 """
|
Chris@87
|
77 m = asanyarray(m)
|
Chris@87
|
78 if m.ndim < 2:
|
Chris@87
|
79 raise ValueError("Input must be >= 2-d.")
|
Chris@87
|
80 return m[:, ::-1]
|
Chris@87
|
81
|
Chris@87
|
82
|
Chris@87
|
83 def flipud(m):
|
Chris@87
|
84 """
|
Chris@87
|
85 Flip array in the up/down direction.
|
Chris@87
|
86
|
Chris@87
|
87 Flip the entries in each column in the up/down direction.
|
Chris@87
|
88 Rows are preserved, but appear in a different order than before.
|
Chris@87
|
89
|
Chris@87
|
90 Parameters
|
Chris@87
|
91 ----------
|
Chris@87
|
92 m : array_like
|
Chris@87
|
93 Input array.
|
Chris@87
|
94
|
Chris@87
|
95 Returns
|
Chris@87
|
96 -------
|
Chris@87
|
97 out : array_like
|
Chris@87
|
98 A view of `m` with the rows reversed. Since a view is
|
Chris@87
|
99 returned, this operation is :math:`\\mathcal O(1)`.
|
Chris@87
|
100
|
Chris@87
|
101 See Also
|
Chris@87
|
102 --------
|
Chris@87
|
103 fliplr : Flip array in the left/right direction.
|
Chris@87
|
104 rot90 : Rotate array counterclockwise.
|
Chris@87
|
105
|
Chris@87
|
106 Notes
|
Chris@87
|
107 -----
|
Chris@87
|
108 Equivalent to ``A[::-1,...]``.
|
Chris@87
|
109 Does not require the array to be two-dimensional.
|
Chris@87
|
110
|
Chris@87
|
111 Examples
|
Chris@87
|
112 --------
|
Chris@87
|
113 >>> A = np.diag([1.0, 2, 3])
|
Chris@87
|
114 >>> A
|
Chris@87
|
115 array([[ 1., 0., 0.],
|
Chris@87
|
116 [ 0., 2., 0.],
|
Chris@87
|
117 [ 0., 0., 3.]])
|
Chris@87
|
118 >>> np.flipud(A)
|
Chris@87
|
119 array([[ 0., 0., 3.],
|
Chris@87
|
120 [ 0., 2., 0.],
|
Chris@87
|
121 [ 1., 0., 0.]])
|
Chris@87
|
122
|
Chris@87
|
123 >>> A = np.random.randn(2,3,5)
|
Chris@87
|
124 >>> np.all(np.flipud(A)==A[::-1,...])
|
Chris@87
|
125 True
|
Chris@87
|
126
|
Chris@87
|
127 >>> np.flipud([1,2])
|
Chris@87
|
128 array([2, 1])
|
Chris@87
|
129
|
Chris@87
|
130 """
|
Chris@87
|
131 m = asanyarray(m)
|
Chris@87
|
132 if m.ndim < 1:
|
Chris@87
|
133 raise ValueError("Input must be >= 1-d.")
|
Chris@87
|
134 return m[::-1, ...]
|
Chris@87
|
135
|
Chris@87
|
136
|
Chris@87
|
137 def rot90(m, k=1):
|
Chris@87
|
138 """
|
Chris@87
|
139 Rotate an array by 90 degrees in the counter-clockwise direction.
|
Chris@87
|
140
|
Chris@87
|
141 The first two dimensions are rotated; therefore, the array must be at
|
Chris@87
|
142 least 2-D.
|
Chris@87
|
143
|
Chris@87
|
144 Parameters
|
Chris@87
|
145 ----------
|
Chris@87
|
146 m : array_like
|
Chris@87
|
147 Array of two or more dimensions.
|
Chris@87
|
148 k : integer
|
Chris@87
|
149 Number of times the array is rotated by 90 degrees.
|
Chris@87
|
150
|
Chris@87
|
151 Returns
|
Chris@87
|
152 -------
|
Chris@87
|
153 y : ndarray
|
Chris@87
|
154 Rotated array.
|
Chris@87
|
155
|
Chris@87
|
156 See Also
|
Chris@87
|
157 --------
|
Chris@87
|
158 fliplr : Flip an array horizontally.
|
Chris@87
|
159 flipud : Flip an array vertically.
|
Chris@87
|
160
|
Chris@87
|
161 Examples
|
Chris@87
|
162 --------
|
Chris@87
|
163 >>> m = np.array([[1,2],[3,4]], int)
|
Chris@87
|
164 >>> m
|
Chris@87
|
165 array([[1, 2],
|
Chris@87
|
166 [3, 4]])
|
Chris@87
|
167 >>> np.rot90(m)
|
Chris@87
|
168 array([[2, 4],
|
Chris@87
|
169 [1, 3]])
|
Chris@87
|
170 >>> np.rot90(m, 2)
|
Chris@87
|
171 array([[4, 3],
|
Chris@87
|
172 [2, 1]])
|
Chris@87
|
173
|
Chris@87
|
174 """
|
Chris@87
|
175 m = asanyarray(m)
|
Chris@87
|
176 if m.ndim < 2:
|
Chris@87
|
177 raise ValueError("Input must >= 2-d.")
|
Chris@87
|
178 k = k % 4
|
Chris@87
|
179 if k == 0:
|
Chris@87
|
180 return m
|
Chris@87
|
181 elif k == 1:
|
Chris@87
|
182 return fliplr(m).swapaxes(0, 1)
|
Chris@87
|
183 elif k == 2:
|
Chris@87
|
184 return fliplr(flipud(m))
|
Chris@87
|
185 else:
|
Chris@87
|
186 # k == 3
|
Chris@87
|
187 return fliplr(m.swapaxes(0, 1))
|
Chris@87
|
188
|
Chris@87
|
189
|
Chris@87
|
190 def eye(N, M=None, k=0, dtype=float):
|
Chris@87
|
191 """
|
Chris@87
|
192 Return a 2-D array with ones on the diagonal and zeros elsewhere.
|
Chris@87
|
193
|
Chris@87
|
194 Parameters
|
Chris@87
|
195 ----------
|
Chris@87
|
196 N : int
|
Chris@87
|
197 Number of rows in the output.
|
Chris@87
|
198 M : int, optional
|
Chris@87
|
199 Number of columns in the output. If None, defaults to `N`.
|
Chris@87
|
200 k : int, optional
|
Chris@87
|
201 Index of the diagonal: 0 (the default) refers to the main diagonal,
|
Chris@87
|
202 a positive value refers to an upper diagonal, and a negative value
|
Chris@87
|
203 to a lower diagonal.
|
Chris@87
|
204 dtype : data-type, optional
|
Chris@87
|
205 Data-type of the returned array.
|
Chris@87
|
206
|
Chris@87
|
207 Returns
|
Chris@87
|
208 -------
|
Chris@87
|
209 I : ndarray of shape (N,M)
|
Chris@87
|
210 An array where all elements are equal to zero, except for the `k`-th
|
Chris@87
|
211 diagonal, whose values are equal to one.
|
Chris@87
|
212
|
Chris@87
|
213 See Also
|
Chris@87
|
214 --------
|
Chris@87
|
215 identity : (almost) equivalent function
|
Chris@87
|
216 diag : diagonal 2-D array from a 1-D array specified by the user.
|
Chris@87
|
217
|
Chris@87
|
218 Examples
|
Chris@87
|
219 --------
|
Chris@87
|
220 >>> np.eye(2, dtype=int)
|
Chris@87
|
221 array([[1, 0],
|
Chris@87
|
222 [0, 1]])
|
Chris@87
|
223 >>> np.eye(3, k=1)
|
Chris@87
|
224 array([[ 0., 1., 0.],
|
Chris@87
|
225 [ 0., 0., 1.],
|
Chris@87
|
226 [ 0., 0., 0.]])
|
Chris@87
|
227
|
Chris@87
|
228 """
|
Chris@87
|
229 if M is None:
|
Chris@87
|
230 M = N
|
Chris@87
|
231 m = zeros((N, M), dtype=dtype)
|
Chris@87
|
232 if k >= M:
|
Chris@87
|
233 return m
|
Chris@87
|
234 if k >= 0:
|
Chris@87
|
235 i = k
|
Chris@87
|
236 else:
|
Chris@87
|
237 i = (-k) * M
|
Chris@87
|
238 m[:M-k].flat[i::M+1] = 1
|
Chris@87
|
239 return m
|
Chris@87
|
240
|
Chris@87
|
241
|
Chris@87
|
242 def diag(v, k=0):
|
Chris@87
|
243 """
|
Chris@87
|
244 Extract a diagonal or construct a diagonal array.
|
Chris@87
|
245
|
Chris@87
|
246 See the more detailed documentation for ``numpy.diagonal`` if you use this
|
Chris@87
|
247 function to extract a diagonal and wish to write to the resulting array;
|
Chris@87
|
248 whether it returns a copy or a view depends on what version of numpy you
|
Chris@87
|
249 are using.
|
Chris@87
|
250
|
Chris@87
|
251 Parameters
|
Chris@87
|
252 ----------
|
Chris@87
|
253 v : array_like
|
Chris@87
|
254 If `v` is a 2-D array, return a copy of its `k`-th diagonal.
|
Chris@87
|
255 If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
|
Chris@87
|
256 diagonal.
|
Chris@87
|
257 k : int, optional
|
Chris@87
|
258 Diagonal in question. The default is 0. Use `k>0` for diagonals
|
Chris@87
|
259 above the main diagonal, and `k<0` for diagonals below the main
|
Chris@87
|
260 diagonal.
|
Chris@87
|
261
|
Chris@87
|
262 Returns
|
Chris@87
|
263 -------
|
Chris@87
|
264 out : ndarray
|
Chris@87
|
265 The extracted diagonal or constructed diagonal array.
|
Chris@87
|
266
|
Chris@87
|
267 See Also
|
Chris@87
|
268 --------
|
Chris@87
|
269 diagonal : Return specified diagonals.
|
Chris@87
|
270 diagflat : Create a 2-D array with the flattened input as a diagonal.
|
Chris@87
|
271 trace : Sum along diagonals.
|
Chris@87
|
272 triu : Upper triangle of an array.
|
Chris@87
|
273 tril : Lower triangle of an array.
|
Chris@87
|
274
|
Chris@87
|
275 Examples
|
Chris@87
|
276 --------
|
Chris@87
|
277 >>> x = np.arange(9).reshape((3,3))
|
Chris@87
|
278 >>> x
|
Chris@87
|
279 array([[0, 1, 2],
|
Chris@87
|
280 [3, 4, 5],
|
Chris@87
|
281 [6, 7, 8]])
|
Chris@87
|
282
|
Chris@87
|
283 >>> np.diag(x)
|
Chris@87
|
284 array([0, 4, 8])
|
Chris@87
|
285 >>> np.diag(x, k=1)
|
Chris@87
|
286 array([1, 5])
|
Chris@87
|
287 >>> np.diag(x, k=-1)
|
Chris@87
|
288 array([3, 7])
|
Chris@87
|
289
|
Chris@87
|
290 >>> np.diag(np.diag(x))
|
Chris@87
|
291 array([[0, 0, 0],
|
Chris@87
|
292 [0, 4, 0],
|
Chris@87
|
293 [0, 0, 8]])
|
Chris@87
|
294
|
Chris@87
|
295 """
|
Chris@87
|
296 v = asarray(v)
|
Chris@87
|
297 s = v.shape
|
Chris@87
|
298 if len(s) == 1:
|
Chris@87
|
299 n = s[0]+abs(k)
|
Chris@87
|
300 res = zeros((n, n), v.dtype)
|
Chris@87
|
301 if k >= 0:
|
Chris@87
|
302 i = k
|
Chris@87
|
303 else:
|
Chris@87
|
304 i = (-k) * n
|
Chris@87
|
305 res[:n-k].flat[i::n+1] = v
|
Chris@87
|
306 return res
|
Chris@87
|
307 elif len(s) == 2:
|
Chris@87
|
308 return v.diagonal(k)
|
Chris@87
|
309 else:
|
Chris@87
|
310 raise ValueError("Input must be 1- or 2-d.")
|
Chris@87
|
311
|
Chris@87
|
312
|
Chris@87
|
313 def diagflat(v, k=0):
|
Chris@87
|
314 """
|
Chris@87
|
315 Create a two-dimensional array with the flattened input as a diagonal.
|
Chris@87
|
316
|
Chris@87
|
317 Parameters
|
Chris@87
|
318 ----------
|
Chris@87
|
319 v : array_like
|
Chris@87
|
320 Input data, which is flattened and set as the `k`-th
|
Chris@87
|
321 diagonal of the output.
|
Chris@87
|
322 k : int, optional
|
Chris@87
|
323 Diagonal to set; 0, the default, corresponds to the "main" diagonal,
|
Chris@87
|
324 a positive (negative) `k` giving the number of the diagonal above
|
Chris@87
|
325 (below) the main.
|
Chris@87
|
326
|
Chris@87
|
327 Returns
|
Chris@87
|
328 -------
|
Chris@87
|
329 out : ndarray
|
Chris@87
|
330 The 2-D output array.
|
Chris@87
|
331
|
Chris@87
|
332 See Also
|
Chris@87
|
333 --------
|
Chris@87
|
334 diag : MATLAB work-alike for 1-D and 2-D arrays.
|
Chris@87
|
335 diagonal : Return specified diagonals.
|
Chris@87
|
336 trace : Sum along diagonals.
|
Chris@87
|
337
|
Chris@87
|
338 Examples
|
Chris@87
|
339 --------
|
Chris@87
|
340 >>> np.diagflat([[1,2], [3,4]])
|
Chris@87
|
341 array([[1, 0, 0, 0],
|
Chris@87
|
342 [0, 2, 0, 0],
|
Chris@87
|
343 [0, 0, 3, 0],
|
Chris@87
|
344 [0, 0, 0, 4]])
|
Chris@87
|
345
|
Chris@87
|
346 >>> np.diagflat([1,2], 1)
|
Chris@87
|
347 array([[0, 1, 0],
|
Chris@87
|
348 [0, 0, 2],
|
Chris@87
|
349 [0, 0, 0]])
|
Chris@87
|
350
|
Chris@87
|
351 """
|
Chris@87
|
352 try:
|
Chris@87
|
353 wrap = v.__array_wrap__
|
Chris@87
|
354 except AttributeError:
|
Chris@87
|
355 wrap = None
|
Chris@87
|
356 v = asarray(v).ravel()
|
Chris@87
|
357 s = len(v)
|
Chris@87
|
358 n = s + abs(k)
|
Chris@87
|
359 res = zeros((n, n), v.dtype)
|
Chris@87
|
360 if (k >= 0):
|
Chris@87
|
361 i = arange(0, n-k)
|
Chris@87
|
362 fi = i+k+i*n
|
Chris@87
|
363 else:
|
Chris@87
|
364 i = arange(0, n+k)
|
Chris@87
|
365 fi = i+(i-k)*n
|
Chris@87
|
366 res.flat[fi] = v
|
Chris@87
|
367 if not wrap:
|
Chris@87
|
368 return res
|
Chris@87
|
369 return wrap(res)
|
Chris@87
|
370
|
Chris@87
|
371
|
Chris@87
|
372 def tri(N, M=None, k=0, dtype=float):
|
Chris@87
|
373 """
|
Chris@87
|
374 An array with ones at and below the given diagonal and zeros elsewhere.
|
Chris@87
|
375
|
Chris@87
|
376 Parameters
|
Chris@87
|
377 ----------
|
Chris@87
|
378 N : int
|
Chris@87
|
379 Number of rows in the array.
|
Chris@87
|
380 M : int, optional
|
Chris@87
|
381 Number of columns in the array.
|
Chris@87
|
382 By default, `M` is taken equal to `N`.
|
Chris@87
|
383 k : int, optional
|
Chris@87
|
384 The sub-diagonal at and below which the array is filled.
|
Chris@87
|
385 `k` = 0 is the main diagonal, while `k` < 0 is below it,
|
Chris@87
|
386 and `k` > 0 is above. The default is 0.
|
Chris@87
|
387 dtype : dtype, optional
|
Chris@87
|
388 Data type of the returned array. The default is float.
|
Chris@87
|
389
|
Chris@87
|
390 Returns
|
Chris@87
|
391 -------
|
Chris@87
|
392 tri : ndarray of shape (N, M)
|
Chris@87
|
393 Array with its lower triangle filled with ones and zero elsewhere;
|
Chris@87
|
394 in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise.
|
Chris@87
|
395
|
Chris@87
|
396 Examples
|
Chris@87
|
397 --------
|
Chris@87
|
398 >>> np.tri(3, 5, 2, dtype=int)
|
Chris@87
|
399 array([[1, 1, 1, 0, 0],
|
Chris@87
|
400 [1, 1, 1, 1, 0],
|
Chris@87
|
401 [1, 1, 1, 1, 1]])
|
Chris@87
|
402
|
Chris@87
|
403 >>> np.tri(3, 5, -1)
|
Chris@87
|
404 array([[ 0., 0., 0., 0., 0.],
|
Chris@87
|
405 [ 1., 0., 0., 0., 0.],
|
Chris@87
|
406 [ 1., 1., 0., 0., 0.]])
|
Chris@87
|
407
|
Chris@87
|
408 """
|
Chris@87
|
409 if M is None:
|
Chris@87
|
410 M = N
|
Chris@87
|
411
|
Chris@87
|
412 m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
|
Chris@87
|
413 arange(-k, M-k, dtype=_min_int(-k, M - k)))
|
Chris@87
|
414
|
Chris@87
|
415 # Avoid making a copy if the requested type is already bool
|
Chris@87
|
416 m = m.astype(dtype, copy=False)
|
Chris@87
|
417
|
Chris@87
|
418 return m
|
Chris@87
|
419
|
Chris@87
|
420
|
Chris@87
|
421 def tril(m, k=0):
|
Chris@87
|
422 """
|
Chris@87
|
423 Lower triangle of an array.
|
Chris@87
|
424
|
Chris@87
|
425 Return a copy of an array with elements above the `k`-th diagonal zeroed.
|
Chris@87
|
426
|
Chris@87
|
427 Parameters
|
Chris@87
|
428 ----------
|
Chris@87
|
429 m : array_like, shape (M, N)
|
Chris@87
|
430 Input array.
|
Chris@87
|
431 k : int, optional
|
Chris@87
|
432 Diagonal above which to zero elements. `k = 0` (the default) is the
|
Chris@87
|
433 main diagonal, `k < 0` is below it and `k > 0` is above.
|
Chris@87
|
434
|
Chris@87
|
435 Returns
|
Chris@87
|
436 -------
|
Chris@87
|
437 tril : ndarray, shape (M, N)
|
Chris@87
|
438 Lower triangle of `m`, of same shape and data-type as `m`.
|
Chris@87
|
439
|
Chris@87
|
440 See Also
|
Chris@87
|
441 --------
|
Chris@87
|
442 triu : same thing, only for the upper triangle
|
Chris@87
|
443
|
Chris@87
|
444 Examples
|
Chris@87
|
445 --------
|
Chris@87
|
446 >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
|
Chris@87
|
447 array([[ 0, 0, 0],
|
Chris@87
|
448 [ 4, 0, 0],
|
Chris@87
|
449 [ 7, 8, 0],
|
Chris@87
|
450 [10, 11, 12]])
|
Chris@87
|
451
|
Chris@87
|
452 """
|
Chris@87
|
453 m = asanyarray(m)
|
Chris@87
|
454 mask = tri(*m.shape[-2:], k=k, dtype=bool)
|
Chris@87
|
455
|
Chris@87
|
456 return where(mask, m, zeros(1, m.dtype))
|
Chris@87
|
457
|
Chris@87
|
458
|
Chris@87
|
459 def triu(m, k=0):
|
Chris@87
|
460 """
|
Chris@87
|
461 Upper triangle of an array.
|
Chris@87
|
462
|
Chris@87
|
463 Return a copy of a matrix with the elements below the `k`-th diagonal
|
Chris@87
|
464 zeroed.
|
Chris@87
|
465
|
Chris@87
|
466 Please refer to the documentation for `tril` for further details.
|
Chris@87
|
467
|
Chris@87
|
468 See Also
|
Chris@87
|
469 --------
|
Chris@87
|
470 tril : lower triangle of an array
|
Chris@87
|
471
|
Chris@87
|
472 Examples
|
Chris@87
|
473 --------
|
Chris@87
|
474 >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
|
Chris@87
|
475 array([[ 1, 2, 3],
|
Chris@87
|
476 [ 4, 5, 6],
|
Chris@87
|
477 [ 0, 8, 9],
|
Chris@87
|
478 [ 0, 0, 12]])
|
Chris@87
|
479
|
Chris@87
|
480 """
|
Chris@87
|
481 m = asanyarray(m)
|
Chris@87
|
482 mask = tri(*m.shape[-2:], k=k-1, dtype=bool)
|
Chris@87
|
483
|
Chris@87
|
484 return where(mask, zeros(1, m.dtype), m)
|
Chris@87
|
485
|
Chris@87
|
486
|
Chris@87
|
487 # Originally borrowed from John Hunter and matplotlib
|
Chris@87
|
488 def vander(x, N=None, increasing=False):
|
Chris@87
|
489 """
|
Chris@87
|
490 Generate a Vandermonde matrix.
|
Chris@87
|
491
|
Chris@87
|
492 The columns of the output matrix are powers of the input vector. The
|
Chris@87
|
493 order of the powers is determined by the `increasing` boolean argument.
|
Chris@87
|
494 Specifically, when `increasing` is False, the `i`-th output column is
|
Chris@87
|
495 the input vector raised element-wise to the power of ``N - i - 1``. Such
|
Chris@87
|
496 a matrix with a geometric progression in each row is named for Alexandre-
|
Chris@87
|
497 Theophile Vandermonde.
|
Chris@87
|
498
|
Chris@87
|
499 Parameters
|
Chris@87
|
500 ----------
|
Chris@87
|
501 x : array_like
|
Chris@87
|
502 1-D input array.
|
Chris@87
|
503 N : int, optional
|
Chris@87
|
504 Number of columns in the output. If `N` is not specified, a square
|
Chris@87
|
505 array is returned (``N = len(x)``).
|
Chris@87
|
506 increasing : bool, optional
|
Chris@87
|
507 Order of the powers of the columns. If True, the powers increase
|
Chris@87
|
508 from left to right, if False (the default) they are reversed.
|
Chris@87
|
509
|
Chris@87
|
510 .. versionadded:: 1.9.0
|
Chris@87
|
511
|
Chris@87
|
512 Returns
|
Chris@87
|
513 -------
|
Chris@87
|
514 out : ndarray
|
Chris@87
|
515 Vandermonde matrix. If `increasing` is False, the first column is
|
Chris@87
|
516 ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
|
Chris@87
|
517 True, the columns are ``x^0, x^1, ..., x^(N-1)``.
|
Chris@87
|
518
|
Chris@87
|
519 See Also
|
Chris@87
|
520 --------
|
Chris@87
|
521 polynomial.polynomial.polyvander
|
Chris@87
|
522
|
Chris@87
|
523 Examples
|
Chris@87
|
524 --------
|
Chris@87
|
525 >>> x = np.array([1, 2, 3, 5])
|
Chris@87
|
526 >>> N = 3
|
Chris@87
|
527 >>> np.vander(x, N)
|
Chris@87
|
528 array([[ 1, 1, 1],
|
Chris@87
|
529 [ 4, 2, 1],
|
Chris@87
|
530 [ 9, 3, 1],
|
Chris@87
|
531 [25, 5, 1]])
|
Chris@87
|
532
|
Chris@87
|
533 >>> np.column_stack([x**(N-1-i) for i in range(N)])
|
Chris@87
|
534 array([[ 1, 1, 1],
|
Chris@87
|
535 [ 4, 2, 1],
|
Chris@87
|
536 [ 9, 3, 1],
|
Chris@87
|
537 [25, 5, 1]])
|
Chris@87
|
538
|
Chris@87
|
539 >>> x = np.array([1, 2, 3, 5])
|
Chris@87
|
540 >>> np.vander(x)
|
Chris@87
|
541 array([[ 1, 1, 1, 1],
|
Chris@87
|
542 [ 8, 4, 2, 1],
|
Chris@87
|
543 [ 27, 9, 3, 1],
|
Chris@87
|
544 [125, 25, 5, 1]])
|
Chris@87
|
545 >>> np.vander(x, increasing=True)
|
Chris@87
|
546 array([[ 1, 1, 1, 1],
|
Chris@87
|
547 [ 1, 2, 4, 8],
|
Chris@87
|
548 [ 1, 3, 9, 27],
|
Chris@87
|
549 [ 1, 5, 25, 125]])
|
Chris@87
|
550
|
Chris@87
|
551 The determinant of a square Vandermonde matrix is the product
|
Chris@87
|
552 of the differences between the values of the input vector:
|
Chris@87
|
553
|
Chris@87
|
554 >>> np.linalg.det(np.vander(x))
|
Chris@87
|
555 48.000000000000043
|
Chris@87
|
556 >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
|
Chris@87
|
557 48
|
Chris@87
|
558
|
Chris@87
|
559 """
|
Chris@87
|
560 x = asarray(x)
|
Chris@87
|
561 if x.ndim != 1:
|
Chris@87
|
562 raise ValueError("x must be a one-dimensional array or sequence.")
|
Chris@87
|
563 if N is None:
|
Chris@87
|
564 N = len(x)
|
Chris@87
|
565
|
Chris@87
|
566 v = empty((len(x), N), dtype=promote_types(x.dtype, int))
|
Chris@87
|
567 tmp = v[:, ::-1] if not increasing else v
|
Chris@87
|
568
|
Chris@87
|
569 if N > 0:
|
Chris@87
|
570 tmp[:, 0] = 1
|
Chris@87
|
571 if N > 1:
|
Chris@87
|
572 tmp[:, 1:] = x[:, None]
|
Chris@87
|
573 multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1)
|
Chris@87
|
574
|
Chris@87
|
575 return v
|
Chris@87
|
576
|
Chris@87
|
577
|
Chris@87
|
578 def histogram2d(x, y, bins=10, range=None, normed=False, weights=None):
|
Chris@87
|
579 """
|
Chris@87
|
580 Compute the bi-dimensional histogram of two data samples.
|
Chris@87
|
581
|
Chris@87
|
582 Parameters
|
Chris@87
|
583 ----------
|
Chris@87
|
584 x : array_like, shape (N,)
|
Chris@87
|
585 An array containing the x coordinates of the points to be
|
Chris@87
|
586 histogrammed.
|
Chris@87
|
587 y : array_like, shape (N,)
|
Chris@87
|
588 An array containing the y coordinates of the points to be
|
Chris@87
|
589 histogrammed.
|
Chris@87
|
590 bins : int or [int, int] or array_like or [array, array], optional
|
Chris@87
|
591 The bin specification:
|
Chris@87
|
592
|
Chris@87
|
593 * If int, the number of bins for the two dimensions (nx=ny=bins).
|
Chris@87
|
594 * If [int, int], the number of bins in each dimension
|
Chris@87
|
595 (nx, ny = bins).
|
Chris@87
|
596 * If array_like, the bin edges for the two dimensions
|
Chris@87
|
597 (x_edges=y_edges=bins).
|
Chris@87
|
598 * If [array, array], the bin edges in each dimension
|
Chris@87
|
599 (x_edges, y_edges = bins).
|
Chris@87
|
600
|
Chris@87
|
601 range : array_like, shape(2,2), optional
|
Chris@87
|
602 The leftmost and rightmost edges of the bins along each dimension
|
Chris@87
|
603 (if not specified explicitly in the `bins` parameters):
|
Chris@87
|
604 ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
|
Chris@87
|
605 will be considered outliers and not tallied in the histogram.
|
Chris@87
|
606 normed : bool, optional
|
Chris@87
|
607 If False, returns the number of samples in each bin. If True,
|
Chris@87
|
608 returns the bin density ``bin_count / sample_count / bin_area``.
|
Chris@87
|
609 weights : array_like, shape(N,), optional
|
Chris@87
|
610 An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
|
Chris@87
|
611 Weights are normalized to 1 if `normed` is True. If `normed` is
|
Chris@87
|
612 False, the values of the returned histogram are equal to the sum of
|
Chris@87
|
613 the weights belonging to the samples falling into each bin.
|
Chris@87
|
614
|
Chris@87
|
615 Returns
|
Chris@87
|
616 -------
|
Chris@87
|
617 H : ndarray, shape(nx, ny)
|
Chris@87
|
618 The bi-dimensional histogram of samples `x` and `y`. Values in `x`
|
Chris@87
|
619 are histogrammed along the first dimension and values in `y` are
|
Chris@87
|
620 histogrammed along the second dimension.
|
Chris@87
|
621 xedges : ndarray, shape(nx,)
|
Chris@87
|
622 The bin edges along the first dimension.
|
Chris@87
|
623 yedges : ndarray, shape(ny,)
|
Chris@87
|
624 The bin edges along the second dimension.
|
Chris@87
|
625
|
Chris@87
|
626 See Also
|
Chris@87
|
627 --------
|
Chris@87
|
628 histogram : 1D histogram
|
Chris@87
|
629 histogramdd : Multidimensional histogram
|
Chris@87
|
630
|
Chris@87
|
631 Notes
|
Chris@87
|
632 -----
|
Chris@87
|
633 When `normed` is True, then the returned histogram is the sample
|
Chris@87
|
634 density, defined such that the sum over bins of the product
|
Chris@87
|
635 ``bin_value * bin_area`` is 1.
|
Chris@87
|
636
|
Chris@87
|
637 Please note that the histogram does not follow the Cartesian convention
|
Chris@87
|
638 where `x` values are on the abscissa and `y` values on the ordinate
|
Chris@87
|
639 axis. Rather, `x` is histogrammed along the first dimension of the
|
Chris@87
|
640 array (vertical), and `y` along the second dimension of the array
|
Chris@87
|
641 (horizontal). This ensures compatibility with `histogramdd`.
|
Chris@87
|
642
|
Chris@87
|
643 Examples
|
Chris@87
|
644 --------
|
Chris@87
|
645 >>> import matplotlib as mpl
|
Chris@87
|
646 >>> import matplotlib.pyplot as plt
|
Chris@87
|
647
|
Chris@87
|
648 Construct a 2D-histogram with variable bin width. First define the bin
|
Chris@87
|
649 edges:
|
Chris@87
|
650
|
Chris@87
|
651 >>> xedges = [0, 1, 1.5, 3, 5]
|
Chris@87
|
652 >>> yedges = [0, 2, 3, 4, 6]
|
Chris@87
|
653
|
Chris@87
|
654 Next we create a histogram H with random bin content:
|
Chris@87
|
655
|
Chris@87
|
656 >>> x = np.random.normal(3, 1, 100)
|
Chris@87
|
657 >>> y = np.random.normal(1, 1, 100)
|
Chris@87
|
658 >>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))
|
Chris@87
|
659
|
Chris@87
|
660 Or we fill the histogram H with a determined bin content:
|
Chris@87
|
661
|
Chris@87
|
662 >>> H = np.ones((4, 4)).cumsum().reshape(4, 4)
|
Chris@87
|
663 >>> print H[::-1] # This shows the bin content in the order as plotted
|
Chris@87
|
664 [[ 13. 14. 15. 16.]
|
Chris@87
|
665 [ 9. 10. 11. 12.]
|
Chris@87
|
666 [ 5. 6. 7. 8.]
|
Chris@87
|
667 [ 1. 2. 3. 4.]]
|
Chris@87
|
668
|
Chris@87
|
669 Imshow can only do an equidistant representation of bins:
|
Chris@87
|
670
|
Chris@87
|
671 >>> fig = plt.figure(figsize=(7, 3))
|
Chris@87
|
672 >>> ax = fig.add_subplot(131)
|
Chris@87
|
673 >>> ax.set_title('imshow: equidistant')
|
Chris@87
|
674 >>> im = plt.imshow(H, interpolation='nearest', origin='low',
|
Chris@87
|
675 extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
|
Chris@87
|
676
|
Chris@87
|
677 pcolormesh can display exact bin edges:
|
Chris@87
|
678
|
Chris@87
|
679 >>> ax = fig.add_subplot(132)
|
Chris@87
|
680 >>> ax.set_title('pcolormesh: exact bin edges')
|
Chris@87
|
681 >>> X, Y = np.meshgrid(xedges, yedges)
|
Chris@87
|
682 >>> ax.pcolormesh(X, Y, H)
|
Chris@87
|
683 >>> ax.set_aspect('equal')
|
Chris@87
|
684
|
Chris@87
|
685 NonUniformImage displays exact bin edges with interpolation:
|
Chris@87
|
686
|
Chris@87
|
687 >>> ax = fig.add_subplot(133)
|
Chris@87
|
688 >>> ax.set_title('NonUniformImage: interpolated')
|
Chris@87
|
689 >>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear')
|
Chris@87
|
690 >>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
|
Chris@87
|
691 >>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])
|
Chris@87
|
692 >>> im.set_data(xcenters, ycenters, H)
|
Chris@87
|
693 >>> ax.images.append(im)
|
Chris@87
|
694 >>> ax.set_xlim(xedges[0], xedges[-1])
|
Chris@87
|
695 >>> ax.set_ylim(yedges[0], yedges[-1])
|
Chris@87
|
696 >>> ax.set_aspect('equal')
|
Chris@87
|
697 >>> plt.show()
|
Chris@87
|
698
|
Chris@87
|
699 """
|
Chris@87
|
700 from numpy import histogramdd
|
Chris@87
|
701
|
Chris@87
|
702 try:
|
Chris@87
|
703 N = len(bins)
|
Chris@87
|
704 except TypeError:
|
Chris@87
|
705 N = 1
|
Chris@87
|
706
|
Chris@87
|
707 if N != 1 and N != 2:
|
Chris@87
|
708 xedges = yedges = asarray(bins, float)
|
Chris@87
|
709 bins = [xedges, yedges]
|
Chris@87
|
710 hist, edges = histogramdd([x, y], bins, range, normed, weights)
|
Chris@87
|
711 return hist, edges[0], edges[1]
|
Chris@87
|
712
|
Chris@87
|
713
|
Chris@87
|
714 def mask_indices(n, mask_func, k=0):
|
Chris@87
|
715 """
|
Chris@87
|
716 Return the indices to access (n, n) arrays, given a masking function.
|
Chris@87
|
717
|
Chris@87
|
718 Assume `mask_func` is a function that, for a square array a of size
|
Chris@87
|
719 ``(n, n)`` with a possible offset argument `k`, when called as
|
Chris@87
|
720 ``mask_func(a, k)`` returns a new array with zeros in certain locations
|
Chris@87
|
721 (functions like `triu` or `tril` do precisely this). Then this function
|
Chris@87
|
722 returns the indices where the non-zero values would be located.
|
Chris@87
|
723
|
Chris@87
|
724 Parameters
|
Chris@87
|
725 ----------
|
Chris@87
|
726 n : int
|
Chris@87
|
727 The returned indices will be valid to access arrays of shape (n, n).
|
Chris@87
|
728 mask_func : callable
|
Chris@87
|
729 A function whose call signature is similar to that of `triu`, `tril`.
|
Chris@87
|
730 That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`.
|
Chris@87
|
731 `k` is an optional argument to the function.
|
Chris@87
|
732 k : scalar
|
Chris@87
|
733 An optional argument which is passed through to `mask_func`. Functions
|
Chris@87
|
734 like `triu`, `tril` take a second argument that is interpreted as an
|
Chris@87
|
735 offset.
|
Chris@87
|
736
|
Chris@87
|
737 Returns
|
Chris@87
|
738 -------
|
Chris@87
|
739 indices : tuple of arrays.
|
Chris@87
|
740 The `n` arrays of indices corresponding to the locations where
|
Chris@87
|
741 ``mask_func(np.ones((n, n)), k)`` is True.
|
Chris@87
|
742
|
Chris@87
|
743 See Also
|
Chris@87
|
744 --------
|
Chris@87
|
745 triu, tril, triu_indices, tril_indices
|
Chris@87
|
746
|
Chris@87
|
747 Notes
|
Chris@87
|
748 -----
|
Chris@87
|
749 .. versionadded:: 1.4.0
|
Chris@87
|
750
|
Chris@87
|
751 Examples
|
Chris@87
|
752 --------
|
Chris@87
|
753 These are the indices that would allow you to access the upper triangular
|
Chris@87
|
754 part of any 3x3 array:
|
Chris@87
|
755
|
Chris@87
|
756 >>> iu = np.mask_indices(3, np.triu)
|
Chris@87
|
757
|
Chris@87
|
758 For example, if `a` is a 3x3 array:
|
Chris@87
|
759
|
Chris@87
|
760 >>> a = np.arange(9).reshape(3, 3)
|
Chris@87
|
761 >>> a
|
Chris@87
|
762 array([[0, 1, 2],
|
Chris@87
|
763 [3, 4, 5],
|
Chris@87
|
764 [6, 7, 8]])
|
Chris@87
|
765 >>> a[iu]
|
Chris@87
|
766 array([0, 1, 2, 4, 5, 8])
|
Chris@87
|
767
|
Chris@87
|
768 An offset can be passed also to the masking function. This gets us the
|
Chris@87
|
769 indices starting on the first diagonal right of the main one:
|
Chris@87
|
770
|
Chris@87
|
771 >>> iu1 = np.mask_indices(3, np.triu, 1)
|
Chris@87
|
772
|
Chris@87
|
773 with which we now extract only three elements:
|
Chris@87
|
774
|
Chris@87
|
775 >>> a[iu1]
|
Chris@87
|
776 array([1, 2, 5])
|
Chris@87
|
777
|
Chris@87
|
778 """
|
Chris@87
|
779 m = ones((n, n), int)
|
Chris@87
|
780 a = mask_func(m, k)
|
Chris@87
|
781 return where(a != 0)
|
Chris@87
|
782
|
Chris@87
|
783
|
Chris@87
|
784 def tril_indices(n, k=0, m=None):
|
Chris@87
|
785 """
|
Chris@87
|
786 Return the indices for the lower-triangle of an (n, m) array.
|
Chris@87
|
787
|
Chris@87
|
788 Parameters
|
Chris@87
|
789 ----------
|
Chris@87
|
790 n : int
|
Chris@87
|
791 The row dimension of the arrays for which the returned
|
Chris@87
|
792 indices will be valid.
|
Chris@87
|
793 k : int, optional
|
Chris@87
|
794 Diagonal offset (see `tril` for details).
|
Chris@87
|
795 m : int, optional
|
Chris@87
|
796 .. versionadded:: 1.9.0
|
Chris@87
|
797
|
Chris@87
|
798 The column dimension of the arrays for which the returned
|
Chris@87
|
799 arrays will be valid.
|
Chris@87
|
800 By default `m` is taken equal to `n`.
|
Chris@87
|
801
|
Chris@87
|
802
|
Chris@87
|
803 Returns
|
Chris@87
|
804 -------
|
Chris@87
|
805 inds : tuple of arrays
|
Chris@87
|
806 The indices for the triangle. The returned tuple contains two arrays,
|
Chris@87
|
807 each with the indices along one dimension of the array.
|
Chris@87
|
808
|
Chris@87
|
809 See also
|
Chris@87
|
810 --------
|
Chris@87
|
811 triu_indices : similar function, for upper-triangular.
|
Chris@87
|
812 mask_indices : generic function accepting an arbitrary mask function.
|
Chris@87
|
813 tril, triu
|
Chris@87
|
814
|
Chris@87
|
815 Notes
|
Chris@87
|
816 -----
|
Chris@87
|
817 .. versionadded:: 1.4.0
|
Chris@87
|
818
|
Chris@87
|
819 Examples
|
Chris@87
|
820 --------
|
Chris@87
|
821 Compute two different sets of indices to access 4x4 arrays, one for the
|
Chris@87
|
822 lower triangular part starting at the main diagonal, and one starting two
|
Chris@87
|
823 diagonals further right:
|
Chris@87
|
824
|
Chris@87
|
825 >>> il1 = np.tril_indices(4)
|
Chris@87
|
826 >>> il2 = np.tril_indices(4, 2)
|
Chris@87
|
827
|
Chris@87
|
828 Here is how they can be used with a sample array:
|
Chris@87
|
829
|
Chris@87
|
830 >>> a = np.arange(16).reshape(4, 4)
|
Chris@87
|
831 >>> a
|
Chris@87
|
832 array([[ 0, 1, 2, 3],
|
Chris@87
|
833 [ 4, 5, 6, 7],
|
Chris@87
|
834 [ 8, 9, 10, 11],
|
Chris@87
|
835 [12, 13, 14, 15]])
|
Chris@87
|
836
|
Chris@87
|
837 Both for indexing:
|
Chris@87
|
838
|
Chris@87
|
839 >>> a[il1]
|
Chris@87
|
840 array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15])
|
Chris@87
|
841
|
Chris@87
|
842 And for assigning values:
|
Chris@87
|
843
|
Chris@87
|
844 >>> a[il1] = -1
|
Chris@87
|
845 >>> a
|
Chris@87
|
846 array([[-1, 1, 2, 3],
|
Chris@87
|
847 [-1, -1, 6, 7],
|
Chris@87
|
848 [-1, -1, -1, 11],
|
Chris@87
|
849 [-1, -1, -1, -1]])
|
Chris@87
|
850
|
Chris@87
|
851 These cover almost the whole array (two diagonals right of the main one):
|
Chris@87
|
852
|
Chris@87
|
853 >>> a[il2] = -10
|
Chris@87
|
854 >>> a
|
Chris@87
|
855 array([[-10, -10, -10, 3],
|
Chris@87
|
856 [-10, -10, -10, -10],
|
Chris@87
|
857 [-10, -10, -10, -10],
|
Chris@87
|
858 [-10, -10, -10, -10]])
|
Chris@87
|
859
|
Chris@87
|
860 """
|
Chris@87
|
861 return where(tri(n, m, k=k, dtype=bool))
|
Chris@87
|
862
|
Chris@87
|
863
|
Chris@87
|
864 def tril_indices_from(arr, k=0):
|
Chris@87
|
865 """
|
Chris@87
|
866 Return the indices for the lower-triangle of arr.
|
Chris@87
|
867
|
Chris@87
|
868 See `tril_indices` for full details.
|
Chris@87
|
869
|
Chris@87
|
870 Parameters
|
Chris@87
|
871 ----------
|
Chris@87
|
872 arr : array_like
|
Chris@87
|
873 The indices will be valid for square arrays whose dimensions are
|
Chris@87
|
874 the same as arr.
|
Chris@87
|
875 k : int, optional
|
Chris@87
|
876 Diagonal offset (see `tril` for details).
|
Chris@87
|
877
|
Chris@87
|
878 See Also
|
Chris@87
|
879 --------
|
Chris@87
|
880 tril_indices, tril
|
Chris@87
|
881
|
Chris@87
|
882 Notes
|
Chris@87
|
883 -----
|
Chris@87
|
884 .. versionadded:: 1.4.0
|
Chris@87
|
885
|
Chris@87
|
886 """
|
Chris@87
|
887 if arr.ndim != 2:
|
Chris@87
|
888 raise ValueError("input array must be 2-d")
|
Chris@87
|
889 return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
|
Chris@87
|
890
|
Chris@87
|
891
|
Chris@87
|
892 def triu_indices(n, k=0, m=None):
|
Chris@87
|
893 """
|
Chris@87
|
894 Return the indices for the upper-triangle of an (n, m) array.
|
Chris@87
|
895
|
Chris@87
|
896 Parameters
|
Chris@87
|
897 ----------
|
Chris@87
|
898 n : int
|
Chris@87
|
899 The size of the arrays for which the returned indices will
|
Chris@87
|
900 be valid.
|
Chris@87
|
901 k : int, optional
|
Chris@87
|
902 Diagonal offset (see `triu` for details).
|
Chris@87
|
903 m : int, optional
|
Chris@87
|
904 .. versionadded:: 1.9.0
|
Chris@87
|
905
|
Chris@87
|
906 The column dimension of the arrays for which the returned
|
Chris@87
|
907 arrays will be valid.
|
Chris@87
|
908 By default `m` is taken equal to `n`.
|
Chris@87
|
909
|
Chris@87
|
910
|
Chris@87
|
911 Returns
|
Chris@87
|
912 -------
|
Chris@87
|
913 inds : tuple, shape(2) of ndarrays, shape(`n`)
|
Chris@87
|
914 The indices for the triangle. The returned tuple contains two arrays,
|
Chris@87
|
915 each with the indices along one dimension of the array. Can be used
|
Chris@87
|
916 to slice a ndarray of shape(`n`, `n`).
|
Chris@87
|
917
|
Chris@87
|
918 See also
|
Chris@87
|
919 --------
|
Chris@87
|
920 tril_indices : similar function, for lower-triangular.
|
Chris@87
|
921 mask_indices : generic function accepting an arbitrary mask function.
|
Chris@87
|
922 triu, tril
|
Chris@87
|
923
|
Chris@87
|
924 Notes
|
Chris@87
|
925 -----
|
Chris@87
|
926 .. versionadded:: 1.4.0
|
Chris@87
|
927
|
Chris@87
|
928 Examples
|
Chris@87
|
929 --------
|
Chris@87
|
930 Compute two different sets of indices to access 4x4 arrays, one for the
|
Chris@87
|
931 upper triangular part starting at the main diagonal, and one starting two
|
Chris@87
|
932 diagonals further right:
|
Chris@87
|
933
|
Chris@87
|
934 >>> iu1 = np.triu_indices(4)
|
Chris@87
|
935 >>> iu2 = np.triu_indices(4, 2)
|
Chris@87
|
936
|
Chris@87
|
937 Here is how they can be used with a sample array:
|
Chris@87
|
938
|
Chris@87
|
939 >>> a = np.arange(16).reshape(4, 4)
|
Chris@87
|
940 >>> a
|
Chris@87
|
941 array([[ 0, 1, 2, 3],
|
Chris@87
|
942 [ 4, 5, 6, 7],
|
Chris@87
|
943 [ 8, 9, 10, 11],
|
Chris@87
|
944 [12, 13, 14, 15]])
|
Chris@87
|
945
|
Chris@87
|
946 Both for indexing:
|
Chris@87
|
947
|
Chris@87
|
948 >>> a[iu1]
|
Chris@87
|
949 array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
|
Chris@87
|
950
|
Chris@87
|
951 And for assigning values:
|
Chris@87
|
952
|
Chris@87
|
953 >>> a[iu1] = -1
|
Chris@87
|
954 >>> a
|
Chris@87
|
955 array([[-1, -1, -1, -1],
|
Chris@87
|
956 [ 4, -1, -1, -1],
|
Chris@87
|
957 [ 8, 9, -1, -1],
|
Chris@87
|
958 [12, 13, 14, -1]])
|
Chris@87
|
959
|
Chris@87
|
960 These cover only a small part of the whole array (two diagonals right
|
Chris@87
|
961 of the main one):
|
Chris@87
|
962
|
Chris@87
|
963 >>> a[iu2] = -10
|
Chris@87
|
964 >>> a
|
Chris@87
|
965 array([[ -1, -1, -10, -10],
|
Chris@87
|
966 [ 4, -1, -1, -10],
|
Chris@87
|
967 [ 8, 9, -1, -1],
|
Chris@87
|
968 [ 12, 13, 14, -1]])
|
Chris@87
|
969
|
Chris@87
|
970 """
|
Chris@87
|
971 return where(~tri(n, m, k=k-1, dtype=bool))
|
Chris@87
|
972
|
Chris@87
|
973
|
Chris@87
|
974 def triu_indices_from(arr, k=0):
|
Chris@87
|
975 """
|
Chris@87
|
976 Return the indices for the upper-triangle of arr.
|
Chris@87
|
977
|
Chris@87
|
978 See `triu_indices` for full details.
|
Chris@87
|
979
|
Chris@87
|
980 Parameters
|
Chris@87
|
981 ----------
|
Chris@87
|
982 arr : ndarray, shape(N, N)
|
Chris@87
|
983 The indices will be valid for square arrays.
|
Chris@87
|
984 k : int, optional
|
Chris@87
|
985 Diagonal offset (see `triu` for details).
|
Chris@87
|
986
|
Chris@87
|
987 Returns
|
Chris@87
|
988 -------
|
Chris@87
|
989 triu_indices_from : tuple, shape(2) of ndarray, shape(N)
|
Chris@87
|
990 Indices for the upper-triangle of `arr`.
|
Chris@87
|
991
|
Chris@87
|
992 See Also
|
Chris@87
|
993 --------
|
Chris@87
|
994 triu_indices, triu
|
Chris@87
|
995
|
Chris@87
|
996 Notes
|
Chris@87
|
997 -----
|
Chris@87
|
998 .. versionadded:: 1.4.0
|
Chris@87
|
999
|
Chris@87
|
1000 """
|
Chris@87
|
1001 if arr.ndim != 2:
|
Chris@87
|
1002 raise ValueError("input array must be 2-d")
|
Chris@87
|
1003 return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])
|