streamplot.py 23 KB

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