streamplot.py 22 KB

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