streamplot.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. """
  2. Streamline plotting for 2D vector fields.
  3. """
  4. import numpy as np
  5. import matplotlib
  6. import matplotlib.cbook as cbook
  7. import matplotlib.cm as cm
  8. import matplotlib.colors as mcolors
  9. import matplotlib.collections as mcollections
  10. import matplotlib.lines as mlines
  11. import matplotlib.patches as patches
  12. __all__ = ['streamplot']
  13. def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
  14. cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
  15. minlength=0.1, transform=None, zorder=None, start_points=None,
  16. maxlength=4.0, integration_direction='both'):
  17. """
  18. Draw streamlines of a vector flow.
  19. Parameters
  20. ----------
  21. x, y : 1D arrays
  22. An evenly spaced grid.
  23. u, v : 2D arrays
  24. *x* and *y*-velocities. The number of rows and columns must match
  25. the length of *y* and *x*, respectively.
  26. density : float or (float, float)
  27. Controls the closeness of streamlines. When ``density = 1``, the domain
  28. is divided into a 30x30 grid. *density* linearly scales this grid.
  29. Each cell in the grid can have, at most, one traversing streamline.
  30. For different densities in each direction, use a tuple
  31. (density_x, density_y).
  32. linewidth : float or 2D array
  33. The width of the stream lines. With a 2D array the line width can be
  34. varied across the grid. The array must have the same shape as *u*
  35. and *v*.
  36. color : color or 2D array
  37. The streamline color. If given an array, its values are converted to
  38. colors using *cmap* and *norm*. The array must have the same shape
  39. as *u* and *v*.
  40. cmap : `~matplotlib.colors.Colormap`
  41. Colormap used to plot streamlines and arrows. This is only used if
  42. *color* is an array.
  43. norm : `~matplotlib.colors.Normalize`
  44. Normalize object used to scale luminance data to 0, 1. If ``None``,
  45. stretch (min, max) to (0, 1). This is only used if *color* is an array.
  46. arrowsize : float
  47. Scaling factor for the arrow size.
  48. arrowstyle : str
  49. Arrow style specification.
  50. See `~matplotlib.patches.FancyArrowPatch`.
  51. minlength : float
  52. Minimum length of streamline in axes coordinates.
  53. start_points : Nx2 array
  54. Coordinates of starting points for the streamlines in data coordinates
  55. (the same coordinates as the *x* and *y* arrays).
  56. zorder : int
  57. The zorder of the stream lines and arrows.
  58. Artists with lower zorder values are drawn first.
  59. maxlength : float
  60. Maximum length of streamline in axes coordinates.
  61. integration_direction : {'forward', 'backward', 'both'}, default: 'both'
  62. Integrate the streamline in forward, backward or both directions.
  63. Returns
  64. -------
  65. StreamplotSet
  66. Container object with attributes
  67. - ``lines``: `.LineCollection` of streamlines
  68. - ``arrows``: `.PatchCollection` containing `.FancyArrowPatch`
  69. objects representing the arrows half-way along stream lines.
  70. This container will probably change in the future to allow changes
  71. to the colormap, alpha, etc. for both lines and arrows, but these
  72. changes should be backward compatible.
  73. """
  74. grid = Grid(x, y)
  75. mask = StreamMask(density)
  76. dmap = DomainMap(grid, mask)
  77. if zorder is None:
  78. zorder = mlines.Line2D.zorder
  79. # default to data coordinates
  80. if transform is None:
  81. transform = axes.transData
  82. if color is None:
  83. color = axes._get_lines.get_next_color()
  84. if linewidth is None:
  85. linewidth = matplotlib.rcParams['lines.linewidth']
  86. line_kw = {}
  87. arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
  88. cbook._check_in_list(['both', 'forward', 'backward'],
  89. integration_direction=integration_direction)
  90. if integration_direction == 'both':
  91. maxlength /= 2.
  92. use_multicolor_lines = isinstance(color, np.ndarray)
  93. if use_multicolor_lines:
  94. if color.shape != grid.shape:
  95. raise ValueError("If 'color' is given, it must match the shape of "
  96. "'Grid(x, y)'")
  97. line_colors = []
  98. color = np.ma.masked_invalid(color)
  99. else:
  100. line_kw['color'] = color
  101. arrow_kw['color'] = color
  102. if isinstance(linewidth, np.ndarray):
  103. if linewidth.shape != grid.shape:
  104. raise ValueError("If 'linewidth' is given, it must match the "
  105. "shape of 'Grid(x, y)'")
  106. line_kw['linewidth'] = []
  107. else:
  108. line_kw['linewidth'] = linewidth
  109. arrow_kw['linewidth'] = linewidth
  110. line_kw['zorder'] = zorder
  111. arrow_kw['zorder'] = zorder
  112. # Sanity checks.
  113. if u.shape != grid.shape or v.shape != grid.shape:
  114. raise ValueError("'u' and 'v' must match the shape of 'Grid(x, y)'")
  115. u = np.ma.masked_invalid(u)
  116. v = np.ma.masked_invalid(v)
  117. integrate = get_integrator(u, v, dmap, minlength, maxlength,
  118. integration_direction)
  119. trajectories = []
  120. if start_points is None:
  121. for xm, ym in _gen_starting_points(mask.shape):
  122. if mask[ym, xm] == 0:
  123. xg, yg = dmap.mask2grid(xm, ym)
  124. t = integrate(xg, yg)
  125. if t is not None:
  126. trajectories.append(t)
  127. else:
  128. sp2 = np.asanyarray(start_points, dtype=float).copy()
  129. # Check if start_points are outside the data boundaries
  130. for xs, ys in sp2:
  131. if not (grid.x_origin <= xs <= grid.x_origin + grid.width and
  132. grid.y_origin <= ys <= grid.y_origin + grid.height):
  133. raise ValueError("Starting point ({}, {}) outside of data "
  134. "boundaries".format(xs, ys))
  135. # Convert start_points from data to array coords
  136. # Shift the seed points from the bottom left of the data so that
  137. # data2grid works properly.
  138. sp2[:, 0] -= grid.x_origin
  139. sp2[:, 1] -= grid.y_origin
  140. for xs, ys in sp2:
  141. xg, yg = dmap.data2grid(xs, ys)
  142. t = integrate(xg, yg)
  143. if t is not None:
  144. trajectories.append(t)
  145. if use_multicolor_lines:
  146. if norm is None:
  147. norm = mcolors.Normalize(color.min(), color.max())
  148. if cmap is None:
  149. cmap = cm.get_cmap(matplotlib.rcParams['image.cmap'])
  150. else:
  151. cmap = cm.get_cmap(cmap)
  152. streamlines = []
  153. arrows = []
  154. for t in trajectories:
  155. tgx = np.array(t[0])
  156. tgy = np.array(t[1])
  157. # Rescale from grid-coordinates to data-coordinates.
  158. tx, ty = dmap.grid2data(*np.array(t))
  159. tx += grid.x_origin
  160. ty += grid.y_origin
  161. points = np.transpose([tx, ty]).reshape(-1, 1, 2)
  162. streamlines.extend(np.hstack([points[:-1], points[1:]]))
  163. # Add arrows half way along each trajectory.
  164. s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
  165. n = np.searchsorted(s, s[-1] / 2.)
  166. arrow_tail = (tx[n], ty[n])
  167. arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
  168. if isinstance(linewidth, np.ndarray):
  169. line_widths = interpgrid(linewidth, tgx, tgy)[:-1]
  170. line_kw['linewidth'].extend(line_widths)
  171. arrow_kw['linewidth'] = line_widths[n]
  172. if use_multicolor_lines:
  173. color_values = interpgrid(color, tgx, tgy)[:-1]
  174. line_colors.append(color_values)
  175. arrow_kw['color'] = cmap(norm(color_values[n]))
  176. p = patches.FancyArrowPatch(
  177. arrow_tail, arrow_head, transform=transform, **arrow_kw)
  178. axes.add_patch(p)
  179. arrows.append(p)
  180. lc = mcollections.LineCollection(
  181. streamlines, transform=transform, **line_kw)
  182. lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width]
  183. lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height]
  184. if use_multicolor_lines:
  185. lc.set_array(np.ma.hstack(line_colors))
  186. lc.set_cmap(cmap)
  187. lc.set_norm(norm)
  188. axes.add_collection(lc)
  189. axes.autoscale_view()
  190. ac = matplotlib.collections.PatchCollection(arrows)
  191. stream_container = StreamplotSet(lc, ac)
  192. return stream_container
  193. class StreamplotSet:
  194. def __init__(self, lines, arrows, **kwargs):
  195. if kwargs:
  196. cbook.warn_deprecated(
  197. "3.3",
  198. message="Passing arbitrary keyword arguments to StreamplotSet "
  199. "is deprecated since %(since) and will become an "
  200. "error %(removal)s.")
  201. self.lines = lines
  202. self.arrows = arrows
  203. # Coordinate definitions
  204. # ========================
  205. class DomainMap:
  206. """
  207. Map representing different coordinate systems.
  208. Coordinate definitions:
  209. * axes-coordinates goes from 0 to 1 in the domain.
  210. * data-coordinates are specified by the input x-y coordinates.
  211. * grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
  212. where N and M match the shape of the input data.
  213. * mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
  214. where N and M are user-specified to control the density of streamlines.
  215. This class also has methods for adding trajectories to the StreamMask.
  216. Before adding a trajectory, run `start_trajectory` to keep track of regions
  217. crossed by a given trajectory. Later, if you decide the trajectory is bad
  218. (e.g., if the trajectory is very short) just call `undo_trajectory`.
  219. """
  220. def __init__(self, grid, mask):
  221. self.grid = grid
  222. self.mask = mask
  223. # Constants for conversion between grid- and mask-coordinates
  224. self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1)
  225. self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1)
  226. self.x_mask2grid = 1. / self.x_grid2mask
  227. self.y_mask2grid = 1. / self.y_grid2mask
  228. self.x_data2grid = 1. / grid.dx
  229. self.y_data2grid = 1. / grid.dy
  230. def grid2mask(self, xi, yi):
  231. """Return nearest space in mask-coords from given grid-coords."""
  232. return (int(xi * self.x_grid2mask + 0.5),
  233. int(yi * self.y_grid2mask + 0.5))
  234. def mask2grid(self, xm, ym):
  235. return xm * self.x_mask2grid, ym * self.y_mask2grid
  236. def data2grid(self, xd, yd):
  237. return xd * self.x_data2grid, yd * self.y_data2grid
  238. def grid2data(self, xg, yg):
  239. return xg / self.x_data2grid, yg / self.y_data2grid
  240. def start_trajectory(self, xg, yg):
  241. xm, ym = self.grid2mask(xg, yg)
  242. self.mask._start_trajectory(xm, ym)
  243. def reset_start_point(self, xg, yg):
  244. xm, ym = self.grid2mask(xg, yg)
  245. self.mask._current_xy = (xm, ym)
  246. def update_trajectory(self, xg, yg):
  247. if not self.grid.within_grid(xg, yg):
  248. raise InvalidIndexError
  249. xm, ym = self.grid2mask(xg, yg)
  250. self.mask._update_trajectory(xm, ym)
  251. def undo_trajectory(self):
  252. self.mask._undo_trajectory()
  253. class Grid:
  254. """Grid of data."""
  255. def __init__(self, x, y):
  256. if x.ndim == 1:
  257. pass
  258. elif x.ndim == 2:
  259. x_row = x[0, :]
  260. if not np.allclose(x_row, x):
  261. raise ValueError("The rows of 'x' must be equal")
  262. x = x_row
  263. else:
  264. raise ValueError("'x' can have at maximum 2 dimensions")
  265. if y.ndim == 1:
  266. pass
  267. elif y.ndim == 2:
  268. y_col = y[:, 0]
  269. if not np.allclose(y_col, y.T):
  270. raise ValueError("The columns of 'y' must be equal")
  271. y = y_col
  272. else:
  273. raise ValueError("'y' can have at maximum 2 dimensions")
  274. self.nx = len(x)
  275. self.ny = len(y)
  276. self.dx = x[1] - x[0]
  277. self.dy = y[1] - y[0]
  278. self.x_origin = x[0]
  279. self.y_origin = y[0]
  280. self.width = x[-1] - x[0]
  281. self.height = y[-1] - y[0]
  282. if not np.allclose(np.diff(x), self.width / (self.nx - 1)):
  283. raise ValueError("'x' values must be equally spaced")
  284. if not np.allclose(np.diff(y), self.height / (self.ny - 1)):
  285. raise ValueError("'y' values must be equally spaced")
  286. @property
  287. def shape(self):
  288. return self.ny, self.nx
  289. def within_grid(self, xi, yi):
  290. """Return True if point is a valid index of grid."""
  291. # Note that xi/yi can be floats; so, for example, we can't simply check
  292. # `xi < self.nx` since *xi* can be `self.nx - 1 < xi < self.nx`
  293. return 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1
  294. class StreamMask:
  295. """
  296. Mask to keep track of discrete regions crossed by streamlines.
  297. The resolution of this grid determines the approximate spacing between
  298. trajectories. Streamlines are only allowed to pass through zeroed cells:
  299. When a streamline enters a cell, that cell is set to 1, and no new
  300. streamlines are allowed to enter.
  301. """
  302. def __init__(self, density):
  303. try:
  304. self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
  305. except ValueError as err:
  306. raise ValueError("'density' must be a scalar or be of length "
  307. "2") from err
  308. if self.nx < 0 or self.ny < 0:
  309. raise ValueError("'density' must be positive")
  310. self._mask = np.zeros((self.ny, self.nx))
  311. self.shape = self._mask.shape
  312. self._current_xy = None
  313. def __getitem__(self, args):
  314. return self._mask[args]
  315. def _start_trajectory(self, xm, ym):
  316. """Start recording streamline trajectory"""
  317. self._traj = []
  318. self._update_trajectory(xm, ym)
  319. def _undo_trajectory(self):
  320. """Remove current trajectory from mask"""
  321. for t in self._traj:
  322. self._mask[t] = 0
  323. def _update_trajectory(self, xm, ym):
  324. """
  325. Update current trajectory position in mask.
  326. If the new position has already been filled, raise `InvalidIndexError`.
  327. """
  328. if self._current_xy != (xm, ym):
  329. if self[ym, xm] == 0:
  330. self._traj.append((ym, xm))
  331. self._mask[ym, xm] = 1
  332. self._current_xy = (xm, ym)
  333. else:
  334. raise InvalidIndexError
  335. class InvalidIndexError(Exception):
  336. pass
  337. class TerminateTrajectory(Exception):
  338. pass
  339. # Integrator definitions
  340. # =======================
  341. def get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
  342. # rescale velocity onto grid-coordinates for integrations.
  343. u, v = dmap.data2grid(u, v)
  344. # speed (path length) will be in axes-coordinates
  345. u_ax = u / (dmap.grid.nx - 1)
  346. v_ax = v / (dmap.grid.ny - 1)
  347. speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
  348. def forward_time(xi, yi):
  349. if not dmap.grid.within_grid(xi, yi):
  350. raise OutOfBounds
  351. ds_dt = interpgrid(speed, xi, yi)
  352. if ds_dt == 0:
  353. raise TerminateTrajectory()
  354. dt_ds = 1. / ds_dt
  355. ui = interpgrid(u, xi, yi)
  356. vi = interpgrid(v, xi, yi)
  357. return ui * dt_ds, vi * dt_ds
  358. def backward_time(xi, yi):
  359. dxi, dyi = forward_time(xi, yi)
  360. return -dxi, -dyi
  361. def integrate(x0, y0):
  362. """
  363. Return x, y grid-coordinates of trajectory based on starting point.
  364. Integrate both forward and backward in time from starting point in
  365. grid coordinates.
  366. Integration is terminated when a trajectory reaches a domain boundary
  367. or when it crosses into an already occupied cell in the StreamMask. The
  368. resulting trajectory is None if it is shorter than `minlength`.
  369. """
  370. stotal, x_traj, y_traj = 0., [], []
  371. try:
  372. dmap.start_trajectory(x0, y0)
  373. except InvalidIndexError:
  374. return None
  375. if integration_direction in ['both', 'backward']:
  376. s, xt, yt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength)
  377. stotal += s
  378. x_traj += xt[::-1]
  379. y_traj += yt[::-1]
  380. if integration_direction in ['both', 'forward']:
  381. dmap.reset_start_point(x0, y0)
  382. s, xt, yt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength)
  383. if len(x_traj) > 0:
  384. xt = xt[1:]
  385. yt = yt[1:]
  386. stotal += s
  387. x_traj += xt
  388. y_traj += yt
  389. if stotal > minlength:
  390. return x_traj, y_traj
  391. else: # reject short trajectories
  392. dmap.undo_trajectory()
  393. return None
  394. return integrate
  395. class OutOfBounds(IndexError):
  396. pass
  397. def _integrate_rk12(x0, y0, dmap, f, maxlength):
  398. """
  399. 2nd-order Runge-Kutta algorithm with adaptive step size.
  400. This method is also referred to as the improved Euler's method, or Heun's
  401. method. This method is favored over higher-order methods because:
  402. 1. To get decent looking trajectories and to sample every mask cell
  403. on the trajectory we need a small timestep, so a lower order
  404. solver doesn't hurt us unless the data is *very* high resolution.
  405. In fact, for cases where the user inputs
  406. data smaller or of similar grid size to the mask grid, the higher
  407. order corrections are negligible because of the very fast linear
  408. interpolation used in `interpgrid`.
  409. 2. For high resolution input data (i.e. beyond the mask
  410. resolution), we must reduce the timestep. Therefore, an adaptive
  411. timestep is more suited to the problem as this would be very hard
  412. to judge automatically otherwise.
  413. This integrator is about 1.5 - 2x as fast as both the RK4 and RK45
  414. solvers in most setups on my machine. I would recommend removing the
  415. other two to keep things simple.
  416. """
  417. # This error is below that needed to match the RK4 integrator. It
  418. # is set for visual reasons -- too low and corners start
  419. # appearing ugly and jagged. Can be tuned.
  420. maxerror = 0.003
  421. # This limit is important (for all integrators) to avoid the
  422. # trajectory skipping some mask cells. We could relax this
  423. # condition if we use the code which is commented out below to
  424. # increment the location gradually. However, due to the efficient
  425. # nature of the interpolation, this doesn't boost speed by much
  426. # for quite a bit of complexity.
  427. maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
  428. ds = maxds
  429. stotal = 0
  430. xi = x0
  431. yi = y0
  432. xf_traj = []
  433. yf_traj = []
  434. while True:
  435. try:
  436. if dmap.grid.within_grid(xi, yi):
  437. xf_traj.append(xi)
  438. yf_traj.append(yi)
  439. else:
  440. raise OutOfBounds
  441. # Compute the two intermediate gradients.
  442. # f should raise OutOfBounds if the locations given are
  443. # outside the grid.
  444. k1x, k1y = f(xi, yi)
  445. k2x, k2y = f(xi + ds * k1x, yi + ds * k1y)
  446. except OutOfBounds:
  447. # Out of the domain during this step.
  448. # Take an Euler step to the boundary to improve neatness
  449. # unless the trajectory is currently empty.
  450. if xf_traj:
  451. ds, xf_traj, yf_traj = _euler_step(xf_traj, yf_traj,
  452. dmap, f)
  453. stotal += ds
  454. break
  455. except TerminateTrajectory:
  456. break
  457. dx1 = ds * k1x
  458. dy1 = ds * k1y
  459. dx2 = ds * 0.5 * (k1x + k2x)
  460. dy2 = ds * 0.5 * (k1y + k2y)
  461. nx, ny = dmap.grid.shape
  462. # Error is normalized to the axes coordinates
  463. error = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1))
  464. # Only save step if within error tolerance
  465. if error < maxerror:
  466. xi += dx2
  467. yi += dy2
  468. try:
  469. dmap.update_trajectory(xi, yi)
  470. except InvalidIndexError:
  471. break
  472. if stotal + ds > maxlength:
  473. break
  474. stotal += ds
  475. # recalculate stepsize based on step error
  476. if error == 0:
  477. ds = maxds
  478. else:
  479. ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
  480. return stotal, xf_traj, yf_traj
  481. def _euler_step(xf_traj, yf_traj, dmap, f):
  482. """Simple Euler integration step that extends streamline to boundary."""
  483. ny, nx = dmap.grid.shape
  484. xi = xf_traj[-1]
  485. yi = yf_traj[-1]
  486. cx, cy = f(xi, yi)
  487. if cx == 0:
  488. dsx = np.inf
  489. elif cx < 0:
  490. dsx = xi / -cx
  491. else:
  492. dsx = (nx - 1 - xi) / cx
  493. if cy == 0:
  494. dsy = np.inf
  495. elif cy < 0:
  496. dsy = yi / -cy
  497. else:
  498. dsy = (ny - 1 - yi) / cy
  499. ds = min(dsx, dsy)
  500. xf_traj.append(xi + cx * ds)
  501. yf_traj.append(yi + cy * ds)
  502. return ds, xf_traj, yf_traj
  503. # Utility functions
  504. # ========================
  505. def interpgrid(a, xi, yi):
  506. """Fast 2D, linear interpolation on an integer grid"""
  507. Ny, Nx = np.shape(a)
  508. if isinstance(xi, np.ndarray):
  509. x = xi.astype(int)
  510. y = yi.astype(int)
  511. # Check that xn, yn don't exceed max index
  512. xn = np.clip(x + 1, 0, Nx - 1)
  513. yn = np.clip(y + 1, 0, Ny - 1)
  514. else:
  515. x = int(xi)
  516. y = int(yi)
  517. # conditional is faster than clipping for integers
  518. if x == (Nx - 1):
  519. xn = x
  520. else:
  521. xn = x + 1
  522. if y == (Ny - 1):
  523. yn = y
  524. else:
  525. yn = y + 1
  526. a00 = a[y, x]
  527. a01 = a[y, xn]
  528. a10 = a[yn, x]
  529. a11 = a[yn, xn]
  530. xt = xi - x
  531. yt = yi - y
  532. a0 = a00 * (1 - xt) + a01 * xt
  533. a1 = a10 * (1 - xt) + a11 * xt
  534. ai = a0 * (1 - yt) + a1 * yt
  535. if not isinstance(xi, np.ndarray):
  536. if np.ma.is_masked(ai):
  537. raise TerminateTrajectory
  538. return ai
  539. def _gen_starting_points(shape):
  540. """
  541. Yield starting points for streamlines.
  542. Trying points on the boundary first gives higher quality streamlines.
  543. This algorithm starts with a point on the mask corner and spirals inward.
  544. This algorithm is inefficient, but fast compared to rest of streamplot.
  545. """
  546. ny, nx = shape
  547. xfirst = 0
  548. yfirst = 1
  549. xlast = nx - 1
  550. ylast = ny - 1
  551. x, y = 0, 0
  552. direction = 'right'
  553. for i in range(nx * ny):
  554. yield x, y
  555. if direction == 'right':
  556. x += 1
  557. if x >= xlast:
  558. xlast -= 1
  559. direction = 'up'
  560. elif direction == 'up':
  561. y += 1
  562. if y >= ylast:
  563. ylast -= 1
  564. direction = 'left'
  565. elif direction == 'left':
  566. x -= 1
  567. if x <= xfirst:
  568. xfirst += 1
  569. direction = 'down'
  570. elif direction == 'down':
  571. y -= 1
  572. if y <= yfirst:
  573. yfirst += 1
  574. direction = 'right'