You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

670 lines
21 KiB

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