ZTWHHH commited on
Commit
229cc51
·
verified ·
1 Parent(s): 32c773a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. vllm/lib/python3.10/site-packages/charset_normalizer-3.4.0.dist-info/LICENSE +21 -0
  3. vllm/lib/python3.10/site-packages/contourpy/__init__.py +285 -0
  4. vllm/lib/python3.10/site-packages/contourpy/__pycache__/__init__.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/contourpy/__pycache__/_version.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/contourpy/__pycache__/array.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/contourpy/__pycache__/chunk.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/contourpy/__pycache__/convert.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/contourpy/__pycache__/dechunk.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/contourpy/__pycache__/enum_util.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/contourpy/__pycache__/typecheck.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/contourpy/__pycache__/types.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so +3 -0
  14. vllm/lib/python3.10/site-packages/contourpy/_contourpy.pyi +199 -0
  15. vllm/lib/python3.10/site-packages/contourpy/_version.py +1 -0
  16. vllm/lib/python3.10/site-packages/contourpy/array.py +261 -0
  17. vllm/lib/python3.10/site-packages/contourpy/chunk.py +95 -0
  18. vllm/lib/python3.10/site-packages/contourpy/convert.py +621 -0
  19. vllm/lib/python3.10/site-packages/contourpy/dechunk.py +207 -0
  20. vllm/lib/python3.10/site-packages/contourpy/enum_util.py +57 -0
  21. vllm/lib/python3.10/site-packages/contourpy/py.typed +0 -0
  22. vllm/lib/python3.10/site-packages/contourpy/typecheck.py +203 -0
  23. vllm/lib/python3.10/site-packages/contourpy/types.py +13 -0
  24. vllm/lib/python3.10/site-packages/contourpy/util/__init__.py +5 -0
  25. vllm/lib/python3.10/site-packages/contourpy/util/__pycache__/__init__.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/contourpy/util/__pycache__/mpl_util.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/contourpy/util/_build_config.py +60 -0
  28. vllm/lib/python3.10/site-packages/contourpy/util/bokeh_renderer.py +336 -0
  29. vllm/lib/python3.10/site-packages/contourpy/util/bokeh_util.py +74 -0
  30. vllm/lib/python3.10/site-packages/contourpy/util/data.py +78 -0
  31. vllm/lib/python3.10/site-packages/contourpy/util/mpl_renderer.py +535 -0
  32. vllm/lib/python3.10/site-packages/contourpy/util/mpl_util.py +77 -0
  33. vllm/lib/python3.10/site-packages/contourpy/util/renderer.py +166 -0
  34. vllm/lib/python3.10/site-packages/freetype/__init__.py +2413 -0
  35. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__init__.py +12 -0
  36. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__pycache__/__init__.cpython-310.pyc +0 -0
  37. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__pycache__/hook-freetype.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/hook-freetype.py +4 -0
  39. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__init__.py +0 -0
  40. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/conftest.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/test_freetype.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/conftest.py +1 -0
  44. vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/test_freetype.py +30 -0
  45. vllm/lib/python3.10/site-packages/freetype/ft_enums/__init__.py +126 -0
  46. vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_color_root_transform.py +6 -0
  47. vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_encodings.py +108 -0
  48. vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_face_flags.py +132 -0
  49. vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_fstypes.py +64 -0
  50. vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_glyph_formats.py +63 -0
.gitattributes CHANGED
@@ -1955,3 +1955,5 @@ videollama2/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_e
1955
  llava_next/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-c128ec02.so filter=lfs diff=lfs merge=lfs -text
1956
  parrot/lib/python3.10/site-packages/scipy/special/_specfun.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1957
  videollama2/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
1955
  llava_next/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-c128ec02.so filter=lfs diff=lfs merge=lfs -text
1956
  parrot/lib/python3.10/site-packages/scipy/special/_specfun.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1957
  videollama2/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1958
+ vllm/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1959
+ vllm/lib/python3.10/site-packages/freetype/libfreetype.so filter=lfs diff=lfs merge=lfs -text
vllm/lib/python3.10/site-packages/charset_normalizer-3.4.0.dist-info/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2019 TAHRI Ahmed R.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
vllm/lib/python3.10/site-packages/contourpy/__init__.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+
7
+ from contourpy._contourpy import (
8
+ ContourGenerator,
9
+ FillType,
10
+ LineType,
11
+ Mpl2005ContourGenerator,
12
+ Mpl2014ContourGenerator,
13
+ SerialContourGenerator,
14
+ ThreadedContourGenerator,
15
+ ZInterp,
16
+ max_threads,
17
+ )
18
+ from contourpy._version import __version__
19
+ from contourpy.chunk import calc_chunk_sizes
20
+ from contourpy.convert import (
21
+ convert_filled,
22
+ convert_lines,
23
+ convert_multi_filled,
24
+ convert_multi_lines,
25
+ )
26
+ from contourpy.dechunk import (
27
+ dechunk_filled,
28
+ dechunk_lines,
29
+ dechunk_multi_filled,
30
+ dechunk_multi_lines,
31
+ )
32
+ from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp
33
+
34
+ if TYPE_CHECKING:
35
+ from typing import Any
36
+
37
+ from numpy.typing import ArrayLike
38
+
39
+ from ._contourpy import CoordinateArray, MaskArray
40
+
41
+ __all__ = [
42
+ "__version__",
43
+ "contour_generator",
44
+ "convert_filled",
45
+ "convert_lines",
46
+ "convert_multi_filled",
47
+ "convert_multi_lines",
48
+ "dechunk_filled",
49
+ "dechunk_lines",
50
+ "dechunk_multi_filled",
51
+ "dechunk_multi_lines",
52
+ "max_threads",
53
+ "FillType",
54
+ "LineType",
55
+ "ContourGenerator",
56
+ "Mpl2005ContourGenerator",
57
+ "Mpl2014ContourGenerator",
58
+ "SerialContourGenerator",
59
+ "ThreadedContourGenerator",
60
+ "ZInterp",
61
+ ]
62
+
63
+
64
+ # Simple mapping of algorithm name to class name.
65
+ _class_lookup: dict[str, type[ContourGenerator]] = {
66
+ "mpl2005": Mpl2005ContourGenerator,
67
+ "mpl2014": Mpl2014ContourGenerator,
68
+ "serial": SerialContourGenerator,
69
+ "threaded": ThreadedContourGenerator,
70
+ }
71
+
72
+
73
+ def _remove_z_mask(
74
+ z: ArrayLike | np.ma.MaskedArray[Any, Any] | None,
75
+ ) -> tuple[CoordinateArray, MaskArray | None]:
76
+ # Preserve mask if present.
77
+ z_array = np.ma.asarray(z, dtype=np.float64) # type: ignore[no-untyped-call]
78
+ z_masked = np.ma.masked_invalid(z_array, copy=False) # type: ignore[no-untyped-call]
79
+
80
+ if np.ma.is_masked(z_masked): # type: ignore[no-untyped-call]
81
+ mask = np.ma.getmask(z_masked) # type: ignore[no-untyped-call]
82
+ else:
83
+ mask = None
84
+
85
+ return np.ma.getdata(z_masked), mask # type: ignore[no-untyped-call]
86
+
87
+
88
+ def contour_generator(
89
+ x: ArrayLike | None = None,
90
+ y: ArrayLike | None = None,
91
+ z: ArrayLike | np.ma.MaskedArray[Any, Any] | None = None,
92
+ *,
93
+ name: str = "serial",
94
+ corner_mask: bool | None = None,
95
+ line_type: LineType | str | None = None,
96
+ fill_type: FillType | str | None = None,
97
+ chunk_size: int | tuple[int, int] | None = None,
98
+ chunk_count: int | tuple[int, int] | None = None,
99
+ total_chunk_count: int | None = None,
100
+ quad_as_tri: bool = False,
101
+ z_interp: ZInterp | str | None = ZInterp.Linear,
102
+ thread_count: int = 0,
103
+ ) -> ContourGenerator:
104
+ """Create and return a :class:`~.ContourGenerator` object.
105
+
106
+ The class and properties of the returned :class:`~.ContourGenerator` are determined by the
107
+ function arguments, with sensible defaults.
108
+
109
+ Args:
110
+ x (array-like of shape (ny, nx) or (nx,), optional): The x-coordinates of the ``z`` values.
111
+ May be 2D with the same shape as ``z.shape``, or 1D with length ``nx = z.shape[1]``.
112
+ If not specified are assumed to be ``np.arange(nx)``. Must be ordered monotonically.
113
+ y (array-like of shape (ny, nx) or (ny,), optional): The y-coordinates of the ``z`` values.
114
+ May be 2D with the same shape as ``z.shape``, or 1D with length ``ny = z.shape[0]``.
115
+ If not specified are assumed to be ``np.arange(ny)``. Must be ordered monotonically.
116
+ z (array-like of shape (ny, nx), may be a masked array): The 2D gridded values to calculate
117
+ the contours of. May be a masked array, and any invalid values (``np.inf`` or
118
+ ``np.nan``) will also be masked out.
119
+ name (str): Algorithm name, one of ``"serial"``, ``"threaded"``, ``"mpl2005"`` or
120
+ ``"mpl2014"``, default ``"serial"``.
121
+ corner_mask (bool, optional): Enable/disable corner masking, which only has an effect if
122
+ ``z`` is a masked array. If ``False``, any quad touching a masked point is masked out.
123
+ If ``True``, only the triangular corners of quads nearest these points are always masked
124
+ out, other triangular corners comprising three unmasked points are contoured as usual.
125
+ If not specified, uses the default provided by the algorithm ``name``.
126
+ line_type (LineType or str, optional): The format of contour line data returned from calls
127
+ to :meth:`~.ContourGenerator.lines`, specified either as a :class:`~.LineType` or its
128
+ string equivalent such as ``"SeparateCode"``.
129
+ If not specified, uses the default provided by the algorithm ``name``.
130
+ The relationship between the :class:`~.LineType` enum and the data format returned from
131
+ :meth:`~.ContourGenerator.lines` is explained at :ref:`line_type`.
132
+ fill_type (FillType or str, optional): The format of filled contour data returned from calls
133
+ to :meth:`~.ContourGenerator.filled`, specified either as a :class:`~.FillType` or its
134
+ string equivalent such as ``"OuterOffset"``.
135
+ If not specified, uses the default provided by the algorithm ``name``.
136
+ The relationship between the :class:`~.FillType` enum and the data format returned from
137
+ :meth:`~.ContourGenerator.filled` is explained at :ref:`fill_type`.
138
+ chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same
139
+ size in both directions if only one value is specified.
140
+ chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the
141
+ same count in both directions if only one value is specified.
142
+ total_chunk_count (int, optional): Total number of chunks.
143
+ quad_as_tri (bool): Enable/disable treating quads as 4 triangles, default ``False``.
144
+ If ``False``, a contour line within a quad is a straight line between points on two of
145
+ its edges. If ``True``, each full quad is divided into 4 triangles using a virtual point
146
+ at the centre (mean x, y of the corner points) and a contour line is piecewise linear
147
+ within those triangles. Corner-masked triangles are not affected by this setting, only
148
+ full unmasked quads.
149
+ z_interp (ZInterp or str, optional): How to interpolate ``z`` values when determining where
150
+ contour lines intersect the edges of quads and the ``z`` values of the central points of
151
+ quads, specified either as a :class:`~contourpy.ZInterp` or its string equivalent such
152
+ as ``"Log"``. Default is ``ZInterp.Linear``.
153
+ thread_count (int): Number of threads to use for contour calculation, default 0. Threads can
154
+ only be used with an algorithm ``name`` that supports threads (currently only
155
+ ``name="threaded"``) and there must be at least the same number of chunks as threads.
156
+ If ``thread_count=0`` and ``name="threaded"`` then it uses the maximum number of threads
157
+ as determined by the C++11 call ``std::thread::hardware_concurrency()``. If ``name`` is
158
+ something other than ``"threaded"`` then the ``thread_count`` will be set to ``1``.
159
+
160
+ Return:
161
+ :class:`~.ContourGenerator`.
162
+
163
+ Note:
164
+ A maximum of one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` may be
165
+ specified.
166
+
167
+ Warning:
168
+ The ``name="mpl2005"`` algorithm does not implement chunking for contour lines.
169
+ """
170
+ x = np.asarray(x, dtype=np.float64)
171
+ y = np.asarray(y, dtype=np.float64)
172
+ z, mask = _remove_z_mask(z)
173
+
174
+ # Check arguments: z.
175
+ if z.ndim != 2:
176
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
177
+
178
+ if z.shape[0] < 2 or z.shape[1] < 2:
179
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, but has shape {z.shape}")
180
+
181
+ ny, nx = z.shape
182
+
183
+ # Check arguments: x and y.
184
+ if x.ndim != y.ndim:
185
+ raise TypeError(f"Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match")
186
+
187
+ if x.ndim == 0:
188
+ x = np.arange(nx, dtype=np.float64)
189
+ y = np.arange(ny, dtype=np.float64)
190
+ x, y = np.meshgrid(x, y)
191
+ elif x.ndim == 1:
192
+ if len(x) != nx:
193
+ raise TypeError(f"Length of x ({len(x)}) must match number of columns in z ({nx})")
194
+ if len(y) != ny:
195
+ raise TypeError(f"Length of y ({len(y)}) must match number of rows in z ({ny})")
196
+ x, y = np.meshgrid(x, y)
197
+ elif x.ndim == 2:
198
+ if x.shape != z.shape:
199
+ raise TypeError(f"Shapes of x {x.shape} and z {z.shape} do not match")
200
+ if y.shape != z.shape:
201
+ raise TypeError(f"Shapes of y {y.shape} and z {z.shape} do not match")
202
+ else:
203
+ raise TypeError(f"Inputs x and y must be None, 1D or 2D, not {x.ndim}D")
204
+
205
+ # Check mask shape just in case.
206
+ if mask is not None and mask.shape != z.shape:
207
+ raise ValueError("If mask is set it must be a 2D array with the same shape as z")
208
+
209
+ # Check arguments: name.
210
+ if name not in _class_lookup:
211
+ raise ValueError(f"Unrecognised contour generator name: {name}")
212
+
213
+ # Check arguments: chunk_size, chunk_count and total_chunk_count.
214
+ y_chunk_size, x_chunk_size = calc_chunk_sizes(
215
+ chunk_size, chunk_count, total_chunk_count, ny, nx)
216
+
217
+ cls = _class_lookup[name]
218
+
219
+ # Check arguments: corner_mask.
220
+ if corner_mask is None:
221
+ # Set it to default, which is True if the algorithm supports it.
222
+ corner_mask = cls.supports_corner_mask()
223
+ elif corner_mask and not cls.supports_corner_mask():
224
+ raise ValueError(f"{name} contour generator does not support corner_mask=True")
225
+
226
+ # Check arguments: line_type.
227
+ if line_type is None:
228
+ line_type = cls.default_line_type
229
+ else:
230
+ line_type = as_line_type(line_type)
231
+
232
+ if not cls.supports_line_type(line_type):
233
+ raise ValueError(f"{name} contour generator does not support line_type {line_type}")
234
+
235
+ # Check arguments: fill_type.
236
+ if fill_type is None:
237
+ fill_type = cls.default_fill_type
238
+ else:
239
+ fill_type = as_fill_type(fill_type)
240
+
241
+ if not cls.supports_fill_type(fill_type):
242
+ raise ValueError(f"{name} contour generator does not support fill_type {fill_type}")
243
+
244
+ # Check arguments: quad_as_tri.
245
+ if quad_as_tri and not cls.supports_quad_as_tri():
246
+ raise ValueError(f"{name} contour generator does not support quad_as_tri=True")
247
+
248
+ # Check arguments: z_interp.
249
+ if z_interp is None:
250
+ z_interp = ZInterp.Linear
251
+ else:
252
+ z_interp = as_z_interp(z_interp)
253
+
254
+ if z_interp != ZInterp.Linear and not cls.supports_z_interp():
255
+ raise ValueError(f"{name} contour generator does not support z_interp {z_interp}")
256
+
257
+ # Check arguments: thread_count.
258
+ if thread_count not in (0, 1) and not cls.supports_threads():
259
+ raise ValueError(f"{name} contour generator does not support thread_count {thread_count}")
260
+
261
+ # Prepare args and kwargs for contour generator constructor.
262
+ args = [x, y, z, mask]
263
+ kwargs: dict[str, int | bool | LineType | FillType | ZInterp] = {
264
+ "x_chunk_size": x_chunk_size,
265
+ "y_chunk_size": y_chunk_size,
266
+ }
267
+
268
+ if name not in ("mpl2005", "mpl2014"):
269
+ kwargs["line_type"] = line_type
270
+ kwargs["fill_type"] = fill_type
271
+
272
+ if cls.supports_corner_mask():
273
+ kwargs["corner_mask"] = corner_mask
274
+
275
+ if cls.supports_quad_as_tri():
276
+ kwargs["quad_as_tri"] = quad_as_tri
277
+
278
+ if cls.supports_z_interp():
279
+ kwargs["z_interp"] = z_interp
280
+
281
+ if cls.supports_threads():
282
+ kwargs["thread_count"] = thread_count
283
+
284
+ # Create contour generator.
285
+ return cls(*args, **kwargs)
vllm/lib/python3.10/site-packages/contourpy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (9.73 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/_version.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/array.cpython-310.pyc ADDED
Binary file (9.56 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/chunk.cpython-310.pyc ADDED
Binary file (2.78 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/convert.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/dechunk.cpython-310.pyc ADDED
Binary file (6.21 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/enum_util.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/typecheck.cpython-310.pyc ADDED
Binary file (6.58 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/__pycache__/types.cpython-310.pyc ADDED
Binary file (370 Bytes). View file
 
vllm/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fc196718bf4b5e3c792f194d0786604efddfc2863dc1b3fe906202d12a320c2
3
+ size 854312
vllm/lib/python3.10/site-packages/contourpy/_contourpy.pyi ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import ClassVar, NoReturn, TypeAlias
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ import contourpy._contourpy as cpy
7
+
8
+ # Input numpy array types, the same as in common.h
9
+ CoordinateArray: TypeAlias = npt.NDArray[np.float64]
10
+ MaskArray: TypeAlias = npt.NDArray[np.bool_]
11
+ LevelArray: TypeAlias = npt.ArrayLike
12
+
13
+ # Output numpy array types, the same as in common.h
14
+ PointArray: TypeAlias = npt.NDArray[np.float64]
15
+ CodeArray: TypeAlias = npt.NDArray[np.uint8]
16
+ OffsetArray: TypeAlias = npt.NDArray[np.uint32]
17
+
18
+ # Types returned from filled()
19
+ FillReturn_OuterCode: TypeAlias = tuple[list[PointArray], list[CodeArray]]
20
+ FillReturn_OuterOffset: TypeAlias = tuple[list[PointArray], list[OffsetArray]]
21
+ FillReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]]
22
+ FillReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]]
23
+ FillReturn_ChunkCombinedCodeOffset: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None], list[OffsetArray | None]]
24
+ FillReturn_ChunkCombinedOffsetOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None], list[OffsetArray | None]]
25
+ FillReturn_Chunk: TypeAlias = FillReturn_ChunkCombinedCode | FillReturn_ChunkCombinedOffset | FillReturn_ChunkCombinedCodeOffset | FillReturn_ChunkCombinedOffsetOffset
26
+ FillReturn: TypeAlias = FillReturn_OuterCode | FillReturn_OuterOffset | FillReturn_Chunk
27
+
28
+ # Types returned from lines()
29
+ LineReturn_Separate: TypeAlias = list[PointArray]
30
+ LineReturn_SeparateCode: TypeAlias = tuple[list[PointArray], list[CodeArray]]
31
+ LineReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]]
32
+ LineReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]]
33
+ LineReturn_ChunkCombinedNan: TypeAlias = tuple[list[PointArray | None]]
34
+ LineReturn_Chunk: TypeAlias = LineReturn_ChunkCombinedCode | LineReturn_ChunkCombinedOffset | LineReturn_ChunkCombinedNan
35
+ LineReturn: TypeAlias = LineReturn_Separate | LineReturn_SeparateCode | LineReturn_Chunk
36
+
37
+
38
+ NDEBUG: int
39
+ __version__: str
40
+
41
+ class FillType:
42
+ ChunkCombinedCode: ClassVar[cpy.FillType]
43
+ ChunkCombinedCodeOffset: ClassVar[cpy.FillType]
44
+ ChunkCombinedOffset: ClassVar[cpy.FillType]
45
+ ChunkCombinedOffsetOffset: ClassVar[cpy.FillType]
46
+ OuterCode: ClassVar[cpy.FillType]
47
+ OuterOffset: ClassVar[cpy.FillType]
48
+ __members__: ClassVar[dict[str, cpy.FillType]]
49
+ def __eq__(self, other: object) -> bool: ...
50
+ def __getstate__(self) -> int: ...
51
+ def __hash__(self) -> int: ...
52
+ def __index__(self) -> int: ...
53
+ def __init__(self, value: int) -> None: ...
54
+ def __int__(self) -> int: ...
55
+ def __ne__(self, other: object) -> bool: ...
56
+ def __setstate__(self, state: int) -> NoReturn: ...
57
+ @property
58
+ def name(self) -> str: ...
59
+ @property
60
+ def value(self) -> int: ...
61
+
62
+ class LineType:
63
+ ChunkCombinedCode: ClassVar[cpy.LineType]
64
+ ChunkCombinedNan: ClassVar[cpy.LineType]
65
+ ChunkCombinedOffset: ClassVar[cpy.LineType]
66
+ Separate: ClassVar[cpy.LineType]
67
+ SeparateCode: ClassVar[cpy.LineType]
68
+ __members__: ClassVar[dict[str, cpy.LineType]]
69
+ def __eq__(self, other: object) -> bool: ...
70
+ def __getstate__(self) -> int: ...
71
+ def __hash__(self) -> int: ...
72
+ def __index__(self) -> int: ...
73
+ def __init__(self, value: int) -> None: ...
74
+ def __int__(self) -> int: ...
75
+ def __ne__(self, other: object) -> bool: ...
76
+ def __setstate__(self, state: int) -> NoReturn: ...
77
+ @property
78
+ def name(self) -> str: ...
79
+ @property
80
+ def value(self) -> int: ...
81
+
82
+ class ZInterp:
83
+ Linear: ClassVar[cpy.ZInterp]
84
+ Log: ClassVar[cpy.ZInterp]
85
+ __members__: ClassVar[dict[str, cpy.ZInterp]]
86
+ def __eq__(self, other: object) -> bool: ...
87
+ def __getstate__(self) -> int: ...
88
+ def __hash__(self) -> int: ...
89
+ def __index__(self) -> int: ...
90
+ def __init__(self, value: int) -> None: ...
91
+ def __int__(self) -> int: ...
92
+ def __ne__(self, other: object) -> bool: ...
93
+ def __setstate__(self, state: int) -> NoReturn: ...
94
+ @property
95
+ def name(self) -> str: ...
96
+ @property
97
+ def value(self) -> int: ...
98
+
99
+ def max_threads() -> int: ...
100
+
101
+ class ContourGenerator:
102
+ def create_contour(self, level: float) -> LineReturn: ...
103
+ def create_filled_contour(self, lower_level: float, upper_level: float) -> FillReturn: ...
104
+ def filled(self, lower_level: float, upper_level: float) -> FillReturn: ...
105
+ def lines(self, level: float) -> LineReturn: ...
106
+ def multi_filled(self, levels: LevelArray) -> list[FillReturn]: ...
107
+ def multi_lines(self, levels: LevelArray) -> list[LineReturn]: ...
108
+ @staticmethod
109
+ def supports_corner_mask() -> bool: ...
110
+ @staticmethod
111
+ def supports_fill_type(fill_type: FillType) -> bool: ...
112
+ @staticmethod
113
+ def supports_line_type(line_type: LineType) -> bool: ...
114
+ @staticmethod
115
+ def supports_quad_as_tri() -> bool: ...
116
+ @staticmethod
117
+ def supports_threads() -> bool: ...
118
+ @staticmethod
119
+ def supports_z_interp() -> bool: ...
120
+ @property
121
+ def chunk_count(self) -> tuple[int, int]: ...
122
+ @property
123
+ def chunk_size(self) -> tuple[int, int]: ...
124
+ @property
125
+ def corner_mask(self) -> bool: ...
126
+ @property
127
+ def fill_type(self) -> FillType: ...
128
+ @property
129
+ def line_type(self) -> LineType: ...
130
+ @property
131
+ def quad_as_tri(self) -> bool: ...
132
+ @property
133
+ def thread_count(self) -> int: ...
134
+ @property
135
+ def z_interp(self) -> ZInterp: ...
136
+ default_fill_type: cpy.FillType
137
+ default_line_type: cpy.LineType
138
+
139
+ class Mpl2005ContourGenerator(ContourGenerator):
140
+ def __init__(
141
+ self,
142
+ x: CoordinateArray,
143
+ y: CoordinateArray,
144
+ z: CoordinateArray,
145
+ mask: MaskArray,
146
+ *,
147
+ x_chunk_size: int = 0,
148
+ y_chunk_size: int = 0,
149
+ ) -> None: ...
150
+
151
+ class Mpl2014ContourGenerator(ContourGenerator):
152
+ def __init__(
153
+ self,
154
+ x: CoordinateArray,
155
+ y: CoordinateArray,
156
+ z: CoordinateArray,
157
+ mask: MaskArray,
158
+ *,
159
+ corner_mask: bool,
160
+ x_chunk_size: int = 0,
161
+ y_chunk_size: int = 0,
162
+ ) -> None: ...
163
+
164
+ class SerialContourGenerator(ContourGenerator):
165
+ def __init__(
166
+ self,
167
+ x: CoordinateArray,
168
+ y: CoordinateArray,
169
+ z: CoordinateArray,
170
+ mask: MaskArray,
171
+ *,
172
+ corner_mask: bool,
173
+ line_type: LineType,
174
+ fill_type: FillType,
175
+ quad_as_tri: bool,
176
+ z_interp: ZInterp,
177
+ x_chunk_size: int = 0,
178
+ y_chunk_size: int = 0,
179
+ ) -> None: ...
180
+ def _write_cache(self) -> NoReturn: ...
181
+
182
+ class ThreadedContourGenerator(ContourGenerator):
183
+ def __init__(
184
+ self,
185
+ x: CoordinateArray,
186
+ y: CoordinateArray,
187
+ z: CoordinateArray,
188
+ mask: MaskArray,
189
+ *,
190
+ corner_mask: bool,
191
+ line_type: LineType,
192
+ fill_type: FillType,
193
+ quad_as_tri: bool,
194
+ z_interp: ZInterp,
195
+ x_chunk_size: int = 0,
196
+ y_chunk_size: int = 0,
197
+ thread_count: int = 0,
198
+ ) -> None: ...
199
+ def _write_cache(self) -> None: ...
vllm/lib/python3.10/site-packages/contourpy/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "1.3.1"
vllm/lib/python3.10/site-packages/contourpy/array.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from itertools import chain, pairwise
4
+ from typing import TYPE_CHECKING
5
+
6
+ import numpy as np
7
+
8
+ from contourpy.typecheck import check_code_array, check_offset_array, check_point_array
9
+ from contourpy.types import CLOSEPOLY, LINETO, MOVETO, code_dtype, offset_dtype, point_dtype
10
+
11
+ if TYPE_CHECKING:
12
+ import contourpy._contourpy as cpy
13
+
14
+
15
+ def codes_from_offsets(offsets: cpy.OffsetArray) -> cpy.CodeArray:
16
+ """Determine codes from offsets, assuming they all correspond to closed polygons.
17
+ """
18
+ check_offset_array(offsets)
19
+
20
+ n = offsets[-1]
21
+ codes = np.full(n, LINETO, dtype=code_dtype)
22
+ codes[offsets[:-1]] = MOVETO
23
+ codes[offsets[1:] - 1] = CLOSEPOLY
24
+ return codes
25
+
26
+
27
+ def codes_from_offsets_and_points(
28
+ offsets: cpy.OffsetArray,
29
+ points: cpy.PointArray,
30
+ ) -> cpy.CodeArray:
31
+ """Determine codes from offsets and points, using the equality of the start and end points of
32
+ each line to determine if lines are closed or not.
33
+ """
34
+ check_offset_array(offsets)
35
+ check_point_array(points)
36
+
37
+ codes = np.full(len(points), LINETO, dtype=code_dtype)
38
+ codes[offsets[:-1]] = MOVETO
39
+
40
+ end_offsets = offsets[1:] - 1
41
+ closed = np.all(points[offsets[:-1]] == points[end_offsets], axis=1)
42
+ codes[end_offsets[closed]] = CLOSEPOLY
43
+
44
+ return codes
45
+
46
+
47
+ def codes_from_points(points: cpy.PointArray) -> cpy.CodeArray:
48
+ """Determine codes for a single line, using the equality of the start and end points to
49
+ determine if the line is closed or not.
50
+ """
51
+ check_point_array(points)
52
+
53
+ n = len(points)
54
+ codes = np.full(n, LINETO, dtype=code_dtype)
55
+ codes[0] = MOVETO
56
+ if np.all(points[0] == points[-1]):
57
+ codes[-1] = CLOSEPOLY
58
+ return codes
59
+
60
+
61
+ def concat_codes(list_of_codes: list[cpy.CodeArray]) -> cpy.CodeArray:
62
+ """Concatenate a list of codes arrays into a single code array.
63
+ """
64
+ if not list_of_codes:
65
+ raise ValueError("Empty list passed to concat_codes")
66
+
67
+ return np.concatenate(list_of_codes, dtype=code_dtype)
68
+
69
+
70
+ def concat_codes_or_none(list_of_codes_or_none: list[cpy.CodeArray | None]) -> cpy.CodeArray | None:
71
+ """Concatenate a list of codes arrays or None into a single code array or None.
72
+ """
73
+ list_of_codes = [codes for codes in list_of_codes_or_none if codes is not None]
74
+ if list_of_codes:
75
+ return concat_codes(list_of_codes)
76
+ else:
77
+ return None
78
+
79
+
80
+ def concat_offsets(list_of_offsets: list[cpy.OffsetArray]) -> cpy.OffsetArray:
81
+ """Concatenate a list of offsets arrays into a single offset array.
82
+ """
83
+ if not list_of_offsets:
84
+ raise ValueError("Empty list passed to concat_offsets")
85
+
86
+ n = len(list_of_offsets)
87
+ cumulative = np.cumsum([offsets[-1] for offsets in list_of_offsets], dtype=offset_dtype)
88
+ ret: cpy.OffsetArray = np.concatenate(
89
+ (list_of_offsets[0], *(list_of_offsets[i+1][1:] + cumulative[i] for i in range(n-1))),
90
+ dtype=offset_dtype,
91
+ )
92
+ return ret
93
+
94
+
95
+ def concat_offsets_or_none(
96
+ list_of_offsets_or_none: list[cpy.OffsetArray | None],
97
+ ) -> cpy.OffsetArray | None:
98
+ """Concatenate a list of offsets arrays or None into a single offset array or None.
99
+ """
100
+ list_of_offsets = [offsets for offsets in list_of_offsets_or_none if offsets is not None]
101
+ if list_of_offsets:
102
+ return concat_offsets(list_of_offsets)
103
+ else:
104
+ return None
105
+
106
+
107
+ def concat_points(list_of_points: list[cpy.PointArray]) -> cpy.PointArray:
108
+ """Concatenate a list of point arrays into a single point array.
109
+ """
110
+ if not list_of_points:
111
+ raise ValueError("Empty list passed to concat_points")
112
+
113
+ return np.concatenate(list_of_points, dtype=point_dtype)
114
+
115
+
116
+ def concat_points_or_none(
117
+ list_of_points_or_none: list[cpy.PointArray | None],
118
+ ) -> cpy.PointArray | None:
119
+ """Concatenate a list of point arrays or None into a single point array or None.
120
+ """
121
+ list_of_points = [points for points in list_of_points_or_none if points is not None]
122
+ if list_of_points:
123
+ return concat_points(list_of_points)
124
+ else:
125
+ return None
126
+
127
+
128
+ def concat_points_or_none_with_nan(
129
+ list_of_points_or_none: list[cpy.PointArray | None],
130
+ ) -> cpy.PointArray | None:
131
+ """Concatenate a list of points or None into a single point array or None, with NaNs used to
132
+ separate each line.
133
+ """
134
+ list_of_points = [points for points in list_of_points_or_none if points is not None]
135
+ if list_of_points:
136
+ return concat_points_with_nan(list_of_points)
137
+ else:
138
+ return None
139
+
140
+
141
+ def concat_points_with_nan(list_of_points: list[cpy.PointArray]) -> cpy.PointArray:
142
+ """Concatenate a list of points into a single point array with NaNs used to separate each line.
143
+ """
144
+ if not list_of_points:
145
+ raise ValueError("Empty list passed to concat_points_with_nan")
146
+
147
+ if len(list_of_points) == 1:
148
+ return list_of_points[0]
149
+ else:
150
+ nan_spacer = np.full((1, 2), np.nan, dtype=point_dtype)
151
+ list_of_points = [list_of_points[0],
152
+ *list(chain(*((nan_spacer, x) for x in list_of_points[1:])))]
153
+ return concat_points(list_of_points)
154
+
155
+
156
+ def insert_nan_at_offsets(points: cpy.PointArray, offsets: cpy.OffsetArray) -> cpy.PointArray:
157
+ """Insert NaNs into a point array at locations specified by an offset array.
158
+ """
159
+ check_point_array(points)
160
+ check_offset_array(offsets)
161
+
162
+ if len(offsets) <= 2:
163
+ return points
164
+ else:
165
+ nan_spacer = np.array([np.nan, np.nan], dtype=point_dtype)
166
+ # Convert offsets to int64 to avoid numpy error when mixing signed and unsigned ints.
167
+ return np.insert(points, offsets[1:-1].astype(np.int64), nan_spacer, axis=0)
168
+
169
+
170
+ def offsets_from_codes(codes: cpy.CodeArray) -> cpy.OffsetArray:
171
+ """Determine offsets from codes using locations of MOVETO codes.
172
+ """
173
+ check_code_array(codes)
174
+
175
+ return np.append(np.nonzero(codes == MOVETO)[0], len(codes)).astype(offset_dtype)
176
+
177
+
178
+ def offsets_from_lengths(list_of_points: list[cpy.PointArray]) -> cpy.OffsetArray:
179
+ """Determine offsets from lengths of point arrays.
180
+ """
181
+ if not list_of_points:
182
+ raise ValueError("Empty list passed to offsets_from_lengths")
183
+
184
+ return np.cumsum([0] + [len(line) for line in list_of_points], dtype=offset_dtype)
185
+
186
+
187
+ def outer_offsets_from_list_of_codes(list_of_codes: list[cpy.CodeArray]) -> cpy.OffsetArray:
188
+ """Determine outer offsets from codes using locations of MOVETO codes.
189
+ """
190
+ if not list_of_codes:
191
+ raise ValueError("Empty list passed to outer_offsets_from_list_of_codes")
192
+
193
+ return np.cumsum([0] + [np.count_nonzero(codes == MOVETO) for codes in list_of_codes],
194
+ dtype=offset_dtype)
195
+
196
+
197
+ def outer_offsets_from_list_of_offsets(list_of_offsets: list[cpy.OffsetArray]) -> cpy.OffsetArray:
198
+ """Determine outer offsets from a list of offsets.
199
+ """
200
+ if not list_of_offsets:
201
+ raise ValueError("Empty list passed to outer_offsets_from_list_of_offsets")
202
+
203
+ return np.cumsum([0] + [len(offsets)-1 for offsets in list_of_offsets], dtype=offset_dtype)
204
+
205
+
206
+ def remove_nan(points: cpy.PointArray) -> tuple[cpy.PointArray, cpy.OffsetArray]:
207
+ """Remove NaN from a points array, also return the offsets corresponding to the NaN removed.
208
+ """
209
+ check_point_array(points)
210
+
211
+ nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0]
212
+ if len(nan_offsets) == 0:
213
+ return points, np.array([0, len(points)], dtype=offset_dtype)
214
+ else:
215
+ points = np.delete(points, nan_offsets, axis=0)
216
+ nan_offsets -= np.arange(len(nan_offsets))
217
+ offsets: cpy.OffsetArray = np.empty(len(nan_offsets)+2, dtype=offset_dtype)
218
+ offsets[0] = 0
219
+ offsets[1:-1] = nan_offsets
220
+ offsets[-1] = len(points)
221
+ return points, offsets
222
+
223
+
224
+ def split_codes_by_offsets(codes: cpy.CodeArray, offsets: cpy.OffsetArray) -> list[cpy.CodeArray]:
225
+ """Split a code array at locations specified by an offset array into a list of code arrays.
226
+ """
227
+ check_code_array(codes)
228
+ check_offset_array(offsets)
229
+
230
+ if len(offsets) > 2:
231
+ return np.split(codes, offsets[1:-1])
232
+ else:
233
+ return [codes]
234
+
235
+
236
+ def split_points_by_offsets(
237
+ points: cpy.PointArray,
238
+ offsets: cpy.OffsetArray,
239
+ ) -> list[cpy.PointArray]:
240
+ """Split a point array at locations specified by an offset array into a list of point arrays.
241
+ """
242
+ check_point_array(points)
243
+ check_offset_array(offsets)
244
+
245
+ if len(offsets) > 2:
246
+ return np.split(points, offsets[1:-1])
247
+ else:
248
+ return [points]
249
+
250
+
251
+ def split_points_at_nan(points: cpy.PointArray) -> list[cpy.PointArray]:
252
+ """Split a points array at NaNs into a list of point arrays.
253
+ """
254
+ check_point_array(points)
255
+
256
+ nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0]
257
+ if len(nan_offsets) == 0:
258
+ return [points]
259
+ else:
260
+ nan_offsets = np.concatenate(([-1], nan_offsets, [len(points)]))
261
+ return [points[s+1:e] for s, e in pairwise(nan_offsets)]
vllm/lib/python3.10/site-packages/contourpy/chunk.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+
6
+ def calc_chunk_sizes(
7
+ chunk_size: int | tuple[int, int] | None,
8
+ chunk_count: int | tuple[int, int] | None,
9
+ total_chunk_count: int | None,
10
+ ny: int,
11
+ nx: int,
12
+ ) -> tuple[int, int]:
13
+ """Calculate chunk sizes.
14
+
15
+ Args:
16
+ chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same
17
+ size in both directions if only one is specified. Cannot be negative.
18
+ chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the
19
+ same count in both directions if only one is specified. If less than 1, set to 1.
20
+ total_chunk_count (int, optional): Total number of chunks. If less than 1, set to 1.
21
+ ny (int): Number of grid points in y-direction.
22
+ nx (int): Number of grid points in x-direction.
23
+
24
+ Return:
25
+ tuple(int, int): Chunk sizes (y_chunk_size, x_chunk_size).
26
+
27
+ Note:
28
+ Zero or one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` should be
29
+ specified.
30
+ """
31
+ if sum([chunk_size is not None, chunk_count is not None, total_chunk_count is not None]) > 1:
32
+ raise ValueError("Only one of chunk_size, chunk_count and total_chunk_count should be set")
33
+
34
+ if nx < 2 or ny < 2:
35
+ raise ValueError(f"(ny, nx) must be at least (2, 2), not ({ny}, {nx})")
36
+
37
+ if total_chunk_count is not None:
38
+ max_chunk_count = (nx-1)*(ny-1)
39
+ total_chunk_count = min(max(total_chunk_count, 1), max_chunk_count)
40
+ if total_chunk_count == 1:
41
+ chunk_size = 0
42
+ elif total_chunk_count == max_chunk_count:
43
+ chunk_size = (1, 1)
44
+ else:
45
+ factors = two_factors(total_chunk_count)
46
+ if ny > nx:
47
+ chunk_count = factors
48
+ else:
49
+ chunk_count = (factors[1], factors[0])
50
+
51
+ if chunk_count is not None:
52
+ if isinstance(chunk_count, tuple):
53
+ y_chunk_count, x_chunk_count = chunk_count
54
+ else:
55
+ y_chunk_count = x_chunk_count = chunk_count
56
+ x_chunk_count = min(max(x_chunk_count, 1), nx-1)
57
+ y_chunk_count = min(max(y_chunk_count, 1), ny-1)
58
+ chunk_size = (math.ceil((ny-1) / y_chunk_count), math.ceil((nx-1) / x_chunk_count))
59
+
60
+ if chunk_size is None:
61
+ y_chunk_size = x_chunk_size = 0
62
+ elif isinstance(chunk_size, tuple):
63
+ y_chunk_size, x_chunk_size = chunk_size
64
+ else:
65
+ y_chunk_size = x_chunk_size = chunk_size
66
+
67
+ if x_chunk_size < 0 or y_chunk_size < 0:
68
+ raise ValueError("chunk_size cannot be negative")
69
+
70
+ return y_chunk_size, x_chunk_size
71
+
72
+
73
+ def two_factors(n: int) -> tuple[int, int]:
74
+ """Split an integer into two integer factors.
75
+
76
+ The two factors will be as close as possible to the sqrt of n, and are returned in decreasing
77
+ order. Worst case returns (n, 1).
78
+
79
+ Args:
80
+ n (int): The integer to factorize, must be positive.
81
+
82
+ Return:
83
+ tuple(int, int): The two factors of n, in decreasing order.
84
+ """
85
+ if n < 0:
86
+ raise ValueError(f"two_factors expects positive integer not {n}")
87
+
88
+ i = math.ceil(math.sqrt(n))
89
+ while n % i != 0:
90
+ i -= 1
91
+ j = n // i
92
+ if i > j:
93
+ return i, j
94
+ else:
95
+ return j, i
vllm/lib/python3.10/site-packages/contourpy/convert.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from itertools import pairwise
4
+ from typing import TYPE_CHECKING, cast
5
+
6
+ import numpy as np
7
+
8
+ from contourpy._contourpy import FillType, LineType
9
+ import contourpy.array as arr
10
+ from contourpy.enum_util import as_fill_type, as_line_type
11
+ from contourpy.typecheck import check_filled, check_lines
12
+ from contourpy.types import MOVETO, offset_dtype
13
+
14
+ if TYPE_CHECKING:
15
+ import contourpy._contourpy as cpy
16
+
17
+
18
+ def _convert_filled_from_OuterCode(
19
+ filled: cpy.FillReturn_OuterCode,
20
+ fill_type_to: FillType,
21
+ ) -> cpy.FillReturn:
22
+ if fill_type_to == FillType.OuterCode:
23
+ return filled
24
+ elif fill_type_to == FillType.OuterOffset:
25
+ return (filled[0], [arr.offsets_from_codes(codes) for codes in filled[1]])
26
+
27
+ if len(filled[0]) > 0:
28
+ points = arr.concat_points(filled[0])
29
+ codes = arr.concat_codes(filled[1])
30
+ else:
31
+ points = None
32
+ codes = None
33
+
34
+ if fill_type_to == FillType.ChunkCombinedCode:
35
+ return ([points], [codes])
36
+ elif fill_type_to == FillType.ChunkCombinedOffset:
37
+ return ([points], [None if codes is None else arr.offsets_from_codes(codes)])
38
+ elif fill_type_to == FillType.ChunkCombinedCodeOffset:
39
+ outer_offsets = None if points is None else arr.offsets_from_lengths(filled[0])
40
+ ret1: cpy.FillReturn_ChunkCombinedCodeOffset = ([points], [codes], [outer_offsets])
41
+ return ret1
42
+ elif fill_type_to == FillType.ChunkCombinedOffsetOffset:
43
+ if codes is None:
44
+ ret2: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None])
45
+ else:
46
+ offsets = arr.offsets_from_codes(codes)
47
+ outer_offsets = arr.outer_offsets_from_list_of_codes(filled[1])
48
+ ret2 = ([points], [offsets], [outer_offsets])
49
+ return ret2
50
+ else:
51
+ raise ValueError(f"Invalid FillType {fill_type_to}")
52
+
53
+
54
+ def _convert_filled_from_OuterOffset(
55
+ filled: cpy.FillReturn_OuterOffset,
56
+ fill_type_to: FillType,
57
+ ) -> cpy.FillReturn:
58
+ if fill_type_to == FillType.OuterCode:
59
+ separate_codes = [arr.codes_from_offsets(offsets) for offsets in filled[1]]
60
+ return (filled[0], separate_codes)
61
+ elif fill_type_to == FillType.OuterOffset:
62
+ return filled
63
+
64
+ if len(filled[0]) > 0:
65
+ points = arr.concat_points(filled[0])
66
+ offsets = arr.concat_offsets(filled[1])
67
+ else:
68
+ points = None
69
+ offsets = None
70
+
71
+ if fill_type_to == FillType.ChunkCombinedCode:
72
+ return ([points], [None if offsets is None else arr.codes_from_offsets(offsets)])
73
+ elif fill_type_to == FillType.ChunkCombinedOffset:
74
+ return ([points], [offsets])
75
+ elif fill_type_to == FillType.ChunkCombinedCodeOffset:
76
+ if offsets is None:
77
+ ret1: cpy.FillReturn_ChunkCombinedCodeOffset = ([None], [None], [None])
78
+ else:
79
+ codes = arr.codes_from_offsets(offsets)
80
+ outer_offsets = arr.offsets_from_lengths(filled[0])
81
+ ret1 = ([points], [codes], [outer_offsets])
82
+ return ret1
83
+ elif fill_type_to == FillType.ChunkCombinedOffsetOffset:
84
+ if points is None:
85
+ ret2: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None])
86
+ else:
87
+ outer_offsets = arr.outer_offsets_from_list_of_offsets(filled[1])
88
+ ret2 = ([points], [offsets], [outer_offsets])
89
+ return ret2
90
+ else:
91
+ raise ValueError(f"Invalid FillType {fill_type_to}")
92
+
93
+
94
+ def _convert_filled_from_ChunkCombinedCode(
95
+ filled: cpy.FillReturn_ChunkCombinedCode,
96
+ fill_type_to: FillType,
97
+ ) -> cpy.FillReturn:
98
+ if fill_type_to == FillType.ChunkCombinedCode:
99
+ return filled
100
+ elif fill_type_to == FillType.ChunkCombinedOffset:
101
+ codes = [None if codes is None else arr.offsets_from_codes(codes) for codes in filled[1]]
102
+ return (filled[0], codes)
103
+ else:
104
+ raise ValueError(
105
+ f"Conversion from {FillType.ChunkCombinedCode} to {fill_type_to} not supported")
106
+
107
+
108
+ def _convert_filled_from_ChunkCombinedOffset(
109
+ filled: cpy.FillReturn_ChunkCombinedOffset,
110
+ fill_type_to: FillType,
111
+ ) -> cpy.FillReturn:
112
+ if fill_type_to == FillType.ChunkCombinedCode:
113
+ chunk_codes: list[cpy.CodeArray | None] = []
114
+ for points, offsets in zip(*filled):
115
+ if points is None:
116
+ chunk_codes.append(None)
117
+ else:
118
+ if TYPE_CHECKING:
119
+ assert offsets is not None
120
+ chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points))
121
+ return (filled[0], chunk_codes)
122
+ elif fill_type_to == FillType.ChunkCombinedOffset:
123
+ return filled
124
+ else:
125
+ raise ValueError(
126
+ f"Conversion from {FillType.ChunkCombinedOffset} to {fill_type_to} not supported")
127
+
128
+
129
+ def _convert_filled_from_ChunkCombinedCodeOffset(
130
+ filled: cpy.FillReturn_ChunkCombinedCodeOffset,
131
+ fill_type_to: FillType,
132
+ ) -> cpy.FillReturn:
133
+ if fill_type_to == FillType.OuterCode:
134
+ separate_points = []
135
+ separate_codes = []
136
+ for points, codes, outer_offsets in zip(*filled):
137
+ if points is not None:
138
+ if TYPE_CHECKING:
139
+ assert codes is not None
140
+ assert outer_offsets is not None
141
+ separate_points += arr.split_points_by_offsets(points, outer_offsets)
142
+ separate_codes += arr.split_codes_by_offsets(codes, outer_offsets)
143
+ return (separate_points, separate_codes)
144
+ elif fill_type_to == FillType.OuterOffset:
145
+ separate_points = []
146
+ separate_offsets = []
147
+ for points, codes, outer_offsets in zip(*filled):
148
+ if points is not None:
149
+ if TYPE_CHECKING:
150
+ assert codes is not None
151
+ assert outer_offsets is not None
152
+ separate_points += arr.split_points_by_offsets(points, outer_offsets)
153
+ separate_codes = arr.split_codes_by_offsets(codes, outer_offsets)
154
+ separate_offsets += [arr.offsets_from_codes(codes) for codes in separate_codes]
155
+ return (separate_points, separate_offsets)
156
+ elif fill_type_to == FillType.ChunkCombinedCode:
157
+ ret1: cpy.FillReturn_ChunkCombinedCode = (filled[0], filled[1])
158
+ return ret1
159
+ elif fill_type_to == FillType.ChunkCombinedOffset:
160
+ all_offsets = [None if codes is None else arr.offsets_from_codes(codes)
161
+ for codes in filled[1]]
162
+ ret2: cpy.FillReturn_ChunkCombinedOffset = (filled[0], all_offsets)
163
+ return ret2
164
+ elif fill_type_to == FillType.ChunkCombinedCodeOffset:
165
+ return filled
166
+ elif fill_type_to == FillType.ChunkCombinedOffsetOffset:
167
+ chunk_offsets: list[cpy.OffsetArray | None] = []
168
+ chunk_outer_offsets: list[cpy.OffsetArray | None] = []
169
+ for codes, outer_offsets in zip(*filled[1:]):
170
+ if codes is None:
171
+ chunk_offsets.append(None)
172
+ chunk_outer_offsets.append(None)
173
+ else:
174
+ if TYPE_CHECKING:
175
+ assert outer_offsets is not None
176
+ offsets = arr.offsets_from_codes(codes)
177
+ outer_offsets = np.array([np.nonzero(offsets == oo)[0][0] for oo in outer_offsets],
178
+ dtype=offset_dtype)
179
+ chunk_offsets.append(offsets)
180
+ chunk_outer_offsets.append(outer_offsets)
181
+ ret3: cpy.FillReturn_ChunkCombinedOffsetOffset = (
182
+ filled[0], chunk_offsets, chunk_outer_offsets,
183
+ )
184
+ return ret3
185
+ else:
186
+ raise ValueError(f"Invalid FillType {fill_type_to}")
187
+
188
+
189
+ def _convert_filled_from_ChunkCombinedOffsetOffset(
190
+ filled: cpy.FillReturn_ChunkCombinedOffsetOffset,
191
+ fill_type_to: FillType,
192
+ ) -> cpy.FillReturn:
193
+ if fill_type_to == FillType.OuterCode:
194
+ separate_points = []
195
+ separate_codes = []
196
+ for points, offsets, outer_offsets in zip(*filled):
197
+ if points is not None:
198
+ if TYPE_CHECKING:
199
+ assert offsets is not None
200
+ assert outer_offsets is not None
201
+ codes = arr.codes_from_offsets_and_points(offsets, points)
202
+ outer_offsets = offsets[outer_offsets]
203
+ separate_points += arr.split_points_by_offsets(points, outer_offsets)
204
+ separate_codes += arr.split_codes_by_offsets(codes, outer_offsets)
205
+ return (separate_points, separate_codes)
206
+ elif fill_type_to == FillType.OuterOffset:
207
+ separate_points = []
208
+ separate_offsets = []
209
+ for points, offsets, outer_offsets in zip(*filled):
210
+ if points is not None:
211
+ if TYPE_CHECKING:
212
+ assert offsets is not None
213
+ assert outer_offsets is not None
214
+ if len(outer_offsets) > 2:
215
+ separate_offsets += [offsets[s:e+1] - offsets[s] for s, e in
216
+ pairwise(outer_offsets)]
217
+ else:
218
+ separate_offsets.append(offsets)
219
+ separate_points += arr.split_points_by_offsets(points, offsets[outer_offsets])
220
+ return (separate_points, separate_offsets)
221
+ elif fill_type_to == FillType.ChunkCombinedCode:
222
+ chunk_codes: list[cpy.CodeArray | None] = []
223
+ for points, offsets, outer_offsets in zip(*filled):
224
+ if points is None:
225
+ chunk_codes.append(None)
226
+ else:
227
+ if TYPE_CHECKING:
228
+ assert offsets is not None
229
+ assert outer_offsets is not None
230
+ chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points))
231
+ ret1: cpy.FillReturn_ChunkCombinedCode = (filled[0], chunk_codes)
232
+ return ret1
233
+ elif fill_type_to == FillType.ChunkCombinedOffset:
234
+ return (filled[0], filled[1])
235
+ elif fill_type_to == FillType.ChunkCombinedCodeOffset:
236
+ chunk_codes = []
237
+ chunk_outer_offsets: list[cpy.OffsetArray | None] = []
238
+ for points, offsets, outer_offsets in zip(*filled):
239
+ if points is None:
240
+ chunk_codes.append(None)
241
+ chunk_outer_offsets.append(None)
242
+ else:
243
+ if TYPE_CHECKING:
244
+ assert offsets is not None
245
+ assert outer_offsets is not None
246
+ chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points))
247
+ chunk_outer_offsets.append(offsets[outer_offsets])
248
+ ret2: cpy.FillReturn_ChunkCombinedCodeOffset = (filled[0], chunk_codes, chunk_outer_offsets)
249
+ return ret2
250
+ elif fill_type_to == FillType.ChunkCombinedOffsetOffset:
251
+ return filled
252
+ else:
253
+ raise ValueError(f"Invalid FillType {fill_type_to}")
254
+
255
+
256
+ def convert_filled(
257
+ filled: cpy.FillReturn,
258
+ fill_type_from: FillType | str,
259
+ fill_type_to: FillType | str,
260
+ ) -> cpy.FillReturn:
261
+ """Convert filled contours from one :class:`~.FillType` to another.
262
+
263
+ Args:
264
+ filled (sequence of arrays): Filled contour polygons to convert, such as those returned by
265
+ :meth:`.ContourGenerator.filled`.
266
+ fill_type_from (FillType or str): :class:`~.FillType` to convert from as enum or
267
+ string equivalent.
268
+ fill_type_to (FillType or str): :class:`~.FillType` to convert to as enum or string
269
+ equivalent.
270
+
271
+ Return:
272
+ Converted filled contour polygons.
273
+
274
+ When converting non-chunked fill types (``FillType.OuterCode`` or ``FillType.OuterOffset``) to
275
+ chunked ones, all polygons are placed in the first chunk. When converting in the other
276
+ direction, all chunk information is discarded. Converting a fill type that is not aware of the
277
+ relationship between outer boundaries and contained holes (``FillType.ChunkCombinedCode`` or
278
+ ``FillType.ChunkCombinedOffset``) to one that is will raise a ``ValueError``.
279
+
280
+ .. versionadded:: 1.2.0
281
+ """
282
+ fill_type_from = as_fill_type(fill_type_from)
283
+ fill_type_to = as_fill_type(fill_type_to)
284
+
285
+ check_filled(filled, fill_type_from)
286
+
287
+ if fill_type_from == FillType.OuterCode:
288
+ if TYPE_CHECKING:
289
+ filled = cast(cpy.FillReturn_OuterCode, filled)
290
+ return _convert_filled_from_OuterCode(filled, fill_type_to)
291
+ elif fill_type_from == FillType.OuterOffset:
292
+ if TYPE_CHECKING:
293
+ filled = cast(cpy.FillReturn_OuterOffset, filled)
294
+ return _convert_filled_from_OuterOffset(filled, fill_type_to)
295
+ elif fill_type_from == FillType.ChunkCombinedCode:
296
+ if TYPE_CHECKING:
297
+ filled = cast(cpy.FillReturn_ChunkCombinedCode, filled)
298
+ return _convert_filled_from_ChunkCombinedCode(filled, fill_type_to)
299
+ elif fill_type_from == FillType.ChunkCombinedOffset:
300
+ if TYPE_CHECKING:
301
+ filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled)
302
+ return _convert_filled_from_ChunkCombinedOffset(filled, fill_type_to)
303
+ elif fill_type_from == FillType.ChunkCombinedCodeOffset:
304
+ if TYPE_CHECKING:
305
+ filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled)
306
+ return _convert_filled_from_ChunkCombinedCodeOffset(filled, fill_type_to)
307
+ elif fill_type_from == FillType.ChunkCombinedOffsetOffset:
308
+ if TYPE_CHECKING:
309
+ filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled)
310
+ return _convert_filled_from_ChunkCombinedOffsetOffset(filled, fill_type_to)
311
+ else:
312
+ raise ValueError(f"Invalid FillType {fill_type_from}")
313
+
314
+
315
+ def _convert_lines_from_Separate(
316
+ lines: cpy.LineReturn_Separate,
317
+ line_type_to: LineType,
318
+ ) -> cpy.LineReturn:
319
+ if line_type_to == LineType.Separate:
320
+ return lines
321
+ elif line_type_to == LineType.SeparateCode:
322
+ separate_codes = [arr.codes_from_points(line) for line in lines]
323
+ return (lines, separate_codes)
324
+ elif line_type_to == LineType.ChunkCombinedCode:
325
+ if not lines:
326
+ ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None])
327
+ else:
328
+ points = arr.concat_points(lines)
329
+ offsets = arr.offsets_from_lengths(lines)
330
+ codes = arr.codes_from_offsets_and_points(offsets, points)
331
+ ret1 = ([points], [codes])
332
+ return ret1
333
+ elif line_type_to == LineType.ChunkCombinedOffset:
334
+ if not lines:
335
+ ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None])
336
+ else:
337
+ ret2 = ([arr.concat_points(lines)], [arr.offsets_from_lengths(lines)])
338
+ return ret2
339
+ elif line_type_to == LineType.ChunkCombinedNan:
340
+ if not lines:
341
+ ret3: cpy.LineReturn_ChunkCombinedNan = ([None],)
342
+ else:
343
+ ret3 = ([arr.concat_points_with_nan(lines)],)
344
+ return ret3
345
+ else:
346
+ raise ValueError(f"Invalid LineType {line_type_to}")
347
+
348
+
349
+ def _convert_lines_from_SeparateCode(
350
+ lines: cpy.LineReturn_SeparateCode,
351
+ line_type_to: LineType,
352
+ ) -> cpy.LineReturn:
353
+ if line_type_to == LineType.Separate:
354
+ # Drop codes.
355
+ return lines[0]
356
+ elif line_type_to == LineType.SeparateCode:
357
+ return lines
358
+ elif line_type_to == LineType.ChunkCombinedCode:
359
+ if not lines[0]:
360
+ ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None])
361
+ else:
362
+ ret1 = ([arr.concat_points(lines[0])], [arr.concat_codes(lines[1])])
363
+ return ret1
364
+ elif line_type_to == LineType.ChunkCombinedOffset:
365
+ if not lines[0]:
366
+ ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None])
367
+ else:
368
+ ret2 = ([arr.concat_points(lines[0])], [arr.offsets_from_lengths(lines[0])])
369
+ return ret2
370
+ elif line_type_to == LineType.ChunkCombinedNan:
371
+ if not lines[0]:
372
+ ret3: cpy.LineReturn_ChunkCombinedNan = ([None],)
373
+ else:
374
+ ret3 = ([arr.concat_points_with_nan(lines[0])],)
375
+ return ret3
376
+ else:
377
+ raise ValueError(f"Invalid LineType {line_type_to}")
378
+
379
+
380
+ def _convert_lines_from_ChunkCombinedCode(
381
+ lines: cpy.LineReturn_ChunkCombinedCode,
382
+ line_type_to: LineType,
383
+ ) -> cpy.LineReturn:
384
+ if line_type_to in (LineType.Separate, LineType.SeparateCode):
385
+ separate_lines = []
386
+ for points, codes in zip(*lines):
387
+ if points is not None:
388
+ if TYPE_CHECKING:
389
+ assert codes is not None
390
+ split_at = np.nonzero(codes == MOVETO)[0]
391
+ if len(split_at) > 1:
392
+ separate_lines += np.split(points, split_at[1:])
393
+ else:
394
+ separate_lines.append(points)
395
+ if line_type_to == LineType.Separate:
396
+ return separate_lines
397
+ else:
398
+ separate_codes = [arr.codes_from_points(line) for line in separate_lines]
399
+ return (separate_lines, separate_codes)
400
+ elif line_type_to == LineType.ChunkCombinedCode:
401
+ return lines
402
+ elif line_type_to == LineType.ChunkCombinedOffset:
403
+ chunk_offsets = [None if codes is None else arr.offsets_from_codes(codes)
404
+ for codes in lines[1]]
405
+ return (lines[0], chunk_offsets)
406
+ elif line_type_to == LineType.ChunkCombinedNan:
407
+ points_nan: list[cpy.PointArray | None] = []
408
+ for points, codes in zip(*lines):
409
+ if points is None:
410
+ points_nan.append(None)
411
+ else:
412
+ if TYPE_CHECKING:
413
+ assert codes is not None
414
+ offsets = arr.offsets_from_codes(codes)
415
+ points_nan.append(arr.insert_nan_at_offsets(points, offsets))
416
+ return (points_nan,)
417
+ else:
418
+ raise ValueError(f"Invalid LineType {line_type_to}")
419
+
420
+
421
+ def _convert_lines_from_ChunkCombinedOffset(
422
+ lines: cpy.LineReturn_ChunkCombinedOffset,
423
+ line_type_to: LineType,
424
+ ) -> cpy.LineReturn:
425
+ if line_type_to in (LineType.Separate, LineType.SeparateCode):
426
+ separate_lines = []
427
+ for points, offsets in zip(*lines):
428
+ if points is not None:
429
+ if TYPE_CHECKING:
430
+ assert offsets is not None
431
+ separate_lines += arr.split_points_by_offsets(points, offsets)
432
+ if line_type_to == LineType.Separate:
433
+ return separate_lines
434
+ else:
435
+ separate_codes = [arr.codes_from_points(line) for line in separate_lines]
436
+ return (separate_lines, separate_codes)
437
+ elif line_type_to == LineType.ChunkCombinedCode:
438
+ chunk_codes: list[cpy.CodeArray | None] = []
439
+ for points, offsets in zip(*lines):
440
+ if points is None:
441
+ chunk_codes.append(None)
442
+ else:
443
+ if TYPE_CHECKING:
444
+ assert offsets is not None
445
+ chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points))
446
+ return (lines[0], chunk_codes)
447
+ elif line_type_to == LineType.ChunkCombinedOffset:
448
+ return lines
449
+ elif line_type_to == LineType.ChunkCombinedNan:
450
+ points_nan: list[cpy.PointArray | None] = []
451
+ for points, offsets in zip(*lines):
452
+ if points is None:
453
+ points_nan.append(None)
454
+ else:
455
+ if TYPE_CHECKING:
456
+ assert offsets is not None
457
+ points_nan.append(arr.insert_nan_at_offsets(points, offsets))
458
+ return (points_nan,)
459
+ else:
460
+ raise ValueError(f"Invalid LineType {line_type_to}")
461
+
462
+
463
+ def _convert_lines_from_ChunkCombinedNan(
464
+ lines: cpy.LineReturn_ChunkCombinedNan,
465
+ line_type_to: LineType,
466
+ ) -> cpy.LineReturn:
467
+ if line_type_to in (LineType.Separate, LineType.SeparateCode):
468
+ separate_lines = []
469
+ for points in lines[0]:
470
+ if points is not None:
471
+ separate_lines += arr.split_points_at_nan(points)
472
+ if line_type_to == LineType.Separate:
473
+ return separate_lines
474
+ else:
475
+ separate_codes = [arr.codes_from_points(points) for points in separate_lines]
476
+ return (separate_lines, separate_codes)
477
+ elif line_type_to == LineType.ChunkCombinedCode:
478
+ chunk_points: list[cpy.PointArray | None] = []
479
+ chunk_codes: list[cpy.CodeArray | None] = []
480
+ for points in lines[0]:
481
+ if points is None:
482
+ chunk_points.append(None)
483
+ chunk_codes.append(None)
484
+ else:
485
+ points, offsets = arr.remove_nan(points)
486
+ chunk_points.append(points)
487
+ chunk_codes.append(arr.codes_from_offsets_and_points(offsets, points))
488
+ return (chunk_points, chunk_codes)
489
+ elif line_type_to == LineType.ChunkCombinedOffset:
490
+ chunk_points = []
491
+ chunk_offsets: list[cpy.OffsetArray | None] = []
492
+ for points in lines[0]:
493
+ if points is None:
494
+ chunk_points.append(None)
495
+ chunk_offsets.append(None)
496
+ else:
497
+ points, offsets = arr.remove_nan(points)
498
+ chunk_points.append(points)
499
+ chunk_offsets.append(offsets)
500
+ return (chunk_points, chunk_offsets)
501
+ elif line_type_to == LineType.ChunkCombinedNan:
502
+ return lines
503
+ else:
504
+ raise ValueError(f"Invalid LineType {line_type_to}")
505
+
506
+
507
+ def convert_lines(
508
+ lines: cpy.LineReturn,
509
+ line_type_from: LineType | str,
510
+ line_type_to: LineType | str,
511
+ ) -> cpy.LineReturn:
512
+ """Convert contour lines from one :class:`~.LineType` to another.
513
+
514
+ Args:
515
+ lines (sequence of arrays): Contour lines to convert, such as those returned by
516
+ :meth:`.ContourGenerator.lines`.
517
+ line_type_from (LineType or str): :class:`~.LineType` to convert from as enum or
518
+ string equivalent.
519
+ line_type_to (LineType or str): :class:`~.LineType` to convert to as enum or string
520
+ equivalent.
521
+
522
+ Return:
523
+ Converted contour lines.
524
+
525
+ When converting non-chunked line types (``LineType.Separate`` or ``LineType.SeparateCode``) to
526
+ chunked ones (``LineType.ChunkCombinedCode``, ``LineType.ChunkCombinedOffset`` or
527
+ ``LineType.ChunkCombinedNan``), all lines are placed in the first chunk. When converting in the
528
+ other direction, all chunk information is discarded.
529
+
530
+ .. versionadded:: 1.2.0
531
+ """
532
+ line_type_from = as_line_type(line_type_from)
533
+ line_type_to = as_line_type(line_type_to)
534
+
535
+ check_lines(lines, line_type_from)
536
+
537
+ if line_type_from == LineType.Separate:
538
+ if TYPE_CHECKING:
539
+ lines = cast(cpy.LineReturn_Separate, lines)
540
+ return _convert_lines_from_Separate(lines, line_type_to)
541
+ elif line_type_from == LineType.SeparateCode:
542
+ if TYPE_CHECKING:
543
+ lines = cast(cpy.LineReturn_SeparateCode, lines)
544
+ return _convert_lines_from_SeparateCode(lines, line_type_to)
545
+ elif line_type_from == LineType.ChunkCombinedCode:
546
+ if TYPE_CHECKING:
547
+ lines = cast(cpy.LineReturn_ChunkCombinedCode, lines)
548
+ return _convert_lines_from_ChunkCombinedCode(lines, line_type_to)
549
+ elif line_type_from == LineType.ChunkCombinedOffset:
550
+ if TYPE_CHECKING:
551
+ lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines)
552
+ return _convert_lines_from_ChunkCombinedOffset(lines, line_type_to)
553
+ elif line_type_from == LineType.ChunkCombinedNan:
554
+ if TYPE_CHECKING:
555
+ lines = cast(cpy.LineReturn_ChunkCombinedNan, lines)
556
+ return _convert_lines_from_ChunkCombinedNan(lines, line_type_to)
557
+ else:
558
+ raise ValueError(f"Invalid LineType {line_type_from}")
559
+
560
+
561
+ def convert_multi_filled(
562
+ multi_filled: list[cpy.FillReturn],
563
+ fill_type_from: FillType | str,
564
+ fill_type_to: FillType | str,
565
+ ) -> list[cpy.FillReturn]:
566
+ """Convert multiple sets of filled contours from one :class:`~.FillType` to another.
567
+
568
+ Args:
569
+ multi_filled (nested sequence of arrays): Filled contour polygons to convert, such as those
570
+ returned by :meth:`.ContourGenerator.multi_filled`.
571
+ fill_type_from (FillType or str): :class:`~.FillType` to convert from as enum or
572
+ string equivalent.
573
+ fill_type_to (FillType or str): :class:`~.FillType` to convert to as enum or string
574
+ equivalent.
575
+
576
+ Return:
577
+ Converted sets filled contour polygons.
578
+
579
+ When converting non-chunked fill types (``FillType.OuterCode`` or ``FillType.OuterOffset``) to
580
+ chunked ones, all polygons are placed in the first chunk. When converting in the other
581
+ direction, all chunk information is discarded. Converting a fill type that is not aware of the
582
+ relationship between outer boundaries and contained holes (``FillType.ChunkCombinedCode`` or
583
+ ``FillType.ChunkCombinedOffset``) to one that is will raise a ``ValueError``.
584
+
585
+ .. versionadded:: 1.3.0
586
+ """
587
+ fill_type_from = as_fill_type(fill_type_from)
588
+ fill_type_to = as_fill_type(fill_type_to)
589
+
590
+ return [convert_filled(filled, fill_type_from, fill_type_to) for filled in multi_filled]
591
+
592
+
593
+ def convert_multi_lines(
594
+ multi_lines: list[cpy.LineReturn],
595
+ line_type_from: LineType | str,
596
+ line_type_to: LineType | str,
597
+ ) -> list[cpy.LineReturn]:
598
+ """Convert multiple sets of contour lines from one :class:`~.LineType` to another.
599
+
600
+ Args:
601
+ multi_lines (nested sequence of arrays): Contour lines to convert, such as those returned by
602
+ :meth:`.ContourGenerator.multi_lines`.
603
+ line_type_from (LineType or str): :class:`~.LineType` to convert from as enum or
604
+ string equivalent.
605
+ line_type_to (LineType or str): :class:`~.LineType` to convert to as enum or string
606
+ equivalent.
607
+
608
+ Return:
609
+ Converted set of contour lines.
610
+
611
+ When converting non-chunked line types (``LineType.Separate`` or ``LineType.SeparateCode``) to
612
+ chunked ones (``LineType.ChunkCombinedCode``, ``LineType.ChunkCombinedOffset`` or
613
+ ``LineType.ChunkCombinedNan``), all lines are placed in the first chunk. When converting in the
614
+ other direction, all chunk information is discarded.
615
+
616
+ .. versionadded:: 1.3.0
617
+ """
618
+ line_type_from = as_line_type(line_type_from)
619
+ line_type_to = as_line_type(line_type_to)
620
+
621
+ return [convert_lines(lines, line_type_from, line_type_to) for lines in multi_lines]
vllm/lib/python3.10/site-packages/contourpy/dechunk.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, cast
4
+
5
+ from contourpy._contourpy import FillType, LineType
6
+ from contourpy.array import (
7
+ concat_codes_or_none,
8
+ concat_offsets_or_none,
9
+ concat_points_or_none,
10
+ concat_points_or_none_with_nan,
11
+ )
12
+ from contourpy.enum_util import as_fill_type, as_line_type
13
+ from contourpy.typecheck import check_filled, check_lines
14
+
15
+ if TYPE_CHECKING:
16
+ import contourpy._contourpy as cpy
17
+
18
+
19
+ def dechunk_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> cpy.FillReturn:
20
+ """Return the specified filled contours with chunked data moved into the first chunk.
21
+
22
+ Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and
23
+ those that are but only contain a single chunk are returned unmodified. Individual polygons are
24
+ unchanged, they are not geometrically combined.
25
+
26
+ Args:
27
+ filled (sequence of arrays): Filled contour data, such as returned by
28
+ :meth:`.ContourGenerator.filled`.
29
+ fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string
30
+ equivalent.
31
+
32
+ Return:
33
+ Filled contours in a single chunk.
34
+
35
+ .. versionadded:: 1.2.0
36
+ """
37
+ fill_type = as_fill_type(fill_type)
38
+
39
+ if fill_type in (FillType.OuterCode, FillType.OuterOffset):
40
+ # No-op if fill_type is not chunked.
41
+ return filled
42
+
43
+ check_filled(filled, fill_type)
44
+ if len(filled[0]) < 2:
45
+ # No-op if just one chunk.
46
+ return filled
47
+
48
+ if TYPE_CHECKING:
49
+ filled = cast(cpy.FillReturn_Chunk, filled)
50
+ points = concat_points_or_none(filled[0])
51
+
52
+ if fill_type == FillType.ChunkCombinedCode:
53
+ if TYPE_CHECKING:
54
+ filled = cast(cpy.FillReturn_ChunkCombinedCode, filled)
55
+ if points is None:
56
+ ret1: cpy.FillReturn_ChunkCombinedCode = ([None], [None])
57
+ else:
58
+ ret1 = ([points], [concat_codes_or_none(filled[1])])
59
+ return ret1
60
+ elif fill_type == FillType.ChunkCombinedOffset:
61
+ if TYPE_CHECKING:
62
+ filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled)
63
+ if points is None:
64
+ ret2: cpy.FillReturn_ChunkCombinedOffset = ([None], [None])
65
+ else:
66
+ ret2 = ([points], [concat_offsets_or_none(filled[1])])
67
+ return ret2
68
+ elif fill_type == FillType.ChunkCombinedCodeOffset:
69
+ if TYPE_CHECKING:
70
+ filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled)
71
+ if points is None:
72
+ ret3: cpy.FillReturn_ChunkCombinedCodeOffset = ([None], [None], [None])
73
+ else:
74
+ outer_offsets = concat_offsets_or_none(filled[2])
75
+ ret3 = ([points], [concat_codes_or_none(filled[1])], [outer_offsets])
76
+ return ret3
77
+ elif fill_type == FillType.ChunkCombinedOffsetOffset:
78
+ if TYPE_CHECKING:
79
+ filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled)
80
+ if points is None:
81
+ ret4: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None])
82
+ else:
83
+ outer_offsets = concat_offsets_or_none(filled[2])
84
+ ret4 = ([points], [concat_offsets_or_none(filled[1])], [outer_offsets])
85
+ return ret4
86
+ else:
87
+ raise ValueError(f"Invalid FillType {fill_type}")
88
+
89
+
90
+ def dechunk_lines(lines: cpy.LineReturn, line_type: LineType | str) -> cpy.LineReturn:
91
+ """Return the specified contour lines with chunked data moved into the first chunk.
92
+
93
+ Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and
94
+ those that are but only contain a single chunk are returned unmodified. Individual lines are
95
+ unchanged, they are not geometrically combined.
96
+
97
+ Args:
98
+ lines (sequence of arrays): Contour line data, such as returned by
99
+ :meth:`.ContourGenerator.lines`.
100
+ line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string
101
+ equivalent.
102
+
103
+ Return:
104
+ Contour lines in a single chunk.
105
+
106
+ .. versionadded:: 1.2.0
107
+ """
108
+ line_type = as_line_type(line_type)
109
+
110
+ if line_type in (LineType.Separate, LineType.SeparateCode):
111
+ # No-op if line_type is not chunked.
112
+ return lines
113
+
114
+ check_lines(lines, line_type)
115
+ if len(lines[0]) < 2:
116
+ # No-op if just one chunk.
117
+ return lines
118
+
119
+ if TYPE_CHECKING:
120
+ lines = cast(cpy.LineReturn_Chunk, lines)
121
+
122
+ if line_type == LineType.ChunkCombinedCode:
123
+ if TYPE_CHECKING:
124
+ lines = cast(cpy.LineReturn_ChunkCombinedCode, lines)
125
+ points = concat_points_or_none(lines[0])
126
+ if points is None:
127
+ ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None])
128
+ else:
129
+ ret1 = ([points], [concat_codes_or_none(lines[1])])
130
+ return ret1
131
+ elif line_type == LineType.ChunkCombinedOffset:
132
+ if TYPE_CHECKING:
133
+ lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines)
134
+ points = concat_points_or_none(lines[0])
135
+ if points is None:
136
+ ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None])
137
+ else:
138
+ ret2 = ([points], [concat_offsets_or_none(lines[1])])
139
+ return ret2
140
+ elif line_type == LineType.ChunkCombinedNan:
141
+ if TYPE_CHECKING:
142
+ lines = cast(cpy.LineReturn_ChunkCombinedNan, lines)
143
+ points = concat_points_or_none_with_nan(lines[0])
144
+ ret3: cpy.LineReturn_ChunkCombinedNan = ([points],)
145
+ return ret3
146
+ else:
147
+ raise ValueError(f"Invalid LineType {line_type}")
148
+
149
+
150
+ def dechunk_multi_filled(
151
+ multi_filled: list[cpy.FillReturn],
152
+ fill_type: FillType | str,
153
+ ) -> list[cpy.FillReturn]:
154
+ """Return multiple sets of filled contours with chunked data moved into the first chunks.
155
+
156
+ Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and
157
+ those that are but only contain a single chunk are returned unmodified. Individual polygons are
158
+ unchanged, they are not geometrically combined.
159
+
160
+ Args:
161
+ multi_filled (nested sequence of arrays): Filled contour data, such as returned by
162
+ :meth:`.ContourGenerator.multi_filled`.
163
+ fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string
164
+ equivalent.
165
+
166
+ Return:
167
+ Multiple sets of filled contours in a single chunk.
168
+
169
+ .. versionadded:: 1.3.0
170
+ """
171
+ fill_type = as_fill_type(fill_type)
172
+
173
+ if fill_type in (FillType.OuterCode, FillType.OuterOffset):
174
+ # No-op if fill_type is not chunked.
175
+ return multi_filled
176
+
177
+ return [dechunk_filled(filled, fill_type) for filled in multi_filled]
178
+
179
+
180
+ def dechunk_multi_lines(
181
+ multi_lines: list[cpy.LineReturn],
182
+ line_type: LineType | str,
183
+ ) -> list[cpy.LineReturn]:
184
+ """Return multiple sets of contour lines with all chunked data moved into the first chunks.
185
+
186
+ Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and
187
+ those that are but only contain a single chunk are returned unmodified. Individual lines are
188
+ unchanged, they are not geometrically combined.
189
+
190
+ Args:
191
+ multi_lines (nested sequence of arrays): Contour line data, such as returned by
192
+ :meth:`.ContourGenerator.multi_lines`.
193
+ line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string
194
+ equivalent.
195
+
196
+ Return:
197
+ Multiple sets of contour lines in a single chunk.
198
+
199
+ .. versionadded:: 1.3.0
200
+ """
201
+ line_type = as_line_type(line_type)
202
+
203
+ if line_type in (LineType.Separate, LineType.SeparateCode):
204
+ # No-op if line_type is not chunked.
205
+ return multi_lines
206
+
207
+ return [dechunk_lines(lines, line_type) for lines in multi_lines]
vllm/lib/python3.10/site-packages/contourpy/enum_util.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from contourpy._contourpy import FillType, LineType, ZInterp
4
+
5
+
6
+ def as_fill_type(fill_type: FillType | str) -> FillType:
7
+ """Coerce a FillType or string value to a FillType.
8
+
9
+ Args:
10
+ fill_type (FillType or str): Value to convert.
11
+
12
+ Return:
13
+ FillType: Converted value.
14
+ """
15
+ if isinstance(fill_type, str):
16
+ try:
17
+ return FillType.__members__[fill_type]
18
+ except KeyError as e:
19
+ raise ValueError(f"'{fill_type}' is not a valid FillType") from e
20
+ else:
21
+ return fill_type
22
+
23
+
24
+ def as_line_type(line_type: LineType | str) -> LineType:
25
+ """Coerce a LineType or string value to a LineType.
26
+
27
+ Args:
28
+ line_type (LineType or str): Value to convert.
29
+
30
+ Return:
31
+ LineType: Converted value.
32
+ """
33
+ if isinstance(line_type, str):
34
+ try:
35
+ return LineType.__members__[line_type]
36
+ except KeyError as e:
37
+ raise ValueError(f"'{line_type}' is not a valid LineType") from e
38
+ else:
39
+ return line_type
40
+
41
+
42
+ def as_z_interp(z_interp: ZInterp | str) -> ZInterp:
43
+ """Coerce a ZInterp or string value to a ZInterp.
44
+
45
+ Args:
46
+ z_interp (ZInterp or str): Value to convert.
47
+
48
+ Return:
49
+ ZInterp: Converted value.
50
+ """
51
+ if isinstance(z_interp, str):
52
+ try:
53
+ return ZInterp.__members__[z_interp]
54
+ except KeyError as e:
55
+ raise ValueError(f"'{z_interp}' is not a valid ZInterp") from e
56
+ else:
57
+ return z_interp
vllm/lib/python3.10/site-packages/contourpy/py.typed ADDED
File without changes
vllm/lib/python3.10/site-packages/contourpy/typecheck.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, cast
4
+
5
+ import numpy as np
6
+
7
+ from contourpy import FillType, LineType
8
+ from contourpy.enum_util import as_fill_type, as_line_type
9
+ from contourpy.types import MOVETO, code_dtype, offset_dtype, point_dtype
10
+
11
+ if TYPE_CHECKING:
12
+ import contourpy._contourpy as cpy
13
+
14
+
15
+ # Minimalist array-checking functions that check dtype, ndims and shape only.
16
+ # They do not walk the arrays to check the contents for performance reasons.
17
+ def check_code_array(codes: Any) -> None:
18
+ if not isinstance(codes, np.ndarray):
19
+ raise TypeError(f"Expected numpy array not {type(codes)}")
20
+ if codes.dtype != code_dtype:
21
+ raise ValueError(f"Expected numpy array of dtype {code_dtype} not {codes.dtype}")
22
+ if not (codes.ndim == 1 and len(codes) > 1):
23
+ raise ValueError(f"Expected numpy array of shape (?,) not {codes.shape}")
24
+ if codes[0] != MOVETO:
25
+ raise ValueError(f"First element of code array must be {MOVETO}, not {codes[0]}")
26
+
27
+
28
+ def check_offset_array(offsets: Any) -> None:
29
+ if not isinstance(offsets, np.ndarray):
30
+ raise TypeError(f"Expected numpy array not {type(offsets)}")
31
+ if offsets.dtype != offset_dtype:
32
+ raise ValueError(f"Expected numpy array of dtype {offset_dtype} not {offsets.dtype}")
33
+ if not (offsets.ndim == 1 and len(offsets) > 1):
34
+ raise ValueError(f"Expected numpy array of shape (?,) not {offsets.shape}")
35
+ if offsets[0] != 0:
36
+ raise ValueError(f"First element of offset array must be 0, not {offsets[0]}")
37
+
38
+
39
+ def check_point_array(points: Any) -> None:
40
+ if not isinstance(points, np.ndarray):
41
+ raise TypeError(f"Expected numpy array not {type(points)}")
42
+ if points.dtype != point_dtype:
43
+ raise ValueError(f"Expected numpy array of dtype {point_dtype} not {points.dtype}")
44
+ if not (points.ndim == 2 and points.shape[1] ==2 and points.shape[0] > 1):
45
+ raise ValueError(f"Expected numpy array of shape (?, 2) not {points.shape}")
46
+
47
+
48
+ def _check_tuple_of_lists_with_same_length(
49
+ maybe_tuple: Any,
50
+ tuple_length: int,
51
+ allow_empty_lists: bool = True,
52
+ ) -> None:
53
+ if not isinstance(maybe_tuple, tuple):
54
+ raise TypeError(f"Expected tuple not {type(maybe_tuple)}")
55
+ if len(maybe_tuple) != tuple_length:
56
+ raise ValueError(f"Expected tuple of length {tuple_length} not {len(maybe_tuple)}")
57
+ for maybe_list in maybe_tuple:
58
+ if not isinstance(maybe_list, list):
59
+ msg = f"Expected tuple to contain {tuple_length} lists but found a {type(maybe_list)}"
60
+ raise TypeError(msg)
61
+ lengths = [len(item) for item in maybe_tuple]
62
+ if len(set(lengths)) != 1:
63
+ msg = f"Expected {tuple_length} lists with same length but lengths are {lengths}"
64
+ raise ValueError(msg)
65
+ if not allow_empty_lists and lengths[0] == 0:
66
+ raise ValueError(f"Expected {tuple_length} non-empty lists")
67
+
68
+
69
+ def check_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> None:
70
+ fill_type = as_fill_type(fill_type)
71
+
72
+ if fill_type == FillType.OuterCode:
73
+ if TYPE_CHECKING:
74
+ filled = cast(cpy.FillReturn_OuterCode, filled)
75
+ _check_tuple_of_lists_with_same_length(filled, 2)
76
+ for i, (points, codes) in enumerate(zip(*filled)):
77
+ check_point_array(points)
78
+ check_code_array(codes)
79
+ if len(points) != len(codes):
80
+ raise ValueError(f"Points and codes have different lengths in polygon {i}")
81
+ elif fill_type == FillType.OuterOffset:
82
+ if TYPE_CHECKING:
83
+ filled = cast(cpy.FillReturn_OuterOffset, filled)
84
+ _check_tuple_of_lists_with_same_length(filled, 2)
85
+ for i, (points, offsets) in enumerate(zip(*filled)):
86
+ check_point_array(points)
87
+ check_offset_array(offsets)
88
+ if offsets[-1] != len(points):
89
+ raise ValueError(f"Inconsistent points and offsets in polygon {i}")
90
+ elif fill_type == FillType.ChunkCombinedCode:
91
+ if TYPE_CHECKING:
92
+ filled = cast(cpy.FillReturn_ChunkCombinedCode, filled)
93
+ _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False)
94
+ for chunk, (points_or_none, codes_or_none) in enumerate(zip(*filled)):
95
+ if points_or_none is not None and codes_or_none is not None:
96
+ check_point_array(points_or_none)
97
+ check_code_array(codes_or_none)
98
+ if len(points_or_none) != len(codes_or_none):
99
+ raise ValueError(f"Points and codes have different lengths in chunk {chunk}")
100
+ elif not (points_or_none is None and codes_or_none is None):
101
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
102
+ elif fill_type == FillType.ChunkCombinedOffset:
103
+ if TYPE_CHECKING:
104
+ filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled)
105
+ _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False)
106
+ for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*filled)):
107
+ if points_or_none is not None and offsets_or_none is not None:
108
+ check_point_array(points_or_none)
109
+ check_offset_array(offsets_or_none)
110
+ if offsets_or_none[-1] != len(points_or_none):
111
+ raise ValueError(f"Inconsistent points and offsets in chunk {chunk}")
112
+ elif not (points_or_none is None and offsets_or_none is None):
113
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
114
+ elif fill_type == FillType.ChunkCombinedCodeOffset:
115
+ if TYPE_CHECKING:
116
+ filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled)
117
+ _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False)
118
+ for i, (points_or_none, codes_or_none, outer_offsets_or_none) in enumerate(zip(*filled)):
119
+ if (points_or_none is not None and codes_or_none is not None and
120
+ outer_offsets_or_none is not None):
121
+ check_point_array(points_or_none)
122
+ check_code_array(codes_or_none)
123
+ check_offset_array(outer_offsets_or_none)
124
+ if len(codes_or_none) != len(points_or_none):
125
+ raise ValueError(f"Points and codes have different lengths in chunk {i}")
126
+ if outer_offsets_or_none[-1] != len(codes_or_none):
127
+ raise ValueError(f"Inconsistent codes and outer_offsets in chunk {i}")
128
+ elif not (points_or_none is None and codes_or_none is None and
129
+ outer_offsets_or_none is None):
130
+ raise ValueError(f"Inconsistent Nones in chunk {i}")
131
+ elif fill_type == FillType.ChunkCombinedOffsetOffset:
132
+ if TYPE_CHECKING:
133
+ filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled)
134
+ _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False)
135
+ for i, (points_or_none, offsets_or_none, outer_offsets_or_none) in enumerate(zip(*filled)):
136
+ if (points_or_none is not None and offsets_or_none is not None and
137
+ outer_offsets_or_none is not None):
138
+ check_point_array(points_or_none)
139
+ check_offset_array(offsets_or_none)
140
+ check_offset_array(outer_offsets_or_none)
141
+ if offsets_or_none[-1] != len(points_or_none):
142
+ raise ValueError(f"Inconsistent points and offsets in chunk {i}")
143
+ if outer_offsets_or_none[-1] != len(offsets_or_none) - 1:
144
+ raise ValueError(f"Inconsistent offsets and outer_offsets in chunk {i}")
145
+ elif not (points_or_none is None and offsets_or_none is None and
146
+ outer_offsets_or_none is None):
147
+ raise ValueError(f"Inconsistent Nones in chunk {i}")
148
+ else:
149
+ raise ValueError(f"Invalid FillType {fill_type}")
150
+
151
+
152
+ def check_lines(lines: cpy.LineReturn, line_type: LineType | str) -> None:
153
+ line_type = as_line_type(line_type)
154
+
155
+ if line_type == LineType.Separate:
156
+ if TYPE_CHECKING:
157
+ lines = cast(cpy.LineReturn_Separate, lines)
158
+ if not isinstance(lines, list):
159
+ raise TypeError(f"Expected list not {type(lines)}")
160
+ for points in lines:
161
+ check_point_array(points)
162
+ elif line_type == LineType.SeparateCode:
163
+ if TYPE_CHECKING:
164
+ lines = cast(cpy.LineReturn_SeparateCode, lines)
165
+ _check_tuple_of_lists_with_same_length(lines, 2)
166
+ for i, (points, codes) in enumerate(zip(*lines)):
167
+ check_point_array(points)
168
+ check_code_array(codes)
169
+ if len(points) != len(codes):
170
+ raise ValueError(f"Points and codes have different lengths in line {i}")
171
+ elif line_type == LineType.ChunkCombinedCode:
172
+ if TYPE_CHECKING:
173
+ lines = cast(cpy.LineReturn_ChunkCombinedCode, lines)
174
+ _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False)
175
+ for chunk, (points_or_none, codes_or_none) in enumerate(zip(*lines)):
176
+ if points_or_none is not None and codes_or_none is not None:
177
+ check_point_array(points_or_none)
178
+ check_code_array(codes_or_none)
179
+ if len(points_or_none) != len(codes_or_none):
180
+ raise ValueError(f"Points and codes have different lengths in chunk {chunk}")
181
+ elif not (points_or_none is None and codes_or_none is None):
182
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
183
+ elif line_type == LineType.ChunkCombinedOffset:
184
+ if TYPE_CHECKING:
185
+ lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines)
186
+ _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False)
187
+ for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*lines)):
188
+ if points_or_none is not None and offsets_or_none is not None:
189
+ check_point_array(points_or_none)
190
+ check_offset_array(offsets_or_none)
191
+ if offsets_or_none[-1] != len(points_or_none):
192
+ raise ValueError(f"Inconsistent points and offsets in chunk {chunk}")
193
+ elif not (points_or_none is None and offsets_or_none is None):
194
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
195
+ elif line_type == LineType.ChunkCombinedNan:
196
+ if TYPE_CHECKING:
197
+ lines = cast(cpy.LineReturn_ChunkCombinedNan, lines)
198
+ _check_tuple_of_lists_with_same_length(lines, 1, allow_empty_lists=False)
199
+ for _chunk, points_or_none in enumerate(lines[0]):
200
+ if points_or_none is not None:
201
+ check_point_array(points_or_none)
202
+ else:
203
+ raise ValueError(f"Invalid LineType {line_type}")
vllm/lib/python3.10/site-packages/contourpy/types.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ # dtypes of arrays returned by ContourPy.
6
+ point_dtype = np.float64
7
+ code_dtype = np.uint8
8
+ offset_dtype = np.uint32
9
+
10
+ # Kind codes used in Matplotlib Paths.
11
+ MOVETO = 1
12
+ LINETO = 2
13
+ CLOSEPOLY = 79
vllm/lib/python3.10/site-packages/contourpy/util/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from contourpy.util._build_config import build_config
4
+
5
+ __all__ = ["build_config"]
vllm/lib/python3.10/site-packages/contourpy/util/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (297 Bytes). View file
 
vllm/lib/python3.10/site-packages/contourpy/util/__pycache__/mpl_util.cpython-310.pyc ADDED
Binary file (3.1 kB). View file
 
vllm/lib/python3.10/site-packages/contourpy/util/_build_config.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # _build_config.py.in is converted into _build_config.py during the meson build process.
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def build_config() -> dict[str, str]:
7
+ """
8
+ Return a dictionary containing build configuration settings.
9
+
10
+ All dictionary keys and values are strings, for example ``False`` is
11
+ returned as ``"False"``.
12
+
13
+ .. versionadded:: 1.1.0
14
+ """
15
+ return dict(
16
+ # Python settings
17
+ python_version="3.10",
18
+ python_install_dir=r"/usr/local/lib/python3.10/site-packages/",
19
+ python_path=r"/tmp/build-env-wg5819kv/bin/python",
20
+
21
+ # Package versions
22
+ contourpy_version="1.3.1",
23
+ meson_version="1.6.0",
24
+ mesonpy_version="0.17.1",
25
+ pybind11_version="2.13.6",
26
+
27
+ # Misc meson settings
28
+ meson_backend="ninja",
29
+ build_dir=r"/project/.mesonpy-6u_kjjys/lib/contourpy/util",
30
+ source_dir=r"/project/lib/contourpy/util",
31
+ cross_build="False",
32
+
33
+ # Build options
34
+ build_options=r"-Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md -Dvsenv=True --native-file=/project/.mesonpy-6u_kjjys/meson-python-native-file.ini",
35
+ buildtype="release",
36
+ cpp_std="c++17",
37
+ debug="False",
38
+ optimization="3",
39
+ vsenv="True",
40
+ b_ndebug="if-release",
41
+ b_vscrt="from_buildtype",
42
+
43
+ # C++ compiler
44
+ compiler_name="gcc",
45
+ compiler_version="10.2.1",
46
+ linker_id="ld.bfd",
47
+ compile_command="c++",
48
+
49
+ # Host machine
50
+ host_cpu="x86_64",
51
+ host_cpu_family="x86_64",
52
+ host_cpu_endian="little",
53
+ host_cpu_system="linux",
54
+
55
+ # Build machine, same as host machine if not a cross_build
56
+ build_cpu="x86_64",
57
+ build_cpu_family="x86_64",
58
+ build_cpu_endian="little",
59
+ build_cpu_system="linux",
60
+ )
vllm/lib/python3.10/site-packages/contourpy/util/bokeh_renderer.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from bokeh.io import export_png, export_svg, show
7
+ from bokeh.io.export import get_screenshot_as_png
8
+ from bokeh.layouts import gridplot
9
+ from bokeh.models.annotations.labels import Label
10
+ from bokeh.palettes import Category10
11
+ from bokeh.plotting import figure
12
+ import numpy as np
13
+
14
+ from contourpy.enum_util import as_fill_type, as_line_type
15
+ from contourpy.util.bokeh_util import filled_to_bokeh, lines_to_bokeh
16
+ from contourpy.util.renderer import Renderer
17
+
18
+ if TYPE_CHECKING:
19
+ from bokeh.models import GridPlot
20
+ from bokeh.palettes import Palette
21
+ from numpy.typing import ArrayLike
22
+ from selenium.webdriver.remote.webdriver import WebDriver
23
+
24
+ from contourpy import FillType, LineType
25
+ from contourpy._contourpy import FillReturn, LineReturn
26
+
27
+
28
+ class BokehRenderer(Renderer):
29
+ """Utility renderer using Bokeh to render a grid of plots over the same (x, y) range.
30
+
31
+ Args:
32
+ nrows (int, optional): Number of rows of plots, default ``1``.
33
+ ncols (int, optional): Number of columns of plots, default ``1``.
34
+ figsize (tuple(float, float), optional): Figure size in inches (assuming 100 dpi), default
35
+ ``(9, 9)``.
36
+ show_frame (bool, optional): Whether to show frame and axes ticks, default ``True``.
37
+ want_svg (bool, optional): Whether output is required in SVG format or not, default
38
+ ``False``.
39
+
40
+ Warning:
41
+ :class:`~.BokehRenderer`, unlike :class:`~.MplRenderer`, needs to be told in advance if
42
+ output to SVG format will be required later, otherwise it will assume PNG output.
43
+ """
44
+ _figures: list[figure]
45
+ _layout: GridPlot
46
+ _palette: Palette
47
+ _want_svg: bool
48
+
49
+ def __init__(
50
+ self,
51
+ nrows: int = 1,
52
+ ncols: int = 1,
53
+ figsize: tuple[float, float] = (9, 9),
54
+ show_frame: bool = True,
55
+ want_svg: bool = False,
56
+ ) -> None:
57
+ self._want_svg = want_svg
58
+ self._palette = Category10[10]
59
+
60
+ total_size = 100*np.asarray(figsize, dtype=int) # Assuming 100 dpi.
61
+
62
+ nfigures = nrows*ncols
63
+ self._figures = []
64
+ backend = "svg" if self._want_svg else "canvas"
65
+ for _ in range(nfigures):
66
+ fig = figure(output_backend=backend)
67
+ fig.xgrid.visible = False
68
+ fig.ygrid.visible = False
69
+ self._figures.append(fig)
70
+ if not show_frame:
71
+ fig.outline_line_color = None # type: ignore[assignment]
72
+ fig.axis.visible = False
73
+
74
+ self._layout = gridplot(
75
+ self._figures, ncols=ncols, toolbar_location=None, # type: ignore[arg-type]
76
+ width=total_size[0] // ncols, height=total_size[1] // nrows)
77
+
78
+ def _convert_color(self, color: str) -> str:
79
+ if isinstance(color, str) and color[0] == "C":
80
+ index = int(color[1:])
81
+ color = self._palette[index]
82
+ return color
83
+
84
+ def _get_figure(self, ax: figure | int) -> figure:
85
+ if isinstance(ax, int):
86
+ ax = self._figures[ax]
87
+ return ax
88
+
89
+ def filled(
90
+ self,
91
+ filled: FillReturn,
92
+ fill_type: FillType | str,
93
+ ax: figure | int = 0,
94
+ color: str = "C0",
95
+ alpha: float = 0.7,
96
+ ) -> None:
97
+ """Plot filled contours on a single plot.
98
+
99
+ Args:
100
+ filled (sequence of arrays): Filled contour data as returned by
101
+ :meth:`~.ContourGenerator.filled`.
102
+ fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` data as returned
103
+ by :attr:`~.ContourGenerator.fill_type`, or a string equivalent.
104
+ ax (int or Bokeh Figure, optional): Which plot to use, default ``0``.
105
+ color (str, optional): Color to plot with. May be a string color or the letter ``"C"``
106
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
107
+ ``Category10`` palette. Default ``"C0"``.
108
+ alpha (float, optional): Opacity to plot with, default ``0.7``.
109
+ """
110
+ fill_type = as_fill_type(fill_type)
111
+ fig = self._get_figure(ax)
112
+ color = self._convert_color(color)
113
+ xs, ys = filled_to_bokeh(filled, fill_type)
114
+ if len(xs) > 0:
115
+ fig.multi_polygons(xs=[xs], ys=[ys], color=color, fill_alpha=alpha, line_width=0)
116
+
117
+ def grid(
118
+ self,
119
+ x: ArrayLike,
120
+ y: ArrayLike,
121
+ ax: figure | int = 0,
122
+ color: str = "black",
123
+ alpha: float = 0.1,
124
+ point_color: str | None = None,
125
+ quad_as_tri_alpha: float = 0,
126
+ ) -> None:
127
+ """Plot quad grid lines on a single plot.
128
+
129
+ Args:
130
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
131
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
132
+ ax (int or Bokeh Figure, optional): Which plot to use, default ``0``.
133
+ color (str, optional): Color to plot grid lines, default ``"black"``.
134
+ alpha (float, optional): Opacity to plot lines with, default ``0.1``.
135
+ point_color (str, optional): Color to plot grid points or ``None`` if grid points
136
+ should not be plotted, default ``None``.
137
+ quad_as_tri_alpha (float, optional): Opacity to plot ``quad_as_tri`` grid, default
138
+ ``0``.
139
+
140
+ Colors may be a string color or the letter ``"C"`` followed by an integer in the range
141
+ ``"C0"`` to ``"C9"`` to use a color from the ``Category10`` palette.
142
+
143
+ Warning:
144
+ ``quad_as_tri_alpha > 0`` plots all quads as though they are unmasked.
145
+ """
146
+ fig = self._get_figure(ax)
147
+ x, y = self._grid_as_2d(x, y)
148
+ xs = list(x) + list(x.T)
149
+ ys = list(y) + list(y.T)
150
+ kwargs = {"line_color": color, "alpha": alpha}
151
+ fig.multi_line(xs, ys, **kwargs)
152
+ if quad_as_tri_alpha > 0:
153
+ # Assumes no quad mask.
154
+ xmid = (0.25*(x[:-1, :-1] + x[1:, :-1] + x[:-1, 1:] + x[1:, 1:])).ravel()
155
+ ymid = (0.25*(y[:-1, :-1] + y[1:, :-1] + y[:-1, 1:] + y[1:, 1:])).ravel()
156
+ fig.multi_line(
157
+ list(np.stack((x[:-1, :-1].ravel(), xmid, x[1:, 1:].ravel()), axis=1)),
158
+ list(np.stack((y[:-1, :-1].ravel(), ymid, y[1:, 1:].ravel()), axis=1)),
159
+ **kwargs)
160
+ fig.multi_line(
161
+ list(np.stack((x[:-1, 1:].ravel(), xmid, x[1:, :-1].ravel()), axis=1)),
162
+ list(np.stack((y[:-1, 1:].ravel(), ymid, y[1:, :-1].ravel()), axis=1)),
163
+ **kwargs)
164
+ if point_color is not None:
165
+ fig.scatter(
166
+ x=x.ravel(), y=y.ravel(), fill_color=color, line_color=None, alpha=alpha,
167
+ marker="circle", size=8)
168
+
169
+ def lines(
170
+ self,
171
+ lines: LineReturn,
172
+ line_type: LineType | str,
173
+ ax: figure | int = 0,
174
+ color: str = "C0",
175
+ alpha: float = 1.0,
176
+ linewidth: float = 1,
177
+ ) -> None:
178
+ """Plot contour lines on a single plot.
179
+
180
+ Args:
181
+ lines (sequence of arrays): Contour line data as returned by
182
+ :meth:`~.ContourGenerator.lines`.
183
+ line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` data as returned
184
+ by :attr:`~.ContourGenerator.line_type`, or a string equivalent.
185
+ ax (int or Bokeh Figure, optional): Which plot to use, default ``0``.
186
+ color (str, optional): Color to plot lines. May be a string color or the letter ``"C"``
187
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
188
+ ``Category10`` palette. Default ``"C0"``.
189
+ alpha (float, optional): Opacity to plot lines with, default ``1.0``.
190
+ linewidth (float, optional): Width of lines, default ``1``.
191
+
192
+ Note:
193
+ Assumes all lines are open line strips not closed line loops.
194
+ """
195
+ line_type = as_line_type(line_type)
196
+ fig = self._get_figure(ax)
197
+ color = self._convert_color(color)
198
+ xs, ys = lines_to_bokeh(lines, line_type)
199
+ if xs is not None:
200
+ fig.line(xs, ys, line_color=color, line_alpha=alpha, line_width=linewidth)
201
+
202
+ def mask(
203
+ self,
204
+ x: ArrayLike,
205
+ y: ArrayLike,
206
+ z: ArrayLike | np.ma.MaskedArray[Any, Any],
207
+ ax: figure | int = 0,
208
+ color: str = "black",
209
+ ) -> None:
210
+ """Plot masked out grid points as circles on a single plot.
211
+
212
+ Args:
213
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
214
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
215
+ z (masked array of shape (ny, nx): z-values.
216
+ ax (int or Bokeh Figure, optional): Which plot to use, default ``0``.
217
+ color (str, optional): Circle color, default ``"black"``.
218
+ """
219
+ mask = np.ma.getmask(z) # type: ignore[no-untyped-call]
220
+ if mask is np.ma.nomask:
221
+ return
222
+ fig = self._get_figure(ax)
223
+ color = self._convert_color(color)
224
+ x, y = self._grid_as_2d(x, y)
225
+ fig.scatter(x[mask], y[mask], fill_color=color, marker="circle", size=10)
226
+
227
+ def save(
228
+ self,
229
+ filename: str,
230
+ transparent: bool = False,
231
+ *,
232
+ webdriver: WebDriver | None = None,
233
+ ) -> None:
234
+ """Save plots to SVG or PNG file.
235
+
236
+ Args:
237
+ filename (str): Filename to save to.
238
+ transparent (bool, optional): Whether background should be transparent, default
239
+ ``False``.
240
+ webdriver (WebDriver, optional): Selenium WebDriver instance to use to create the image.
241
+
242
+ .. versionadded:: 1.1.1
243
+
244
+ Warning:
245
+ To output to SVG file, ``want_svg=True`` must have been passed to the constructor.
246
+ """
247
+ if transparent:
248
+ for fig in self._figures:
249
+ fig.background_fill_color = None # type: ignore[assignment]
250
+ fig.border_fill_color = None # type: ignore[assignment]
251
+
252
+ if self._want_svg:
253
+ export_svg(self._layout, filename=filename, webdriver=webdriver)
254
+ else:
255
+ export_png(self._layout, filename=filename, webdriver=webdriver)
256
+
257
+ def save_to_buffer(self, *, webdriver: WebDriver | None = None) -> io.BytesIO:
258
+ """Save plots to an ``io.BytesIO`` buffer.
259
+
260
+ Args:
261
+ webdriver (WebDriver, optional): Selenium WebDriver instance to use to create the image.
262
+
263
+ .. versionadded:: 1.1.1
264
+
265
+ Return:
266
+ BytesIO: PNG image buffer.
267
+ """
268
+ image = get_screenshot_as_png(self._layout, driver=webdriver)
269
+ buffer = io.BytesIO()
270
+ image.save(buffer, "png")
271
+ return buffer
272
+
273
+ def show(self) -> None:
274
+ """Show plots in web browser, in usual Bokeh manner.
275
+ """
276
+ show(self._layout)
277
+
278
+ def title(self, title: str, ax: figure | int = 0, color: str | None = None) -> None:
279
+ """Set the title of a single plot.
280
+
281
+ Args:
282
+ title (str): Title text.
283
+ ax (int or Bokeh Figure, optional): Which plot to set the title of, default ``0``.
284
+ color (str, optional): Color to set title. May be a string color or the letter ``"C"``
285
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
286
+ ``Category10`` palette. Default ``None`` which is ``black``.
287
+ """
288
+ fig = self._get_figure(ax)
289
+ fig.title = title # type: ignore[assignment]
290
+ fig.title.align = "center" # type: ignore[attr-defined]
291
+ if color is not None:
292
+ fig.title.text_color = self._convert_color(color) # type: ignore[attr-defined]
293
+
294
+ def z_values(
295
+ self,
296
+ x: ArrayLike,
297
+ y: ArrayLike,
298
+ z: ArrayLike,
299
+ ax: figure | int = 0,
300
+ color: str = "green",
301
+ fmt: str = ".1f",
302
+ quad_as_tri: bool = False,
303
+ ) -> None:
304
+ """Show ``z`` values on a single plot.
305
+
306
+ Args:
307
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
308
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
309
+ z (array-like of shape (ny, nx): z-values.
310
+ ax (int or Bokeh Figure, optional): Which plot to use, default ``0``.
311
+ color (str, optional): Color of added text. May be a string color or the letter ``"C"``
312
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
313
+ ``Category10`` palette. Default ``"green"``.
314
+ fmt (str, optional): Format to display z-values, default ``".1f"``.
315
+ quad_as_tri (bool, optional): Whether to show z-values at the ``quad_as_tri`` centres
316
+ of quads.
317
+
318
+ Warning:
319
+ ``quad_as_tri=True`` shows z-values for all quads, even if masked.
320
+ """
321
+ fig = self._get_figure(ax)
322
+ color = self._convert_color(color)
323
+ x, y = self._grid_as_2d(x, y)
324
+ z = np.asarray(z)
325
+ ny, nx = z.shape
326
+ kwargs = {"text_color": color, "text_align": "center", "text_baseline": "middle"}
327
+ for j in range(ny):
328
+ for i in range(nx):
329
+ fig.add_layout(Label(x=x[j, i], y=y[j, i], text=f"{z[j, i]:{fmt}}", **kwargs))
330
+ if quad_as_tri:
331
+ for j in range(ny-1):
332
+ for i in range(nx-1):
333
+ xx = np.mean(x[j:j+2, i:i+2])
334
+ yy = np.mean(y[j:j+2, i:i+2])
335
+ zz = np.mean(z[j:j+2, i:i+2])
336
+ fig.add_layout(Label(x=xx, y=yy, text=f"{zz:{fmt}}", **kwargs))
vllm/lib/python3.10/site-packages/contourpy/util/bokeh_util.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, cast
4
+
5
+ from contourpy import FillType, LineType
6
+ from contourpy.array import offsets_from_codes
7
+ from contourpy.convert import convert_lines
8
+ from contourpy.dechunk import dechunk_lines
9
+
10
+ if TYPE_CHECKING:
11
+ from contourpy._contourpy import (
12
+ CoordinateArray,
13
+ FillReturn,
14
+ LineReturn,
15
+ LineReturn_ChunkCombinedNan,
16
+ )
17
+
18
+
19
+ def filled_to_bokeh(
20
+ filled: FillReturn,
21
+ fill_type: FillType,
22
+ ) -> tuple[list[list[CoordinateArray]], list[list[CoordinateArray]]]:
23
+ xs: list[list[CoordinateArray]] = []
24
+ ys: list[list[CoordinateArray]] = []
25
+ if fill_type in (FillType.OuterOffset, FillType.ChunkCombinedOffset,
26
+ FillType.OuterCode, FillType.ChunkCombinedCode):
27
+ have_codes = fill_type in (FillType.OuterCode, FillType.ChunkCombinedCode)
28
+
29
+ for points, offsets in zip(*filled):
30
+ if points is None:
31
+ continue
32
+ if have_codes:
33
+ offsets = offsets_from_codes(offsets)
34
+ xs.append([]) # New outer with zero or more holes.
35
+ ys.append([])
36
+ for i in range(len(offsets)-1):
37
+ xys = points[offsets[i]:offsets[i+1]]
38
+ xs[-1].append(xys[:, 0])
39
+ ys[-1].append(xys[:, 1])
40
+ elif fill_type in (FillType.ChunkCombinedCodeOffset, FillType.ChunkCombinedOffsetOffset):
41
+ for points, codes_or_offsets, outer_offsets in zip(*filled):
42
+ if points is None:
43
+ continue
44
+ for j in range(len(outer_offsets)-1):
45
+ if fill_type == FillType.ChunkCombinedCodeOffset:
46
+ codes = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]]
47
+ offsets = offsets_from_codes(codes) + outer_offsets[j]
48
+ else:
49
+ offsets = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]+1]
50
+ xs.append([]) # New outer with zero or more holes.
51
+ ys.append([])
52
+ for k in range(len(offsets)-1):
53
+ xys = points[offsets[k]:offsets[k+1]]
54
+ xs[-1].append(xys[:, 0])
55
+ ys[-1].append(xys[:, 1])
56
+ else:
57
+ raise RuntimeError(f"Conversion of FillType {fill_type} to Bokeh is not implemented")
58
+
59
+ return xs, ys
60
+
61
+
62
+ def lines_to_bokeh(
63
+ lines: LineReturn,
64
+ line_type: LineType,
65
+ ) -> tuple[CoordinateArray | None, CoordinateArray | None]:
66
+ lines = convert_lines(lines, line_type, LineType.ChunkCombinedNan)
67
+ lines = dechunk_lines(lines, LineType.ChunkCombinedNan)
68
+ if TYPE_CHECKING:
69
+ lines = cast(LineReturn_ChunkCombinedNan, lines)
70
+ points = lines[0][0]
71
+ if points is None:
72
+ return None, None
73
+ else:
74
+ return points[:, 0], points[:, 1]
vllm/lib/python3.10/site-packages/contourpy/util/data.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ import numpy as np
6
+
7
+ if TYPE_CHECKING:
8
+ from contourpy._contourpy import CoordinateArray
9
+
10
+
11
+ def simple(
12
+ shape: tuple[int, int], want_mask: bool = False,
13
+ ) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]:
14
+ """Return simple test data consisting of the sum of two gaussians.
15
+
16
+ Args:
17
+ shape (tuple(int, int)): 2D shape of data to return.
18
+ want_mask (bool, optional): Whether test data should be masked or not, default ``False``.
19
+
20
+ Return:
21
+ Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if
22
+ ``want_mask=True``.
23
+ """
24
+ ny, nx = shape
25
+ x = np.arange(nx, dtype=np.float64)
26
+ y = np.arange(ny, dtype=np.float64)
27
+ x, y = np.meshgrid(x, y)
28
+
29
+ xscale = nx - 1.0
30
+ yscale = ny - 1.0
31
+
32
+ # z is sum of 2D gaussians.
33
+ amp = np.asarray([1.0, -1.0, 0.8, -0.9, 0.7])
34
+ mid = np.asarray([[0.4, 0.2], [0.3, 0.8], [0.9, 0.75], [0.7, 0.3], [0.05, 0.7]])
35
+ width = np.asarray([0.4, 0.2, 0.2, 0.2, 0.1])
36
+
37
+ z = np.zeros_like(x)
38
+ for i in range(len(amp)):
39
+ z += amp[i]*np.exp(-((x/xscale - mid[i, 0])**2 + (y/yscale - mid[i, 1])**2) / width[i]**2)
40
+
41
+ if want_mask:
42
+ mask = np.logical_or(
43
+ ((x/xscale - 1.0)**2 / 0.2 + (y/yscale - 0.0)**2 / 0.1) < 1.0,
44
+ ((x/xscale - 0.2)**2 / 0.02 + (y/yscale - 0.45)**2 / 0.08) < 1.0,
45
+ )
46
+ z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call]
47
+
48
+ return x, y, z
49
+
50
+
51
+ def random(
52
+ shape: tuple[int, int], seed: int = 2187, mask_fraction: float = 0.0,
53
+ ) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]:
54
+ """Return random test data in the range 0 to 1.
55
+
56
+ Args:
57
+ shape (tuple(int, int)): 2D shape of data to return.
58
+ seed (int, optional): Seed for random number generator, default 2187.
59
+ mask_fraction (float, optional): Fraction of elements to mask, default 0.
60
+
61
+ Return:
62
+ Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if
63
+ ``mask_fraction`` is greater than zero.
64
+ """
65
+ ny, nx = shape
66
+ x = np.arange(nx, dtype=np.float64)
67
+ y = np.arange(ny, dtype=np.float64)
68
+ x, y = np.meshgrid(x, y)
69
+
70
+ rng = np.random.default_rng(seed)
71
+ z = rng.uniform(size=shape)
72
+
73
+ if mask_fraction > 0.0:
74
+ mask_fraction = min(mask_fraction, 0.99)
75
+ mask = rng.uniform(size=shape) < mask_fraction
76
+ z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call]
77
+
78
+ return x, y, z
vllm/lib/python3.10/site-packages/contourpy/util/mpl_renderer.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from itertools import pairwise
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ import matplotlib.collections as mcollections
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+
11
+ from contourpy import FillType, LineType
12
+ from contourpy.convert import convert_filled, convert_lines
13
+ from contourpy.enum_util import as_fill_type, as_line_type
14
+ from contourpy.util.mpl_util import filled_to_mpl_paths, lines_to_mpl_paths
15
+ from contourpy.util.renderer import Renderer
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Sequence
19
+
20
+ from matplotlib.axes import Axes
21
+ from matplotlib.figure import Figure
22
+ from numpy.typing import ArrayLike
23
+
24
+ import contourpy._contourpy as cpy
25
+
26
+
27
+ class MplRenderer(Renderer):
28
+ """Utility renderer using Matplotlib to render a grid of plots over the same (x, y) range.
29
+
30
+ Args:
31
+ nrows (int, optional): Number of rows of plots, default ``1``.
32
+ ncols (int, optional): Number of columns of plots, default ``1``.
33
+ figsize (tuple(float, float), optional): Figure size in inches, default ``(9, 9)``.
34
+ show_frame (bool, optional): Whether to show frame and axes ticks, default ``True``.
35
+ backend (str, optional): Matplotlib backend to use or ``None`` for default backend.
36
+ Default ``None``.
37
+ gridspec_kw (dict, optional): Gridspec keyword arguments to pass to ``plt.subplots``,
38
+ default None.
39
+ """
40
+ _axes: Sequence[Axes]
41
+ _fig: Figure
42
+ _want_tight: bool
43
+
44
+ def __init__(
45
+ self,
46
+ nrows: int = 1,
47
+ ncols: int = 1,
48
+ figsize: tuple[float, float] = (9, 9),
49
+ show_frame: bool = True,
50
+ backend: str | None = None,
51
+ gridspec_kw: dict[str, Any] | None = None,
52
+ ) -> None:
53
+ if backend is not None:
54
+ import matplotlib as mpl
55
+ mpl.use(backend)
56
+
57
+ kwargs: dict[str, Any] = {"figsize": figsize, "squeeze": False,
58
+ "sharex": True, "sharey": True}
59
+ if gridspec_kw is not None:
60
+ kwargs["gridspec_kw"] = gridspec_kw
61
+ else:
62
+ kwargs["subplot_kw"] = {"aspect": "equal"}
63
+
64
+ self._fig, axes = plt.subplots(nrows, ncols, **kwargs)
65
+ self._axes = axes.flatten()
66
+ if not show_frame:
67
+ for ax in self._axes:
68
+ ax.axis("off")
69
+
70
+ self._want_tight = True
71
+
72
+ def __del__(self) -> None:
73
+ if hasattr(self, "_fig"):
74
+ plt.close(self._fig)
75
+
76
+ def _autoscale(self) -> None:
77
+ # Using axes._need_autoscale attribute if need to autoscale before rendering after adding
78
+ # lines/filled. Only want to autoscale once per axes regardless of how many lines/filled
79
+ # added.
80
+ for ax in self._axes:
81
+ if getattr(ax, "_need_autoscale", False):
82
+ ax.autoscale_view(tight=True)
83
+ ax._need_autoscale = False # type: ignore[attr-defined]
84
+ if self._want_tight and len(self._axes) > 1:
85
+ self._fig.tight_layout()
86
+
87
+ def _get_ax(self, ax: Axes | int) -> Axes:
88
+ if isinstance(ax, int):
89
+ ax = self._axes[ax]
90
+ return ax
91
+
92
+ def filled(
93
+ self,
94
+ filled: cpy.FillReturn,
95
+ fill_type: FillType | str,
96
+ ax: Axes | int = 0,
97
+ color: str = "C0",
98
+ alpha: float = 0.7,
99
+ ) -> None:
100
+ """Plot filled contours on a single Axes.
101
+
102
+ Args:
103
+ filled (sequence of arrays): Filled contour data as returned by
104
+ :meth:`~.ContourGenerator.filled`.
105
+ fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` data as returned
106
+ by :attr:`~.ContourGenerator.fill_type`, or string equivalent
107
+ ax (int or Maplotlib Axes, optional): Which axes to plot on, default ``0``.
108
+ color (str, optional): Color to plot with. May be a string color or the letter ``"C"``
109
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
110
+ ``tab10`` colormap. Default ``"C0"``.
111
+ alpha (float, optional): Opacity to plot with, default ``0.7``.
112
+ """
113
+ fill_type = as_fill_type(fill_type)
114
+ ax = self._get_ax(ax)
115
+ paths = filled_to_mpl_paths(filled, fill_type)
116
+ collection = mcollections.PathCollection(
117
+ paths, facecolors=color, edgecolors="none", lw=0, alpha=alpha)
118
+ ax.add_collection(collection)
119
+ ax._need_autoscale = True # type: ignore[attr-defined]
120
+
121
+ def grid(
122
+ self,
123
+ x: ArrayLike,
124
+ y: ArrayLike,
125
+ ax: Axes | int = 0,
126
+ color: str = "black",
127
+ alpha: float = 0.1,
128
+ point_color: str | None = None,
129
+ quad_as_tri_alpha: float = 0,
130
+ ) -> None:
131
+ """Plot quad grid lines on a single Axes.
132
+
133
+ Args:
134
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
135
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
136
+ ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``.
137
+ color (str, optional): Color to plot grid lines, default ``"black"``.
138
+ alpha (float, optional): Opacity to plot lines with, default ``0.1``.
139
+ point_color (str, optional): Color to plot grid points or ``None`` if grid points
140
+ should not be plotted, default ``None``.
141
+ quad_as_tri_alpha (float, optional): Opacity to plot ``quad_as_tri`` grid, default 0.
142
+
143
+ Colors may be a string color or the letter ``"C"`` followed by an integer in the range
144
+ ``"C0"`` to ``"C9"`` to use a color from the ``tab10`` colormap.
145
+
146
+ Warning:
147
+ ``quad_as_tri_alpha > 0`` plots all quads as though they are unmasked.
148
+ """
149
+ ax = self._get_ax(ax)
150
+ x, y = self._grid_as_2d(x, y)
151
+ kwargs: dict[str, Any] = {"color": color, "alpha": alpha}
152
+ ax.plot(x, y, x.T, y.T, **kwargs)
153
+ if quad_as_tri_alpha > 0:
154
+ # Assumes no quad mask.
155
+ xmid = 0.25*(x[:-1, :-1] + x[1:, :-1] + x[:-1, 1:] + x[1:, 1:])
156
+ ymid = 0.25*(y[:-1, :-1] + y[1:, :-1] + y[:-1, 1:] + y[1:, 1:])
157
+ kwargs["alpha"] = quad_as_tri_alpha
158
+ ax.plot(
159
+ np.stack((x[:-1, :-1], xmid, x[1:, 1:])).reshape((3, -1)),
160
+ np.stack((y[:-1, :-1], ymid, y[1:, 1:])).reshape((3, -1)),
161
+ np.stack((x[1:, :-1], xmid, x[:-1, 1:])).reshape((3, -1)),
162
+ np.stack((y[1:, :-1], ymid, y[:-1, 1:])).reshape((3, -1)),
163
+ **kwargs)
164
+ if point_color is not None:
165
+ ax.plot(x, y, color=point_color, alpha=alpha, marker="o", lw=0)
166
+ ax._need_autoscale = True # type: ignore[attr-defined]
167
+
168
+ def lines(
169
+ self,
170
+ lines: cpy.LineReturn,
171
+ line_type: LineType | str,
172
+ ax: Axes | int = 0,
173
+ color: str = "C0",
174
+ alpha: float = 1.0,
175
+ linewidth: float = 1,
176
+ ) -> None:
177
+ """Plot contour lines on a single Axes.
178
+
179
+ Args:
180
+ lines (sequence of arrays): Contour line data as returned by
181
+ :meth:`~.ContourGenerator.lines`.
182
+ line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` data as returned
183
+ by :attr:`~.ContourGenerator.line_type`, or string equivalent.
184
+ ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``.
185
+ color (str, optional): Color to plot lines. May be a string color or the letter ``"C"``
186
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
187
+ ``tab10`` colormap. Default ``"C0"``.
188
+ alpha (float, optional): Opacity to plot lines with, default ``1.0``.
189
+ linewidth (float, optional): Width of lines, default ``1``.
190
+ """
191
+ line_type = as_line_type(line_type)
192
+ ax = self._get_ax(ax)
193
+ paths = lines_to_mpl_paths(lines, line_type)
194
+ collection = mcollections.PathCollection(
195
+ paths, facecolors="none", edgecolors=color, lw=linewidth, alpha=alpha)
196
+ ax.add_collection(collection)
197
+ ax._need_autoscale = True # type: ignore[attr-defined]
198
+
199
+ def mask(
200
+ self,
201
+ x: ArrayLike,
202
+ y: ArrayLike,
203
+ z: ArrayLike | np.ma.MaskedArray[Any, Any],
204
+ ax: Axes | int = 0,
205
+ color: str = "black",
206
+ ) -> None:
207
+ """Plot masked out grid points as circles on a single Axes.
208
+
209
+ Args:
210
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
211
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
212
+ z (masked array of shape (ny, nx): z-values.
213
+ ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``.
214
+ color (str, optional): Circle color, default ``"black"``.
215
+ """
216
+ mask = np.ma.getmask(z) # type: ignore[no-untyped-call]
217
+ if mask is np.ma.nomask:
218
+ return
219
+ ax = self._get_ax(ax)
220
+ x, y = self._grid_as_2d(x, y)
221
+ ax.plot(x[mask], y[mask], "o", c=color)
222
+
223
+ def save(self, filename: str, transparent: bool = False) -> None:
224
+ """Save plots to SVG or PNG file.
225
+
226
+ Args:
227
+ filename (str): Filename to save to.
228
+ transparent (bool, optional): Whether background should be transparent, default
229
+ ``False``.
230
+ """
231
+ self._autoscale()
232
+ self._fig.savefig(filename, transparent=transparent)
233
+
234
+ def save_to_buffer(self) -> io.BytesIO:
235
+ """Save plots to an ``io.BytesIO`` buffer.
236
+
237
+ Return:
238
+ BytesIO: PNG image buffer.
239
+ """
240
+ self._autoscale()
241
+ buf = io.BytesIO()
242
+ self._fig.savefig(buf, format="png")
243
+ buf.seek(0)
244
+ return buf
245
+
246
+ def show(self) -> None:
247
+ """Show plots in an interactive window, in the usual Matplotlib manner.
248
+ """
249
+ self._autoscale()
250
+ plt.show()
251
+
252
+ def title(self, title: str, ax: Axes | int = 0, color: str | None = None) -> None:
253
+ """Set the title of a single Axes.
254
+
255
+ Args:
256
+ title (str): Title text.
257
+ ax (int or Matplotlib Axes, optional): Which Axes to set the title of, default ``0``.
258
+ color (str, optional): Color to set title. May be a string color or the letter ``"C"``
259
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
260
+ ``tab10`` colormap. Default is ``None`` which uses Matplotlib's default title color
261
+ that depends on the stylesheet in use.
262
+ """
263
+ if color:
264
+ self._get_ax(ax).set_title(title, color=color)
265
+ else:
266
+ self._get_ax(ax).set_title(title)
267
+
268
+ def z_values(
269
+ self,
270
+ x: ArrayLike,
271
+ y: ArrayLike,
272
+ z: ArrayLike,
273
+ ax: Axes | int = 0,
274
+ color: str = "green",
275
+ fmt: str = ".1f",
276
+ quad_as_tri: bool = False,
277
+ ) -> None:
278
+ """Show ``z`` values on a single Axes.
279
+
280
+ Args:
281
+ x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points.
282
+ y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points.
283
+ z (array-like of shape (ny, nx): z-values.
284
+ ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``.
285
+ color (str, optional): Color of added text. May be a string color or the letter ``"C"``
286
+ followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the
287
+ ``tab10`` colormap. Default ``"green"``.
288
+ fmt (str, optional): Format to display z-values, default ``".1f"``.
289
+ quad_as_tri (bool, optional): Whether to show z-values at the ``quad_as_tri`` centers
290
+ of quads.
291
+
292
+ Warning:
293
+ ``quad_as_tri=True`` shows z-values for all quads, even if masked.
294
+ """
295
+ ax = self._get_ax(ax)
296
+ x, y = self._grid_as_2d(x, y)
297
+ z = np.asarray(z)
298
+ ny, nx = z.shape
299
+ for j in range(ny):
300
+ for i in range(nx):
301
+ ax.text(x[j, i], y[j, i], f"{z[j, i]:{fmt}}", ha="center", va="center",
302
+ color=color, clip_on=True)
303
+ if quad_as_tri:
304
+ for j in range(ny-1):
305
+ for i in range(nx-1):
306
+ xx = np.mean(x[j:j+2, i:i+2])
307
+ yy = np.mean(y[j:j+2, i:i+2])
308
+ zz = np.mean(z[j:j+2, i:i+2])
309
+ ax.text(xx, yy, f"{zz:{fmt}}", ha="center", va="center", color=color,
310
+ clip_on=True)
311
+
312
+
313
+ class MplTestRenderer(MplRenderer):
314
+ """Test renderer implemented using Matplotlib.
315
+
316
+ No whitespace around plots and no spines/ticks displayed.
317
+ Uses Agg backend, so can only save to file/buffer, cannot call ``show()``.
318
+ """
319
+ def __init__(
320
+ self,
321
+ nrows: int = 1,
322
+ ncols: int = 1,
323
+ figsize: tuple[float, float] = (9, 9),
324
+ ) -> None:
325
+ gridspec = {
326
+ "left": 0.01,
327
+ "right": 0.99,
328
+ "top": 0.99,
329
+ "bottom": 0.01,
330
+ "wspace": 0.01,
331
+ "hspace": 0.01,
332
+ }
333
+ super().__init__(
334
+ nrows, ncols, figsize, show_frame=True, backend="Agg", gridspec_kw=gridspec,
335
+ )
336
+
337
+ for ax in self._axes:
338
+ ax.set_xmargin(0.0)
339
+ ax.set_ymargin(0.0)
340
+ ax.set_xticks([])
341
+ ax.set_yticks([])
342
+
343
+ self._want_tight = False
344
+
345
+
346
+ class MplDebugRenderer(MplRenderer):
347
+ """Debug renderer implemented using Matplotlib.
348
+
349
+ Extends ``MplRenderer`` to add extra information to help in debugging such as markers, arrows,
350
+ text, etc.
351
+ """
352
+ def __init__(
353
+ self,
354
+ nrows: int = 1,
355
+ ncols: int = 1,
356
+ figsize: tuple[float, float] = (9, 9),
357
+ show_frame: bool = True,
358
+ ) -> None:
359
+ super().__init__(nrows, ncols, figsize, show_frame)
360
+
361
+ def _arrow(
362
+ self,
363
+ ax: Axes,
364
+ line_start: cpy.CoordinateArray,
365
+ line_end: cpy.CoordinateArray,
366
+ color: str,
367
+ alpha: float,
368
+ arrow_size: float,
369
+ ) -> None:
370
+ mid = 0.5*(line_start + line_end)
371
+ along = line_end - line_start
372
+ along /= np.sqrt(np.dot(along, along)) # Unit vector.
373
+ right = np.asarray((along[1], -along[0]))
374
+ arrow = np.stack((
375
+ mid - (along*0.5 - right)*arrow_size,
376
+ mid + along*0.5*arrow_size,
377
+ mid - (along*0.5 + right)*arrow_size,
378
+ ))
379
+ ax.plot(arrow[:, 0], arrow[:, 1], "-", c=color, alpha=alpha)
380
+
381
+ def filled(
382
+ self,
383
+ filled: cpy.FillReturn,
384
+ fill_type: FillType | str,
385
+ ax: Axes | int = 0,
386
+ color: str = "C1",
387
+ alpha: float = 0.7,
388
+ line_color: str = "C0",
389
+ line_alpha: float = 0.7,
390
+ point_color: str = "C0",
391
+ start_point_color: str = "red",
392
+ arrow_size: float = 0.1,
393
+ ) -> None:
394
+ fill_type = as_fill_type(fill_type)
395
+ super().filled(filled, fill_type, ax, color, alpha)
396
+
397
+ if line_color is None and point_color is None:
398
+ return
399
+
400
+ ax = self._get_ax(ax)
401
+ filled = convert_filled(filled, fill_type, FillType.ChunkCombinedOffset)
402
+
403
+ # Lines.
404
+ if line_color is not None:
405
+ for points, offsets in zip(*filled):
406
+ if points is None:
407
+ continue
408
+ for start, end in pairwise(offsets):
409
+ xys = points[start:end]
410
+ ax.plot(xys[:, 0], xys[:, 1], c=line_color, alpha=line_alpha)
411
+
412
+ if arrow_size > 0.0:
413
+ n = len(xys)
414
+ for i in range(n-1):
415
+ self._arrow(ax, xys[i], xys[i+1], line_color, line_alpha, arrow_size)
416
+
417
+ # Points.
418
+ if point_color is not None:
419
+ for points, offsets in zip(*filled):
420
+ if points is None:
421
+ continue
422
+ mask = np.ones(offsets[-1], dtype=bool)
423
+ mask[offsets[1:]-1] = False # Exclude end points.
424
+ if start_point_color is not None:
425
+ start_indices = offsets[:-1]
426
+ mask[start_indices] = False # Exclude start points.
427
+ ax.plot(
428
+ points[:, 0][mask], points[:, 1][mask], "o", c=point_color, alpha=line_alpha)
429
+
430
+ if start_point_color is not None:
431
+ ax.plot(points[:, 0][start_indices], points[:, 1][start_indices], "o",
432
+ c=start_point_color, alpha=line_alpha)
433
+
434
+ def lines(
435
+ self,
436
+ lines: cpy.LineReturn,
437
+ line_type: LineType | str,
438
+ ax: Axes | int = 0,
439
+ color: str = "C0",
440
+ alpha: float = 1.0,
441
+ linewidth: float = 1,
442
+ point_color: str = "C0",
443
+ start_point_color: str = "red",
444
+ arrow_size: float = 0.1,
445
+ ) -> None:
446
+ line_type = as_line_type(line_type)
447
+ super().lines(lines, line_type, ax, color, alpha, linewidth)
448
+
449
+ if arrow_size == 0.0 and point_color is None:
450
+ return
451
+
452
+ ax = self._get_ax(ax)
453
+ separate_lines = convert_lines(lines, line_type, LineType.Separate)
454
+ if TYPE_CHECKING:
455
+ separate_lines = cast(cpy.LineReturn_Separate, separate_lines)
456
+
457
+ if arrow_size > 0.0:
458
+ for line in separate_lines:
459
+ for i in range(len(line)-1):
460
+ self._arrow(ax, line[i], line[i+1], color, alpha, arrow_size)
461
+
462
+ if point_color is not None:
463
+ for line in separate_lines:
464
+ start_index = 0
465
+ end_index = len(line)
466
+ if start_point_color is not None:
467
+ ax.plot(line[0, 0], line[0, 1], "o", c=start_point_color, alpha=alpha)
468
+ start_index = 1
469
+ if line[0][0] == line[-1][0] and line[0][1] == line[-1][1]:
470
+ end_index -= 1
471
+ ax.plot(line[start_index:end_index, 0], line[start_index:end_index, 1], "o",
472
+ c=color, alpha=alpha)
473
+
474
+ def point_numbers(
475
+ self,
476
+ x: ArrayLike,
477
+ y: ArrayLike,
478
+ z: ArrayLike,
479
+ ax: Axes | int = 0,
480
+ color: str = "red",
481
+ ) -> None:
482
+ ax = self._get_ax(ax)
483
+ x, y = self._grid_as_2d(x, y)
484
+ z = np.asarray(z)
485
+ ny, nx = z.shape
486
+ for j in range(ny):
487
+ for i in range(nx):
488
+ quad = i + j*nx
489
+ ax.text(x[j, i], y[j, i], str(quad), ha="right", va="top", color=color,
490
+ clip_on=True)
491
+
492
+ def quad_numbers(
493
+ self,
494
+ x: ArrayLike,
495
+ y: ArrayLike,
496
+ z: ArrayLike,
497
+ ax: Axes | int = 0,
498
+ color: str = "blue",
499
+ ) -> None:
500
+ ax = self._get_ax(ax)
501
+ x, y = self._grid_as_2d(x, y)
502
+ z = np.asarray(z)
503
+ ny, nx = z.shape
504
+ for j in range(1, ny):
505
+ for i in range(1, nx):
506
+ quad = i + j*nx
507
+ xmid = x[j-1:j+1, i-1:i+1].mean()
508
+ ymid = y[j-1:j+1, i-1:i+1].mean()
509
+ ax.text(xmid, ymid, str(quad), ha="center", va="center", color=color, clip_on=True)
510
+
511
+ def z_levels(
512
+ self,
513
+ x: ArrayLike,
514
+ y: ArrayLike,
515
+ z: ArrayLike,
516
+ lower_level: float,
517
+ upper_level: float | None = None,
518
+ ax: Axes | int = 0,
519
+ color: str = "green",
520
+ ) -> None:
521
+ ax = self._get_ax(ax)
522
+ x, y = self._grid_as_2d(x, y)
523
+ z = np.asarray(z)
524
+ ny, nx = z.shape
525
+ for j in range(ny):
526
+ for i in range(nx):
527
+ zz = z[j, i]
528
+ if upper_level is not None and zz > upper_level:
529
+ z_level = 2
530
+ elif zz > lower_level:
531
+ z_level = 1
532
+ else:
533
+ z_level = 0
534
+ ax.text(x[j, i], y[j, i], str(z_level), ha="left", va="bottom", color=color,
535
+ clip_on=True)
vllm/lib/python3.10/site-packages/contourpy/util/mpl_util.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from itertools import pairwise
4
+ from typing import TYPE_CHECKING, cast
5
+
6
+ import matplotlib.path as mpath
7
+ import numpy as np
8
+
9
+ from contourpy import FillType, LineType
10
+ from contourpy.array import codes_from_offsets
11
+
12
+ if TYPE_CHECKING:
13
+ from contourpy._contourpy import FillReturn, LineReturn, LineReturn_Separate
14
+
15
+
16
+ def filled_to_mpl_paths(filled: FillReturn, fill_type: FillType) -> list[mpath.Path]:
17
+ if fill_type in (FillType.OuterCode, FillType.ChunkCombinedCode):
18
+ paths = [mpath.Path(points, codes) for points, codes in zip(*filled) if points is not None]
19
+ elif fill_type in (FillType.OuterOffset, FillType.ChunkCombinedOffset):
20
+ paths = [mpath.Path(points, codes_from_offsets(offsets))
21
+ for points, offsets in zip(*filled) if points is not None]
22
+ elif fill_type == FillType.ChunkCombinedCodeOffset:
23
+ paths = []
24
+ for points, codes, outer_offsets in zip(*filled):
25
+ if points is None:
26
+ continue
27
+ points = np.split(points, outer_offsets[1:-1])
28
+ codes = np.split(codes, outer_offsets[1:-1])
29
+ paths += [mpath.Path(p, c) for p, c in zip(points, codes)]
30
+ elif fill_type == FillType.ChunkCombinedOffsetOffset:
31
+ paths = []
32
+ for points, offsets, outer_offsets in zip(*filled):
33
+ if points is None:
34
+ continue
35
+ for i in range(len(outer_offsets)-1):
36
+ offs = offsets[outer_offsets[i]:outer_offsets[i+1]+1]
37
+ pts = points[offs[0]:offs[-1]]
38
+ paths += [mpath.Path(pts, codes_from_offsets(offs - offs[0]))]
39
+ else:
40
+ raise RuntimeError(f"Conversion of FillType {fill_type} to MPL Paths is not implemented")
41
+ return paths
42
+
43
+
44
+ def lines_to_mpl_paths(lines: LineReturn, line_type: LineType) -> list[mpath.Path]:
45
+ if line_type == LineType.Separate:
46
+ if TYPE_CHECKING:
47
+ lines = cast(LineReturn_Separate, lines)
48
+ paths = []
49
+ for line in lines:
50
+ # Drawing as Paths so that they can be closed correctly.
51
+ closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1]
52
+ paths.append(mpath.Path(line, closed=closed))
53
+ elif line_type in (LineType.SeparateCode, LineType.ChunkCombinedCode):
54
+ paths = [mpath.Path(points, codes) for points, codes in zip(*lines) if points is not None]
55
+ elif line_type == LineType.ChunkCombinedOffset:
56
+ paths = []
57
+ for points, offsets in zip(*lines):
58
+ if points is None:
59
+ continue
60
+ for i in range(len(offsets)-1):
61
+ line = points[offsets[i]:offsets[i+1]]
62
+ closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1]
63
+ paths.append(mpath.Path(line, closed=closed))
64
+ elif line_type == LineType.ChunkCombinedNan:
65
+ paths = []
66
+ for points in lines[0]:
67
+ if points is None:
68
+ continue
69
+ nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0]
70
+ nan_offsets = np.concatenate([[-1], nan_offsets, [len(points)]])
71
+ for s, e in pairwise(nan_offsets):
72
+ line = points[s+1:e]
73
+ closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1]
74
+ paths.append(mpath.Path(line, closed=closed))
75
+ else:
76
+ raise RuntimeError(f"Conversion of LineType {line_type} to MPL Paths is not implemented")
77
+ return paths
vllm/lib/python3.10/site-packages/contourpy/util/renderer.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ import numpy as np
7
+
8
+ if TYPE_CHECKING:
9
+ import io
10
+
11
+ from numpy.typing import ArrayLike
12
+
13
+ from contourpy._contourpy import CoordinateArray, FillReturn, FillType, LineReturn, LineType
14
+
15
+
16
+ class Renderer(ABC):
17
+ """Abstract base class for renderers."""
18
+
19
+ def _grid_as_2d(self, x: ArrayLike, y: ArrayLike) -> tuple[CoordinateArray, CoordinateArray]:
20
+ x = np.asarray(x)
21
+ y = np.asarray(y)
22
+ if x.ndim == 1:
23
+ x, y = np.meshgrid(x, y)
24
+ return x, y
25
+
26
+ @abstractmethod
27
+ def filled(
28
+ self,
29
+ filled: FillReturn,
30
+ fill_type: FillType | str,
31
+ ax: Any = 0,
32
+ color: str = "C0",
33
+ alpha: float = 0.7,
34
+ ) -> None:
35
+ pass
36
+
37
+ @abstractmethod
38
+ def grid(
39
+ self,
40
+ x: ArrayLike,
41
+ y: ArrayLike,
42
+ ax: Any = 0,
43
+ color: str = "black",
44
+ alpha: float = 0.1,
45
+ point_color: str | None = None,
46
+ quad_as_tri_alpha: float = 0,
47
+ ) -> None:
48
+ pass
49
+
50
+ @abstractmethod
51
+ def lines(
52
+ self,
53
+ lines: LineReturn,
54
+ line_type: LineType | str,
55
+ ax: Any = 0,
56
+ color: str = "C0",
57
+ alpha: float = 1.0,
58
+ linewidth: float = 1,
59
+ ) -> None:
60
+ pass
61
+
62
+ @abstractmethod
63
+ def mask(
64
+ self,
65
+ x: ArrayLike,
66
+ y: ArrayLike,
67
+ z: ArrayLike | np.ma.MaskedArray[Any, Any],
68
+ ax: Any = 0,
69
+ color: str = "black",
70
+ ) -> None:
71
+ pass
72
+
73
+ def multi_filled(
74
+ self,
75
+ multi_filled: list[FillReturn],
76
+ fill_type: FillType | str,
77
+ ax: Any = 0,
78
+ color: str | None = None,
79
+ **kwargs: Any,
80
+ ) -> None:
81
+ """Plot multiple sets of filled contours on a single axes.
82
+
83
+ Args:
84
+ multi_filled (list of filled contour arrays): Multiple filled contour sets as returned
85
+ by :meth:`.ContourGenerator.multi_filled`.
86
+ fill_type (FillType or str): Type of filled data as returned by
87
+ :attr:`~.ContourGenerator.fill_type`, or string equivalent.
88
+ ax (int or Renderer-specific axes or figure object, optional): Which axes to plot on,
89
+ default ``0``.
90
+ color (str or None, optional): If a string color then this same color is used for all
91
+ filled contours. If ``None``, the default, then the filled contour sets use colors
92
+ from the ``tab10`` colormap in order, wrapping around to the beginning if more than
93
+ 10 sets of filled contours are rendered.
94
+ kwargs: All other keyword argument are passed on to
95
+ :meth:`.Renderer.filled` unchanged.
96
+
97
+ .. versionadded:: 1.3.0
98
+ """
99
+ if color is not None:
100
+ kwargs["color"] = color
101
+ for i, filled in enumerate(multi_filled):
102
+ if color is None:
103
+ kwargs["color"] = f"C{i % 10}"
104
+ self.filled(filled, fill_type, ax, **kwargs)
105
+
106
+ def multi_lines(
107
+ self,
108
+ multi_lines: list[LineReturn],
109
+ line_type: LineType | str,
110
+ ax: Any = 0,
111
+ color: str | None = None,
112
+ **kwargs: Any,
113
+ ) -> None:
114
+ """Plot multiple sets of contour lines on a single axes.
115
+
116
+ Args:
117
+ multi_lines (list of contour line arrays): Multiple contour line sets as returned by
118
+ :meth:`.ContourGenerator.multi_lines`.
119
+ line_type (LineType or str): Type of line data as returned by
120
+ :attr:`~.ContourGenerator.line_type`, or string equivalent.
121
+ ax (int or Renderer-specific axes or figure object, optional): Which axes to plot on,
122
+ default ``0``.
123
+ color (str or None, optional): If a string color then this same color is used for all
124
+ lines. If ``None``, the default, then the line sets use colors from the ``tab10``
125
+ colormap in order, wrapping around to the beginning if more than 10 sets of lines
126
+ are rendered.
127
+ kwargs: All other keyword argument are passed on to
128
+ :meth:`Renderer.lines` unchanged.
129
+
130
+ .. versionadded:: 1.3.0
131
+ """
132
+ if color is not None:
133
+ kwargs["color"] = color
134
+ for i, lines in enumerate(multi_lines):
135
+ if color is None:
136
+ kwargs["color"] = f"C{i % 10}"
137
+ self.lines(lines, line_type, ax, **kwargs)
138
+
139
+ @abstractmethod
140
+ def save(self, filename: str, transparent: bool = False) -> None:
141
+ pass
142
+
143
+ @abstractmethod
144
+ def save_to_buffer(self) -> io.BytesIO:
145
+ pass
146
+
147
+ @abstractmethod
148
+ def show(self) -> None:
149
+ pass
150
+
151
+ @abstractmethod
152
+ def title(self, title: str, ax: Any = 0, color: str | None = None) -> None:
153
+ pass
154
+
155
+ @abstractmethod
156
+ def z_values(
157
+ self,
158
+ x: ArrayLike,
159
+ y: ArrayLike,
160
+ z: ArrayLike,
161
+ ax: Any = 0,
162
+ color: str = "green",
163
+ fmt: str = ".1f",
164
+ quad_as_tri: bool = False,
165
+ ) -> None:
166
+ pass
vllm/lib/python3.10/site-packages/freetype/__init__.py ADDED
@@ -0,0 +1,2413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ '''
9
+ FreeType high-level python API
10
+
11
+ This the bindings for the high-level API of FreeType (that must be installed
12
+ somewhere on your system).
13
+
14
+ Note: C Library will be searched using the ctypes.util.find_library. However,
15
+ this search might fail. In such a case (or for other reasons), you may
16
+ have to specify an explicit path below.
17
+ '''
18
+ import io
19
+ import sys
20
+ from ctypes import *
21
+ import ctypes.util
22
+ import struct
23
+
24
+ from freetype.raw import *
25
+
26
+ # Hack to get unicode class in python3
27
+ PY3 = sys.version_info[0] == 3
28
+ if PY3: unicode = str
29
+
30
+
31
+ def unmake_tag(i):
32
+ # roughly opposite of FT_MAKE_TAG, converts 32-bit int to Python string
33
+ # could do with .to_bytes if limited to Python 3.2 or higher...
34
+ b = struct.pack('>I', i)
35
+ return b.decode('ascii', errors='replace')
36
+
37
+ _handle = None
38
+
39
+
40
+ FT_Library_filename = filename
41
+
42
+ class _FT_Library_Wrapper(FT_Library):
43
+ '''Subclass of FT_Library to help with calling FT_Done_FreeType'''
44
+ # for some reason this doesn't get carried over and ctypes complains
45
+ _type_ = FT_Library._type_
46
+
47
+ # Store ref to FT_Done_FreeType otherwise it will be deleted before needed.
48
+ _ft_done_freetype = FT_Done_FreeType
49
+
50
+ def __del__(self):
51
+ # call FT_Done_FreeType
52
+ # This does not work properly (seg fault on sime system (OSX))
53
+ # self._ft_done_freetype(self)
54
+ pass
55
+
56
+
57
+ def _init_freetype():
58
+ global _handle
59
+
60
+ _handle = _FT_Library_Wrapper()
61
+ error = FT_Init_FreeType( byref(_handle) )
62
+
63
+ if error: raise FT_Exception(error)
64
+
65
+ try:
66
+ set_lcd_filter( FT_LCD_FILTER_DEFAULT )
67
+ except:
68
+ pass
69
+
70
+ # -----------------------------------------------------------------------------
71
+ # High-level API of FreeType 2
72
+ # -----------------------------------------------------------------------------
73
+
74
+
75
+ def get_handle():
76
+ '''
77
+ Get unique FT_Library handle
78
+ '''
79
+
80
+ if not _handle:
81
+ _init_freetype()
82
+
83
+ return _handle
84
+
85
+ def version():
86
+ '''
87
+ Return the version of the FreeType library being used as a tuple of
88
+ ( major version number, minor version number, patch version number )
89
+ '''
90
+ amajor = FT_Int()
91
+ aminor = FT_Int()
92
+ apatch = FT_Int()
93
+
94
+ library = get_handle()
95
+ FT_Library_Version(library, byref(amajor), byref(aminor), byref(apatch))
96
+ return (amajor.value, aminor.value, apatch.value)
97
+
98
+
99
+ # -----------------------------------------------------------------------------
100
+ # Stand alone functions
101
+ # -----------------------------------------------------------------------------
102
+ def set_lcd_filter(filt):
103
+ '''
104
+ This function is used to apply color filtering to LCD decimated bitmaps,
105
+ like the ones used when calling FT_Render_Glyph with FT_RENDER_MODE_LCD or
106
+ FT_RENDER_MODE_LCD_V.
107
+
108
+ **Note**
109
+
110
+ This feature is always disabled by default. Clients must make an explicit
111
+ call to this function with a 'filter' value other than FT_LCD_FILTER_NONE
112
+ in order to enable it.
113
+
114
+ Due to PATENTS covering subpixel rendering, this function doesn't do
115
+ anything except returning 'FT_Err_Unimplemented_Feature' if the
116
+ configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not defined in
117
+ your build of the library, which should correspond to all default builds of
118
+ FreeType.
119
+
120
+ The filter affects glyph bitmaps rendered through FT_Render_Glyph,
121
+ FT_Outline_Get_Bitmap, FT_Load_Glyph, and FT_Load_Char.
122
+
123
+ It does not affect the output of FT_Outline_Render and
124
+ FT_Outline_Get_Bitmap.
125
+
126
+ If this feature is activated, the dimensions of LCD glyph bitmaps are
127
+ either larger or taller than the dimensions of the corresponding outline
128
+ with regards to the pixel grid. For example, for FT_RENDER_MODE_LCD, the
129
+ filter adds up to 3 pixels to the left, and up to 3 pixels to the right.
130
+
131
+ The bitmap offset values are adjusted correctly, so clients shouldn't need
132
+ to modify their layout and glyph positioning code when enabling the filter.
133
+ '''
134
+ library = get_handle()
135
+ error = FT_Library_SetLcdFilter(library, filt)
136
+ if error: raise FT_Exception(error)
137
+
138
+
139
+
140
+ def set_lcd_filter_weights(a,b,c,d,e):
141
+ '''
142
+ Use this function to override the filter weights selected by
143
+ FT_Library_SetLcdFilter. By default, FreeType uses the quintuple (0x00,
144
+ 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, 0x40, 0x70,
145
+ 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and FT_LCD_FILTER_LEGACY.
146
+
147
+ **Note**
148
+
149
+ Only available if version > 2.4.0
150
+ '''
151
+ if version()>=(2,4,0):
152
+ library = get_handle()
153
+ weights = FT_Char(5)(a,b,c,d,e)
154
+ error = FT_Library_SetLcdFilterWeights(library, weights)
155
+ if error: raise FT_Exception(error)
156
+ else:
157
+ raise RuntimeError(
158
+ 'set_lcd_filter_weights require freetype > 2.4.0')
159
+
160
+
161
+ def _encode_filename(filename):
162
+ encoded = filename.encode(sys.getfilesystemencoding())
163
+ if "?" not in filename and b"?" in encoded:
164
+ # A bug, decoding mbcs always ignore exception, still isn't fixed in Python 2,
165
+ # view http://bugs.python.org/issue850997 for detail
166
+ raise UnicodeError()
167
+ return encoded
168
+
169
+
170
+
171
+ # -----------------------------------------------------------------------------
172
+ # Direct wrapper (simple renaming)
173
+ # -----------------------------------------------------------------------------
174
+ Vector = FT_Vector
175
+ Matrix = FT_Matrix
176
+
177
+
178
+ # -----------------------------------------------------------------------------
179
+ # Handling for FT_Done_MM_Var, which was added in FreeType 2.9. Prior to that,
180
+ # we need to import libc and use libc free on the memory allocated for the
181
+ # FT_MM_Var data structure. See Face.get_variation_info().
182
+ # -----------------------------------------------------------------------------
183
+ if version() < (2,9,1):
184
+ if platform.system() == "Windows":
185
+ libcpath = ctypes.util.find_library("msvcrt")
186
+ else:
187
+ libcpath = ctypes.util.find_library("c")
188
+ libc = CDLL(libcpath)
189
+ libc.free.argtypes = [c_void_p]
190
+ libc.free.restype = None
191
+
192
+ def FT_Done_MM_Var_func(p):
193
+ libc.free(p)
194
+ else:
195
+ def FT_Done_MM_Var_func(p):
196
+ error = FT_Done_MM_Var(get_handle(), p)
197
+ if error:
198
+ raise FT_Exception("Failure calling FT_Done_MM_Var")
199
+
200
+
201
+ # -----------------------------------------------------------------------------
202
+ class BBox( object ):
203
+ '''
204
+ FT_BBox wrapper.
205
+
206
+ A structure used to hold an outline's bounding box, i.e., the coordinates
207
+ of its extrema in the horizontal and vertical directions.
208
+
209
+ **Note**
210
+
211
+ The bounding box is specified with the coordinates of the lower left and
212
+ the upper right corner. In PostScript, those values are often called
213
+ (llx,lly) and (urx,ury), respectively.
214
+
215
+ If 'yMin' is negative, this value gives the glyph's descender. Otherwise,
216
+ the glyph doesn't descend below the baseline. Similarly, if 'ymax' is
217
+ positive, this value gives the glyph's ascender.
218
+
219
+ 'xMin' gives the horizontal distance from the glyph's origin to the left
220
+ edge of the glyph's bounding box. If 'xMin' is negative, the glyph
221
+ extends to the left of the origin.
222
+ '''
223
+
224
+ def __init__(self, bbox):
225
+ '''
226
+ Create a new BBox object.
227
+
228
+ :param bbox: a FT_BBox or a tuple of 4 values
229
+ '''
230
+ if type(bbox) is FT_BBox:
231
+ self._FT_BBox = bbox
232
+ else:
233
+ self._FT_BBox = FT_BBox(*bbox)
234
+
235
+ xMin = property(lambda self: self._FT_BBox.xMin,
236
+ doc = 'The horizontal minimum (left-most).')
237
+
238
+ yMin = property(lambda self: self._FT_BBox.yMin,
239
+ doc = 'The vertical minimum (bottom-most).')
240
+
241
+ xMax = property(lambda self: self._FT_BBox.xMax,
242
+ doc = 'The horizontal maximum (right-most).')
243
+
244
+ yMax = property(lambda self: self._FT_BBox.yMax,
245
+ doc = 'The vertical maximum (top-most).')
246
+
247
+
248
+
249
+
250
+
251
+ # -----------------------------------------------------------------------------
252
+ class GlyphMetrics( object ):
253
+ '''
254
+
255
+ A structure used to model the metrics of a single glyph. The values are
256
+ expressed in 26.6 fractional pixel format; if the flag FT_LOAD_NO_SCALE has
257
+ been used while loading the glyph, values are expressed in font units
258
+ instead.
259
+
260
+ **Note**
261
+
262
+ If not disabled with FT_LOAD_NO_HINTING, the values represent dimensions of
263
+ the hinted glyph (in case hinting is applicable).
264
+
265
+ Stroking a glyph with an outside border does not increase ‘horiAdvance’ or
266
+ ‘vertAdvance’; you have to manually adjust these values to account for the
267
+ added width and height.
268
+ '''
269
+
270
+ def __init__(self, metrics ):
271
+ '''
272
+ Create a new GlyphMetrics object.
273
+
274
+ :param metrics: a FT_Glyph_Metrics
275
+ '''
276
+ self._FT_Glyph_Metrics = metrics
277
+
278
+ width = property( lambda self: self._FT_Glyph_Metrics.width,
279
+ doc = '''The glyph's width.''' )
280
+
281
+ height = property( lambda self: self._FT_Glyph_Metrics.height,
282
+ doc = '''The glyph's height.''' )
283
+
284
+ horiBearingX = property( lambda self: self._FT_Glyph_Metrics.horiBearingX,
285
+ doc = '''Left side bearing for horizontal layout.''' )
286
+
287
+ horiBearingY = property( lambda self: self._FT_Glyph_Metrics.horiBearingY,
288
+ doc = '''Top side bearing for horizontal layout.''' )
289
+
290
+ horiAdvance = property( lambda self: self._FT_Glyph_Metrics.horiAdvance,
291
+ doc = '''Advance width for horizontal layout.''' )
292
+
293
+ vertBearingX = property( lambda self: self._FT_Glyph_Metrics.vertBearingX,
294
+ doc = '''Left side bearing for vertical layout.''' )
295
+
296
+ vertBearingY = property( lambda self: self._FT_Glyph_Metrics.vertBearingY,
297
+ doc = '''Top side bearing for vertical layout. Larger positive values
298
+ mean further below the vertical glyph origin.''' )
299
+
300
+ vertAdvance = property( lambda self: self._FT_Glyph_Metrics.vertAdvance,
301
+ doc = '''Advance height for vertical layout. Positive values mean the
302
+ glyph has a positive advance downward.''' )
303
+
304
+
305
+ # -----------------------------------------------------------------------------
306
+ class SizeMetrics( object ):
307
+ '''
308
+ The size metrics structure gives the metrics of a size object.
309
+
310
+ **Note**
311
+
312
+ The scaling values, if relevant, are determined first during a size
313
+ changing operation. The remaining fields are then set by the driver. For
314
+ scalable formats, they are usually set to scaled values of the
315
+ corresponding fields in Face.
316
+
317
+ Note that due to glyph hinting, these values might not be exact for certain
318
+ fonts. Thus they must be treated as unreliable with an error margin of at
319
+ least one pixel!
320
+
321
+ Indeed, the only way to get the exact metrics is to render all glyphs. As
322
+ this would be a definite performance hit, it is up to client applications
323
+ to perform such computations.
324
+
325
+ The SizeMetrics structure is valid for bitmap fonts also.
326
+ '''
327
+
328
+ def __init__(self, metrics ):
329
+ '''
330
+ Create a new SizeMetrics object.
331
+
332
+ :param metrics: a FT_SizeMetrics
333
+ '''
334
+ self._FT_Size_Metrics = metrics
335
+
336
+ x_ppem = property( lambda self: self._FT_Size_Metrics.x_ppem,
337
+ doc = '''The width of the scaled EM square in pixels, hence the term
338
+ 'ppem' (pixels per EM). It is also referred to as 'nominal
339
+ width'.''' )
340
+
341
+ y_ppem = property( lambda self: self._FT_Size_Metrics.y_ppem,
342
+ doc = '''The height of the scaled EM square in pixels, hence the term
343
+ 'ppem' (pixels per EM). It is also referred to as 'nominal
344
+ height'.''' )
345
+
346
+ x_scale = property( lambda self: self._FT_Size_Metrics.x_scale,
347
+ doc = '''A 16.16 fractional scaling value used to convert horizontal
348
+ metrics from font units to 26.6 fractional pixels. Only
349
+ relevant for scalable font formats.''' )
350
+
351
+ y_scale = property( lambda self: self._FT_Size_Metrics.y_scale,
352
+ doc = '''A 16.16 fractional scaling value used to convert vertical
353
+ metrics from font units to 26.6 fractional pixels. Only
354
+ relevant for scalable font formats.''' )
355
+
356
+ ascender = property( lambda self: self._FT_Size_Metrics.ascender,
357
+ doc = '''The ascender in 26.6 fractional pixels. See Face for the
358
+ details.''' )
359
+
360
+ descender = property( lambda self: self._FT_Size_Metrics.descender,
361
+ doc = '''The descender in 26.6 fractional pixels. See Face for the
362
+ details.''' )
363
+
364
+ height = property( lambda self: self._FT_Size_Metrics.height,
365
+ doc = '''The height in 26.6 fractional pixels. See Face for the details.''' )
366
+
367
+ max_advance = property(lambda self: self._FT_Size_Metrics.max_advance,
368
+ doc = '''The maximal advance width in 26.6 fractional pixels. See
369
+ Face for the details.''' )
370
+
371
+
372
+
373
+ # -----------------------------------------------------------------------------
374
+ class BitmapSize( object ):
375
+ '''
376
+ FT_Bitmap_Size wrapper
377
+
378
+ This structure models the metrics of a bitmap strike (i.e., a set of glyphs
379
+ for a given point size and resolution) in a bitmap font. It is used for the
380
+ 'available_sizes' field of Face.
381
+
382
+ **Note**
383
+
384
+ Windows FNT: The nominal size given in a FNT font is not reliable. Thus
385
+ when the driver finds it incorrect, it sets 'size' to some calculated
386
+ values and sets 'x_ppem' and 'y_ppem' to the pixel width and height given
387
+ in the font, respectively.
388
+
389
+ TrueType embedded bitmaps: 'size', 'width', and 'height' values are not
390
+ contained in the bitmap strike itself. They are computed from the global
391
+ font parameters.
392
+ '''
393
+ def __init__(self, size ):
394
+ '''
395
+ Create a new SizeMetrics object.
396
+
397
+ :param size: a FT_Bitmap_Size
398
+ '''
399
+ self._FT_Bitmap_Size = size
400
+
401
+ height = property( lambda self: self._FT_Bitmap_Size.height,
402
+ doc = '''The vertical distance, in pixels, between two consecutive
403
+ baselines. It is always positive.''')
404
+
405
+ width = property( lambda self: self._FT_Bitmap_Size.width,
406
+ doc = '''The average width, in pixels, of all glyphs in the strike.''')
407
+
408
+ size = property( lambda self: self._FT_Bitmap_Size.size,
409
+ doc = '''The nominal size of the strike in 26.6 fractional points. This
410
+ field is not very useful.''')
411
+
412
+ x_ppem = property( lambda self: self._FT_Bitmap_Size.x_ppem,
413
+ doc = '''The horizontal ppem (nominal width) in 26.6 fractional
414
+ pixels.''')
415
+
416
+ y_ppem = property( lambda self: self._FT_Bitmap_Size.y_ppem,
417
+ doc = '''The vertical ppem (nominal width) in 26.6 fractional
418
+ pixels.''')
419
+
420
+
421
+ # -----------------------------------------------------------------------------
422
+ class Bitmap(object):
423
+ '''
424
+ FT_Bitmap wrapper
425
+
426
+ A structure used to describe a bitmap or pixmap to the raster. Note that we
427
+ now manage pixmaps of various depths through the 'pixel_mode' field.
428
+
429
+ *Note*:
430
+
431
+ For now, the only pixel modes supported by FreeType are mono and
432
+ grays. However, drivers might be added in the future to support more
433
+ 'colorful' options.
434
+ '''
435
+ def __init__(self, bitmap):
436
+ '''
437
+ Create a new Bitmap object.
438
+
439
+ :param bitmap: a FT_Bitmap
440
+ '''
441
+ self._FT_Bitmap = bitmap
442
+
443
+ rows = property(lambda self: self._FT_Bitmap.rows,
444
+ doc = '''The number of bitmap rows.''')
445
+
446
+ width = property(lambda self: self._FT_Bitmap.width,
447
+ doc = '''The number of pixels in bitmap row.''')
448
+
449
+ pitch = property(lambda self: self._FT_Bitmap.pitch,
450
+ doc = '''The pitch's absolute value is the number of bytes taken by one
451
+ bitmap row, including padding. However, the pitch is positive
452
+ when the bitmap has a 'down' flow, and negative when it has an
453
+ 'up' flow. In all cases, the pitch is an offset to add to a
454
+ bitmap pointer in order to go down one row.
455
+
456
+ Note that 'padding' means the alignment of a bitmap to a byte
457
+ border, and FreeType functions normally align to the smallest
458
+ possible integer value.
459
+
460
+ For the B/W rasterizer, 'pitch' is always an even number.
461
+
462
+ To change the pitch of a bitmap (say, to make it a multiple of
463
+ 4), use FT_Bitmap_Convert. Alternatively, you might use callback
464
+ functions to directly render to the application's surface; see
465
+ the file 'example2.py' in the tutorial for a demonstration.''')
466
+
467
+ def _get_buffer(self):
468
+ data = [self._FT_Bitmap.buffer[i] for i in range(self.rows*self.pitch)]
469
+ return data
470
+ buffer = property(_get_buffer,
471
+ doc = '''A typeless pointer to the bitmap buffer. This value should be
472
+ aligned on 32-bit boundaries in most cases.''')
473
+
474
+ num_grays = property(lambda self: self._FT_Bitmap.num_grays,
475
+ doc = '''This field is only used with FT_PIXEL_MODE_GRAY; it gives
476
+ the number of gray levels used in the bitmap.''')
477
+
478
+ pixel_mode = property(lambda self: self._FT_Bitmap.pixel_mode,
479
+ doc = '''The pixel mode, i.e., how pixel bits are stored. See
480
+ FT_Pixel_Mode for possible values.''')
481
+
482
+ palette_mode = property(lambda self: self._FT_Bitmap.palette_mode,
483
+ doc ='''This field is intended for paletted pixel modes; it
484
+ indicates how the palette is stored. Not used currently.''')
485
+
486
+ palette = property(lambda self: self._FT_Bitmap.palette,
487
+ doc = '''A typeless pointer to the bitmap palette; this field is
488
+ intended for paletted pixel modes. Not used currently.''')
489
+
490
+
491
+
492
+
493
+ # -----------------------------------------------------------------------------
494
+ class Charmap( object ):
495
+ '''
496
+ FT_Charmap wrapper.
497
+
498
+ A handle to a given character map. A charmap is used to translate character
499
+ codes in a given encoding into glyph indexes for its parent's face. Some
500
+ font formats may provide several charmaps per font.
501
+
502
+ Each face object owns zero or more charmaps, but only one of them can be
503
+ 'active' and used by FT_Get_Char_Index or FT_Load_Char.
504
+
505
+ The list of available charmaps in a face is available through the
506
+ 'face.num_charmaps' and 'face.charmaps' fields of FT_FaceRec.
507
+
508
+ The currently active charmap is available as 'face.charmap'. You should
509
+ call FT_Set_Charmap to change it.
510
+
511
+ **Note**:
512
+
513
+ When a new face is created (either through FT_New_Face or FT_Open_Face),
514
+ the library looks for a Unicode charmap within the list and automatically
515
+ activates it.
516
+
517
+ **See also**:
518
+
519
+ See FT_CharMapRec for the publicly accessible fields of a given character
520
+ map.
521
+ '''
522
+
523
+ def __init__( self, charmap ):
524
+ '''
525
+ Create a new Charmap object.
526
+
527
+ Parameters:
528
+ -----------
529
+ charmap : a FT_Charmap
530
+ '''
531
+ self._FT_Charmap = charmap
532
+
533
+ encoding = property( lambda self: self._FT_Charmap.contents.encoding,
534
+ doc = '''An FT_Encoding tag identifying the charmap. Use this with
535
+ FT_Select_Charmap.''')
536
+
537
+ platform_id = property( lambda self: self._FT_Charmap.contents.platform_id,
538
+ doc = '''An ID number describing the platform for the following
539
+ encoding ID. This comes directly from the TrueType
540
+ specification and should be emulated for other
541
+ formats.''')
542
+
543
+ encoding_id = property( lambda self: self._FT_Charmap.contents.encoding_id,
544
+ doc = '''A platform specific encoding number. This also comes from
545
+ the TrueType specification and should be emulated
546
+ similarly.''')
547
+
548
+ def _get_encoding_name(self):
549
+ encoding = self.encoding
550
+ for key,value in FT_ENCODINGS.items():
551
+ if encoding == value:
552
+ return key
553
+ return 'Unknown encoding'
554
+ encoding_name = property( _get_encoding_name,
555
+ doc = '''A platform specific encoding name. This also comes from
556
+ the TrueType specification and should be emulated
557
+ similarly.''')
558
+
559
+ def _get_index( self ):
560
+ return FT_Get_Charmap_Index( self._FT_Charmap )
561
+ index = property( _get_index,
562
+ doc = '''The index into the array of character maps within the face to
563
+ which 'charmap' belongs. If an error occurs, -1 is returned.''')
564
+
565
+ def _get_cmap_language_id( self ):
566
+ return FT_Get_CMap_Language_ID( self._FT_Charmap )
567
+ cmap_language_id = property( _get_cmap_language_id,
568
+ doc = '''The language ID of 'charmap'. If 'charmap' doesn't
569
+ belong to a TrueType/sfnt face, just return 0 as the
570
+ default value.''')
571
+
572
+ def _get_cmap_format( self ):
573
+ return FT_Get_CMap_Format( self._FT_Charmap )
574
+ cmap_format = property( _get_cmap_format,
575
+ doc = '''The format of 'charmap'. If 'charmap' doesn't belong to a
576
+ TrueType/sfnt face, return -1.''')
577
+
578
+
579
+
580
+ # -----------------------------------------------------------------------------
581
+ class Outline( object ):
582
+ '''
583
+ FT_Outline wrapper.
584
+
585
+ This structure is used to describe an outline to the scan-line converter.
586
+ '''
587
+ def __init__( self, outline ):
588
+ '''
589
+ Create a new Outline object.
590
+
591
+ :param charmap: a FT_Outline
592
+ '''
593
+ self._FT_Outline = outline
594
+
595
+ n_contours = property(lambda self: self._FT_Outline.n_contours)
596
+ def _get_contours(self):
597
+ n = self._FT_Outline.n_contours
598
+ data = [self._FT_Outline.contours[i] for i in range(n)]
599
+ return data
600
+ contours = property(_get_contours,
601
+ doc = '''The number of contours in the outline.''')
602
+
603
+ n_points = property(lambda self: self._FT_Outline.n_points)
604
+ def _get_points(self):
605
+ n = self._FT_Outline.n_points
606
+ data = []
607
+ for i in range(n):
608
+ v = self._FT_Outline.points[i]
609
+ data.append( (v.x,v.y) )
610
+ return data
611
+ points = property( _get_points,
612
+ doc = '''The number of points in the outline.''')
613
+
614
+ def _get_tags(self):
615
+ n = self._FT_Outline.n_points
616
+ data = [self._FT_Outline.tags[i] for i in range(n)]
617
+ return data
618
+ tags = property(_get_tags,
619
+ doc = '''A list of 'n_points' chars, giving each outline point's type.
620
+
621
+ If bit 0 is unset, the point is 'off' the curve, i.e., a Bezier
622
+ control point, while it is 'on' if set.
623
+
624
+ Bit 1 is meaningful for 'off' points only. If set, it indicates a
625
+ third-order Bezier arc control point; and a second-order control
626
+ point if unset.
627
+
628
+ If bit 2 is set, bits 5-7 contain the drop-out mode (as defined
629
+ in the OpenType specification; the value is the same as the
630
+ argument to the SCANMODE instruction).
631
+
632
+ Bits 3 and 4 are reserved for internal purposes.''')
633
+
634
+ flags = property(lambda self: self._FT_Outline.flags,
635
+ doc = '''A set of bit flags used to characterize the outline and give
636
+ hints to the scan-converter and hinter on how to
637
+ convert/grid-fit it. See FT_OUTLINE_FLAGS.''')
638
+
639
+ def get_inside_border( self ):
640
+ '''
641
+ Retrieve the FT_StrokerBorder value corresponding to the 'inside'
642
+ borders of a given outline.
643
+
644
+ :return: The border index. FT_STROKER_BORDER_RIGHT for empty or invalid
645
+ outlines.
646
+ '''
647
+ return FT_Outline_GetInsideBorder( byref(self._FT_Outline) )
648
+
649
+ def get_outside_border( self ):
650
+ '''
651
+ Retrieve the FT_StrokerBorder value corresponding to the 'outside'
652
+ borders of a given outline.
653
+
654
+ :return: The border index. FT_STROKER_BORDER_RIGHT for empty or invalid
655
+ outlines.
656
+ '''
657
+ return FT_Outline_GetOutsideBorder( byref(self._FT_Outline) )
658
+
659
+ def get_bbox(self):
660
+ '''
661
+ Compute the exact bounding box of an outline. This is slower than
662
+ computing the control box. However, it uses an advanced algorithm which
663
+ returns very quickly when the two boxes coincide. Otherwise, the
664
+ outline Bezier arcs are traversed to extract their extrema.
665
+ '''
666
+ bbox = FT_BBox()
667
+ error = FT_Outline_Get_BBox(byref(self._FT_Outline), byref(bbox))
668
+ if error: raise FT_Exception(error)
669
+ return BBox(bbox)
670
+
671
+ def get_cbox(self):
672
+ '''
673
+ Return an outline's 'control box'. The control box encloses all the
674
+ outline's points, including Bezier control points. Though it coincides
675
+ with the exact bounding box for most glyphs, it can be slightly larger
676
+ in some situations (like when rotating an outline which contains Bezier
677
+ outside arcs).
678
+
679
+ Computing the control box is very fast, while getting the bounding box
680
+ can take much more time as it needs to walk over all segments and arcs
681
+ in the outline. To get the latter, you can use the 'ftbbox' component
682
+ which is dedicated to this single task.
683
+ '''
684
+ bbox = FT_BBox()
685
+ FT_Outline_Get_CBox(byref(self._FT_Outline), byref(bbox))
686
+ return BBox(bbox)
687
+
688
+ _od_move_to_noop = FT_Outline_MoveToFunc(lambda a, b: 0)
689
+ def _od_move_to_builder(self, cb):
690
+ if cb is None:
691
+ return self._od_move_to_noop
692
+ def move_to(a, b):
693
+ return cb(a[0], b) or 0
694
+ return FT_Outline_MoveToFunc(move_to)
695
+
696
+ _od_line_to_noop = FT_Outline_LineToFunc(lambda a, b: 0)
697
+ def _od_line_to_builder(self, cb):
698
+ if cb is None:
699
+ return self._od_line_to_noop
700
+ def line_to(a, b):
701
+ return cb(a[0], b) or 0
702
+ return FT_Outline_LineToFunc(line_to)
703
+
704
+ _od_conic_to_noop = FT_Outline_ConicToFunc(lambda a, b, c: 0)
705
+ def _od_conic_to_builder(self, cb):
706
+ if cb is None:
707
+ return self._od_conic_to_noop
708
+ def conic_to(a, b, c):
709
+ return cb(a[0], b[0], c) or 0
710
+ return FT_Outline_ConicToFunc(conic_to)
711
+
712
+ _od_cubic_to_noop = FT_Outline_CubicToFunc(lambda a, b, c, d: 0)
713
+ def _od_cubic_to_builder(self, cb):
714
+ if cb is None:
715
+ return self._od_cubic_to_noop
716
+ def cubic_to(a, b, c, d):
717
+ return cb(a[0], b[0], c[0], d) or 0
718
+ return FT_Outline_CubicToFunc(cubic_to)
719
+
720
+ def decompose(self, context=None, move_to=None, line_to=None, conic_to=None, cubic_to=None, shift=0, delta=0):
721
+ '''
722
+ Decompose the outline into a sequence of move, line, conic, and
723
+ cubic segments.
724
+
725
+ :param context: Arbitrary contextual object which will be passed as
726
+ the last parameter of all callbacks. Typically an
727
+ object to be drawn to, but can be anything.
728
+
729
+ :param move_to: Callback which will be passed an `FT_Vector`
730
+ control point and the context. Called when outline
731
+ needs to jump to a new path component.
732
+
733
+ :param line_to: Callback which will be passed an `FT_Vector`
734
+ control point and the context. Called to draw a
735
+ straight line from the current position to the
736
+ control point.
737
+
738
+ :param conic_to: Callback which will be passed two `FT_Vector`
739
+ control points and the context. Called to draw a
740
+ second-order Bézier curve from the current
741
+ position using the passed control points.
742
+
743
+ :param curve_to: Callback which will be passed three `FT_Vector`
744
+ control points and the context. Called to draw a
745
+ third-order Bézier curve from the current position
746
+ using the passed control points.
747
+
748
+ :param shift: Passed to FreeType which will transform vectors via
749
+ `x = (x << shift) - delta` and `y = (y << shift) - delta`
750
+
751
+ :param delta: Passed to FreeType which will transform vectors via
752
+ `x = (x << shift) - delta` and `y = (y << shift) - delta`
753
+
754
+ :since: 1.3
755
+ '''
756
+ func = FT_Outline_Funcs(
757
+ move_to = self._od_move_to_builder(move_to),
758
+ line_to = self._od_line_to_builder(line_to),
759
+ conic_to = self._od_conic_to_builder(conic_to),
760
+ cubic_to = self._od_cubic_to_builder(cubic_to),
761
+ shift = shift,
762
+ delta = FT_Pos(delta),
763
+ )
764
+
765
+ error = FT_Outline_Decompose( byref(self._FT_Outline), byref(func), py_object(context) )
766
+ if error: raise FT_Exception( error )
767
+
768
+
769
+
770
+ # -----------------------------------------------------------------------------
771
+ class Glyph( object ):
772
+ '''
773
+ FT_Glyph wrapper.
774
+
775
+ The root glyph structure contains a given glyph image plus its advance
776
+ width in 16.16 fixed float format.
777
+ '''
778
+ def __init__( self, glyph ):
779
+ '''
780
+ Create Glyph object from an FT glyph.
781
+
782
+ :param glyph: valid FT_Glyph object
783
+ '''
784
+ self._FT_Glyph = glyph
785
+
786
+ def __del__( self ):
787
+ '''
788
+ Destroy glyph.
789
+ '''
790
+ FT_Done_Glyph( self._FT_Glyph )
791
+
792
+ def _get_format( self ):
793
+ return self._FT_Glyph.contents.format
794
+ format = property( _get_format,
795
+ doc = '''The format of the glyph's image.''')
796
+
797
+
798
+ def stroke( self, stroker, destroy=False ):
799
+ '''
800
+ Stroke a given outline glyph object with a given stroker.
801
+
802
+ :param stroker: A stroker handle.
803
+
804
+ :param destroy: A Boolean. If 1, the source glyph object is destroyed on
805
+ success.
806
+
807
+ **Note**:
808
+
809
+ The source glyph is untouched in case of error.
810
+ '''
811
+ error = FT_Glyph_Stroke( byref(self._FT_Glyph),
812
+ stroker._FT_Stroker, destroy )
813
+ if error: raise FT_Exception( error )
814
+
815
+ def to_bitmap( self, mode, origin, destroy=False ):
816
+ '''
817
+ Convert a given glyph object to a bitmap glyph object.
818
+
819
+ :param mode: An enumeration that describes how the data is rendered.
820
+
821
+ :param origin: A pointer to a vector used to translate the glyph image
822
+ before rendering. Can be 0 (if no translation). The origin is
823
+ expressed in 26.6 pixels.
824
+
825
+ We also detect a plain vector and make a pointer out of it,
826
+ if that's the case.
827
+
828
+ :param destroy: A boolean that indicates that the original glyph image
829
+ should be destroyed by this function. It is never destroyed
830
+ in case of error.
831
+
832
+ **Note**:
833
+
834
+ This function does nothing if the glyph format isn't scalable.
835
+
836
+ The glyph image is translated with the 'origin' vector before
837
+ rendering.
838
+
839
+ The first parameter is a pointer to an FT_Glyph handle, that will be
840
+ replaced by this function (with newly allocated data). Typically, you
841
+ would use (omitting error handling):
842
+ '''
843
+ if ( type(origin) == FT_Vector ):
844
+ error = FT_Glyph_To_Bitmap( byref(self._FT_Glyph),
845
+ mode, byref(origin), destroy )
846
+ else:
847
+ error = FT_Glyph_To_Bitmap( byref(self._FT_Glyph),
848
+ mode, origin, destroy )
849
+
850
+ if error: raise FT_Exception( error )
851
+ return BitmapGlyph( self._FT_Glyph )
852
+
853
+ def get_cbox(self, bbox_mode):
854
+ '''
855
+ Return an outline's 'control box'. The control box encloses all the
856
+ outline's points, including Bezier control points. Though it coincides
857
+ with the exact bounding box for most glyphs, it can be slightly larger
858
+ in some situations (like when rotating an outline which contains Bezier
859
+ outside arcs).
860
+
861
+ Computing the control box is very fast, while getting the bounding box
862
+ can take much more time as it needs to walk over all segments and arcs
863
+ in the outline. To get the latter, you can use the 'ftbbox' component
864
+ which is dedicated to this single task.
865
+
866
+ :param mode: The mode which indicates how to interpret the returned
867
+ bounding box values.
868
+
869
+ **Note**:
870
+
871
+ Coordinates are relative to the glyph origin, using the y upwards
872
+ convention.
873
+
874
+ If the glyph has been loaded with FT_LOAD_NO_SCALE, 'bbox_mode' must be
875
+ set to FT_GLYPH_BBOX_UNSCALED to get unscaled font units in 26.6 pixel
876
+ format. The value FT_GLYPH_BBOX_SUBPIXELS is another name for this
877
+ constant.
878
+
879
+ Note that the maximum coordinates are exclusive, which means that one
880
+ can compute the width and height of the glyph image (be it in integer
881
+ or 26.6 pixels) as:
882
+
883
+ width = bbox.xMax - bbox.xMin;
884
+ height = bbox.yMax - bbox.yMin;
885
+
886
+ Note also that for 26.6 coordinates, if 'bbox_mode' is set to
887
+ FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted, which
888
+ corresponds to:
889
+
890
+ bbox.xMin = FLOOR(bbox.xMin);
891
+ bbox.yMin = FLOOR(bbox.yMin);
892
+ bbox.xMax = CEILING(bbox.xMax);
893
+ bbox.yMax = CEILING(bbox.yMax);
894
+
895
+ To get the bbox in pixel coordinates, set 'bbox_mode' to
896
+ FT_GLYPH_BBOX_TRUNCATE.
897
+
898
+ To get the bbox in grid-fitted pixel coordinates, set 'bbox_mode' to
899
+ FT_GLYPH_BBOX_PIXELS.
900
+ '''
901
+ bbox = FT_BBox()
902
+ FT_Glyph_Get_CBox(byref(self._FT_Glyph.contents), bbox_mode, byref(bbox))
903
+ return BBox(bbox)
904
+
905
+
906
+
907
+ # -----------------------------------------------------------------------------
908
+ class BitmapGlyph( object ):
909
+ '''
910
+ FT_BitmapGlyph wrapper.
911
+
912
+ A structure used for bitmap glyph images. This really is a 'sub-class' of
913
+ FT_GlyphRec.
914
+ '''
915
+ def __init__( self, glyph ):
916
+ '''
917
+ Create Glyph object from an FT glyph.
918
+
919
+ Parameters:
920
+ -----------
921
+ glyph: valid FT_Glyph object
922
+ '''
923
+ self._FT_BitmapGlyph = cast(glyph, FT_BitmapGlyph)
924
+
925
+ # def __del__( self ):
926
+ # '''
927
+ # Destroy glyph.
928
+ # '''
929
+ # FT_Done_Glyph( cast(self._FT_BitmapGlyph, FT_Glyph) )
930
+
931
+
932
+ def _get_format( self ):
933
+ return self._FT_BitmapGlyph.contents.format
934
+ format = property( _get_format,
935
+ doc = '''The format of the glyph's image.''')
936
+
937
+
938
+ def _get_bitmap( self ):
939
+ return Bitmap( self._FT_BitmapGlyph.contents.bitmap )
940
+ bitmap = property( _get_bitmap,
941
+ doc = '''A descriptor for the bitmap.''')
942
+
943
+
944
+ def _get_left( self ):
945
+ return self._FT_BitmapGlyph.contents.left
946
+ left = property( _get_left,
947
+ doc = '''The left-side bearing, i.e., the horizontal distance from the
948
+ current pen position to the left border of the glyph bitmap.''')
949
+
950
+
951
+ def _get_top( self ):
952
+ return self._FT_BitmapGlyph.contents.top
953
+ top = property( _get_top,
954
+ doc = '''The top-side bearing, i.e., the vertical distance from the
955
+ current pen position to the top border of the glyph bitmap.
956
+ This distance is positive for upwards y!''')
957
+
958
+
959
+ # -----------------------------------------------------------------------------
960
+ class GlyphSlot( object ):
961
+ '''
962
+ FT_GlyphSlot wrapper.
963
+
964
+ FreeType root glyph slot class structure. A glyph slot is a container where
965
+ individual glyphs can be loaded, be they in outline or bitmap format.
966
+ '''
967
+
968
+ def __init__( self, slot ):
969
+ '''
970
+ Create GlyphSlot object from an FT glyph slot.
971
+
972
+ Parameters:
973
+ -----------
974
+ glyph: valid FT_GlyphSlot object
975
+ '''
976
+ self._FT_GlyphSlot = slot
977
+
978
+ def render( self, render_mode ):
979
+ '''
980
+ Convert a given glyph image to a bitmap. It does so by inspecting the
981
+ glyph image format, finding the relevant renderer, and invoking it.
982
+
983
+ :param render_mode: The render mode used to render the glyph image into
984
+ a bitmap. See FT_Render_Mode for a list of possible
985
+ values.
986
+
987
+ If FT_RENDER_MODE_NORMAL is used, a previous call
988
+ of FT_Load_Glyph with flag FT_LOAD_COLOR makes
989
+ FT_Render_Glyph provide a default blending of
990
+ colored glyph layers associated with the current
991
+ glyph slot (provided the font contains such layers)
992
+ instead of rendering the glyph slot's outline.
993
+ This is an experimental feature; see FT_LOAD_COLOR
994
+ for more information.
995
+
996
+ **Note**:
997
+
998
+ To get meaningful results, font scaling values must be set with
999
+ functions like FT_Set_Char_Size before calling FT_Render_Glyph.
1000
+
1001
+ When FreeType outputs a bitmap of a glyph, it really outputs an alpha
1002
+ coverage map. If a pixel is completely covered by a filled-in
1003
+ outline, the bitmap contains 0xFF at that pixel, meaning that
1004
+ 0xFF/0xFF fraction of that pixel is covered, meaning the pixel is
1005
+ 100% black (or 0% bright). If a pixel is only 50% covered
1006
+ (value 0x80), the pixel is made 50% black (50% bright or a middle
1007
+ shade of grey). 0% covered means 0% black (100% bright or white).
1008
+
1009
+ On high-DPI screens like on smartphones and tablets, the pixels are
1010
+ so small that their chance of being completely covered and therefore
1011
+ completely black are fairly good. On the low-DPI screens, however,
1012
+ the situation is different. The pixels are too large for most of the
1013
+ details of a glyph and shades of gray are the norm rather than the
1014
+ exception.
1015
+
1016
+ This is relevant because all our screens have a second problem: they
1017
+ are not linear. 1 + 1 is not 2. Twice the value does not result in
1018
+ twice the brightness. When a pixel is only 50% covered, the coverage
1019
+ map says 50% black, and this translates to a pixel value of 128 when
1020
+ you use 8 bits per channel (0-255). However, this does not translate
1021
+ to 50% brightness for that pixel on our sRGB and gamma 2.2 screens.
1022
+ Due to their non-linearity, they dwell longer in the darks and only a
1023
+ pixel value of about 186 results in 50% brightness – 128 ends up too
1024
+ dark on both bright and dark backgrounds. The net result is that dark
1025
+ text looks burnt-out, pixely and blotchy on bright background, bright
1026
+ text too frail on dark backgrounds, and colored text on colored
1027
+ background (for example, red on green) seems to have dark halos or
1028
+ ‘dirt’ around it. The situation is especially ugly for diagonal stems
1029
+ like in ‘w’ glyph shapes where the quality of FreeType's
1030
+ anti-aliasing depends on the correct display of grays. On high-DPI
1031
+ screens where smaller, fully black pixels reign supreme, this doesn't
1032
+ matter, but on our low-DPI screens with all the gray shades, it does.
1033
+ 0% and 100% brightness are the same things in linear and non-linear
1034
+ space, just all the shades in-between aren't.
1035
+
1036
+ The blending function for placing text over a background is
1037
+
1038
+ dst = alpha * src + (1 - alpha) * dst
1039
+
1040
+ which is known as the OVER operator.
1041
+
1042
+ To correctly composite an anti-aliased pixel of a glyph onto a
1043
+ surface, take the foreground and background colors (e.g., in sRGB
1044
+ space) and apply gamma to get them in a linear space, use OVER to
1045
+ blend the two linear colors using the glyph pixel as the alpha value
1046
+ (remember, the glyph bitmap is an alpha coverage bitmap), and apply
1047
+ inverse gamma to the blended pixel and write it back to the image.
1048
+
1049
+ Internal testing at Adobe found that a target inverse gamma of 1.8
1050
+ for step 3 gives good results across a wide range of displays with
1051
+ an sRGB gamma curve or a similar one.
1052
+
1053
+ This process can cost performance. There is an approximation that
1054
+ does not need to know about the background color; see
1055
+ https://bel.fi/alankila/lcd/ and
1056
+ https://bel.fi/alankila/lcd/alpcor.html for details.
1057
+
1058
+ **ATTENTION:** Linear blending is even more important when dealing
1059
+ with subpixel-rendered glyphs to prevent color-fringing! A
1060
+ subpixel-rendered glyph must first be filtered with a filter that
1061
+ gives equal weight to the three color primaries and does not exceed a
1062
+ sum of 0x100, see section ‘Subpixel Rendering’. Then the only
1063
+ difference to gray linear blending is that subpixel-rendered linear
1064
+ blending is done 3 times per pixel: red foreground subpixel to red
1065
+ background subpixel and so on for green and blue.
1066
+ '''
1067
+ error = FT_Render_Glyph( self._FT_GlyphSlot, render_mode )
1068
+ if error: raise FT_Exception( error )
1069
+
1070
+ def get_glyph( self ):
1071
+ '''
1072
+ A function used to extract a glyph image from a slot. Note that the
1073
+ created FT_Glyph object must be released with FT_Done_Glyph.
1074
+ '''
1075
+ aglyph = FT_Glyph()
1076
+ error = FT_Get_Glyph( self._FT_GlyphSlot, byref(aglyph) )
1077
+ if error: raise FT_Exception( error )
1078
+ return Glyph( aglyph )
1079
+
1080
+ def _get_bitmap( self ):
1081
+ return Bitmap( self._FT_GlyphSlot.contents.bitmap )
1082
+ bitmap = property( _get_bitmap,
1083
+ doc = '''This field is used as a bitmap descriptor when the slot format
1084
+ is FT_GLYPH_FORMAT_BITMAP. Note that the address and content of
1085
+ the bitmap buffer can change between calls of FT_Load_Glyph and
1086
+ a few other functions.''')
1087
+
1088
+ def _get_metrics( self ):
1089
+ return GlyphMetrics( self._FT_GlyphSlot.contents.metrics )
1090
+ metrics = property( _get_metrics,
1091
+ doc = '''The metrics of the last loaded glyph in the slot. The returned
1092
+ values depend on the last load flags (see the FT_Load_Glyph API
1093
+ function) and can be expressed either in 26.6 fractional pixels or font
1094
+ units. Note that even when the glyph image is transformed, the metrics
1095
+ are not.''')
1096
+
1097
+ def _get_next( self ):
1098
+ return GlyphSlot( self._FT_GlyphSlot.contents.next )
1099
+ next = property( _get_next,
1100
+ doc = '''In some cases (like some font tools), several glyph slots per
1101
+ face object can be a good thing. As this is rare, the glyph slots
1102
+ are listed through a direct, single-linked list using its 'next'
1103
+ field.''')
1104
+
1105
+ advance = property( lambda self: self._FT_GlyphSlot.contents.advance,
1106
+ doc = '''This shorthand is, depending on FT_LOAD_IGNORE_TRANSFORM, the
1107
+ transformed advance width for the glyph (in 26.6 fractional
1108
+ pixel format). As specified with FT_LOAD_VERTICAL_LAYOUT, it
1109
+ uses either the 'horiAdvance' or the 'vertAdvance' value of
1110
+ 'metrics' field.''')
1111
+
1112
+ def _get_outline( self ):
1113
+ return Outline( self._FT_GlyphSlot.contents.outline )
1114
+ outline = property( _get_outline,
1115
+ doc = '''The outline descriptor for the current glyph image if its
1116
+ format is FT_GLYPH_FORMAT_OUTLINE. Once a glyph is loaded,
1117
+ 'outline' can be transformed, distorted, embolded,
1118
+ etc. However, it must not be freed.''')
1119
+
1120
+ format = property( lambda self: self._FT_GlyphSlot.contents.format,
1121
+ doc = '''This field indicates the format of the image contained in the
1122
+ glyph slot. Typically FT_GLYPH_FORMAT_BITMAP,
1123
+ FT_GLYPH_FORMAT_OUTLINE, or FT_GLYPH_FORMAT_COMPOSITE, but
1124
+ others are possible.''')
1125
+
1126
+ bitmap_top = property( lambda self:
1127
+ self._FT_GlyphSlot.contents.bitmap_top,
1128
+ doc = '''This is the bitmap's top bearing expressed in integer
1129
+ pixels. Remember that this is the distance from the
1130
+ baseline to the top-most glyph scanline, upwards y
1131
+ coordinates being positive.''')
1132
+
1133
+ bitmap_left = property( lambda self:
1134
+ self._FT_GlyphSlot.contents.bitmap_left,
1135
+ doc = '''This is the bitmap's left bearing expressed in integer
1136
+ pixels. Of course, this is only valid if the format is
1137
+ FT_GLYPH_FORMAT_BITMAP.''')
1138
+
1139
+ linearHoriAdvance = property( lambda self:
1140
+ self._FT_GlyphSlot.contents.linearHoriAdvance,
1141
+ doc = '''The advance width of the unhinted glyph. Its value
1142
+ is expressed in 16.16 fractional pixels, unless
1143
+ FT_LOAD_LINEAR_DESIGN is set when loading the glyph.
1144
+ This field can be important to perform correct
1145
+ WYSIWYG layout. Only relevant for outline glyphs.''')
1146
+
1147
+ linearVertAdvance = property( lambda self:
1148
+ self._FT_GlyphSlot.contents.linearVertAdvance,
1149
+ doc = '''The advance height of the unhinted glyph. Its value
1150
+ is expressed in 16.16 fractional pixels, unless
1151
+ FT_LOAD_LINEAR_DESIGN is set when loading the glyph.
1152
+ This field can be important to perform correct
1153
+ WYSIWYG layout. Only relevant for outline glyphs.''')
1154
+
1155
+
1156
+ # -----------------------------------------------------------------------------
1157
+ # Face wrapper
1158
+ # -----------------------------------------------------------------------------
1159
+ class Face( object ):
1160
+ '''
1161
+ FT_Face wrapper
1162
+
1163
+ FreeType root face class structure. A face object models a typeface in a
1164
+ font file.
1165
+ '''
1166
+ def __init__( self, path_or_stream, index = 0 ):
1167
+ '''
1168
+ Build a new Face
1169
+
1170
+ :param Union[str, typing.BinaryIO] path_or_stream:
1171
+ A path to the font file or an io.BytesIO stream.
1172
+
1173
+ :param int index:
1174
+ The index of the face within the font.
1175
+ The first face has index 0.
1176
+ '''
1177
+ library = get_handle( )
1178
+ face = FT_Face( )
1179
+ self._FT_Face = None
1180
+ #error = FT_New_Face( library, path_or_stream, 0, byref(face) )
1181
+ self._filebodys = []
1182
+ if hasattr(path_or_stream, "read"):
1183
+ error = self._init_from_memory(library, face, index, path_or_stream.read())
1184
+ else:
1185
+ try:
1186
+ error = self._init_from_file(library, face, index, path_or_stream)
1187
+ except UnicodeError:
1188
+ with open(path_or_stream, mode="rb") as f:
1189
+ filebody = f.read()
1190
+ error = self._init_from_memory(library, face, index, filebody)
1191
+ if error:
1192
+ raise FT_Exception(error)
1193
+ self._index = index
1194
+ self._FT_Face = face
1195
+ self._name_strings = dict()
1196
+
1197
+ def _init_from_file(self, library, face, index, path):
1198
+ u_filename = c_char_p(_encode_filename(path))
1199
+ error = FT_New_Face(library, u_filename, index, byref(face))
1200
+ return error
1201
+
1202
+ def _init_from_memory(self, library, face, index, byte_stream):
1203
+ error = FT_New_Memory_Face(
1204
+ library, byte_stream, len(byte_stream), index, byref(face)
1205
+ )
1206
+ self._filebodys.append(byte_stream) # prevent gc
1207
+ return error
1208
+
1209
+ def _init_name_string_map(self):
1210
+ # build map of (nID, pID, eID, lID) keys to name string bytes
1211
+ self._name_strings = dict()
1212
+
1213
+ for nidx in range(self._get_sfnt_name_count()):
1214
+ namerec = self.get_sfnt_name(nidx)
1215
+ nk = (namerec.name_id,
1216
+ namerec.platform_id,
1217
+ namerec.encoding_id,
1218
+ namerec.language_id)
1219
+
1220
+ self._name_strings[nk] = namerec.string
1221
+
1222
+ @classmethod
1223
+ def from_bytes(cls, bytes_, index=0):
1224
+ return cls(io.BytesIO(bytes_), index)
1225
+
1226
+ def __del__( self ):
1227
+ '''
1228
+ Discard face object, as well as all of its child slots and sizes.
1229
+ '''
1230
+ # We check FT_Done_Face because by the time we're called it
1231
+ # may already be gone (see #44 and discussion in #169)
1232
+ if FT_Done_Face is not None and self._FT_Face is not None:
1233
+ FT_Done_Face( self._FT_Face )
1234
+
1235
+
1236
+ def attach_file( self, filename ):
1237
+ '''
1238
+ Attach data to a face object. Normally, this is used to read
1239
+ additional information for the face object. For example, you can attach
1240
+ an AFM file that comes with a Type 1 font to get the kerning values and
1241
+ other metrics.
1242
+
1243
+ :param filename: Filename to attach
1244
+
1245
+ **Note**
1246
+
1247
+ The meaning of the 'attach' (i.e., what really happens when the new
1248
+ file is read) is not fixed by FreeType itself. It really depends on the
1249
+ font format (and thus the font driver).
1250
+
1251
+ Client applications are expected to know what they are doing when
1252
+ invoking this function. Most drivers simply do not implement file
1253
+ attachments.
1254
+ '''
1255
+
1256
+ try:
1257
+ u_filename = c_char_p(_encode_filename(filename))
1258
+ error = FT_Attach_File( self._FT_Face, u_filename )
1259
+ except UnicodeError:
1260
+ with open(filename, mode='rb') as f:
1261
+ filebody = f.read()
1262
+ parameters = FT_Open_Args()
1263
+ parameters.flags = FT_OPEN_MEMORY
1264
+ parameters.memory_base = filebody
1265
+ parameters.memory_size = len(filebody)
1266
+ parameters.stream = None
1267
+ error = FT_Attach_Stream( self._FT_Face, parameters )
1268
+ self._filebodys.append(filebody) # prevent gc
1269
+ if error: raise FT_Exception( error)
1270
+
1271
+
1272
+ def set_char_size( self, width=0, height=0, hres=72, vres=72 ):
1273
+ '''
1274
+ This function calls FT_Request_Size to request the nominal size (in
1275
+ points).
1276
+
1277
+ :param float width: The nominal width, in 26.6 fractional points.
1278
+
1279
+ :param float height: The nominal height, in 26.6 fractional points.
1280
+
1281
+ :param float hres: The horizontal resolution in dpi.
1282
+
1283
+ :param float vres: The vertical resolution in dpi.
1284
+
1285
+ **Note**
1286
+
1287
+ If either the character width or height is zero, it is set equal to the
1288
+ other value.
1289
+
1290
+ If either the horizontal or vertical resolution is zero, it is set
1291
+ equal to the other value.
1292
+
1293
+ A character width or height smaller than 1pt is set to 1pt; if both
1294
+ resolution values are zero, they are set to 72dpi.
1295
+
1296
+ Don't use this function if you are using the FreeType cache API.
1297
+ '''
1298
+ error = FT_Set_Char_Size( self._FT_Face, width, height, hres, vres )
1299
+ if error: raise FT_Exception( error)
1300
+
1301
+ def set_pixel_sizes( self, width, height ):
1302
+ '''
1303
+ This function calls FT_Request_Size to request the nominal size (in
1304
+ pixels).
1305
+
1306
+ :param width: The nominal width, in pixels.
1307
+
1308
+ :param height: The nominal height, in pixels.
1309
+ '''
1310
+ error = FT_Set_Pixel_Sizes( self._FT_Face, width, height )
1311
+ if error: raise FT_Exception(error)
1312
+
1313
+ def select_charmap( self, encoding ):
1314
+ '''
1315
+ Select a given charmap by its encoding tag (as listed in 'freetype.h').
1316
+
1317
+ **Note**:
1318
+
1319
+ This function returns an error if no charmap in the face corresponds to
1320
+ the encoding queried here.
1321
+
1322
+ Because many fonts contain more than a single cmap for Unicode
1323
+ encoding, this function has some special code to select the one which
1324
+ covers Unicode best ('best' in the sense that a UCS-4 cmap is preferred
1325
+ to a UCS-2 cmap). It is thus preferable to FT_Set_Charmap in this case.
1326
+ '''
1327
+ error = FT_Select_Charmap( self._FT_Face, encoding )
1328
+ if error: raise FT_Exception(error)
1329
+
1330
+ def set_charmap( self, charmap ):
1331
+ '''
1332
+ Select a given charmap for character code to glyph index mapping.
1333
+
1334
+ :param charmap: A handle to the selected charmap, or an index to face->charmaps[]
1335
+ '''
1336
+ if ( type(charmap) == Charmap ):
1337
+ error = FT_Set_Charmap( self._FT_Face, charmap._FT_Charmap )
1338
+ # Type 14 is allowed to fail, to match ft2demo's behavior.
1339
+ if ( charmap.cmap_format == 14 ):
1340
+ error = 0
1341
+ else:
1342
+ # Treat "charmap" as plain number
1343
+ error = FT_Set_Charmap( self._FT_Face, self._FT_Face.contents.charmaps[charmap] )
1344
+ if error : raise FT_Exception(error)
1345
+
1346
+ def get_char_index( self, charcode ):
1347
+ '''
1348
+ Return the glyph index of a given character code. This function uses a
1349
+ charmap object to do the mapping.
1350
+
1351
+ :param charcode: The character code.
1352
+
1353
+ **Note**:
1354
+
1355
+ If you use FreeType to manipulate the contents of font files directly,
1356
+ be aware that the glyph index returned by this function doesn't always
1357
+ correspond to the internal indices used within the file. This is done
1358
+ to ensure that value 0 always corresponds to the 'missing glyph'.
1359
+ '''
1360
+ if isinstance(charcode, (str,unicode)):
1361
+ charcode = ord(charcode)
1362
+ return FT_Get_Char_Index( self._FT_Face, charcode )
1363
+
1364
+ def get_glyph_name(self, agindex, buffer_max=64):
1365
+ '''
1366
+ This function is used to return the glyph name for the given charcode.
1367
+
1368
+ :param agindex: The glyph index.
1369
+
1370
+ :param buffer_max: The maximum number of bytes to use to store the
1371
+ glyph name.
1372
+
1373
+ :param glyph_name: The glyph name, possibly truncated.
1374
+
1375
+ '''
1376
+ buff = create_string_buffer(buffer_max)
1377
+ error = FT_Get_Glyph_Name(self._FT_Face, FT_UInt(agindex), byref(buff),
1378
+ FT_UInt(buffer_max))
1379
+ if error: raise FT_Exception(error)
1380
+ return buff.value
1381
+
1382
+ def get_chars( self ):
1383
+ '''
1384
+ This generator function is used to return all unicode character
1385
+ codes in the current charmap of a given face. For each character it
1386
+ also returns the corresponding glyph index.
1387
+
1388
+ :return: character code, glyph index
1389
+
1390
+ **Note**:
1391
+ Note that 'agindex' is set to 0 if the charmap is empty. The
1392
+ character code itself can be 0 in two cases: if the charmap is empty
1393
+ or if the value 0 is the first valid character code.
1394
+ '''
1395
+ charcode, agindex = self.get_first_char()
1396
+ yield charcode, agindex
1397
+ while agindex != 0:
1398
+ charcode, agindex = self.get_next_char(charcode, 0)
1399
+ yield charcode, agindex
1400
+
1401
+ def get_first_char( self ):
1402
+ '''
1403
+ This function is used to return the first character code in the current
1404
+ charmap of a given face. It also returns the corresponding glyph index.
1405
+
1406
+ :return: Glyph index of first character code. 0 if charmap is empty.
1407
+
1408
+ **Note**:
1409
+
1410
+ You should use this function with get_next_char to be able to parse
1411
+ all character codes available in a given charmap. The code should look
1412
+ like this:
1413
+
1414
+ Note that 'agindex' is set to 0 if the charmap is empty. The result
1415
+ itself can be 0 in two cases: if the charmap is empty or if the value 0
1416
+ is the first valid character code.
1417
+ '''
1418
+ agindex = FT_UInt()
1419
+ charcode = FT_Get_First_Char( self._FT_Face, byref(agindex) )
1420
+ return charcode, agindex.value
1421
+
1422
+ def get_next_char( self, charcode, agindex ):
1423
+ '''
1424
+ This function is used to return the next character code in the current
1425
+ charmap of a given face following the value 'charcode', as well as the
1426
+ corresponding glyph index.
1427
+
1428
+ :param charcode: The starting character code.
1429
+
1430
+ :param agindex: Glyph index of next character code. 0 if charmap is empty.
1431
+
1432
+ **Note**:
1433
+
1434
+ You should use this function with FT_Get_First_Char to walk over all
1435
+ character codes available in a given charmap. See the note for this
1436
+ function for a simple code example.
1437
+
1438
+ Note that 'agindex' is set to 0 when there are no more codes in the
1439
+ charmap.
1440
+ '''
1441
+ agindex = FT_UInt( 0 ) #agindex )
1442
+ charcode = FT_Get_Next_Char( self._FT_Face, charcode, byref(agindex) )
1443
+ return charcode, agindex.value
1444
+
1445
+ def get_name_index( self, name ):
1446
+ '''
1447
+ Return the glyph index of a given glyph name. This function uses driver
1448
+ specific objects to do the translation.
1449
+
1450
+ :param name: The glyph name.
1451
+ '''
1452
+ if not isinstance(name, bytes):
1453
+ raise FT_Exception(0x06, "FT_Get_Name_Index() expects a binary "
1454
+ "string for the name parameter.")
1455
+ return FT_Get_Name_Index( self._FT_Face, name )
1456
+
1457
+ def set_transform( self, matrix, delta ):
1458
+ '''
1459
+ A function used to set the transformation that is applied to glyph
1460
+ images when they are loaded into a glyph slot through FT_Load_Glyph.
1461
+
1462
+ :param matrix: A pointer to the transformation's 2x2 matrix.
1463
+ Use 0 for the identity matrix.
1464
+
1465
+ :parm delta: A pointer to the translation vector.
1466
+ Use 0 for the null vector.
1467
+
1468
+ **Note**:
1469
+
1470
+ The transformation is only applied to scalable image formats after the
1471
+ glyph has been loaded. It means that hinting is unaltered by the
1472
+ transformation and is performed on the character size given in the last
1473
+ call to FT_Set_Char_Size or FT_Set_Pixel_Sizes.
1474
+
1475
+ Note that this also transforms the 'face.glyph.advance' field, but
1476
+ not the values in 'face.glyph.metrics'.
1477
+ '''
1478
+ FT_Set_Transform( self._FT_Face,
1479
+ byref(matrix), byref(delta) )
1480
+
1481
+ def select_size( self, strike_index ):
1482
+ '''
1483
+ Select a bitmap strike.
1484
+
1485
+ :param strike_index: The index of the bitmap strike in the
1486
+ 'available_sizes' field of Face object.
1487
+ '''
1488
+ error = FT_Select_Size( self._FT_Face, strike_index )
1489
+ if error: raise FT_Exception( error )
1490
+
1491
+ def load_glyph( self, index, flags = FT_LOAD_RENDER ):
1492
+ '''
1493
+ A function used to load a single glyph into the glyph slot of a face
1494
+ object.
1495
+
1496
+ :param index: The index of the glyph in the font file. For CID-keyed
1497
+ fonts (either in PS or in CFF format) this argument
1498
+ specifies the CID value.
1499
+
1500
+ :param flags: A flag indicating what to load for this glyph. The FT_LOAD_XXX
1501
+ constants can be used to control the glyph loading process
1502
+ (e.g., whether the outline should be scaled, whether to load
1503
+ bitmaps or not, whether to hint the outline, etc).
1504
+
1505
+ **Note**:
1506
+
1507
+ The loaded glyph may be transformed. See FT_Set_Transform for the
1508
+ details.
1509
+
1510
+ For subsetted CID-keyed fonts, 'FT_Err_Invalid_Argument' is returned
1511
+ for invalid CID values (this is, for CID values which don't have a
1512
+ corresponding glyph in the font). See the discussion of the
1513
+ FT_FACE_FLAG_CID_KEYED flag for more details.
1514
+ '''
1515
+ error = FT_Load_Glyph( self._FT_Face, index, flags )
1516
+ if error: raise FT_Exception( error )
1517
+
1518
+ def load_char( self, char, flags = FT_LOAD_RENDER ):
1519
+ '''
1520
+ A function used to load a single glyph into the glyph slot of a face
1521
+ object, according to its character code.
1522
+
1523
+ :param char: The glyph's character code, according to the current
1524
+ charmap used in the face.
1525
+
1526
+ :param flags: A flag indicating what to load for this glyph. The
1527
+ FT_LOAD_XXX constants can be used to control the glyph
1528
+ loading process (e.g., whether the outline should be
1529
+ scaled, whether to load bitmaps or not, whether to hint
1530
+ the outline, etc).
1531
+
1532
+ **Note**:
1533
+
1534
+ This function simply calls FT_Get_Char_Index and FT_Load_Glyph.
1535
+ '''
1536
+
1537
+ # python 2 with ascii input
1538
+ if ( isinstance(char, str) and ( len(char) == 1 ) ):
1539
+ char = ord(char)
1540
+ # python 2 with utf8 string input
1541
+ if ( isinstance(char, str) and ( len(char) != 1 ) ):
1542
+ char = ord(char.decode('utf8'))
1543
+ # python 3 or python 2 with __future__.unicode_literals
1544
+ if ( isinstance(char, unicode) and ( len(char) == 1 ) ):
1545
+ char = ord(char)
1546
+ # allow bare integer to pass through
1547
+ error = FT_Load_Char( self._FT_Face, char, flags )
1548
+ if error: raise FT_Exception( error )
1549
+
1550
+
1551
+ def get_advance( self, gindex, flags ):
1552
+ '''
1553
+ Retrieve the advance value of a given glyph outline in an FT_Face. By
1554
+ default, the unhinted advance is returned in font units.
1555
+
1556
+ :param gindex: The glyph index.
1557
+
1558
+ :param flags: A set of bit flags similar to those used when calling
1559
+ FT_Load_Glyph, used to determine what kind of advances
1560
+ you need.
1561
+
1562
+ :return: The advance value, in either font units or 16.16 format.
1563
+
1564
+ If FT_LOAD_VERTICAL_LAYOUT is set, this is the vertical
1565
+ advance corresponding to a vertical layout. Otherwise, it is
1566
+ the horizontal advance in a horizontal layout.
1567
+ '''
1568
+
1569
+ padvance = FT_Fixed(0)
1570
+ error = FT_Get_Advance( self._FT_Face, gindex, flags, byref(padvance) )
1571
+ if error: raise FT_Exception( error )
1572
+ return padvance.value
1573
+
1574
+
1575
+
1576
+ def get_kerning( self, left, right, mode = FT_KERNING_DEFAULT ):
1577
+ '''
1578
+ Return the kerning vector between two glyphs of a same face.
1579
+
1580
+ :param left: The index of the left glyph in the kern pair.
1581
+
1582
+ :param right: The index of the right glyph in the kern pair.
1583
+
1584
+ :param mode: See FT_Kerning_Mode for more information. Determines the scale
1585
+ and dimension of the returned kerning vector.
1586
+
1587
+ **Note**:
1588
+
1589
+ Only horizontal layouts (left-to-right & right-to-left) are supported
1590
+ by this method. Other layouts, or more sophisticated kernings, are out
1591
+ of the scope of this API function -- they can be implemented through
1592
+ format-specific interfaces.
1593
+ '''
1594
+ left_glyph = self.get_char_index( left )
1595
+ right_glyph = self.get_char_index( right )
1596
+ kerning = FT_Vector(0,0)
1597
+ error = FT_Get_Kerning( self._FT_Face,
1598
+ left_glyph, right_glyph, mode, byref(kerning) )
1599
+ if error: raise FT_Exception( error )
1600
+ return kerning
1601
+
1602
+ def get_format(self):
1603
+ '''
1604
+ Return a string describing the format of a given face, using values
1605
+ which can be used as an X11 FONT_PROPERTY. Possible values are
1606
+ 'TrueType', 'Type 1', 'BDF', ‘PCF', ‘Type 42', ‘CID Type 1', ‘CFF',
1607
+ 'PFR', and ‘Windows FNT'.
1608
+ '''
1609
+
1610
+ return FT_Get_X11_Font_Format( self._FT_Face )
1611
+
1612
+
1613
+ def get_fstype(self):
1614
+ '''
1615
+ Return the fsType flags for a font (embedding permissions).
1616
+
1617
+ The return value is a tuple containing the freetype enum name
1618
+ as a string and the actual flag as an int
1619
+ '''
1620
+
1621
+ flag = FT_Get_FSType_Flags( self._FT_Face )
1622
+ for k, v in FT_FSTYPES.items():
1623
+ if v == flag:
1624
+ return k, v
1625
+
1626
+
1627
+ def _get_sfnt_name_count(self):
1628
+ return FT_Get_Sfnt_Name_Count( self._FT_Face )
1629
+ sfnt_name_count = property(_get_sfnt_name_count,
1630
+ doc = '''Number of name strings in the SFNT 'name' table.''')
1631
+
1632
+ def get_sfnt_name( self, index ):
1633
+ '''
1634
+ Retrieve a string of the SFNT 'name' table for a given index
1635
+
1636
+ :param index: The index of the 'name' string.
1637
+
1638
+ **Note**:
1639
+
1640
+ The 'string' array returned in the 'aname' structure is not
1641
+ null-terminated. The application should deallocate it if it is no
1642
+ longer in use.
1643
+
1644
+ Use FT_Get_Sfnt_Name_Count to get the total number of available
1645
+ 'name' table entries, then do a loop until you get the right
1646
+ platform, encoding, and name ID.
1647
+ '''
1648
+ name = FT_SfntName( )
1649
+ error = FT_Get_Sfnt_Name( self._FT_Face, index, byref(name) )
1650
+ if error: raise FT_Exception( error )
1651
+ return SfntName( name )
1652
+
1653
+ def get_best_name_string(self, nameID, default_string='', preferred_order=None):
1654
+ '''
1655
+ Retrieve a name string given nameID. Searches available font names
1656
+ matching nameID and returns the decoded bytes of the best match.
1657
+ "Best" is defined as a preferred list of platform/encoding/languageIDs
1658
+ which can be overridden by supplying a preferred_order matching the
1659
+ scheme of 'sort_order' (see below).
1660
+
1661
+ The routine will attempt to decode the string's bytes to a Python str, when the
1662
+ platform/encoding[/langID] are known (Windows, Mac, or Unicode platforms).
1663
+
1664
+ If you prefer more control over name string selection and decoding than
1665
+ this routine provides:
1666
+ - call self._init_name_string_map()
1667
+ - use (nameID, platformID, encodingID, languageID) as a key into
1668
+ the self._name_strings dict
1669
+ '''
1670
+ if not(self._name_strings):
1671
+ self._init_name_string_map()
1672
+
1673
+ sort_order = preferred_order or (
1674
+ (3, 1, 1033), # Microsoft/Windows/US English
1675
+ (1, 0, 0), # Mac/Roman/English
1676
+ (0, 6, 0), # Unicode/SMP/*
1677
+ (0, 4, 0), # Unicode/SMP/*
1678
+ (0, 3, 0), # Unicode/BMP/*
1679
+ (0, 2, 0), # Unicode/10646-BMP/*
1680
+ (0, 1, 0), # Unicode/1.1/*
1681
+ )
1682
+
1683
+ # get all keys matching nameID
1684
+ keys_present = [k for k in self._name_strings.keys() if k[0] == nameID]
1685
+
1686
+ if keys_present:
1687
+ # sort found keys by sort_order
1688
+ key_order = {k: v for v, k in enumerate(sort_order)}
1689
+ keys_present.sort(key=lambda x: key_order.get(x[1:4]))
1690
+ best_key = keys_present[0]
1691
+ nsbytes = self._name_strings[best_key]
1692
+
1693
+ if best_key[1:3] == (3, 1) or best_key[1] == 0:
1694
+ enc = "utf-16-be"
1695
+ elif best_key[1:4] == (1, 0, 0):
1696
+ enc = "mac-roman"
1697
+ else:
1698
+ enc = "unicode_escape"
1699
+
1700
+ ns = nsbytes.decode(enc)
1701
+
1702
+ else:
1703
+ ns = default_string
1704
+
1705
+ return ns
1706
+
1707
+ def get_variation_info(self):
1708
+ '''
1709
+ Retrieves variation space information for the current face.
1710
+ '''
1711
+ if version() < (2, 8, 1):
1712
+ raise NotImplementedError("freetype-py VF support requires FreeType 2.8.1 or later")
1713
+
1714
+ p_amaster = pointer(FT_MM_Var())
1715
+ error = FT_Get_MM_Var(self._FT_Face, byref(p_amaster))
1716
+
1717
+ if error:
1718
+ raise FT_Exception(error)
1719
+
1720
+ vsi = VariationSpaceInfo(self, p_amaster)
1721
+
1722
+ FT_Done_MM_Var_func(p_amaster)
1723
+
1724
+ return vsi
1725
+
1726
+ def get_var_blend_coords(self):
1727
+ '''
1728
+ Get the current blend coordinates (-1.0..+1.0)
1729
+ '''
1730
+ vsi = self.get_variation_info()
1731
+ num_coords = len(vsi.axes)
1732
+ ft_coords = (FT_Fixed * num_coords)()
1733
+ error = FT_Get_Var_Blend_Coordinates(self._FT_Face, num_coords, byref(ft_coords))
1734
+
1735
+ if error:
1736
+ raise FT_Exception(error)
1737
+
1738
+ coords = tuple([ft_coords[ai]/65536.0 for ai in range(num_coords)])
1739
+
1740
+ return coords
1741
+
1742
+ def set_var_blend_coords(self, coords, reset=False):
1743
+ '''
1744
+ Set blend coords. Using reset=True will set all axes to
1745
+ their default coordinates.
1746
+ '''
1747
+ if reset:
1748
+ error = FT_Set_Var_Blend_Coordinates(self._FT_Face, 0, 0)
1749
+ else:
1750
+ num_coords = len(coords)
1751
+ ft_coords = [int(round(c * 65536.0)) for c in coords]
1752
+ coords_array = (FT_Fixed * num_coords)(*ft_coords)
1753
+ error = FT_Set_Var_Blend_Coordinates(self._FT_Face, num_coords, byref(coords_array))
1754
+
1755
+ if error:
1756
+ raise FT_Exception(error)
1757
+
1758
+ def get_var_design_coords(self):
1759
+ '''
1760
+ Get the current design coordinates
1761
+ '''
1762
+ vsi = self.get_variation_info()
1763
+ num_coords = len(vsi.axes)
1764
+ ft_coords = (FT_Fixed * num_coords)()
1765
+ error = FT_Get_Var_Design_Coordinates(self._FT_Face, num_coords, byref(ft_coords))
1766
+
1767
+ if error:
1768
+ raise FT_Exception(error)
1769
+
1770
+ coords = tuple([ft_coords[ai]/65536.0 for ai in range(num_coords)])
1771
+
1772
+ return coords
1773
+
1774
+ def set_var_design_coords(self, coords, reset=False):
1775
+ '''
1776
+ Set design coords. Using reset=True will set all axes to
1777
+ their default coordinates.
1778
+ '''
1779
+ if reset:
1780
+ error = FT_Set_Var_Design_Coordinates(self._FT_Face, 0, 0)
1781
+
1782
+ else:
1783
+ num_coords = len(coords)
1784
+ ft_coords = [int(round(c * 65536.0)) for c in coords]
1785
+ coords_array = (FT_Fixed * num_coords)(*ft_coords)
1786
+ error = FT_Set_Var_Design_Coordinates(self._FT_Face, num_coords, byref(coords_array))
1787
+
1788
+ if error:
1789
+ raise FT_Exception(error)
1790
+
1791
+ def set_var_named_instance(self, instance_name):
1792
+ '''
1793
+ Set instance by name. This will work with any FreeType with variable support
1794
+ (for our purposes: v2.8.1 or later). If the actual FT_Set_Named_Instance()
1795
+ function is available (v2.9.1 or later), we use it (which, despite what you might
1796
+ expect from its name, sets instances by *index*). Otherwise we just use the coords
1797
+ of the named instance (if found) and call self.set_var_design_coords.
1798
+ '''
1799
+ have_func = freetype.version() >= (2, 9, 1)
1800
+ vsi = self.get_variation_info()
1801
+
1802
+ for inst_idx, inst in enumerate(vsi.instances, start=1):
1803
+ if inst.name == instance_name:
1804
+ if have_func:
1805
+ error = FT_Set_Named_Instance(self._FT_Face, inst_idx)
1806
+ else:
1807
+ error = self.set_var_design_coords(inst.coords)
1808
+
1809
+ if error:
1810
+ raise FT_Exception(error)
1811
+
1812
+ break
1813
+
1814
+ # named instance not found; do nothing
1815
+
1816
+ def _get_postscript_name( self ):
1817
+ return FT_Get_Postscript_Name( self._FT_Face )
1818
+ postscript_name = property( _get_postscript_name,
1819
+ doc = '''ASCII PostScript name of face, if available. This only
1820
+ works with PostScript and TrueType fonts.''')
1821
+
1822
+ def _has_horizontal( self ):
1823
+ return bool( self.face_flags & FT_FACE_FLAG_HORIZONTAL )
1824
+ has_horizontal = property( _has_horizontal,
1825
+ doc = '''True whenever a face object contains horizontal metrics
1826
+ (this is true for all font formats though).''')
1827
+
1828
+ def _has_vertical( self ):
1829
+ return bool( self.face_flags & FT_FACE_FLAG_VERTICAL )
1830
+ has_vertical = property( _has_vertical,
1831
+ doc = '''True whenever a face object contains vertical metrics.''')
1832
+
1833
+ def _has_kerning( self ):
1834
+ return bool( self.face_flags & FT_FACE_FLAG_KERNING )
1835
+ has_kerning = property( _has_kerning,
1836
+ doc = '''True whenever a face object contains kerning data that can
1837
+ be accessed with FT_Get_Kerning.''')
1838
+
1839
+ def _is_scalable( self ):
1840
+ return bool( self.face_flags & FT_FACE_FLAG_SCALABLE )
1841
+ is_scalable = property( _is_scalable,
1842
+ doc = '''true whenever a face object contains a scalable font face
1843
+ (true for TrueType, Type 1, Type 42, CID, OpenType/CFF,
1844
+ and PFR font formats.''')
1845
+
1846
+ def _is_sfnt( self ):
1847
+ return bool( self.face_flags & FT_FACE_FLAG_SFNT )
1848
+ is_sfnt = property( _is_sfnt,
1849
+ doc = '''true whenever a face object contains a font whose format is
1850
+ based on the SFNT storage scheme. This usually means: TrueType
1851
+ fonts, OpenType fonts, as well as SFNT-based embedded bitmap
1852
+ fonts.
1853
+
1854
+ If this macro is true, all functions defined in
1855
+ FT_SFNT_NAMES_H and FT_TRUETYPE_TABLES_H are available.''')
1856
+
1857
+ def _is_fixed_width( self ):
1858
+ return bool( self.face_flags & FT_FACE_FLAG_FIXED_WIDTH )
1859
+ is_fixed_width = property( _is_fixed_width,
1860
+ doc = '''True whenever a face object contains a font face that
1861
+ contains fixed-width (or 'monospace', 'fixed-pitch',
1862
+ etc.) glyphs.''')
1863
+
1864
+ def _has_fixed_sizes( self ):
1865
+ return bool( self.face_flags & FT_FACE_FLAG_FIXED_SIZES )
1866
+ has_fixed_sizes = property( _has_fixed_sizes,
1867
+ doc = '''True whenever a face object contains some embedded
1868
+ bitmaps. See the 'available_sizes' field of the FT_FaceRec
1869
+ structure.''')
1870
+
1871
+ def _has_glyph_names( self ):
1872
+ return bool( self.face_flags & FT_FACE_FLAG_GLYPH_NAMES )
1873
+ has_glyph_names = property( _has_glyph_names,
1874
+ doc = '''True whenever a face object contains some glyph names
1875
+ that can be accessed through FT_Get_Glyph_Name.''')
1876
+
1877
+ def _has_multiple_masters( self ):
1878
+ return bool( self.face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS )
1879
+ has_multiple_masters = property( _has_multiple_masters,
1880
+ doc = '''True whenever a face object contains some
1881
+ multiple masters. The functions provided by
1882
+ FT_MULTIPLE_MASTERS_H are then available to
1883
+ choose the exact design you want.''')
1884
+
1885
+ def _is_cid_keyed( self ):
1886
+ return bool( self.face_flags & FT_FACE_FLAG_CID_KEYED )
1887
+ is_cid_keyed = property( _is_cid_keyed,
1888
+ doc = '''True whenever a face object contains a CID-keyed
1889
+ font. See the discussion of FT_FACE_FLAG_CID_KEYED for
1890
+ more details.
1891
+
1892
+ If this macro is true, all functions defined in FT_CID_H
1893
+ are available.''')
1894
+
1895
+ def _is_tricky( self ):
1896
+ return bool( self.face_flags & FT_FACE_FLAG_TRICKY )
1897
+ is_tricky = property( _is_tricky,
1898
+ doc = '''True whenever a face represents a 'tricky' font. See the
1899
+ discussion of FT_FACE_FLAG_TRICKY for more details.''')
1900
+
1901
+
1902
+ num_faces = property(lambda self: self._FT_Face.contents.num_faces,
1903
+ doc = '''The number of faces in the font file. Some font formats can
1904
+ have multiple faces in a font file.''')
1905
+
1906
+ face_index = property(lambda self: self._FT_Face.contents.face_index,
1907
+ doc = '''The index of the face in the font file. It is set to 0 if
1908
+ there is only one face in the font file.''')
1909
+
1910
+ face_flags = property(lambda self: self._FT_Face.contents.face_flags,
1911
+ doc = '''A set of bit flags that give important information about
1912
+ the face; see FT_FACE_FLAG_XXX for the details.''')
1913
+
1914
+ style_flags = property(lambda self: self._FT_Face.contents.style_flags,
1915
+ doc = '''A set of bit flags indicating the style of the face; see
1916
+ FT_STYLE_FLAG_XXX for the details.''')
1917
+
1918
+ num_glyphs = property(lambda self: self._FT_Face.contents.num_glyphs,
1919
+ doc = '''The number of glyphs in the face. If the face is scalable
1920
+ and has sbits (see 'num_fixed_sizes'), it is set to the number of
1921
+ outline glyphs.
1922
+
1923
+ For CID-keyed fonts, this value gives the highest CID used in the
1924
+ font.''')
1925
+
1926
+ family_name = property(lambda self: self._FT_Face.contents.family_name,
1927
+ doc = '''The face's family name. This is an ASCII string, usually
1928
+ in English, which describes the typeface's family (like
1929
+ 'Times New Roman', 'Bodoni', 'Garamond', etc). This is a
1930
+ least common denominator used to list fonts. Some formats
1931
+ (TrueType & OpenType) provide localized and Unicode
1932
+ versions of this string. Applications should use the
1933
+ format specific interface to access them. Can be NULL
1934
+ (e.g., in fonts embedded in a PDF file).''')
1935
+
1936
+ style_name = property(lambda self: self._FT_Face.contents.style_name,
1937
+ doc = '''The face's style name. This is an ASCII string, usually in
1938
+ English, which describes the typeface's style (like
1939
+ 'Italic', 'Bold', 'Condensed', etc). Not all font formats
1940
+ provide a style name, so this field is optional, and can be
1941
+ set to NULL. As for 'family_name', some formats provide
1942
+ localized and Unicode versions of this string. Applications
1943
+ should use the format specific interface to access them.''')
1944
+
1945
+ num_fixed_sizes = property(lambda self: self._FT_Face.contents.num_fixed_sizes,
1946
+ doc = '''The number of bitmap strikes in the face. Even if the
1947
+ face is scalable, there might still be bitmap strikes,
1948
+ which are called 'sbits' in that case.''')
1949
+
1950
+ def _get_available_sizes( self ):
1951
+ sizes = []
1952
+ n = self.num_fixed_sizes
1953
+ FT_sizes = self._FT_Face.contents.available_sizes
1954
+ for i in range(n):
1955
+ sizes.append( BitmapSize(FT_sizes[i]) )
1956
+ return sizes
1957
+ available_sizes = property(_get_available_sizes,
1958
+ doc = '''A list of FT_Bitmap_Size for all bitmap strikes in the
1959
+ face. It is set to NULL if there is no bitmap strike.''')
1960
+
1961
+ num_charmaps = property(lambda self: self._FT_Face.contents.num_charmaps)
1962
+ def _get_charmaps( self ):
1963
+ charmaps = []
1964
+ n = self._FT_Face.contents.num_charmaps
1965
+ FT_charmaps = self._FT_Face.contents.charmaps
1966
+ for i in range(n):
1967
+ charmaps.append( Charmap(FT_charmaps[i]) )
1968
+ return charmaps
1969
+ charmaps = property(_get_charmaps,
1970
+ doc = '''A list of the charmaps of the face.''')
1971
+
1972
+ # ('generic', FT_Generic),
1973
+
1974
+ def _get_bbox( self ):
1975
+ return BBox( self._FT_Face.contents.bbox )
1976
+ bbox = property( _get_bbox,
1977
+ doc = '''The font bounding box. Coordinates are expressed in font units
1978
+ (see 'units_per_EM'). The box is large enough to contain any
1979
+ glyph from the font. Thus, 'bbox.yMax' can be seen as the
1980
+ 'maximal ascender', and 'bbox.yMin' as the 'minimal
1981
+ descender'. Only relevant for scalable formats.
1982
+
1983
+ Note that the bounding box might be off by (at least) one pixel
1984
+ for hinted fonts. See FT_Size_Metrics for further discussion.''')
1985
+
1986
+ units_per_EM = property(lambda self: self._FT_Face.contents.units_per_EM,
1987
+ doc = '''The number of font units per EM square for this
1988
+ face. This is typically 2048 for TrueType fonts, and 1000
1989
+ for Type 1 fonts. Only relevant for scalable formats.''')
1990
+
1991
+ ascender = property(lambda self: self._FT_Face.contents.ascender,
1992
+ doc = '''The typographic ascender of the face, expressed in font
1993
+ units. For font formats not having this information, it is
1994
+ set to 'bbox.yMax'. Only relevant for scalable formats.''')
1995
+
1996
+ descender = property(lambda self: self._FT_Face.contents.descender,
1997
+ doc = '''The typographic descender of the face, expressed in font
1998
+ units. For font formats not having this information, it is
1999
+ set to 'bbox.yMin'. Note that this field is usually
2000
+ negative. Only relevant for scalable formats.''')
2001
+
2002
+ height = property(lambda self: self._FT_Face.contents.height,
2003
+ doc = '''The height is the vertical distance between two consecutive
2004
+ baselines, expressed in font units. It is always positive. Only
2005
+ relevant for scalable formats.''')
2006
+
2007
+ max_advance_width = property(lambda self: self._FT_Face.contents.max_advance_width,
2008
+ doc = '''The maximal advance width, in font units, for all
2009
+ glyphs in this face. This can be used to make word
2010
+ wrapping computations faster. Only relevant for
2011
+ scalable formats.''')
2012
+
2013
+ max_advance_height = property(lambda self: self._FT_Face.contents.max_advance_height,
2014
+ doc = '''The maximal advance height, in font units, for all
2015
+ glyphs in this face. This is only relevant for
2016
+ vertical layouts, and is set to 'height' for fonts
2017
+ that do not provide vertical metrics. Only relevant
2018
+ for scalable formats.''')
2019
+
2020
+ underline_position = property(lambda self: self._FT_Face.contents.underline_position,
2021
+ doc = '''The position, in font units, of the underline line
2022
+ for this face. It is the center of the underlining
2023
+ stem. Only relevant for scalable formats.''')
2024
+
2025
+ underline_thickness = property(lambda self: self._FT_Face.contents.underline_thickness,
2026
+ doc = '''The thickness, in font units, of the underline for
2027
+ this face. Only relevant for scalable formats.''')
2028
+
2029
+
2030
+ def _get_glyph( self ):
2031
+ return GlyphSlot( self._FT_Face.contents.glyph )
2032
+ glyph = property( _get_glyph,
2033
+ doc = '''The face's associated glyph slot(s).''')
2034
+
2035
+ def _get_size( self ):
2036
+ size = self._FT_Face.contents.size
2037
+ metrics = size.contents.metrics
2038
+ return SizeMetrics(metrics)
2039
+ size = property( _get_size,
2040
+ doc = '''The current active size for this face.''')
2041
+
2042
+ def _get_charmap( self ):
2043
+ return Charmap( self._FT_Face.contents.charmap)
2044
+ charmap = property( _get_charmap,
2045
+ doc = '''The current active charmap for this face.''')
2046
+
2047
+
2048
+
2049
+ # -----------------------------------------------------------------------------
2050
+ # SfntName wrapper
2051
+ # -----------------------------------------------------------------------------
2052
+ class SfntName( object ):
2053
+ '''
2054
+ SfntName wrapper
2055
+
2056
+ A structure used to model an SFNT 'name' table entry.
2057
+ '''
2058
+ def __init__(self, name):
2059
+ '''
2060
+ Create a new SfntName object.
2061
+
2062
+ :param name : SFNT 'name' table entry.
2063
+
2064
+ '''
2065
+ self._FT_SfntName = name
2066
+
2067
+ platform_id = property(lambda self: self._FT_SfntName.platform_id,
2068
+ doc = '''The platform ID for 'string'.''')
2069
+
2070
+ encoding_id = property(lambda self: self._FT_SfntName.encoding_id,
2071
+ doc = '''The encoding ID for 'string'.''')
2072
+
2073
+ language_id = property(lambda self: self._FT_SfntName.language_id,
2074
+ doc = '''The language ID for 'string'.''')
2075
+
2076
+ name_id = property(lambda self: self._FT_SfntName.name_id,
2077
+ doc = '''An identifier for 'string'.''')
2078
+
2079
+ #string = property(lambda self: self._FT_SfntName.string)
2080
+
2081
+ string_len = property(lambda self: self._FT_SfntName.string_len,
2082
+ doc = '''The length of 'string' in bytes.''')
2083
+
2084
+ def _get_string(self):
2085
+ # #s = self._FT_SfntName
2086
+ s = string_at(self._FT_SfntName.string, self._FT_SfntName.string_len)
2087
+ return s
2088
+ # #return s.decode('utf-16be', 'ignore')
2089
+ # return s.decode('utf-8', 'ignore')
2090
+ # #n = s.string_len
2091
+ # #data = [s.string[i] for i in range(n)]
2092
+ # #return data
2093
+ string = property(_get_string,
2094
+ doc = '''The 'name' string. Note that its format differs depending on
2095
+ the (platform,encoding) pair. It can be a Pascal String, a
2096
+ UTF-16 one, etc.
2097
+
2098
+ Generally speaking, the string is not zero-terminated. Please
2099
+ refer to the TrueType specification for details.''')
2100
+
2101
+
2102
+
2103
+ # -----------------------------------------------------------------------------
2104
+ class Stroker( object ):
2105
+ '''
2106
+ FT_Stroker wrapper
2107
+
2108
+ This component generates stroked outlines of a given vectorial glyph. It
2109
+ also allows you to retrieve the 'outside' and/or the 'inside' borders of
2110
+ the stroke.
2111
+
2112
+ This can be useful to generate 'bordered' glyph, i.e., glyphs displayed
2113
+ with a coloured (and anti-aliased) border around their shape.
2114
+ '''
2115
+
2116
+ def __init__( self ):
2117
+ '''
2118
+ Create a new Stroker object.
2119
+ '''
2120
+ library = get_handle( )
2121
+ stroker = FT_Stroker( )
2122
+ error = FT_Stroker_New( library, byref(stroker) )
2123
+ if error: raise FT_Exception( error )
2124
+ self._FT_Stroker = stroker
2125
+
2126
+
2127
+ def __del__( self ):
2128
+ '''
2129
+ Destroy object.
2130
+ '''
2131
+ FT_Stroker_Done( self._FT_Stroker )
2132
+
2133
+
2134
+ def set( self, radius, line_cap, line_join, miter_limit ):
2135
+ '''
2136
+ Reset a stroker object's attributes.
2137
+
2138
+ :param radius: The border radius.
2139
+
2140
+ :param line_cap: The line cap style.
2141
+
2142
+ :param line_join: The line join style.
2143
+
2144
+ :param miter_limit: The miter limit for the FT_STROKER_LINEJOIN_MITER
2145
+ style, expressed as 16.16 fixed point value.
2146
+
2147
+ **Note**:
2148
+
2149
+ The radius is expressed in the same units as the outline coordinates.
2150
+ '''
2151
+ FT_Stroker_Set( self._FT_Stroker,
2152
+ radius, line_cap, line_join, miter_limit )
2153
+
2154
+
2155
+ def rewind( self ):
2156
+ '''
2157
+ Reset a stroker object without changing its attributes. You should call
2158
+ this function before beginning a new series of calls to
2159
+ FT_Stroker_BeginSubPath or FT_Stroker_EndSubPath.
2160
+ '''
2161
+ FT_Stroker_Rewind( self._FT_Stroker )
2162
+
2163
+
2164
+ def parse_outline( self, outline, opened ):
2165
+ '''
2166
+ A convenience function used to parse a whole outline with the
2167
+ stroker. The resulting outline(s) can be retrieved later by functions
2168
+ like FT_Stroker_GetCounts and FT_Stroker_Export.
2169
+
2170
+ :param outline: The source outline.
2171
+
2172
+ :pram opened: A boolean. If 1, the outline is treated as an open path
2173
+ instead of a closed one.
2174
+
2175
+ **Note**:
2176
+
2177
+ If 'opened' is 0 (the default), the outline is treated as a closed
2178
+ path, and the stroker generates two distinct 'border' outlines.
2179
+
2180
+ If 'opened' is 1, the outline is processed as an open path, and the
2181
+ stroker generates a single 'stroke' outline.
2182
+
2183
+ This function calls 'rewind' automatically.
2184
+ '''
2185
+ error = FT_Stroker_ParseOutline( self._FT_Stroker, byref(outline._FT_Outline), opened)
2186
+ if error: raise FT_Exception( error )
2187
+
2188
+
2189
+ def begin_subpath( self, to, _open ):
2190
+ '''
2191
+ Start a new sub-path in the stroker.
2192
+
2193
+ :param to A pointer to the start vector.
2194
+
2195
+ :param _open: A boolean. If 1, the sub-path is treated as an open one.
2196
+
2197
+ **Note**:
2198
+
2199
+ This function is useful when you need to stroke a path that is not
2200
+ stored as an 'Outline' object.
2201
+ '''
2202
+ error = FT_Stroker_BeginSubPath( self._FT_Stroker, to, _open )
2203
+ if error: raise FT_Exception( error )
2204
+
2205
+
2206
+ def end_subpath( self ):
2207
+ '''
2208
+ Close the current sub-path in the stroker.
2209
+
2210
+ **Note**:
2211
+
2212
+ You should call this function after 'begin_subpath'. If the subpath
2213
+ was not 'opened', this function 'draws' a single line segment to the
2214
+ start position when needed.
2215
+ '''
2216
+ error = FT_Stroker_EndSubPath( self._FT_Stroker)
2217
+ if error: raise FT_Exception( error )
2218
+
2219
+
2220
+ def line_to( self, to ):
2221
+ '''
2222
+ 'Draw' a single line segment in the stroker's current sub-path, from
2223
+ the last position.
2224
+
2225
+ :param to: A pointer to the destination point.
2226
+
2227
+ **Note**:
2228
+
2229
+ You should call this function between 'begin_subpath' and
2230
+ 'end_subpath'.
2231
+ '''
2232
+ error = FT_Stroker_LineTo( self._FT_Stroker, to )
2233
+ if error: raise FT_Exception( error )
2234
+
2235
+
2236
+ def conic_to( self, control, to ):
2237
+ '''
2238
+ 'Draw' a single quadratic Bezier in the stroker's current sub-path,
2239
+ from the last position.
2240
+
2241
+ :param control: A pointer to a Bezier control point.
2242
+
2243
+ :param to: A pointer to the destination point.
2244
+
2245
+ **Note**:
2246
+
2247
+ You should call this function between 'begin_subpath' and
2248
+ 'end_subpath'.
2249
+ '''
2250
+ error = FT_Stroker_ConicTo( self._FT_Stroker, control, to )
2251
+ if error: raise FT_Exception( error )
2252
+
2253
+
2254
+ def cubic_to( self, control1, control2, to ):
2255
+ '''
2256
+ 'Draw' a single quadratic Bezier in the stroker's current sub-path,
2257
+ from the last position.
2258
+
2259
+ :param control1: A pointer to the first Bezier control point.
2260
+
2261
+ :param control2: A pointer to second Bezier control point.
2262
+
2263
+ :param to: A pointer to the destination point.
2264
+
2265
+ **Note**:
2266
+
2267
+ You should call this function between 'begin_subpath' and
2268
+ 'end_subpath'.
2269
+ '''
2270
+ error = FT_Stroker_CubicTo( self._FT_Stroker, control1, control2, to )
2271
+ if error: raise FT_Exception( error )
2272
+
2273
+
2274
+ def get_border_counts( self, border ):
2275
+ '''
2276
+ Call this function once you have finished parsing your paths with the
2277
+ stroker. It returns the number of points and contours necessary to
2278
+ export one of the 'border' or 'stroke' outlines generated by the
2279
+ stroker.
2280
+
2281
+ :param border: The border index.
2282
+
2283
+ :return: number of points, number of contours
2284
+ '''
2285
+ anum_points = FT_UInt()
2286
+ anum_contours = FT_UInt()
2287
+ error = FT_Stroker_GetBorderCounts( self._FT_Stroker, border,
2288
+ byref(anum_points), byref(anum_contours) )
2289
+ if error: raise FT_Exception( error )
2290
+ return anum_points.value, anum_contours.value
2291
+
2292
+
2293
+ def export_border( self , border, outline ):
2294
+ '''
2295
+ Call this function after 'get_border_counts' to export the
2296
+ corresponding border to your own 'Outline' structure.
2297
+
2298
+ Note that this function appends the border points and contours to your
2299
+ outline, but does not try to resize its arrays.
2300
+
2301
+ :param border: The border index.
2302
+
2303
+ :param outline: The target outline.
2304
+
2305
+ **Note**:
2306
+
2307
+ Always call this function after get_border_counts to get sure that
2308
+ there is enough room in your 'Outline' object to receive all new
2309
+ data.
2310
+
2311
+ When an outline, or a sub-path, is 'closed', the stroker generates two
2312
+ independent 'border' outlines, named 'left' and 'right'
2313
+
2314
+ When the outline, or a sub-path, is 'opened', the stroker merges the
2315
+ 'border' outlines with caps. The 'left' border receives all points,
2316
+ while the 'right' border becomes empty.
2317
+
2318
+ Use the function export instead if you want to retrieve all borders
2319
+ at once.
2320
+ '''
2321
+ FT_Stroker_ExportBorder( self._FT_Stroker, border, byref(outline._FT_Outline) )
2322
+
2323
+
2324
+ def get_counts( self ):
2325
+ '''
2326
+ Call this function once you have finished parsing your paths with the
2327
+ stroker. It returns the number of points and contours necessary to
2328
+ export all points/borders from the stroked outline/path.
2329
+
2330
+ :return: number of points, number of contours
2331
+ '''
2332
+
2333
+ anum_points = FT_UInt()
2334
+ anum_contours = FT_UInt()
2335
+ error = FT_Stroker_GetCounts( self._FT_Stroker,
2336
+ byref(anum_points), byref(anum_contours) )
2337
+ if error: raise FT_Exception( error )
2338
+ return anum_points.value, anum_contours.value
2339
+
2340
+
2341
+ def export( self, outline ):
2342
+ '''
2343
+ Call this function after get_border_counts to export all borders to
2344
+ your own 'Outline' structure.
2345
+
2346
+ Note that this function appends the border points and contours to your
2347
+ outline, but does not try to resize its arrays.
2348
+
2349
+ :param outline: The target outline.
2350
+ '''
2351
+ FT_Stroker_Export( self._FT_Stroker, byref(outline._FT_Outline) )
2352
+
2353
+
2354
+ # -----------------------------------------------------------------------------
2355
+ # Classes related to Variable Font support
2356
+ #
2357
+ class VariationAxis(object):
2358
+ tag = None
2359
+ coords = tuple()
2360
+
2361
+ def __init__(self, ftvaraxis):
2362
+ self.tag = unmake_tag(ftvaraxis.tag)
2363
+ self.name = ftvaraxis.name.decode('ascii')
2364
+ self.minimum = ftvaraxis.minimum/65536.0
2365
+ self.default = ftvaraxis.default/65536.0
2366
+ self.maximum = ftvaraxis.maximum/65536.0
2367
+ self.strid = ftvaraxis.strid # do we need this? Should be same as 'name'...
2368
+
2369
+ def __repr__(self):
2370
+ return "<VariationAxis '{}' ('{}') [{}, {}, {}]>".format(
2371
+ self.tag, self.name, self.minimum, self.default, self.maximum)
2372
+
2373
+ class VariationInstance(object):
2374
+ def __init__(self, name, psname, coords):
2375
+ self.name = name
2376
+ self.psname = psname
2377
+ self.coords = coords
2378
+
2379
+ def __repr__(self):
2380
+ return "<VariationInstance '{}' {}>".format(
2381
+ self.name, self.coords)
2382
+
2383
+ class VariationSpaceInfo(object):
2384
+ """
2385
+ VF info (axes & instances).
2386
+ """
2387
+ def __init__(self, face, p_ftmmvar):
2388
+ """
2389
+ Build a VariationSpaceInfo object given face (freetype.Face) and
2390
+ p_ftmmvar (pointer to FT_MM_Var).
2391
+ """
2392
+ ftmv = p_ftmmvar.contents
2393
+
2394
+ axes = []
2395
+ for axidx in range(ftmv.num_axis):
2396
+ axes.append(VariationAxis(ftmv.axis[axidx]))
2397
+
2398
+ self.axes = tuple(axes)
2399
+
2400
+ inst = []
2401
+ for instidx in range(ftmv.num_namedstyles):
2402
+ instinfo = ftmv.namedstyle[instidx]
2403
+ nid = instinfo.strid
2404
+ name = face.get_best_name_string(nid)
2405
+ psid = instinfo.psid
2406
+ psname = face.get_best_name_string(psid)
2407
+ coords = []
2408
+ for cidx in range(len(self.axes)):
2409
+ coords.append(instinfo.coords[cidx]/65536.0)
2410
+
2411
+ inst.append(VariationInstance(name, psname, tuple(coords)))
2412
+
2413
+ self.instances = tuple(inst)
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+
4
+ HERE = os.path.dirname(__file__)
5
+
6
+
7
+ def get_hook_dirs():
8
+ return [HERE]
9
+
10
+
11
+ def get_test_dirs():
12
+ return [os.path.join(HERE, 'tests')]
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (488 Bytes). View file
 
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/__pycache__/hook-freetype.cpython-310.pyc ADDED
Binary file (275 Bytes). View file
 
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/hook-freetype.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from PyInstaller.utils.hooks import collect_dynamic_libs
2
+
3
+
4
+ binaries = collect_dynamic_libs("freetype")
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (178 Bytes). View file
 
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (221 Bytes). View file
 
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/__pycache__/test_freetype.cpython-310.pyc ADDED
Binary file (1.48 kB). View file
 
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/conftest.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from PyInstaller.utils.conftest import *
vllm/lib/python3.10/site-packages/freetype/__pyinstaller/tests/test_freetype.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def test_pyi_freetype(pyi_builder):
2
+ pyi_builder.test_source(
3
+ """
4
+ import sys
5
+ import pathlib
6
+
7
+ import freetype
8
+
9
+ # Ensure that the freetype shared library is bundled with the frozen
10
+ # application; otherwise, freetype might be using system-wide library.
11
+
12
+ # Check that freetype.FT_Library_filename is an absolute path;
13
+ # otherwise, it is likely using basename-only ctypes fallback.
14
+ ft_library_file = pathlib.Path(freetype.FT_Library_filename)
15
+ print(f"FT library file (original): {ft_library_file}", file=sys.stderr)
16
+ assert ft_library_file.is_absolute(), \
17
+ "FT library file is not an absolute path!"
18
+
19
+ # Check that fully-resolved freetype.FT_Library_filename is
20
+ # anchored in fully-resolved frozen application directory.
21
+ app_dir = pathlib.Path(__file__).resolve().parent
22
+ print(f"Application directory: {app_dir}", file=sys.stderr)
23
+
24
+ ft_library_path = pathlib.Path(ft_library_file).resolve()
25
+ print(f"FT library file (resolved): {ft_library_path}", file=sys.stderr)
26
+
27
+ assert app_dir in ft_library_path.parents, \
28
+ "FT library is not bundled with frozen application!"
29
+ """
30
+ )
vllm/lib/python3.10/site-packages/freetype/ft_enums/__init__.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ '''
9
+ Freetype enum types
10
+ -------------------
11
+
12
+ FT_CURVE_TAGS: An enumeration type for each point on an outline to indicate
13
+ whether it describes a point used to control a line segment
14
+ or an arc.
15
+
16
+ FT_PIXEL_MODES: An enumeration type used to describe the format of pixels in a
17
+ given bitmap. Note that additional formats may be added in the
18
+ future.
19
+
20
+ FT_GLYPH_BBOX_MODES: The mode how the values of FT_Glyph_Get_CBox are returned.
21
+
22
+ FT_GLYPH_FORMATS: An enumeration type used to describe the format of a given
23
+ glyph image. Note that this version of FreeType only supports
24
+ two image formats, even though future font drivers will be
25
+ able to register their own format.
26
+
27
+ FT_ENCODINGS: An enumeration used to specify character sets supported by
28
+ charmaps. Used in the FT_Select_Charmap API function.
29
+
30
+ FT_RENDER_MODES: An enumeration type that lists the render modes supported by
31
+ FreeType 2. Each mode corresponds to a specific type of
32
+ scanline conversion performed on the outline.
33
+
34
+ FT_LOAD_TARGETS: A list of values that are used to select a specific hinting
35
+ algorithm to use by the hinter. You should OR one of these
36
+ values to your 'load_flags' when calling FT_Load_Glyph.
37
+
38
+ FT_LOAD_FLAGS: A list of bit-field constants used with FT_Load_Glyph to
39
+ indicate what kind of operations to perform during glyph
40
+ loading.
41
+
42
+ FT_STYLE_FLAGS: A list of bit-flags used to indicate the style of a given
43
+ face. These are used in the 'style_flags' field of FT_FaceRec.
44
+
45
+ FT_FSTYPES: A list of bit flags that inform client applications of embedding
46
+ and subsetting restrictions associated with a font.
47
+
48
+ FT_FACE_FLAGS: A list of bit flags used in the 'face_flags' field of the
49
+ FT_FaceRec structure. They inform client applications of
50
+ properties of the corresponding face.
51
+
52
+ FT_OUTLINE_FLAGS: A list of bit-field constants use for the flags in an
53
+ outline's 'flags' field.
54
+
55
+ FT_OPEN_MODES: A list of bit-field constants used within the 'flags' field of
56
+ the FT_Open_Args structure.
57
+
58
+ FT_KERNING_MODES: An enumeration used to specify which kerning values to return
59
+ in FT_Get_Kerning.
60
+
61
+ FT_STROKER_LINEJOINS: These values determine how two joining lines are rendered
62
+ in a stroker.
63
+
64
+ FT_STROKER_LINECAPS: These values determine how the end of opened sub-paths are
65
+ rendered in a stroke.
66
+
67
+ FT_STROKER_BORDERS: These values are used to select a given stroke border in
68
+ FT_Stroker_GetBorderCounts and FT_Stroker_ExportBorder.
69
+
70
+ FT_LCD_FILTERS: A list of values to identify various types of LCD filters.
71
+
72
+ TT_PLATFORMS: A list of valid values for the 'platform_id' identifier code in
73
+ FT_CharMapRec and FT_SfntName structures.
74
+
75
+ TT_APPLE_IDS: A list of valid values for the 'encoding_id' for
76
+ TT_PLATFORM_APPLE_UNICODE charmaps and name entries.
77
+
78
+ TT_MAC_IDS: A list of valid values for the 'encoding_id' for
79
+ TT_PLATFORM_MACINTOSH charmaps and name entries.
80
+
81
+ TT_MS_IDS: A list of valid values for the 'encoding_id' for
82
+ TT_PLATFORM_MICROSOFT charmaps and name entries.
83
+
84
+ TT_ADOBE_IDS: A list of valid values for the 'encoding_id' for
85
+ TT_PLATFORM_ADOBE charmaps. This is a FreeType-specific
86
+ extension!
87
+
88
+ TT_MAC_LANGIDS: Possible values of the language identifier field in the name
89
+ records of the TTF `name' table if the `platform' identifier
90
+ code is TT_PLATFORM_MACINTOSH.
91
+
92
+ TT_MS_LANGIDS: Possible values of the language identifier field in the name
93
+ records of the TTF `name' table if the `platform' identifier
94
+ code is TT_PLATFORM_MICROSOFT.
95
+
96
+ TT_NAME_IDS: Possible values of the `name' identifier field in the name
97
+ records of the TTF `name' table. These values are platform
98
+ independent.
99
+ '''
100
+ from freetype.ft_enums.ft_color_root_transform import *
101
+ from freetype.ft_enums.ft_curve_tags import *
102
+ from freetype.ft_enums.ft_fstypes import *
103
+ from freetype.ft_enums.ft_face_flags import *
104
+ from freetype.ft_enums.ft_encodings import *
105
+ from freetype.ft_enums.ft_glyph_bbox_modes import *
106
+ from freetype.ft_enums.ft_glyph_formats import *
107
+ from freetype.ft_enums.ft_kerning_modes import *
108
+ from freetype.ft_enums.ft_lcd_filters import *
109
+ from freetype.ft_enums.ft_load_flags import *
110
+ from freetype.ft_enums.ft_load_targets import *
111
+ from freetype.ft_enums.ft_open_modes import *
112
+ from freetype.ft_enums.ft_outline_flags import *
113
+ from freetype.ft_enums.ft_pixel_modes import *
114
+ from freetype.ft_enums.ft_render_modes import *
115
+ from freetype.ft_enums.ft_stroker_borders import *
116
+ from freetype.ft_enums.ft_stroker_linecaps import *
117
+ from freetype.ft_enums.ft_stroker_linejoins import *
118
+ from freetype.ft_enums.ft_style_flags import *
119
+ from freetype.ft_enums.tt_adobe_ids import *
120
+ from freetype.ft_enums.tt_apple_ids import *
121
+ from freetype.ft_enums.tt_mac_ids import *
122
+ from freetype.ft_enums.tt_ms_ids import *
123
+ from freetype.ft_enums.tt_ms_langids import *
124
+ from freetype.ft_enums.tt_mac_langids import *
125
+ from freetype.ft_enums.tt_name_ids import *
126
+ from freetype.ft_enums.tt_platforms import *
vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_color_root_transform.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ FT_Color_Root_Transform = {
2
+ 'FT_COLOR_INCLUDE_ROOT_TRANSFORM' : 0,
3
+ 'FT_COLOR_NO_ROOT_TRANSFORM' : 1,
4
+ 'FT_COLOR_ROOT_TRANSFORM_MAX' : 2,
5
+ }
6
+ globals().update(FT_Color_Root_Transform)
vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_encodings.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ """
9
+ An enumeration used to specify character sets supported by charmaps. Used in
10
+ the FT_Select_Charmap API function.
11
+
12
+ FT_ENCODING_NONE
13
+
14
+ The encoding value 0 is reserved.
15
+
16
+ FT_ENCODING_UNICODE
17
+
18
+ Corresponds to the Unicode character set. This value covers all versions of
19
+ the Unicode repertoire, including ASCII and Latin-1. Most fonts include a
20
+ Unicode charmap, but not all of them.
21
+
22
+ For example, if you want to access Unicode value U+1F028 (and the font
23
+ contains it), use value 0x1F028 as the input value for FT_Get_Char_Index.
24
+
25
+ FT_ENCODING_MS_SYMBOL
26
+
27
+ Corresponds to the Microsoft Symbol encoding, used to encode mathematical
28
+ symbols in the 32..255 character code range. For more information, see
29
+ 'http://www.ceviz.net/symbol.htm'.
30
+
31
+ FT_ENCODING_SJIS
32
+
33
+ Corresponds to Japanese SJIS encoding. More info at at
34
+ 'http://langsupport.japanreference.com/encoding.shtml'. See note on
35
+ multi-byte encodings below.
36
+
37
+ FT_ENCODING_PRC
38
+
39
+ Corresponds to encoding systems mainly for Simplified Chinese as
40
+ used in People's Republic of China (PRC). The encoding layout
41
+ is based on GB~2312 and its supersets GBK and GB~18030.
42
+
43
+ FT_ENCODING_BIG5
44
+
45
+ Corresponds to an encoding system for Traditional Chinese as used in Taiwan
46
+ and Hong Kong.
47
+
48
+ FT_ENCODING_WANSUNG
49
+
50
+ Corresponds to the Korean encoding system known as Wansung. For more
51
+ information see 'http://www.microsoft.com/typography/unicode/949.txt'.
52
+
53
+ FT_ENCODING_JOHAB
54
+
55
+ The Korean standard character set (KS C 5601-1992), which corresponds to MS
56
+ Windows code page 1361. This character set includes all possible Hangeul
57
+ character combinations.
58
+
59
+ FT_ENCODING_ADOBE_LATIN_1
60
+
61
+ Corresponds to a Latin-1 encoding as defined in a Type 1 PostScript font. It
62
+ is limited to 256 character codes.
63
+
64
+ FT_ENCODING_ADOBE_STANDARD
65
+
66
+ Corresponds to the Adobe Standard encoding, as found in Type 1, CFF, and
67
+ OpenType/CFF fonts. It is limited to 256 character codes.
68
+
69
+ FT_ENCODING_ADOBE_EXPERT
70
+
71
+ Corresponds to the Adobe Expert encoding, as found in Type 1, CFF, and
72
+ OpenType/CFF fonts. It is limited to 256 character codes.
73
+
74
+ FT_ENCODING_ADOBE_CUSTOM
75
+
76
+ Corresponds to a custom encoding, as found in Type 1, CFF, and OpenType/CFF
77
+ fonts. It is limited to 256 character codes.
78
+
79
+ FT_ENCODING_APPLE_ROMAN
80
+
81
+ Corresponds to the 8-bit Apple roman encoding. Many TrueType and OpenType
82
+ fonts contain a charmap for this encoding, since older versions of Mac OS are
83
+ able to use it.
84
+
85
+ FT_ENCODING_OLD_LATIN_2
86
+
87
+ This value is deprecated and was never used nor reported by FreeType. Don't
88
+ use or test for it.
89
+ """
90
+
91
+ def _FT_ENC_TAG(a,b,c,d):
92
+ return ( ord(a) << 24 | ord(b) << 16 | ord(c) << 8 | ord(d) )
93
+
94
+ FT_ENCODINGS = {'FT_ENCODING_NONE' : _FT_ENC_TAG('\0','\0','\0','\0'),
95
+ 'FT_ENCODING_MS_SYMBOL' : _FT_ENC_TAG( 's','y','m','b' ),
96
+ 'FT_ENCODING_UNICODE' : _FT_ENC_TAG( 'u','n','i','c' ),
97
+ 'FT_ENCODING_SJIS' : _FT_ENC_TAG( 's','j','i','s' ),
98
+ 'FT_ENCODING_PRC' : _FT_ENC_TAG( 'g','b',' ',' ' ),
99
+ 'FT_ENCODING_BIG5' : _FT_ENC_TAG( 'b','i','g','5' ),
100
+ 'FT_ENCODING_WANSUNG' : _FT_ENC_TAG( 'w','a','n','s' ),
101
+ 'FT_ENCODING_JOHAB' : _FT_ENC_TAG( 'j','o','h','a' ),
102
+ 'FT_ENCODING_ADOBE_STANDARD' : _FT_ENC_TAG( 'A','D','O','B' ),
103
+ 'FT_ENCODING_ADOBE_EXPERT' : _FT_ENC_TAG( 'A','D','B','E' ),
104
+ 'FT_ENCODING_ADOBE_CUSTOM' : _FT_ENC_TAG( 'A','D','B','C' ),
105
+ 'FT_ENCODING_ADOBE_LATIN1' : _FT_ENC_TAG( 'l','a','t','1' ),
106
+ 'FT_ENCODING_OLD_LATIN2' : _FT_ENC_TAG( 'l','a','t','2' ),
107
+ 'FT_ENCODING_APPLE_ROMAN' : _FT_ENC_TAG( 'a','r','m','n' ) }
108
+ globals().update(FT_ENCODINGS)
vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_face_flags.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ """
9
+ A list of bit flags used in the 'face_flags' field of the FT_FaceRec
10
+ structure. They inform client applications of properties of the corresponding
11
+ face.
12
+
13
+
14
+ FT_FACE_FLAG_SCALABLE
15
+
16
+ Indicates that the face contains outline glyphs. This doesn't prevent bitmap
17
+ strikes, i.e., a face can have both this and and FT_FACE_FLAG_FIXED_SIZES
18
+ set.
19
+
20
+
21
+ FT_FACE_FLAG_FIXED_SIZES
22
+
23
+ Indicates that the face contains bitmap strikes. See also the
24
+ 'num_fixed_sizes' and 'available_sizes' fields of FT_FaceRec.
25
+
26
+
27
+ FT_FACE_FLAG_FIXED_WIDTH
28
+
29
+ Indicates that the face contains fixed-width characters (like Courier,
30
+ Lucido, MonoType, etc.).
31
+
32
+
33
+ FT_FACE_FLAG_SFNT
34
+
35
+ Indicates that the face uses the 'sfnt' storage scheme. For now, this means
36
+ TrueType and OpenType.
37
+
38
+
39
+ FT_FACE_FLAG_HORIZONTAL
40
+
41
+ Indicates that the face contains horizontal glyph metrics. This should be set
42
+ for all common formats.
43
+
44
+
45
+ FT_FACE_FLAG_VERTICAL
46
+
47
+ Indicates that the face contains vertical glyph metrics. This is only
48
+ available in some formats, not all of them.
49
+
50
+
51
+ FT_FACE_FLAG_KERNING
52
+
53
+ Indicates that the face contains kerning information. If set, the kerning
54
+ distance can be retrieved through the function FT_Get_Kerning. Otherwise the
55
+ function always return the vector (0,0). Note that FreeType doesn't handle
56
+ kerning data from the 'GPOS' table (as present in some OpenType fonts).
57
+
58
+
59
+ FT_FACE_FLAG_MULTIPLE_MASTERS
60
+
61
+ Indicates that the font contains multiple masters and is capable of
62
+ interpolating between them. See the multiple-masters specific API for
63
+ details.
64
+
65
+
66
+ FT_FACE_FLAG_GLYPH_NAMES
67
+
68
+ Indicates that the font contains glyph names that can be retrieved through
69
+ FT_Get_Glyph_Name. Note that some TrueType fonts contain broken glyph name
70
+ tables. Use the function FT_Has_PS_Glyph_Names when needed.
71
+
72
+
73
+ FT_FACE_FLAG_EXTERNAL_STREAM
74
+
75
+ Used internally by FreeType to indicate that a face's stream was provided by
76
+ the client application and should not be destroyed when FT_Done_Face is
77
+ called. Don't read or test this flag.
78
+
79
+
80
+ FT_FACE_FLAG_HINTER
81
+
82
+ Set if the font driver has a hinting machine of its own. For example, with
83
+ TrueType fonts, it makes sense to use data from the SFNT 'gasp' table only if
84
+ the native TrueType hinting engine (with the bytecode interpreter) is
85
+ available and active.
86
+
87
+
88
+ FT_FACE_FLAG_CID_KEYED
89
+
90
+ Set if the font is CID-keyed. In that case, the font is not accessed by glyph
91
+ indices but by CID values. For subsetted CID-keyed fonts this has the
92
+ consequence that not all index values are a valid argument to
93
+ FT_Load_Glyph. Only the CID values for which corresponding glyphs in the
94
+ subsetted font exist make FT_Load_Glyph return successfully; in all other
95
+ cases you get an 'FT_Err_Invalid_Argument' error.
96
+
97
+ Note that CID-keyed fonts which are in an SFNT wrapper don't have this flag
98
+ set since the glyphs are accessed in the normal way (using contiguous
99
+ indices); the 'CID-ness' isn't visible to the application.
100
+
101
+
102
+ FT_FACE_FLAG_TRICKY
103
+
104
+ Set if the font is 'tricky', this is, it always needs the font format's
105
+ native hinting engine to get a reasonable result. A typical example is the
106
+ Chinese font 'mingli.ttf' which uses TrueType bytecode instructions to move
107
+ and scale all of its subglyphs.
108
+
109
+ It is not possible to autohint such fonts using FT_LOAD_FORCE_AUTOHINT; it
110
+ will also ignore FT_LOAD_NO_HINTING. You have to set both FT_LOAD_NO_HINTING
111
+ and FT_LOAD_NO_AUTOHINT to really disable hinting; however, you probably
112
+ never want this except for demonstration purposes.
113
+
114
+ Currently, there are six TrueType fonts in the list of tricky fonts; they are
115
+ hard-coded in file 'ttobjs.c'.
116
+ """
117
+ FT_FACE_FLAGS = { 'FT_FACE_FLAG_SCALABLE' : 1 << 0,
118
+ 'FT_FACE_FLAG_FIXED_SIZES' : 1 << 1,
119
+ 'FT_FACE_FLAG_FIXED_WIDTH' : 1 << 2,
120
+ 'FT_FACE_FLAG_SFNT' : 1 << 3,
121
+ 'FT_FACE_FLAG_HORIZONTAL' : 1 << 4,
122
+ 'FT_FACE_FLAG_VERTICAL' : 1 << 5,
123
+ 'FT_FACE_FLAG_KERNING' : 1 << 6,
124
+ 'FT_FACE_FLAG_FAST_GLYPHS' : 1 << 7,
125
+ 'FT_FACE_FLAG_MULTIPLE_MASTERS' : 1 << 8,
126
+ 'FT_FACE_FLAG_GLYPH_NAMES' : 1 << 9,
127
+ 'FT_FACE_FLAG_EXTERNAL_STREAM' : 1 << 10,
128
+ 'FT_FACE_FLAG_HINTER' : 1 << 11,
129
+ 'FT_FACE_FLAG_CID_KEYED' : 1 << 12,
130
+ 'FT_FACE_FLAG_TRICKY' : 1 << 13
131
+ }
132
+ globals().update(FT_FACE_FLAGS)
vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_fstypes.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ """
9
+ A list of bit flags that inform client applications of embedding and
10
+ subsetting restrictions associated with a font.
11
+
12
+ FT_FSTYPE_INSTALLABLE_EMBEDDING
13
+
14
+ Fonts with no fsType bit set may be embedded and permanently installed on
15
+ the remote system by an application.
16
+
17
+
18
+ FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
19
+
20
+ Fonts that have only this bit set must not be modified, embedded or exchanged
21
+ in any manner without first obtaining permission of the font software
22
+ copyright owner.
23
+
24
+
25
+ FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING
26
+
27
+ If this bit is set, the font may be embedded and temporarily loaded on the
28
+ remote system. Documents containing Preview & Print fonts must be opened
29
+ 'read-only'; no edits can be applied to the document.
30
+
31
+
32
+ FT_FSTYPE_EDITABLE_EMBEDDING
33
+
34
+ If this bit is set, the font may be embedded but must only be installed
35
+ temporarily on other systems. In contrast to Preview & Print fonts,
36
+ documents containing editable fonts may be opened for reading, editing is
37
+ permitted, and changes may be saved.
38
+
39
+
40
+ FT_FSTYPE_NO_SUBSETTING
41
+
42
+ If this bit is set, the font may not be subsetted prior to embedding.
43
+
44
+
45
+ FT_FSTYPE_BITMAP_EMBEDDING_ONLY
46
+
47
+ If this bit is set, only bitmaps contained in the font may be embedded; no
48
+ outline data may be embedded. If there are no bitmaps available in the font,
49
+ then the font is unembeddable.
50
+ """
51
+
52
+ FT_FSTYPES = {'FT_FSTYPE_INSTALLABLE_EMBEDDING' : 0x0000,
53
+ 'FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING' : 0x0002,
54
+ 'FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING' : 0x0004,
55
+ 'FT_FSTYPE_EDITABLE_EMBEDDING' : 0x0008,
56
+ 'FT_FSTYPE_NO_SUBSETTING' : 0x0100,
57
+ 'FT_FSTYPE_BITMAP_EMBEDDING_ONLY' : 0x0200,}
58
+ globals().update(FT_FSTYPES)
59
+ ft_fstype_installable_embedding = FT_FSTYPE_INSTALLABLE_EMBEDDING
60
+ ft_fstype_restricted_license_embedding = FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
61
+ ft_fstype_preview_and_print_embedding = FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING
62
+ ft_fstype_editable_embedding = FT_FSTYPE_EDITABLE_EMBEDDING
63
+ ft_fstype_no_subsetting = FT_FSTYPE_NO_SUBSETTING
64
+ ft_fstype_bitmap_embedding_only = FT_FSTYPE_BITMAP_EMBEDDING_ONLY
vllm/lib/python3.10/site-packages/freetype/ft_enums/ft_glyph_formats.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ #
4
+ # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
5
+ # Distributed under the terms of the new BSD license.
6
+ #
7
+ # -----------------------------------------------------------------------------
8
+ """
9
+ An enumeration type used to describe the format of a given glyph image. Note
10
+ that this version of FreeType only supports two image formats, even though
11
+ future font drivers will be able to register their own format.
12
+
13
+ FT_GLYPH_FORMAT_NONE
14
+
15
+ The value 0 is reserved.
16
+
17
+ FT_GLYPH_FORMAT_COMPOSITE
18
+
19
+ The glyph image is a composite of several other images. This format is only
20
+ used with FT_LOAD_NO_RECURSE, and is used to report compound glyphs (like
21
+ accented characters).
22
+
23
+ FT_GLYPH_FORMAT_BITMAP
24
+
25
+ The glyph image is a bitmap, and can be described as an FT_Bitmap. You
26
+ generally need to access the 'bitmap' field of the FT_GlyphSlotRec structure
27
+ to read it.
28
+
29
+ FT_GLYPH_FORMAT_OUTLINE
30
+
31
+ The glyph image is a vectorial outline made of line segments and Bezier arcs;
32
+ it can be described as an FT_Outline; you generally want to access the
33
+ 'outline' field of the FT_GlyphSlotRec structure to read it.
34
+
35
+ FT_GLYPH_FORMAT_PLOTTER
36
+
37
+ The glyph image is a vectorial path with no inside and outside contours. Some
38
+ Type 1 fonts, like those in the Hershey family, contain glyphs in this
39
+ format. These are described as FT_Outline, but FreeType isn't currently
40
+ capable of rendering them correctly.
41
+
42
+ FT_GLYPH_FORMAT_SVG
43
+
44
+ [Since 2.12] The glyph is represented by an SVG document in the 'SVG~' table.
45
+ """
46
+
47
+ def _FT_IMAGE_TAG(a,b,c,d):
48
+ return ( ord(a) << 24 | ord(b) << 16 | ord(c) << 8 | ord(d) )
49
+
50
+ FT_GLYPH_FORMATS = {
51
+ 'FT_GLYPH_FORMAT_NONE' : _FT_IMAGE_TAG( '\0','\0','\0','\0' ),
52
+ 'FT_GLYPH_FORMAT_COMPOSITE' : _FT_IMAGE_TAG( 'c','o','m','p' ),
53
+ 'FT_GLYPH_FORMAT_BITMAP' : _FT_IMAGE_TAG( 'b','i','t','s' ),
54
+ 'FT_GLYPH_FORMAT_OUTLINE' : _FT_IMAGE_TAG( 'o','u','t','l' ),
55
+ 'FT_GLYPH_FORMAT_PLOTTER' : _FT_IMAGE_TAG( 'p','l','o','t' ),
56
+ 'FT_GLYPH_FORMAT_SVG' : _FT_IMAGE_TAG( 'S','V','G',' ' )}
57
+ globals().update(FT_GLYPH_FORMATS)
58
+ ft_glyph_format_none = FT_GLYPH_FORMAT_NONE
59
+ ft_glyph_format_composite = FT_GLYPH_FORMAT_COMPOSITE
60
+ ft_glyph_format_bitmap = FT_GLYPH_FORMAT_BITMAP
61
+ ft_glyph_format_outline = FT_GLYPH_FORMAT_OUTLINE
62
+ ft_glyph_format_plotter = FT_GLYPH_FORMAT_PLOTTER
63
+ ft_glyph_format_svg = FT_GLYPH_FORMAT_SVG