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