bokeh_util.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING, cast
  3. from contourpy import FillType, LineType
  4. from contourpy.array import offsets_from_codes
  5. from contourpy.convert import convert_lines
  6. from contourpy.dechunk import dechunk_lines
  7. if TYPE_CHECKING:
  8. from contourpy._contourpy import (
  9. CoordinateArray, FillReturn, LineReturn, LineReturn_ChunkCombinedNan,
  10. )
  11. def filled_to_bokeh(
  12. filled: FillReturn,
  13. fill_type: FillType,
  14. ) -> tuple[list[list[CoordinateArray]], list[list[CoordinateArray]]]:
  15. xs: list[list[CoordinateArray]] = []
  16. ys: list[list[CoordinateArray]] = []
  17. if fill_type in (FillType.OuterOffset, FillType.ChunkCombinedOffset,
  18. FillType.OuterCode, FillType.ChunkCombinedCode):
  19. have_codes = fill_type in (FillType.OuterCode, FillType.ChunkCombinedCode)
  20. for points, offsets in zip(*filled):
  21. if points is None:
  22. continue
  23. if have_codes:
  24. offsets = offsets_from_codes(offsets)
  25. xs.append([]) # New outer with zero or more holes.
  26. ys.append([])
  27. for i in range(len(offsets)-1):
  28. xys = points[offsets[i]:offsets[i+1]]
  29. xs[-1].append(xys[:, 0])
  30. ys[-1].append(xys[:, 1])
  31. elif fill_type in (FillType.ChunkCombinedCodeOffset, FillType.ChunkCombinedOffsetOffset):
  32. for points, codes_or_offsets, outer_offsets in zip(*filled):
  33. if points is None:
  34. continue
  35. for j in range(len(outer_offsets)-1):
  36. if fill_type == FillType.ChunkCombinedCodeOffset:
  37. codes = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]]
  38. offsets = offsets_from_codes(codes) + outer_offsets[j]
  39. else:
  40. offsets = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]+1]
  41. xs.append([]) # New outer with zero or more holes.
  42. ys.append([])
  43. for k in range(len(offsets)-1):
  44. xys = points[offsets[k]:offsets[k+1]]
  45. xs[-1].append(xys[:, 0])
  46. ys[-1].append(xys[:, 1])
  47. else:
  48. raise RuntimeError(f"Conversion of FillType {fill_type} to Bokeh is not implemented")
  49. return xs, ys
  50. def lines_to_bokeh(
  51. lines: LineReturn,
  52. line_type: LineType,
  53. ) -> tuple[CoordinateArray | None, CoordinateArray | None]:
  54. lines = convert_lines(lines, line_type, LineType.ChunkCombinedNan)
  55. lines = dechunk_lines(lines, LineType.ChunkCombinedNan)
  56. if TYPE_CHECKING:
  57. lines = cast(LineReturn_ChunkCombinedNan, lines)
  58. points = lines[0][0]
  59. if points is None:
  60. return None, None
  61. else:
  62. return points[:, 0], points[:, 1]