content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
"""\nNothing here but dictionaries for generating LinearSegmentedColormaps,\nand a dictionary of these dictionaries.\n\nDocumentation for each is in pyplot.colormaps(). Please update this\nwith the purpose and type of your colormap if you add data for one here.\n"""\n\nfrom functools import partial\n\nimport numpy as np\n\n_binary_data = {\n 'red': ((0., 1., 1.), (1., 0., 0.)),\n 'green': ((0., 1., 1.), (1., 0., 0.)),\n 'blue': ((0., 1., 1.), (1., 0., 0.))\n }\n\n_autumn_data = {'red': ((0., 1.0, 1.0), (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),\n 'blue': ((0., 0., 0.), (1.0, 0., 0.))}\n\n_bone_data = {'red': ((0., 0., 0.),\n (0.746032, 0.652778, 0.652778),\n (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.),\n (0.365079, 0.319444, 0.319444),\n (0.746032, 0.777778, 0.777778),\n (1.0, 1.0, 1.0)),\n 'blue': ((0., 0., 0.),\n (0.365079, 0.444444, 0.444444),\n (1.0, 1.0, 1.0))}\n\n_cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),\n 'green': ((0., 1., 1.), (1.0, 0., 0.)),\n 'blue': ((0., 1., 1.), (1.0, 1., 1.))}\n\n_copper_data = {'red': ((0., 0., 0.),\n (0.809524, 1.000000, 1.000000),\n (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.),\n (1.0, 0.7812, 0.7812)),\n 'blue': ((0., 0., 0.),\n (1.0, 0.4975, 0.4975))}\n\ndef _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5\ndef _flag_green(x): return np.sin(x * 31.5 * np.pi)\ndef _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5\n_flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue}\n\ndef _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67\ndef _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33\ndef _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi)\n_prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue}\n\ndef _ch_helper(gamma, s, r, h, p0, p1, x):\n """Helper function for generating picklable cubehelix colormaps."""\n # Apply gamma factor to emphasise low or high intensity values\n xg = x ** gamma\n # Calculate amplitude and angle of deviation from the black to white\n # diagonal in the plane of constant perceived intensity.\n a = h * xg * (1 - xg) / 2\n phi = 2 * np.pi * (s / 3 + r * x)\n return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))\n\ndef cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0):\n """\n Return custom data dictionary of (r, g, b) conversion functions, which can\n be used with `.ColormapRegistry.register`, for the cubehelix color scheme.\n\n Unlike most other color schemes cubehelix was designed by D.A. Green to\n be monotonically increasing in terms of perceived brightness.\n Also, when printed on a black and white postscript printer, the scheme\n results in a greyscale with monotonically increasing brightness.\n This color scheme is named cubehelix because the (r, g, b) values produced\n can be visualised as a squashed helix around the diagonal in the\n (r, g, b) color cube.\n\n For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the\n range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black,\n and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*,\n between 0 and 1, the color is the corresponding grey value at that\n fraction along the black to white diagonal (x, x, x) plus a color\n element. This color element is calculated in a plane of constant\n perceived intensity and controlled by the following parameters.\n\n Parameters\n ----------\n gamma : float, default: 1\n Gamma factor emphasizing either low intensity values (gamma < 1), or\n high intensity values (gamma > 1).\n s : float, default: 0.5 (purple)\n The starting color.\n r : float, default: -1.5\n The number of r, g, b rotations in color that are made from the start\n to the end of the color scheme. The default of -1.5 corresponds to ->\n B -> G -> R -> B.\n h : float, default: 1\n The hue, i.e. how saturated the colors are. If this parameter is zero\n then the color scheme is purely a greyscale.\n """\n return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277),\n 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649),\n 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)}\n\n_cubehelix_data = cubehelix()\n\n_bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))\n_brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))\n\n# Gnuplot palette functions\ndef _g0(x): return 0\ndef _g1(x): return 0.5\ndef _g2(x): return 1\ndef _g3(x): return x\ndef _g4(x): return x ** 2\ndef _g5(x): return x ** 3\ndef _g6(x): return x ** 4\ndef _g7(x): return np.sqrt(x)\ndef _g8(x): return np.sqrt(np.sqrt(x))\ndef _g9(x): return np.sin(x * np.pi / 2)\ndef _g10(x): return np.cos(x * np.pi / 2)\ndef _g11(x): return np.abs(x - 0.5)\ndef _g12(x): return (2 * x - 1) ** 2\ndef _g13(x): return np.sin(x * np.pi)\ndef _g14(x): return np.abs(np.cos(x * np.pi))\ndef _g15(x): return np.sin(x * 2 * np.pi)\ndef _g16(x): return np.cos(x * 2 * np.pi)\ndef _g17(x): return np.abs(np.sin(x * 2 * np.pi))\ndef _g18(x): return np.abs(np.cos(x * 2 * np.pi))\ndef _g19(x): return np.abs(np.sin(x * 4 * np.pi))\ndef _g20(x): return np.abs(np.cos(x * 4 * np.pi))\ndef _g21(x): return 3 * x\ndef _g22(x): return 3 * x - 1\ndef _g23(x): return 3 * x - 2\ndef _g24(x): return np.abs(3 * x - 1)\ndef _g25(x): return np.abs(3 * x - 2)\ndef _g26(x): return (3 * x - 1) / 2\ndef _g27(x): return (3 * x - 2) / 2\ndef _g28(x): return np.abs((3 * x - 1) / 2)\ndef _g29(x): return np.abs((3 * x - 2) / 2)\ndef _g30(x): return x / 0.32 - 0.78125\ndef _g31(x): return 2 * x - 0.84\ndef _g32(x):\n ret = np.zeros(len(x))\n m = (x < 0.25)\n ret[m] = 4 * x[m]\n m = (x >= 0.25) & (x < 0.92)\n ret[m] = -2 * x[m] + 1.84\n m = (x >= 0.92)\n ret[m] = x[m] / 0.08 - 11.5\n return ret\ndef _g33(x): return np.abs(2 * x - 0.5)\ndef _g34(x): return 2 * x\ndef _g35(x): return 2 * x - 0.5\ndef _g36(x): return 2 * x - 1\n\ngfunc = {i: globals()[f"_g{i}"] for i in range(37)}\n\n_gnuplot_data = {\n 'red': gfunc[7],\n 'green': gfunc[5],\n 'blue': gfunc[15],\n}\n\n_gnuplot2_data = {\n 'red': gfunc[30],\n 'green': gfunc[31],\n 'blue': gfunc[32],\n}\n\n_ocean_data = {\n 'red': gfunc[23],\n 'green': gfunc[28],\n 'blue': gfunc[3],\n}\n\n_afmhot_data = {\n 'red': gfunc[34],\n 'green': gfunc[35],\n 'blue': gfunc[36],\n}\n\n_rainbow_data = {\n 'red': gfunc[33],\n 'green': gfunc[13],\n 'blue': gfunc[10],\n}\n\n_seismic_data = (\n (0.0, 0.0, 0.3), (0.0, 0.0, 1.0),\n (1.0, 1.0, 1.0), (1.0, 0.0, 0.0),\n (0.5, 0.0, 0.0))\n\n_terrain_data = (\n (0.00, (0.2, 0.2, 0.6)),\n (0.15, (0.0, 0.6, 1.0)),\n (0.25, (0.0, 0.8, 0.4)),\n (0.50, (1.0, 1.0, 0.6)),\n (0.75, (0.5, 0.36, 0.33)),\n (1.00, (1.0, 1.0, 1.0)))\n\n_gray_data = {'red': ((0., 0, 0), (1., 1, 1)),\n 'green': ((0., 0, 0), (1., 1, 1)),\n 'blue': ((0., 0, 0), (1., 1, 1))}\n\n_hot_data = {'red': ((0., 0.0416, 0.0416),\n (0.365079, 1.000000, 1.000000),\n (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.),\n (0.365079, 0.000000, 0.000000),\n (0.746032, 1.000000, 1.000000),\n (1.0, 1.0, 1.0)),\n 'blue': ((0., 0., 0.),\n (0.746032, 0.000000, 0.000000),\n (1.0, 1.0, 1.0))}\n\n_hsv_data = {'red': ((0., 1., 1.),\n (0.158730, 1.000000, 1.000000),\n (0.174603, 0.968750, 0.968750),\n (0.333333, 0.031250, 0.031250),\n (0.349206, 0.000000, 0.000000),\n (0.666667, 0.000000, 0.000000),\n (0.682540, 0.031250, 0.031250),\n (0.841270, 0.968750, 0.968750),\n (0.857143, 1.000000, 1.000000),\n (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.),\n (0.158730, 0.937500, 0.937500),\n (0.174603, 1.000000, 1.000000),\n (0.507937, 1.000000, 1.000000),\n (0.666667, 0.062500, 0.062500),\n (0.682540, 0.000000, 0.000000),\n (1.0, 0., 0.)),\n 'blue': ((0., 0., 0.),\n (0.333333, 0.000000, 0.000000),\n (0.349206, 0.062500, 0.062500),\n (0.507937, 1.000000, 1.000000),\n (0.841270, 1.000000, 1.000000),\n (0.857143, 0.937500, 0.937500),\n (1.0, 0.09375, 0.09375))}\n\n_jet_data = {'red': ((0.00, 0, 0),\n (0.35, 0, 0),\n (0.66, 1, 1),\n (0.89, 1, 1),\n (1.00, 0.5, 0.5)),\n 'green': ((0.000, 0, 0),\n (0.125, 0, 0),\n (0.375, 1, 1),\n (0.640, 1, 1),\n (0.910, 0, 0),\n (1.000, 0, 0)),\n 'blue': ((0.00, 0.5, 0.5),\n (0.11, 1, 1),\n (0.34, 1, 1),\n (0.65, 0, 0),\n (1.00, 0, 0))}\n\n_pink_data = {'red': ((0., 0.1178, 0.1178), (0.015873, 0.195857, 0.195857),\n (0.031746, 0.250661, 0.250661),\n (0.047619, 0.295468, 0.295468),\n (0.063492, 0.334324, 0.334324),\n (0.079365, 0.369112, 0.369112),\n (0.095238, 0.400892, 0.400892),\n (0.111111, 0.430331, 0.430331),\n (0.126984, 0.457882, 0.457882),\n (0.142857, 0.483867, 0.483867),\n (0.158730, 0.508525, 0.508525),\n (0.174603, 0.532042, 0.532042),\n (0.190476, 0.554563, 0.554563),\n (0.206349, 0.576204, 0.576204),\n (0.222222, 0.597061, 0.597061),\n (0.238095, 0.617213, 0.617213),\n (0.253968, 0.636729, 0.636729),\n (0.269841, 0.655663, 0.655663),\n (0.285714, 0.674066, 0.674066),\n (0.301587, 0.691980, 0.691980),\n (0.317460, 0.709441, 0.709441),\n (0.333333, 0.726483, 0.726483),\n (0.349206, 0.743134, 0.743134),\n (0.365079, 0.759421, 0.759421),\n (0.380952, 0.766356, 0.766356),\n (0.396825, 0.773229, 0.773229),\n (0.412698, 0.780042, 0.780042),\n (0.428571, 0.786796, 0.786796),\n (0.444444, 0.793492, 0.793492),\n (0.460317, 0.800132, 0.800132),\n (0.476190, 0.806718, 0.806718),\n (0.492063, 0.813250, 0.813250),\n (0.507937, 0.819730, 0.819730),\n (0.523810, 0.826160, 0.826160),\n (0.539683, 0.832539, 0.832539),\n (0.555556, 0.838870, 0.838870),\n (0.571429, 0.845154, 0.845154),\n (0.587302, 0.851392, 0.851392),\n (0.603175, 0.857584, 0.857584),\n (0.619048, 0.863731, 0.863731),\n (0.634921, 0.869835, 0.869835),\n (0.650794, 0.875897, 0.875897),\n (0.666667, 0.881917, 0.881917),\n (0.682540, 0.887896, 0.887896),\n (0.698413, 0.893835, 0.893835),\n (0.714286, 0.899735, 0.899735),\n (0.730159, 0.905597, 0.905597),\n (0.746032, 0.911421, 0.911421),\n (0.761905, 0.917208, 0.917208),\n (0.777778, 0.922958, 0.922958),\n (0.793651, 0.928673, 0.928673),\n (0.809524, 0.934353, 0.934353),\n (0.825397, 0.939999, 0.939999),\n (0.841270, 0.945611, 0.945611),\n (0.857143, 0.951190, 0.951190),\n (0.873016, 0.956736, 0.956736),\n (0.888889, 0.962250, 0.962250),\n (0.904762, 0.967733, 0.967733),\n (0.920635, 0.973185, 0.973185),\n (0.936508, 0.978607, 0.978607),\n (0.952381, 0.983999, 0.983999),\n (0.968254, 0.989361, 0.989361),\n (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),\n (0.031746, 0.145479, 0.145479),\n (0.047619, 0.178174, 0.178174),\n (0.063492, 0.205738, 0.205738),\n (0.079365, 0.230022, 0.230022),\n (0.095238, 0.251976, 0.251976),\n (0.111111, 0.272166, 0.272166),\n (0.126984, 0.290957, 0.290957),\n (0.142857, 0.308607, 0.308607),\n (0.158730, 0.325300, 0.325300),\n (0.174603, 0.341178, 0.341178),\n (0.190476, 0.356348, 0.356348),\n (0.206349, 0.370899, 0.370899),\n (0.222222, 0.384900, 0.384900),\n (0.238095, 0.398410, 0.398410),\n (0.253968, 0.411476, 0.411476),\n (0.269841, 0.424139, 0.424139),\n (0.285714, 0.436436, 0.436436),\n (0.301587, 0.448395, 0.448395),\n (0.317460, 0.460044, 0.460044),\n (0.333333, 0.471405, 0.471405),\n (0.349206, 0.482498, 0.482498),\n (0.365079, 0.493342, 0.493342),\n (0.380952, 0.517549, 0.517549),\n (0.396825, 0.540674, 0.540674),\n (0.412698, 0.562849, 0.562849),\n (0.428571, 0.584183, 0.584183),\n (0.444444, 0.604765, 0.604765),\n (0.460317, 0.624669, 0.624669),\n (0.476190, 0.643958, 0.643958),\n (0.492063, 0.662687, 0.662687),\n (0.507937, 0.680900, 0.680900),\n (0.523810, 0.698638, 0.698638),\n (0.539683, 0.715937, 0.715937),\n (0.555556, 0.732828, 0.732828),\n (0.571429, 0.749338, 0.749338),\n (0.587302, 0.765493, 0.765493),\n (0.603175, 0.781313, 0.781313),\n (0.619048, 0.796819, 0.796819),\n (0.634921, 0.812029, 0.812029),\n (0.650794, 0.826960, 0.826960),\n (0.666667, 0.841625, 0.841625),\n (0.682540, 0.856040, 0.856040),\n (0.698413, 0.870216, 0.870216),\n (0.714286, 0.884164, 0.884164),\n (0.730159, 0.897896, 0.897896),\n (0.746032, 0.911421, 0.911421),\n (0.761905, 0.917208, 0.917208),\n (0.777778, 0.922958, 0.922958),\n (0.793651, 0.928673, 0.928673),\n (0.809524, 0.934353, 0.934353),\n (0.825397, 0.939999, 0.939999),\n (0.841270, 0.945611, 0.945611),\n (0.857143, 0.951190, 0.951190),\n (0.873016, 0.956736, 0.956736),\n (0.888889, 0.962250, 0.962250),\n (0.904762, 0.967733, 0.967733),\n (0.920635, 0.973185, 0.973185),\n (0.936508, 0.978607, 0.978607),\n (0.952381, 0.983999, 0.983999),\n (0.968254, 0.989361, 0.989361),\n (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),\n 'blue': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),\n (0.031746, 0.145479, 0.145479),\n (0.047619, 0.178174, 0.178174),\n (0.063492, 0.205738, 0.205738),\n (0.079365, 0.230022, 0.230022),\n (0.095238, 0.251976, 0.251976),\n (0.111111, 0.272166, 0.272166),\n (0.126984, 0.290957, 0.290957),\n (0.142857, 0.308607, 0.308607),\n (0.158730, 0.325300, 0.325300),\n (0.174603, 0.341178, 0.341178),\n (0.190476, 0.356348, 0.356348),\n (0.206349, 0.370899, 0.370899),\n (0.222222, 0.384900, 0.384900),\n (0.238095, 0.398410, 0.398410),\n (0.253968, 0.411476, 0.411476),\n (0.269841, 0.424139, 0.424139),\n (0.285714, 0.436436, 0.436436),\n (0.301587, 0.448395, 0.448395),\n (0.317460, 0.460044, 0.460044),\n (0.333333, 0.471405, 0.471405),\n (0.349206, 0.482498, 0.482498),\n (0.365079, 0.493342, 0.493342),\n (0.380952, 0.503953, 0.503953),\n (0.396825, 0.514344, 0.514344),\n (0.412698, 0.524531, 0.524531),\n (0.428571, 0.534522, 0.534522),\n (0.444444, 0.544331, 0.544331),\n (0.460317, 0.553966, 0.553966),\n (0.476190, 0.563436, 0.563436),\n (0.492063, 0.572750, 0.572750),\n (0.507937, 0.581914, 0.581914),\n (0.523810, 0.590937, 0.590937),\n (0.539683, 0.599824, 0.599824),\n (0.555556, 0.608581, 0.608581),\n (0.571429, 0.617213, 0.617213),\n (0.587302, 0.625727, 0.625727),\n (0.603175, 0.634126, 0.634126),\n (0.619048, 0.642416, 0.642416),\n (0.634921, 0.650600, 0.650600),\n (0.650794, 0.658682, 0.658682),\n (0.666667, 0.666667, 0.666667),\n (0.682540, 0.674556, 0.674556),\n (0.698413, 0.682355, 0.682355),\n (0.714286, 0.690066, 0.690066),\n (0.730159, 0.697691, 0.697691),\n (0.746032, 0.705234, 0.705234),\n (0.761905, 0.727166, 0.727166),\n (0.777778, 0.748455, 0.748455),\n (0.793651, 0.769156, 0.769156),\n (0.809524, 0.789314, 0.789314),\n (0.825397, 0.808969, 0.808969),\n (0.841270, 0.828159, 0.828159),\n (0.857143, 0.846913, 0.846913),\n (0.873016, 0.865261, 0.865261),\n (0.888889, 0.883229, 0.883229),\n (0.904762, 0.900837, 0.900837),\n (0.920635, 0.918109, 0.918109),\n (0.936508, 0.935061, 0.935061),\n (0.952381, 0.951711, 0.951711),\n (0.968254, 0.968075, 0.968075),\n (0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))}\n\n_spring_data = {'red': ((0., 1., 1.), (1.0, 1.0, 1.0)),\n 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),\n 'blue': ((0., 1., 1.), (1.0, 0.0, 0.0))}\n\n\n_summer_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),\n 'green': ((0., 0.5, 0.5), (1.0, 1.0, 1.0)),\n 'blue': ((0., 0.4, 0.4), (1.0, 0.4, 0.4))}\n\n\n_winter_data = {'red': ((0., 0., 0.), (1.0, 0.0, 0.0)),\n 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),\n 'blue': ((0., 1., 1.), (1.0, 0.5, 0.5))}\n\n_nipy_spectral_data = {\n 'red': [\n (0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667),\n (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0),\n (0.20, 0.0, 0.0), (0.25, 0.0, 0.0),\n (0.30, 0.0, 0.0), (0.35, 0.0, 0.0),\n (0.40, 0.0, 0.0), (0.45, 0.0, 0.0),\n (0.50, 0.0, 0.0), (0.55, 0.0, 0.0),\n (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333),\n (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0),\n (0.80, 1.0, 1.0), (0.85, 1.0, 1.0),\n (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80),\n (1.0, 0.80, 0.80),\n ],\n 'green': [\n (0.0, 0.0, 0.0), (0.05, 0.0, 0.0),\n (0.10, 0.0, 0.0), (0.15, 0.0, 0.0),\n (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667),\n (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667),\n (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000),\n (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667),\n (0.60, 1.0, 1.0), (0.65, 1.0, 1.0),\n (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000),\n (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0),\n (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),\n (1.0, 0.80, 0.80),\n ],\n 'blue': [\n (0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333),\n (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667),\n (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667),\n (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667),\n (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0),\n (0.5, 0.0, 0.0), (0.55, 0.0, 0.0),\n (0.60, 0.0, 0.0), (0.65, 0.0, 0.0),\n (0.70, 0.0, 0.0), (0.75, 0.0, 0.0),\n (0.80, 0.0, 0.0), (0.85, 0.0, 0.0),\n (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),\n (1.0, 0.80, 0.80),\n ],\n}\n\n\n# 34 colormaps based on color specifications and designs\n# developed by Cynthia Brewer (https://colorbrewer2.org/).\n# The ColorBrewer palettes have been included under the terms\n# of an Apache-stype license (for details, see the file\n# LICENSE_COLORBREWER in the license directory of the matplotlib\n# source distribution).\n\n# RGB values taken from Brewer's Excel sheet, divided by 255\n\n_Blues_data = (\n (0.96862745098039216, 0.98431372549019602, 1.0 ),\n (0.87058823529411766, 0.92156862745098034, 0.96862745098039216),\n (0.77647058823529413, 0.85882352941176465, 0.93725490196078431),\n (0.61960784313725492, 0.792156862745098 , 0.88235294117647056),\n (0.41960784313725491, 0.68235294117647061, 0.83921568627450982),\n (0.25882352941176473, 0.5725490196078431 , 0.77647058823529413),\n (0.12941176470588237, 0.44313725490196076, 0.70980392156862748),\n (0.03137254901960784, 0.31764705882352939, 0.61176470588235299),\n (0.03137254901960784, 0.18823529411764706, 0.41960784313725491)\n )\n\n_BrBG_data = (\n (0.32941176470588235, 0.18823529411764706, 0.0196078431372549 ),\n (0.5490196078431373 , 0.31764705882352939, 0.0392156862745098 ),\n (0.74901960784313726, 0.50588235294117645, 0.17647058823529413),\n (0.87450980392156863, 0.76078431372549016, 0.49019607843137253),\n (0.96470588235294119, 0.90980392156862744, 0.76470588235294112),\n (0.96078431372549022, 0.96078431372549022, 0.96078431372549022),\n (0.7803921568627451 , 0.91764705882352937, 0.89803921568627454),\n (0.50196078431372548, 0.80392156862745101, 0.75686274509803919),\n (0.20784313725490197, 0.59215686274509804, 0.5607843137254902 ),\n (0.00392156862745098, 0.4 , 0.36862745098039218),\n (0.0 , 0.23529411764705882, 0.18823529411764706)\n )\n\n_BuGn_data = (\n (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),\n (0.89803921568627454, 0.96078431372549022, 0.97647058823529409),\n (0.8 , 0.92549019607843142, 0.90196078431372551),\n (0.6 , 0.84705882352941175, 0.78823529411764703),\n (0.4 , 0.76078431372549016, 0.64313725490196083),\n (0.25490196078431371, 0.68235294117647061, 0.46274509803921571),\n (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),\n (0.0 , 0.42745098039215684, 0.17254901960784313),\n (0.0 , 0.26666666666666666, 0.10588235294117647)\n )\n\n_BuPu_data = (\n (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),\n (0.8784313725490196 , 0.92549019607843142, 0.95686274509803926),\n (0.74901960784313726, 0.82745098039215681, 0.90196078431372551),\n (0.61960784313725492, 0.73725490196078436, 0.85490196078431369),\n (0.5490196078431373 , 0.58823529411764708, 0.77647058823529413),\n (0.5490196078431373 , 0.41960784313725491, 0.69411764705882351),\n (0.53333333333333333, 0.25490196078431371, 0.61568627450980395),\n (0.50588235294117645, 0.05882352941176471, 0.48627450980392156),\n (0.30196078431372547, 0.0 , 0.29411764705882354)\n )\n\n_GnBu_data = (\n (0.96862745098039216, 0.9882352941176471 , 0.94117647058823528),\n (0.8784313725490196 , 0.95294117647058818, 0.85882352941176465),\n (0.8 , 0.92156862745098034, 0.77254901960784317),\n (0.6588235294117647 , 0.8666666666666667 , 0.70980392156862748),\n (0.4823529411764706 , 0.8 , 0.7686274509803922 ),\n (0.30588235294117649, 0.70196078431372544, 0.82745098039215681),\n (0.16862745098039217, 0.5490196078431373 , 0.74509803921568629),\n (0.03137254901960784, 0.40784313725490196, 0.67450980392156867),\n (0.03137254901960784, 0.25098039215686274, 0.50588235294117645)\n )\n\n_Greens_data = (\n (0.96862745098039216, 0.9882352941176471 , 0.96078431372549022),\n (0.89803921568627454, 0.96078431372549022, 0.8784313725490196 ),\n (0.7803921568627451 , 0.9137254901960784 , 0.75294117647058822),\n (0.63137254901960782, 0.85098039215686272, 0.60784313725490191),\n (0.45490196078431372, 0.7686274509803922 , 0.46274509803921571),\n (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),\n (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),\n (0.0 , 0.42745098039215684, 0.17254901960784313),\n (0.0 , 0.26666666666666666, 0.10588235294117647)\n )\n\n_Greys_data = (\n (1.0 , 1.0 , 1.0 ),\n (0.94117647058823528, 0.94117647058823528, 0.94117647058823528),\n (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),\n (0.74117647058823533, 0.74117647058823533, 0.74117647058823533),\n (0.58823529411764708, 0.58823529411764708, 0.58823529411764708),\n (0.45098039215686275, 0.45098039215686275, 0.45098039215686275),\n (0.32156862745098042, 0.32156862745098042, 0.32156862745098042),\n (0.14509803921568629, 0.14509803921568629, 0.14509803921568629),\n (0.0 , 0.0 , 0.0 )\n )\n\n_Oranges_data = (\n (1.0 , 0.96078431372549022, 0.92156862745098034),\n (0.99607843137254903, 0.90196078431372551, 0.80784313725490198),\n (0.99215686274509807, 0.81568627450980391, 0.63529411764705879),\n (0.99215686274509807, 0.68235294117647061, 0.41960784313725491),\n (0.99215686274509807, 0.55294117647058827, 0.23529411764705882),\n (0.94509803921568625, 0.41176470588235292, 0.07450980392156863),\n (0.85098039215686272, 0.28235294117647058, 0.00392156862745098),\n (0.65098039215686276, 0.21176470588235294, 0.01176470588235294),\n (0.49803921568627452, 0.15294117647058825, 0.01568627450980392)\n )\n\n_OrRd_data = (\n (1.0 , 0.96862745098039216, 0.92549019607843142),\n (0.99607843137254903, 0.90980392156862744, 0.78431372549019607),\n (0.99215686274509807, 0.83137254901960789, 0.61960784313725492),\n (0.99215686274509807, 0.73333333333333328, 0.51764705882352946),\n (0.9882352941176471 , 0.55294117647058827, 0.34901960784313724),\n (0.93725490196078431, 0.396078431372549 , 0.28235294117647058),\n (0.84313725490196079, 0.18823529411764706, 0.12156862745098039),\n (0.70196078431372544, 0.0 , 0.0 ),\n (0.49803921568627452, 0.0 , 0.0 )\n )\n\n_PiYG_data = (\n (0.55686274509803924, 0.00392156862745098, 0.32156862745098042),\n (0.77254901960784317, 0.10588235294117647, 0.49019607843137253),\n (0.87058823529411766, 0.46666666666666667, 0.68235294117647061),\n (0.94509803921568625, 0.71372549019607845, 0.85490196078431369),\n (0.99215686274509807, 0.8784313725490196 , 0.93725490196078431),\n (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),\n (0.90196078431372551, 0.96078431372549022, 0.81568627450980391),\n (0.72156862745098038, 0.88235294117647056, 0.52549019607843139),\n (0.49803921568627452, 0.73725490196078436, 0.25490196078431371),\n (0.30196078431372547, 0.5725490196078431 , 0.12941176470588237),\n (0.15294117647058825, 0.39215686274509803, 0.09803921568627451)\n )\n\n_PRGn_data = (\n (0.25098039215686274, 0.0 , 0.29411764705882354),\n (0.46274509803921571, 0.16470588235294117, 0.51372549019607838),\n (0.6 , 0.4392156862745098 , 0.6705882352941176 ),\n (0.76078431372549016, 0.6470588235294118 , 0.81176470588235294),\n (0.90588235294117647, 0.83137254901960789, 0.90980392156862744),\n (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),\n (0.85098039215686272, 0.94117647058823528, 0.82745098039215681),\n (0.65098039215686276, 0.85882352941176465, 0.62745098039215685),\n (0.35294117647058826, 0.68235294117647061, 0.38039215686274508),\n (0.10588235294117647, 0.47058823529411764, 0.21568627450980393),\n (0.0 , 0.26666666666666666, 0.10588235294117647)\n )\n\n_PuBu_data = (\n (1.0 , 0.96862745098039216, 0.98431372549019602),\n (0.92549019607843142, 0.90588235294117647, 0.94901960784313721),\n (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),\n (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),\n (0.45490196078431372, 0.66274509803921566, 0.81176470588235294),\n (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),\n (0.0196078431372549 , 0.4392156862745098 , 0.69019607843137254),\n (0.01568627450980392, 0.35294117647058826, 0.55294117647058827),\n (0.00784313725490196, 0.2196078431372549 , 0.34509803921568627)\n )\n\n_PuBuGn_data = (\n (1.0 , 0.96862745098039216, 0.98431372549019602),\n (0.92549019607843142, 0.88627450980392153, 0.94117647058823528),\n (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),\n (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),\n (0.40392156862745099, 0.66274509803921566, 0.81176470588235294),\n (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),\n (0.00784313725490196, 0.50588235294117645, 0.54117647058823526),\n (0.00392156862745098, 0.42352941176470588, 0.34901960784313724),\n (0.00392156862745098, 0.27450980392156865, 0.21176470588235294)\n )\n\n_PuOr_data = (\n (0.49803921568627452, 0.23137254901960785, 0.03137254901960784),\n (0.70196078431372544, 0.34509803921568627, 0.02352941176470588),\n (0.8784313725490196 , 0.50980392156862742, 0.07843137254901961),\n (0.99215686274509807, 0.72156862745098038, 0.38823529411764707),\n (0.99607843137254903, 0.8784313725490196 , 0.71372549019607845),\n (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),\n (0.84705882352941175, 0.85490196078431369, 0.92156862745098034),\n (0.69803921568627447, 0.6705882352941176 , 0.82352941176470584),\n (0.50196078431372548, 0.45098039215686275, 0.67450980392156867),\n (0.32941176470588235, 0.15294117647058825, 0.53333333333333333),\n (0.17647058823529413, 0.0 , 0.29411764705882354)\n )\n\n_PuRd_data = (\n (0.96862745098039216, 0.95686274509803926, 0.97647058823529409),\n (0.90588235294117647, 0.88235294117647056, 0.93725490196078431),\n (0.83137254901960789, 0.72549019607843135, 0.85490196078431369),\n (0.78823529411764703, 0.58039215686274515, 0.7803921568627451 ),\n (0.87450980392156863, 0.396078431372549 , 0.69019607843137254),\n (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),\n (0.80784313725490198, 0.07058823529411765, 0.33725490196078434),\n (0.59607843137254901, 0.0 , 0.2627450980392157 ),\n (0.40392156862745099, 0.0 , 0.12156862745098039)\n )\n\n_Purples_data = (\n (0.9882352941176471 , 0.98431372549019602, 0.99215686274509807),\n (0.93725490196078431, 0.92941176470588238, 0.96078431372549022),\n (0.85490196078431369, 0.85490196078431369, 0.92156862745098034),\n (0.73725490196078436, 0.74117647058823533, 0.86274509803921573),\n (0.61960784313725492, 0.60392156862745094, 0.78431372549019607),\n (0.50196078431372548, 0.49019607843137253, 0.72941176470588232),\n (0.41568627450980394, 0.31764705882352939, 0.63921568627450975),\n (0.32941176470588235, 0.15294117647058825, 0.5607843137254902 ),\n (0.24705882352941178, 0.0 , 0.49019607843137253)\n )\n\n_RdBu_data = (\n (0.40392156862745099, 0.0 , 0.12156862745098039),\n (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),\n (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),\n (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),\n (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),\n (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),\n (0.81960784313725488, 0.89803921568627454, 0.94117647058823528),\n (0.5725490196078431 , 0.77254901960784317, 0.87058823529411766),\n (0.2627450980392157 , 0.57647058823529407, 0.76470588235294112),\n (0.12941176470588237, 0.4 , 0.67450980392156867),\n (0.0196078431372549 , 0.18823529411764706, 0.38039215686274508)\n )\n\n_RdGy_data = (\n (0.40392156862745099, 0.0 , 0.12156862745098039),\n (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),\n (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),\n (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),\n (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),\n (1.0 , 1.0 , 1.0 ),\n (0.8784313725490196 , 0.8784313725490196 , 0.8784313725490196 ),\n (0.72941176470588232, 0.72941176470588232, 0.72941176470588232),\n (0.52941176470588236, 0.52941176470588236, 0.52941176470588236),\n (0.30196078431372547, 0.30196078431372547, 0.30196078431372547),\n (0.10196078431372549, 0.10196078431372549, 0.10196078431372549)\n )\n\n_RdPu_data = (\n (1.0 , 0.96862745098039216, 0.95294117647058818),\n (0.99215686274509807, 0.8784313725490196 , 0.86666666666666667),\n (0.9882352941176471 , 0.77254901960784317, 0.75294117647058822),\n (0.98039215686274506, 0.62352941176470589, 0.70980392156862748),\n (0.96862745098039216, 0.40784313725490196, 0.63137254901960782),\n (0.86666666666666667, 0.20392156862745098, 0.59215686274509804),\n (0.68235294117647061, 0.00392156862745098, 0.49411764705882355),\n (0.47843137254901963, 0.00392156862745098, 0.46666666666666667),\n (0.28627450980392155, 0.0 , 0.41568627450980394)\n )\n\n_RdYlBu_data = (\n (0.6470588235294118 , 0.0 , 0.14901960784313725),\n (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),\n (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),\n (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),\n (0.99607843137254903, 0.8784313725490196 , 0.56470588235294117),\n (1.0 , 1.0 , 0.74901960784313726),\n (0.8784313725490196 , 0.95294117647058818 , 0.97254901960784312),\n (0.6705882352941176 , 0.85098039215686272 , 0.9137254901960784 ),\n (0.45490196078431372, 0.67843137254901964 , 0.81960784313725488),\n (0.27058823529411763, 0.45882352941176469 , 0.70588235294117652),\n (0.19215686274509805, 0.21176470588235294 , 0.58431372549019611)\n )\n\n_RdYlGn_data = (\n (0.6470588235294118 , 0.0 , 0.14901960784313725),\n (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),\n (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),\n (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),\n (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),\n (1.0 , 1.0 , 0.74901960784313726),\n (0.85098039215686272, 0.93725490196078431 , 0.54509803921568623),\n (0.65098039215686276, 0.85098039215686272 , 0.41568627450980394),\n (0.4 , 0.74117647058823533 , 0.38823529411764707),\n (0.10196078431372549, 0.59607843137254901 , 0.31372549019607843),\n (0.0 , 0.40784313725490196 , 0.21568627450980393)\n )\n\n_Reds_data = (\n (1.0 , 0.96078431372549022 , 0.94117647058823528),\n (0.99607843137254903, 0.8784313725490196 , 0.82352941176470584),\n (0.9882352941176471 , 0.73333333333333328 , 0.63137254901960782),\n (0.9882352941176471 , 0.5725490196078431 , 0.44705882352941179),\n (0.98431372549019602, 0.41568627450980394 , 0.29019607843137257),\n (0.93725490196078431, 0.23137254901960785 , 0.17254901960784313),\n (0.79607843137254897, 0.094117647058823528, 0.11372549019607843),\n (0.6470588235294118 , 0.058823529411764705, 0.08235294117647058),\n (0.40392156862745099, 0.0 , 0.05098039215686274)\n )\n\n_Spectral_data = (\n (0.61960784313725492, 0.003921568627450980, 0.25882352941176473),\n (0.83529411764705885, 0.24313725490196078 , 0.30980392156862746),\n (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),\n (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),\n (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),\n (1.0 , 1.0 , 0.74901960784313726),\n (0.90196078431372551, 0.96078431372549022 , 0.59607843137254901),\n (0.6705882352941176 , 0.8666666666666667 , 0.64313725490196083),\n (0.4 , 0.76078431372549016 , 0.6470588235294118 ),\n (0.19607843137254902, 0.53333333333333333 , 0.74117647058823533),\n (0.36862745098039218, 0.30980392156862746 , 0.63529411764705879)\n )\n\n_YlGn_data = (\n (1.0 , 1.0 , 0.89803921568627454),\n (0.96862745098039216, 0.9882352941176471 , 0.72549019607843135),\n (0.85098039215686272, 0.94117647058823528 , 0.63921568627450975),\n (0.67843137254901964, 0.8666666666666667 , 0.55686274509803924),\n (0.47058823529411764, 0.77647058823529413 , 0.47450980392156861),\n (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),\n (0.13725490196078433, 0.51764705882352946 , 0.2627450980392157 ),\n (0.0 , 0.40784313725490196 , 0.21568627450980393),\n (0.0 , 0.27058823529411763 , 0.16078431372549021)\n )\n\n_YlGnBu_data = (\n (1.0 , 1.0 , 0.85098039215686272),\n (0.92941176470588238, 0.97254901960784312 , 0.69411764705882351),\n (0.7803921568627451 , 0.9137254901960784 , 0.70588235294117652),\n (0.49803921568627452, 0.80392156862745101 , 0.73333333333333328),\n (0.25490196078431371, 0.71372549019607845 , 0.7686274509803922 ),\n (0.11372549019607843, 0.56862745098039214 , 0.75294117647058822),\n (0.13333333333333333, 0.36862745098039218 , 0.6588235294117647 ),\n (0.14509803921568629, 0.20392156862745098 , 0.58039215686274515),\n (0.03137254901960784, 0.11372549019607843 , 0.34509803921568627)\n )\n\n_YlOrBr_data = (\n (1.0 , 1.0 , 0.89803921568627454),\n (1.0 , 0.96862745098039216 , 0.73725490196078436),\n (0.99607843137254903, 0.8901960784313725 , 0.56862745098039214),\n (0.99607843137254903, 0.7686274509803922 , 0.30980392156862746),\n (0.99607843137254903, 0.6 , 0.16078431372549021),\n (0.92549019607843142, 0.4392156862745098 , 0.07843137254901961),\n (0.8 , 0.29803921568627451 , 0.00784313725490196),\n (0.6 , 0.20392156862745098 , 0.01568627450980392),\n (0.4 , 0.14509803921568629 , 0.02352941176470588)\n )\n\n_YlOrRd_data = (\n (1.0 , 1.0 , 0.8 ),\n (1.0 , 0.92941176470588238 , 0.62745098039215685),\n (0.99607843137254903, 0.85098039215686272 , 0.46274509803921571),\n (0.99607843137254903, 0.69803921568627447 , 0.29803921568627451),\n (0.99215686274509807, 0.55294117647058827 , 0.23529411764705882),\n (0.9882352941176471 , 0.30588235294117649 , 0.16470588235294117),\n (0.8901960784313725 , 0.10196078431372549 , 0.10980392156862745),\n (0.74117647058823533, 0.0 , 0.14901960784313725),\n (0.50196078431372548, 0.0 , 0.14901960784313725)\n )\n\n\n# ColorBrewer's qualitative maps, implemented using ListedColormap\n# for use with mpl.colors.NoNorm\n\n_Accent_data = (\n (0.49803921568627452, 0.78823529411764703, 0.49803921568627452),\n (0.74509803921568629, 0.68235294117647061, 0.83137254901960789),\n (0.99215686274509807, 0.75294117647058822, 0.52549019607843139),\n (1.0, 1.0, 0.6 ),\n (0.2196078431372549, 0.42352941176470588, 0.69019607843137254),\n (0.94117647058823528, 0.00784313725490196, 0.49803921568627452),\n (0.74901960784313726, 0.35686274509803922, 0.09019607843137254),\n (0.4, 0.4, 0.4 ),\n )\n\n_Dark2_data = (\n (0.10588235294117647, 0.61960784313725492, 0.46666666666666667),\n (0.85098039215686272, 0.37254901960784315, 0.00784313725490196),\n (0.45882352941176469, 0.4392156862745098, 0.70196078431372544),\n (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),\n (0.4, 0.65098039215686276, 0.11764705882352941),\n (0.90196078431372551, 0.6705882352941176, 0.00784313725490196),\n (0.65098039215686276, 0.46274509803921571, 0.11372549019607843),\n (0.4, 0.4, 0.4 ),\n )\n\n_Paired_data = (\n (0.65098039215686276, 0.80784313725490198, 0.8901960784313725 ),\n (0.12156862745098039, 0.47058823529411764, 0.70588235294117652),\n (0.69803921568627447, 0.87450980392156863, 0.54117647058823526),\n (0.2, 0.62745098039215685, 0.17254901960784313),\n (0.98431372549019602, 0.60392156862745094, 0.6 ),\n (0.8901960784313725, 0.10196078431372549, 0.10980392156862745),\n (0.99215686274509807, 0.74901960784313726, 0.43529411764705883),\n (1.0, 0.49803921568627452, 0.0 ),\n (0.792156862745098, 0.69803921568627447, 0.83921568627450982),\n (0.41568627450980394, 0.23921568627450981, 0.60392156862745094),\n (1.0, 1.0, 0.6 ),\n (0.69411764705882351, 0.34901960784313724, 0.15686274509803921),\n )\n\n_Pastel1_data = (\n (0.98431372549019602, 0.70588235294117652, 0.68235294117647061),\n (0.70196078431372544, 0.80392156862745101, 0.8901960784313725 ),\n (0.8, 0.92156862745098034, 0.77254901960784317),\n (0.87058823529411766, 0.79607843137254897, 0.89411764705882357),\n (0.99607843137254903, 0.85098039215686272, 0.65098039215686276),\n (1.0, 1.0, 0.8 ),\n (0.89803921568627454, 0.84705882352941175, 0.74117647058823533),\n (0.99215686274509807, 0.85490196078431369, 0.92549019607843142),\n (0.94901960784313721, 0.94901960784313721, 0.94901960784313721),\n )\n\n_Pastel2_data = (\n (0.70196078431372544, 0.88627450980392153, 0.80392156862745101),\n (0.99215686274509807, 0.80392156862745101, 0.67450980392156867),\n (0.79607843137254897, 0.83529411764705885, 0.90980392156862744),\n (0.95686274509803926, 0.792156862745098, 0.89411764705882357),\n (0.90196078431372551, 0.96078431372549022, 0.78823529411764703),\n (1.0, 0.94901960784313721, 0.68235294117647061),\n (0.94509803921568625, 0.88627450980392153, 0.8 ),\n (0.8, 0.8, 0.8 ),\n )\n\n_Set1_data = (\n (0.89411764705882357, 0.10196078431372549, 0.10980392156862745),\n (0.21568627450980393, 0.49411764705882355, 0.72156862745098038),\n (0.30196078431372547, 0.68627450980392157, 0.29019607843137257),\n (0.59607843137254901, 0.30588235294117649, 0.63921568627450975),\n (1.0, 0.49803921568627452, 0.0 ),\n (1.0, 1.0, 0.2 ),\n (0.65098039215686276, 0.33725490196078434, 0.15686274509803921),\n (0.96862745098039216, 0.50588235294117645, 0.74901960784313726),\n (0.6, 0.6, 0.6),\n )\n\n_Set2_data = (\n (0.4, 0.76078431372549016, 0.6470588235294118 ),\n (0.9882352941176471, 0.55294117647058827, 0.3843137254901961 ),\n (0.55294117647058827, 0.62745098039215685, 0.79607843137254897),\n (0.90588235294117647, 0.54117647058823526, 0.76470588235294112),\n (0.65098039215686276, 0.84705882352941175, 0.32941176470588235),\n (1.0, 0.85098039215686272, 0.18431372549019609),\n (0.89803921568627454, 0.7686274509803922, 0.58039215686274515),\n (0.70196078431372544, 0.70196078431372544, 0.70196078431372544),\n )\n\n_Set3_data = (\n (0.55294117647058827, 0.82745098039215681, 0.7803921568627451 ),\n (1.0, 1.0, 0.70196078431372544),\n (0.74509803921568629, 0.72941176470588232, 0.85490196078431369),\n (0.98431372549019602, 0.50196078431372548, 0.44705882352941179),\n (0.50196078431372548, 0.69411764705882351, 0.82745098039215681),\n (0.99215686274509807, 0.70588235294117652, 0.3843137254901961 ),\n (0.70196078431372544, 0.87058823529411766, 0.41176470588235292),\n (0.9882352941176471, 0.80392156862745101, 0.89803921568627454),\n (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),\n (0.73725490196078436, 0.50196078431372548, 0.74117647058823533),\n (0.8, 0.92156862745098034, 0.77254901960784317),\n (1.0, 0.92941176470588238, 0.43529411764705883),\n )\n\n\n# The next 7 palettes are from the Yorick scientific visualization package,\n# an evolution of the GIST package, both by David H. Munro.\n# They are released under a BSD-like license (see LICENSE_YORICK in\n# the license directory of the matplotlib source distribution).\n#\n# Most palette functions have been reduced to simple function descriptions\n# by Reinier Heeres, since the rgb components were mostly straight lines.\n# gist_earth_data and gist_ncar_data were simplified by a script and some\n# manual effort.\n\n_gist_earth_data = {\n 'red': (\n (0.0, 0.0, 0.0000),\n (0.2824, 0.1882, 0.1882),\n (0.4588, 0.2714, 0.2714),\n (0.5490, 0.4719, 0.4719),\n (0.6980, 0.7176, 0.7176),\n (0.7882, 0.7553, 0.7553),\n (1.0000, 0.9922, 0.9922),\n ),\n 'green': (\n (0.0, 0.0, 0.0000),\n (0.0275, 0.0000, 0.0000),\n (0.1098, 0.1893, 0.1893),\n (0.1647, 0.3035, 0.3035),\n (0.2078, 0.3841, 0.3841),\n (0.2824, 0.5020, 0.5020),\n (0.5216, 0.6397, 0.6397),\n (0.6980, 0.7171, 0.7171),\n (0.7882, 0.6392, 0.6392),\n (0.7922, 0.6413, 0.6413),\n (0.8000, 0.6447, 0.6447),\n (0.8078, 0.6481, 0.6481),\n (0.8157, 0.6549, 0.6549),\n (0.8667, 0.6991, 0.6991),\n (0.8745, 0.7103, 0.7103),\n (0.8824, 0.7216, 0.7216),\n (0.8902, 0.7323, 0.7323),\n (0.8980, 0.7430, 0.7430),\n (0.9412, 0.8275, 0.8275),\n (0.9569, 0.8635, 0.8635),\n (0.9647, 0.8816, 0.8816),\n (0.9961, 0.9733, 0.9733),\n (1.0000, 0.9843, 0.9843),\n ),\n 'blue': (\n (0.0, 0.0, 0.0000),\n (0.0039, 0.1684, 0.1684),\n (0.0078, 0.2212, 0.2212),\n (0.0275, 0.4329, 0.4329),\n (0.0314, 0.4549, 0.4549),\n (0.2824, 0.5004, 0.5004),\n (0.4667, 0.2748, 0.2748),\n (0.5451, 0.3205, 0.3205),\n (0.7843, 0.3961, 0.3961),\n (0.8941, 0.6651, 0.6651),\n (1.0000, 0.9843, 0.9843),\n )\n}\n\n_gist_gray_data = {\n 'red': gfunc[3],\n 'green': gfunc[3],\n 'blue': gfunc[3],\n}\n\ndef _gist_heat_red(x): return 1.5 * x\ndef _gist_heat_green(x): return 2 * x - 1\ndef _gist_heat_blue(x): return 4 * x - 3\n_gist_heat_data = {\n 'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue}\n\n_gist_ncar_data = {\n 'red': (\n (0.0, 0.0, 0.0000),\n (0.3098, 0.0000, 0.0000),\n (0.3725, 0.3993, 0.3993),\n (0.4235, 0.5003, 0.5003),\n (0.5333, 1.0000, 1.0000),\n (0.7922, 1.0000, 1.0000),\n (0.8471, 0.6218, 0.6218),\n (0.8980, 0.9235, 0.9235),\n (1.0000, 0.9961, 0.9961),\n ),\n 'green': (\n (0.0, 0.0, 0.0000),\n (0.0510, 0.3722, 0.3722),\n (0.1059, 0.0000, 0.0000),\n (0.1569, 0.7202, 0.7202),\n (0.1608, 0.7537, 0.7537),\n (0.1647, 0.7752, 0.7752),\n (0.2157, 1.0000, 1.0000),\n (0.2588, 0.9804, 0.9804),\n (0.2706, 0.9804, 0.9804),\n (0.3176, 1.0000, 1.0000),\n (0.3686, 0.8081, 0.8081),\n (0.4275, 1.0000, 1.0000),\n (0.5216, 1.0000, 1.0000),\n (0.6314, 0.7292, 0.7292),\n (0.6863, 0.2796, 0.2796),\n (0.7451, 0.0000, 0.0000),\n (0.7922, 0.0000, 0.0000),\n (0.8431, 0.1753, 0.1753),\n (0.8980, 0.5000, 0.5000),\n (1.0000, 0.9725, 0.9725),\n ),\n 'blue': (\n (0.0, 0.5020, 0.5020),\n (0.0510, 0.0222, 0.0222),\n (0.1098, 1.0000, 1.0000),\n (0.2039, 1.0000, 1.0000),\n (0.2627, 0.6145, 0.6145),\n (0.3216, 0.0000, 0.0000),\n (0.4157, 0.0000, 0.0000),\n (0.4745, 0.2342, 0.2342),\n (0.5333, 0.0000, 0.0000),\n (0.5804, 0.0000, 0.0000),\n (0.6314, 0.0549, 0.0549),\n (0.6902, 0.0000, 0.0000),\n (0.7373, 0.0000, 0.0000),\n (0.7922, 0.9738, 0.9738),\n (0.8000, 1.0000, 1.0000),\n (0.8431, 1.0000, 1.0000),\n (0.8980, 0.9341, 0.9341),\n (1.0000, 0.9961, 0.9961),\n )\n}\n\n_gist_rainbow_data = (\n (0.000, (1.00, 0.00, 0.16)),\n (0.030, (1.00, 0.00, 0.00)),\n (0.215, (1.00, 1.00, 0.00)),\n (0.400, (0.00, 1.00, 0.00)),\n (0.586, (0.00, 1.00, 1.00)),\n (0.770, (0.00, 0.00, 1.00)),\n (0.954, (1.00, 0.00, 1.00)),\n (1.000, (1.00, 0.00, 0.75))\n)\n\n_gist_stern_data = {\n 'red': (\n (0.000, 0.000, 0.000), (0.0547, 1.000, 1.000),\n (0.250, 0.027, 0.250), # (0.2500, 0.250, 0.250),\n (1.000, 1.000, 1.000)),\n 'green': ((0, 0, 0), (1, 1, 1)),\n 'blue': (\n (0.000, 0.000, 0.000), (0.500, 1.000, 1.000),\n (0.735, 0.000, 0.000), (1.000, 1.000, 1.000))\n}\n\ndef _gist_yarg(x): return 1 - x\n_gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg}\n\n# This bipolar colormap was generated from CoolWarmFloat33.csv of\n# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland.\n# <http://www.kennethmoreland.com/color-maps/>\n_coolwarm_data = {\n 'red': [\n (0.0, 0.2298057, 0.2298057),\n (0.03125, 0.26623388, 0.26623388),\n (0.0625, 0.30386891, 0.30386891),\n (0.09375, 0.342804478, 0.342804478),\n (0.125, 0.38301334, 0.38301334),\n (0.15625, 0.424369608, 0.424369608),\n (0.1875, 0.46666708, 0.46666708),\n (0.21875, 0.509635204, 0.509635204),\n (0.25, 0.552953156, 0.552953156),\n (0.28125, 0.596262162, 0.596262162),\n (0.3125, 0.639176211, 0.639176211),\n (0.34375, 0.681291281, 0.681291281),\n (0.375, 0.722193294, 0.722193294),\n (0.40625, 0.761464949, 0.761464949),\n (0.4375, 0.798691636, 0.798691636),\n (0.46875, 0.833466556, 0.833466556),\n (0.5, 0.865395197, 0.865395197),\n (0.53125, 0.897787179, 0.897787179),\n (0.5625, 0.924127593, 0.924127593),\n (0.59375, 0.944468518, 0.944468518),\n (0.625, 0.958852946, 0.958852946),\n (0.65625, 0.96732803, 0.96732803),\n (0.6875, 0.969954137, 0.969954137),\n (0.71875, 0.966811177, 0.966811177),\n (0.75, 0.958003065, 0.958003065),\n (0.78125, 0.943660866, 0.943660866),\n (0.8125, 0.923944917, 0.923944917),\n (0.84375, 0.89904617, 0.89904617),\n (0.875, 0.869186849, 0.869186849),\n (0.90625, 0.834620542, 0.834620542),\n (0.9375, 0.795631745, 0.795631745),\n (0.96875, 0.752534934, 0.752534934),\n (1.0, 0.705673158, 0.705673158)],\n 'green': [\n (0.0, 0.298717966, 0.298717966),\n (0.03125, 0.353094838, 0.353094838),\n (0.0625, 0.406535296, 0.406535296),\n (0.09375, 0.458757618, 0.458757618),\n (0.125, 0.50941904, 0.50941904),\n (0.15625, 0.558148092, 0.558148092),\n (0.1875, 0.604562568, 0.604562568),\n (0.21875, 0.648280772, 0.648280772),\n (0.25, 0.688929332, 0.688929332),\n (0.28125, 0.726149107, 0.726149107),\n (0.3125, 0.759599947, 0.759599947),\n (0.34375, 0.788964712, 0.788964712),\n (0.375, 0.813952739, 0.813952739),\n (0.40625, 0.834302879, 0.834302879),\n (0.4375, 0.849786142, 0.849786142),\n (0.46875, 0.860207984, 0.860207984),\n (0.5, 0.86541021, 0.86541021),\n (0.53125, 0.848937047, 0.848937047),\n (0.5625, 0.827384882, 0.827384882),\n (0.59375, 0.800927443, 0.800927443),\n (0.625, 0.769767752, 0.769767752),\n (0.65625, 0.734132809, 0.734132809),\n (0.6875, 0.694266682, 0.694266682),\n (0.71875, 0.650421156, 0.650421156),\n (0.75, 0.602842431, 0.602842431),\n (0.78125, 0.551750968, 0.551750968),\n (0.8125, 0.49730856, 0.49730856),\n (0.84375, 0.439559467, 0.439559467),\n (0.875, 0.378313092, 0.378313092),\n (0.90625, 0.312874446, 0.312874446),\n (0.9375, 0.24128379, 0.24128379),\n (0.96875, 0.157246067, 0.157246067),\n (1.0, 0.01555616, 0.01555616)],\n 'blue': [\n (0.0, 0.753683153, 0.753683153),\n (0.03125, 0.801466763, 0.801466763),\n (0.0625, 0.84495867, 0.84495867),\n (0.09375, 0.883725899, 0.883725899),\n (0.125, 0.917387822, 0.917387822),\n (0.15625, 0.945619588, 0.945619588),\n (0.1875, 0.968154911, 0.968154911),\n (0.21875, 0.98478814, 0.98478814),\n (0.25, 0.995375608, 0.995375608),\n (0.28125, 0.999836203, 0.999836203),\n (0.3125, 0.998151185, 0.998151185),\n (0.34375, 0.990363227, 0.990363227),\n (0.375, 0.976574709, 0.976574709),\n (0.40625, 0.956945269, 0.956945269),\n (0.4375, 0.931688648, 0.931688648),\n (0.46875, 0.901068838, 0.901068838),\n (0.5, 0.865395561, 0.865395561),\n (0.53125, 0.820880546, 0.820880546),\n (0.5625, 0.774508472, 0.774508472),\n (0.59375, 0.726736146, 0.726736146),\n (0.625, 0.678007945, 0.678007945),\n (0.65625, 0.628751763, 0.628751763),\n (0.6875, 0.579375448, 0.579375448),\n (0.71875, 0.530263762, 0.530263762),\n (0.75, 0.481775914, 0.481775914),\n (0.78125, 0.434243684, 0.434243684),\n (0.8125, 0.387970225, 0.387970225),\n (0.84375, 0.343229596, 0.343229596),\n (0.875, 0.300267182, 0.300267182),\n (0.90625, 0.259301199, 0.259301199),\n (0.9375, 0.220525627, 0.220525627),\n (0.96875, 0.184115123, 0.184115123),\n (1.0, 0.150232812, 0.150232812)]\n }\n\n# Implementation of Carey Rappaport's CMRmap.\n# See `A Color Map for Effective Black-and-White Rendering of Color-Scale\n# Images' by Carey Rappaport\n# https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m\n_CMRmap_data = {'red': ((0.000, 0.00, 0.00),\n (0.125, 0.15, 0.15),\n (0.250, 0.30, 0.30),\n (0.375, 0.60, 0.60),\n (0.500, 1.00, 1.00),\n (0.625, 0.90, 0.90),\n (0.750, 0.90, 0.90),\n (0.875, 0.90, 0.90),\n (1.000, 1.00, 1.00)),\n 'green': ((0.000, 0.00, 0.00),\n (0.125, 0.15, 0.15),\n (0.250, 0.15, 0.15),\n (0.375, 0.20, 0.20),\n (0.500, 0.25, 0.25),\n (0.625, 0.50, 0.50),\n (0.750, 0.75, 0.75),\n (0.875, 0.90, 0.90),\n (1.000, 1.00, 1.00)),\n 'blue': ((0.000, 0.00, 0.00),\n (0.125, 0.50, 0.50),\n (0.250, 0.75, 0.75),\n (0.375, 0.50, 0.50),\n (0.500, 0.15, 0.15),\n (0.625, 0.00, 0.00),\n (0.750, 0.10, 0.10),\n (0.875, 0.50, 0.50),\n (1.000, 1.00, 1.00))}\n\n\n# An MIT licensed, colorblind-friendly heatmap from Wistia:\n# https://github.com/wistia/heatmap-palette\n# https://wistia.com/learn/culture/heatmaps-for-colorblindness\n#\n# >>> import matplotlib.colors as c\n# >>> colors = ["#e4ff7a", "#ffe81a", "#ffbd00", "#ffa000", "#fc7f00"]\n# >>> cm = c.LinearSegmentedColormap.from_list('wistia', colors)\n# >>> _wistia_data = cm._segmentdata\n# >>> del _wistia_data['alpha']\n#\n_wistia_data = {\n 'red': [(0.0, 0.8941176470588236, 0.8941176470588236),\n (0.25, 1.0, 1.0),\n (0.5, 1.0, 1.0),\n (0.75, 1.0, 1.0),\n (1.0, 0.9882352941176471, 0.9882352941176471)],\n 'green': [(0.0, 1.0, 1.0),\n (0.25, 0.9098039215686274, 0.9098039215686274),\n (0.5, 0.7411764705882353, 0.7411764705882353),\n (0.75, 0.6274509803921569, 0.6274509803921569),\n (1.0, 0.4980392156862745, 0.4980392156862745)],\n 'blue': [(0.0, 0.47843137254901963, 0.47843137254901963),\n (0.25, 0.10196078431372549, 0.10196078431372549),\n (0.5, 0.0, 0.0),\n (0.75, 0.0, 0.0),\n (1.0, 0.0, 0.0)],\n}\n\n\n# Categorical palettes from Vega:\n# https://github.com/vega/vega/wiki/Scales\n# (divided by 255)\n#\n\n_tab10_data = (\n (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4\n (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e\n (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c\n (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728\n (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd\n (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b\n (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2\n (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f\n (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22\n (0.09019607843137255, 0.7450980392156863, 0.8117647058823529), # 17becf\n)\n\n_tab20_data = (\n (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4\n (0.6823529411764706, 0.7803921568627451, 0.9098039215686274 ), # aec7e8\n (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e\n (1.0, 0.7333333333333333, 0.47058823529411764 ), # ffbb78\n (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c\n (0.596078431372549, 0.8745098039215686, 0.5411764705882353 ), # 98df8a\n (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728\n (1.0, 0.596078431372549, 0.5882352941176471 ), # ff9896\n (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd\n (0.7725490196078432, 0.6901960784313725, 0.8352941176470589 ), # c5b0d5\n (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b\n (0.7686274509803922, 0.611764705882353, 0.5803921568627451 ), # c49c94\n (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2\n (0.9686274509803922, 0.7137254901960784, 0.8235294117647058 ), # f7b6d2\n (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f\n (0.7803921568627451, 0.7803921568627451, 0.7803921568627451 ), # c7c7c7\n (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22\n (0.8588235294117647, 0.8588235294117647, 0.5529411764705883 ), # dbdb8d\n (0.09019607843137255, 0.7450980392156863, 0.8117647058823529 ), # 17becf\n (0.6196078431372549, 0.8549019607843137, 0.8980392156862745), # 9edae5\n)\n\n_tab20b_data = (\n (0.2235294117647059, 0.23137254901960785, 0.4745098039215686 ), # 393b79\n (0.3215686274509804, 0.32941176470588235, 0.6392156862745098 ), # 5254a3\n (0.4196078431372549, 0.43137254901960786, 0.8117647058823529 ), # 6b6ecf\n (0.611764705882353, 0.6196078431372549, 0.8705882352941177 ), # 9c9ede\n (0.38823529411764707, 0.4745098039215686, 0.2235294117647059 ), # 637939\n (0.5490196078431373, 0.6352941176470588, 0.3215686274509804 ), # 8ca252\n (0.7098039215686275, 0.8117647058823529, 0.4196078431372549 ), # b5cf6b\n (0.807843137254902, 0.8588235294117647, 0.611764705882353 ), # cedb9c\n (0.5490196078431373, 0.42745098039215684, 0.19215686274509805), # 8c6d31\n (0.7411764705882353, 0.6196078431372549, 0.2235294117647059 ), # bd9e39\n (0.9058823529411765, 0.7294117647058823, 0.3215686274509804 ), # e7ba52\n (0.9058823529411765, 0.796078431372549, 0.5803921568627451 ), # e7cb94\n (0.5176470588235295, 0.23529411764705882, 0.2235294117647059 ), # 843c39\n (0.6784313725490196, 0.28627450980392155, 0.2901960784313726 ), # ad494a\n (0.8392156862745098, 0.3803921568627451, 0.4196078431372549 ), # d6616b\n (0.9058823529411765, 0.5882352941176471, 0.611764705882353 ), # e7969c\n (0.4823529411764706, 0.2549019607843137, 0.45098039215686275), # 7b4173\n (0.6470588235294118, 0.3176470588235294, 0.5803921568627451 ), # a55194\n (0.807843137254902, 0.42745098039215684, 0.7411764705882353 ), # ce6dbd\n (0.8705882352941177, 0.6196078431372549, 0.8392156862745098 ), # de9ed6\n)\n\n_tab20c_data = (\n (0.19215686274509805, 0.5098039215686274, 0.7411764705882353 ), # 3182bd\n (0.4196078431372549, 0.6823529411764706, 0.8392156862745098 ), # 6baed6\n (0.6196078431372549, 0.792156862745098, 0.8823529411764706 ), # 9ecae1\n (0.7764705882352941, 0.8588235294117647, 0.9372549019607843 ), # c6dbef\n (0.9019607843137255, 0.3333333333333333, 0.050980392156862744), # e6550d\n (0.9921568627450981, 0.5529411764705883, 0.23529411764705882 ), # fd8d3c\n (0.9921568627450981, 0.6823529411764706, 0.4196078431372549 ), # fdae6b\n (0.9921568627450981, 0.8156862745098039, 0.6352941176470588 ), # fdd0a2\n (0.19215686274509805, 0.6392156862745098, 0.32941176470588235 ), # 31a354\n (0.4549019607843137, 0.7686274509803922, 0.4627450980392157 ), # 74c476\n (0.6313725490196078, 0.8509803921568627, 0.6078431372549019 ), # a1d99b\n (0.7803921568627451, 0.9137254901960784, 0.7529411764705882 ), # c7e9c0\n (0.4588235294117647, 0.4196078431372549, 0.6941176470588235 ), # 756bb1\n (0.6196078431372549, 0.6039215686274509, 0.7843137254901961 ), # 9e9ac8\n (0.7372549019607844, 0.7411764705882353, 0.8627450980392157 ), # bcbddc\n (0.8549019607843137, 0.8549019607843137, 0.9215686274509803 ), # dadaeb\n (0.38823529411764707, 0.38823529411764707, 0.38823529411764707 ), # 636363\n (0.5882352941176471, 0.5882352941176471, 0.5882352941176471 ), # 969696\n (0.7411764705882353, 0.7411764705882353, 0.7411764705882353 ), # bdbdbd\n (0.8509803921568627, 0.8509803921568627, 0.8509803921568627 ), # d9d9d9\n)\n\n\n_petroff10_data = (\n (0.24705882352941178, 0.5647058823529412, 0.8549019607843137), # 3f90da\n (1.0, 0.6627450980392157, 0.054901960784313725), # ffa90e\n (0.7411764705882353, 0.12156862745098039, 0.00392156862745098), # bd1f01\n (0.5803921568627451, 0.6431372549019608, 0.6352941176470588), # 94a4a2\n (0.5137254901960784, 0.17647058823529413, 0.7137254901960784), # 832db6\n (0.6627450980392157, 0.4196078431372549, 0.34901960784313724), # a96b59\n (0.9058823529411765, 0.38823529411764707, 0.0), # e76300\n (0.7254901960784313, 0.6745098039215687, 0.4392156862745098), # b9ac70\n (0.44313725490196076, 0.4588235294117647, 0.5058823529411764), # 717581\n (0.5725490196078431, 0.8549019607843137, 0.8666666666666667), # 92dadd\n)\n\n\ndatad = {\n 'Blues': _Blues_data,\n 'BrBG': _BrBG_data,\n 'BuGn': _BuGn_data,\n 'BuPu': _BuPu_data,\n 'CMRmap': _CMRmap_data,\n 'GnBu': _GnBu_data,\n 'Greens': _Greens_data,\n 'Greys': _Greys_data,\n 'OrRd': _OrRd_data,\n 'Oranges': _Oranges_data,\n 'PRGn': _PRGn_data,\n 'PiYG': _PiYG_data,\n 'PuBu': _PuBu_data,\n 'PuBuGn': _PuBuGn_data,\n 'PuOr': _PuOr_data,\n 'PuRd': _PuRd_data,\n 'Purples': _Purples_data,\n 'RdBu': _RdBu_data,\n 'RdGy': _RdGy_data,\n 'RdPu': _RdPu_data,\n 'RdYlBu': _RdYlBu_data,\n 'RdYlGn': _RdYlGn_data,\n 'Reds': _Reds_data,\n 'Spectral': _Spectral_data,\n 'Wistia': _wistia_data,\n 'YlGn': _YlGn_data,\n 'YlGnBu': _YlGnBu_data,\n 'YlOrBr': _YlOrBr_data,\n 'YlOrRd': _YlOrRd_data,\n 'afmhot': _afmhot_data,\n 'autumn': _autumn_data,\n 'binary': _binary_data,\n 'bone': _bone_data,\n 'brg': _brg_data,\n 'bwr': _bwr_data,\n 'cool': _cool_data,\n 'coolwarm': _coolwarm_data,\n 'copper': _copper_data,\n 'cubehelix': _cubehelix_data,\n 'flag': _flag_data,\n 'gist_earth': _gist_earth_data,\n 'gist_gray': _gist_gray_data,\n 'gist_heat': _gist_heat_data,\n 'gist_ncar': _gist_ncar_data,\n 'gist_rainbow': _gist_rainbow_data,\n 'gist_stern': _gist_stern_data,\n 'gist_yarg': _gist_yarg_data,\n 'gnuplot': _gnuplot_data,\n 'gnuplot2': _gnuplot2_data,\n 'gray': _gray_data,\n 'hot': _hot_data,\n 'hsv': _hsv_data,\n 'jet': _jet_data,\n 'nipy_spectral': _nipy_spectral_data,\n 'ocean': _ocean_data,\n 'pink': _pink_data,\n 'prism': _prism_data,\n 'rainbow': _rainbow_data,\n 'seismic': _seismic_data,\n 'spring': _spring_data,\n 'summer': _summer_data,\n 'terrain': _terrain_data,\n 'winter': _winter_data,\n # Qualitative\n 'Accent': {'listed': _Accent_data},\n 'Dark2': {'listed': _Dark2_data},\n 'Paired': {'listed': _Paired_data},\n 'Pastel1': {'listed': _Pastel1_data},\n 'Pastel2': {'listed': _Pastel2_data},\n 'Set1': {'listed': _Set1_data},\n 'Set2': {'listed': _Set2_data},\n 'Set3': {'listed': _Set3_data},\n 'tab10': {'listed': _tab10_data},\n 'tab20': {'listed': _tab20_data},\n 'tab20b': {'listed': _tab20b_data},\n 'tab20c': {'listed': _tab20c_data},\n}\n
.venv\Lib\site-packages\matplotlib\_cm.py
_cm.py
Python
68,014
0.75
0.043836
0.032353
vue-tools
863
2024-01-20T17:15:31.318527
Apache-2.0
false
8d0b3aa96f6dfa6cdb95f52fb231a1f8
# auto-generated by https://github.com/trygvrad/multivariate_colormaps\n# date: 2024-05-24\n\nimport numpy as np\nfrom matplotlib.colors import SegmentedBivarColormap\n\nBiPeak = np.array(\n [0.000, 0.674, 0.931, 0.000, 0.680, 0.922, 0.000, 0.685, 0.914, 0.000,\n 0.691, 0.906, 0.000, 0.696, 0.898, 0.000, 0.701, 0.890, 0.000, 0.706,\n 0.882, 0.000, 0.711, 0.875, 0.000, 0.715, 0.867, 0.000, 0.720, 0.860,\n 0.000, 0.725, 0.853, 0.000, 0.729, 0.845, 0.000, 0.733, 0.838, 0.000,\n 0.737, 0.831, 0.000, 0.741, 0.824, 0.000, 0.745, 0.816, 0.000, 0.749,\n 0.809, 0.000, 0.752, 0.802, 0.000, 0.756, 0.794, 0.000, 0.759, 0.787,\n 0.000, 0.762, 0.779, 0.000, 0.765, 0.771, 0.000, 0.767, 0.764, 0.000,\n 0.770, 0.755, 0.000, 0.772, 0.747, 0.000, 0.774, 0.739, 0.000, 0.776,\n 0.730, 0.000, 0.777, 0.721, 0.000, 0.779, 0.712, 0.021, 0.780, 0.702,\n 0.055, 0.781, 0.693, 0.079, 0.782, 0.682, 0.097, 0.782, 0.672, 0.111,\n 0.782, 0.661, 0.122, 0.782, 0.650, 0.132, 0.782, 0.639, 0.140, 0.781,\n 0.627, 0.147, 0.781, 0.615, 0.154, 0.780, 0.602, 0.159, 0.778, 0.589,\n 0.164, 0.777, 0.576, 0.169, 0.775, 0.563, 0.173, 0.773, 0.549, 0.177,\n 0.771, 0.535, 0.180, 0.768, 0.520, 0.184, 0.766, 0.505, 0.187, 0.763,\n 0.490, 0.190, 0.760, 0.474, 0.193, 0.756, 0.458, 0.196, 0.753, 0.442,\n 0.200, 0.749, 0.425, 0.203, 0.745, 0.408, 0.206, 0.741, 0.391, 0.210,\n 0.736, 0.373, 0.213, 0.732, 0.355, 0.216, 0.727, 0.337, 0.220, 0.722,\n 0.318, 0.224, 0.717, 0.298, 0.227, 0.712, 0.278, 0.231, 0.707, 0.258,\n 0.235, 0.701, 0.236, 0.239, 0.696, 0.214, 0.242, 0.690, 0.190, 0.246,\n 0.684, 0.165, 0.250, 0.678, 0.136, 0.000, 0.675, 0.934, 0.000, 0.681,\n 0.925, 0.000, 0.687, 0.917, 0.000, 0.692, 0.909, 0.000, 0.697, 0.901,\n 0.000, 0.703, 0.894, 0.000, 0.708, 0.886, 0.000, 0.713, 0.879, 0.000,\n 0.718, 0.872, 0.000, 0.722, 0.864, 0.000, 0.727, 0.857, 0.000, 0.731,\n 0.850, 0.000, 0.736, 0.843, 0.000, 0.740, 0.836, 0.000, 0.744, 0.829,\n 0.000, 0.748, 0.822, 0.000, 0.752, 0.815, 0.000, 0.755, 0.808, 0.000,\n 0.759, 0.800, 0.000, 0.762, 0.793, 0.000, 0.765, 0.786, 0.000, 0.768,\n 0.778, 0.000, 0.771, 0.770, 0.000, 0.773, 0.762, 0.051, 0.776, 0.754,\n 0.087, 0.778, 0.746, 0.111, 0.780, 0.737, 0.131, 0.782, 0.728, 0.146,\n 0.783, 0.719, 0.159, 0.784, 0.710, 0.171, 0.785, 0.700, 0.180, 0.786,\n 0.690, 0.189, 0.786, 0.680, 0.196, 0.787, 0.669, 0.202, 0.787, 0.658,\n 0.208, 0.786, 0.647, 0.213, 0.786, 0.635, 0.217, 0.785, 0.623, 0.221,\n 0.784, 0.610, 0.224, 0.782, 0.597, 0.227, 0.781, 0.584, 0.230, 0.779,\n 0.570, 0.232, 0.777, 0.556, 0.234, 0.775, 0.542, 0.236, 0.772, 0.527,\n 0.238, 0.769, 0.512, 0.240, 0.766, 0.497, 0.242, 0.763, 0.481, 0.244,\n 0.760, 0.465, 0.246, 0.756, 0.448, 0.248, 0.752, 0.432, 0.250, 0.748,\n 0.415, 0.252, 0.744, 0.397, 0.254, 0.739, 0.379, 0.256, 0.735, 0.361,\n 0.259, 0.730, 0.343, 0.261, 0.725, 0.324, 0.264, 0.720, 0.304, 0.266,\n 0.715, 0.284, 0.269, 0.709, 0.263, 0.271, 0.704, 0.242, 0.274, 0.698,\n 0.220, 0.277, 0.692, 0.196, 0.280, 0.686, 0.170, 0.283, 0.680, 0.143,\n 0.000, 0.676, 0.937, 0.000, 0.682, 0.928, 0.000, 0.688, 0.920, 0.000,\n 0.694, 0.913, 0.000, 0.699, 0.905, 0.000, 0.704, 0.897, 0.000, 0.710,\n 0.890, 0.000, 0.715, 0.883, 0.000, 0.720, 0.876, 0.000, 0.724, 0.869,\n 0.000, 0.729, 0.862, 0.000, 0.734, 0.855, 0.000, 0.738, 0.848, 0.000,\n 0.743, 0.841, 0.000, 0.747, 0.834, 0.000, 0.751, 0.827, 0.000, 0.755,\n 0.820, 0.000, 0.759, 0.813, 0.000, 0.762, 0.806, 0.003, 0.766, 0.799,\n 0.066, 0.769, 0.792, 0.104, 0.772, 0.784, 0.131, 0.775, 0.777, 0.152,\n 0.777, 0.769, 0.170, 0.780, 0.761, 0.185, 0.782, 0.753, 0.198, 0.784,\n 0.744, 0.209, 0.786, 0.736, 0.219, 0.787, 0.727, 0.228, 0.788, 0.717,\n 0.236, 0.789, 0.708, 0.243, 0.790, 0.698, 0.249, 0.791, 0.688, 0.254,\n 0.791, 0.677, 0.259, 0.791, 0.666, 0.263, 0.791, 0.654, 0.266, 0.790,\n 0.643, 0.269, 0.789, 0.631, 0.272, 0.788, 0.618, 0.274, 0.787, 0.605,\n 0.276, 0.785, 0.592, 0.278, 0.783, 0.578, 0.279, 0.781, 0.564, 0.280,\n 0.779, 0.549, 0.282, 0.776, 0.535, 0.283, 0.773, 0.519, 0.284, 0.770,\n 0.504, 0.285, 0.767, 0.488, 0.286, 0.763, 0.472, 0.287, 0.759, 0.455,\n 0.288, 0.756, 0.438, 0.289, 0.751, 0.421, 0.291, 0.747, 0.403, 0.292,\n 0.742, 0.385, 0.293, 0.738, 0.367, 0.295, 0.733, 0.348, 0.296, 0.728,\n 0.329, 0.298, 0.723, 0.310, 0.300, 0.717, 0.290, 0.302, 0.712, 0.269,\n 0.304, 0.706, 0.247, 0.306, 0.700, 0.225, 0.308, 0.694, 0.201, 0.310,\n 0.688, 0.176, 0.312, 0.682, 0.149, 0.000, 0.678, 0.939, 0.000, 0.683,\n 0.931, 0.000, 0.689, 0.923, 0.000, 0.695, 0.916, 0.000, 0.701, 0.908,\n 0.000, 0.706, 0.901, 0.000, 0.711, 0.894, 0.000, 0.717, 0.887, 0.000,\n 0.722, 0.880, 0.000, 0.727, 0.873, 0.000, 0.732, 0.866, 0.000, 0.736,\n 0.859, 0.000, 0.741, 0.853, 0.000, 0.745, 0.846, 0.000, 0.750, 0.839,\n 0.000, 0.754, 0.833, 0.035, 0.758, 0.826, 0.091, 0.762, 0.819, 0.126,\n 0.765, 0.812, 0.153, 0.769, 0.805, 0.174, 0.772, 0.798, 0.193, 0.775,\n 0.791, 0.209, 0.778, 0.783, 0.223, 0.781, 0.776, 0.236, 0.784, 0.768,\n 0.247, 0.786, 0.760, 0.257, 0.788, 0.752, 0.266, 0.790, 0.743, 0.273,\n 0.791, 0.734, 0.280, 0.793, 0.725, 0.287, 0.794, 0.715, 0.292, 0.794,\n 0.706, 0.297, 0.795, 0.695, 0.301, 0.795, 0.685, 0.305, 0.795, 0.674,\n 0.308, 0.795, 0.662, 0.310, 0.794, 0.651, 0.312, 0.794, 0.638, 0.314,\n 0.792, 0.626, 0.316, 0.791, 0.613, 0.317, 0.789, 0.599, 0.318, 0.787,\n 0.586, 0.319, 0.785, 0.571, 0.320, 0.783, 0.557, 0.320, 0.780, 0.542,\n 0.321, 0.777, 0.527, 0.321, 0.774, 0.511, 0.322, 0.770, 0.495, 0.322,\n 0.767, 0.478, 0.323, 0.763, 0.462, 0.323, 0.759, 0.445, 0.324, 0.755,\n 0.427, 0.325, 0.750, 0.410, 0.325, 0.745, 0.391, 0.326, 0.741, 0.373,\n 0.327, 0.736, 0.354, 0.328, 0.730, 0.335, 0.329, 0.725, 0.315, 0.330,\n 0.720, 0.295, 0.331, 0.714, 0.274, 0.333, 0.708, 0.253, 0.334, 0.702,\n 0.230, 0.336, 0.696, 0.207, 0.337, 0.690, 0.182, 0.339, 0.684, 0.154,\n 0.000, 0.679, 0.942, 0.000, 0.685, 0.934, 0.000, 0.691, 0.927, 0.000,\n 0.696, 0.919, 0.000, 0.702, 0.912, 0.000, 0.708, 0.905, 0.000, 0.713,\n 0.898, 0.000, 0.718, 0.891, 0.000, 0.724, 0.884, 0.000, 0.729, 0.877,\n 0.000, 0.734, 0.871, 0.000, 0.739, 0.864, 0.000, 0.743, 0.857, 0.035,\n 0.748, 0.851, 0.096, 0.752, 0.844, 0.133, 0.757, 0.838, 0.161, 0.761,\n 0.831, 0.185, 0.765, 0.825, 0.205, 0.769, 0.818, 0.223, 0.772, 0.811,\n 0.238, 0.776, 0.804, 0.252, 0.779, 0.797, 0.265, 0.782, 0.790, 0.276,\n 0.785, 0.783, 0.286, 0.788, 0.775, 0.296, 0.790, 0.767, 0.304, 0.792,\n 0.759, 0.311, 0.794, 0.751, 0.318, 0.796, 0.742, 0.324, 0.797, 0.733,\n 0.329, 0.798, 0.723, 0.334, 0.799, 0.714, 0.338, 0.799, 0.703, 0.341,\n 0.800, 0.693, 0.344, 0.800, 0.682, 0.347, 0.799, 0.670, 0.349, 0.799,\n 0.659, 0.351, 0.798, 0.646, 0.352, 0.797, 0.634, 0.353, 0.795, 0.621,\n 0.354, 0.794, 0.607, 0.354, 0.792, 0.593, 0.355, 0.789, 0.579, 0.355,\n 0.787, 0.564, 0.355, 0.784, 0.549, 0.355, 0.781, 0.534, 0.355, 0.778,\n 0.518, 0.355, 0.774, 0.502, 0.355, 0.770, 0.485, 0.355, 0.766, 0.468,\n 0.355, 0.762, 0.451, 0.355, 0.758, 0.434, 0.355, 0.753, 0.416, 0.356,\n 0.748, 0.397, 0.356, 0.743, 0.379, 0.356, 0.738, 0.360, 0.357, 0.733,\n 0.340, 0.357, 0.728, 0.321, 0.358, 0.722, 0.300, 0.359, 0.716, 0.279,\n 0.360, 0.710, 0.258, 0.361, 0.704, 0.235, 0.361, 0.698, 0.212, 0.362,\n 0.692, 0.187, 0.363, 0.686, 0.160, 0.000, 0.680, 0.945, 0.000, 0.686,\n 0.937, 0.000, 0.692, 0.930, 0.000, 0.698, 0.922, 0.000, 0.703, 0.915,\n 0.000, 0.709, 0.908, 0.000, 0.715, 0.901, 0.000, 0.720, 0.894, 0.000,\n 0.726, 0.888, 0.000, 0.731, 0.881, 0.007, 0.736, 0.875, 0.084, 0.741,\n 0.869, 0.127, 0.746, 0.862, 0.159, 0.751, 0.856, 0.185, 0.755, 0.850,\n 0.208, 0.760, 0.843, 0.227, 0.764, 0.837, 0.245, 0.768, 0.830, 0.260,\n 0.772, 0.824, 0.275, 0.776, 0.817, 0.288, 0.779, 0.811, 0.300, 0.783,\n 0.804, 0.310, 0.786, 0.797, 0.320, 0.789, 0.789, 0.329, 0.792, 0.782,\n 0.337, 0.794, 0.774, 0.345, 0.796, 0.766, 0.351, 0.798, 0.758, 0.357,\n 0.800, 0.749, 0.363, 0.801, 0.740, 0.367, 0.803, 0.731, 0.371, 0.803,\n 0.721, 0.375, 0.804, 0.711, 0.378, 0.804, 0.701, 0.380, 0.804, 0.690,\n 0.382, 0.804, 0.679, 0.384, 0.803, 0.667, 0.385, 0.802, 0.654, 0.386,\n 0.801, 0.642, 0.386, 0.800, 0.629, 0.387, 0.798, 0.615, 0.387, 0.796,\n 0.601, 0.387, 0.793, 0.587, 0.387, 0.791, 0.572, 0.387, 0.788, 0.557,\n 0.386, 0.785, 0.541, 0.386, 0.781, 0.525, 0.385, 0.778, 0.509, 0.385,\n 0.774, 0.492, 0.385, 0.770, 0.475, 0.384, 0.765, 0.457, 0.384, 0.761,\n 0.440, 0.384, 0.756, 0.422, 0.384, 0.751, 0.403, 0.384, 0.746, 0.384,\n 0.384, 0.741, 0.365, 0.384, 0.735, 0.346, 0.384, 0.730, 0.326, 0.384,\n 0.724, 0.305, 0.384, 0.718, 0.284, 0.385, 0.712, 0.263, 0.385, 0.706,\n 0.240, 0.386, 0.700, 0.217, 0.386, 0.694, 0.192, 0.387, 0.687, 0.165,\n 0.000, 0.680, 0.948, 0.000, 0.687, 0.940, 0.000, 0.693, 0.933, 0.000,\n 0.699, 0.925, 0.000, 0.705, 0.918, 0.000, 0.711, 0.912, 0.000, 0.716,\n 0.905, 0.000, 0.722, 0.898, 0.050, 0.728, 0.892, 0.109, 0.733, 0.886,\n 0.147, 0.738, 0.879, 0.177, 0.743, 0.873, 0.202, 0.748, 0.867, 0.224,\n 0.753, 0.861, 0.243, 0.758, 0.855, 0.261, 0.763, 0.849, 0.277, 0.767,\n 0.842, 0.292, 0.771, 0.836, 0.305, 0.775, 0.830, 0.318, 0.779, 0.823,\n 0.329, 0.783, 0.817, 0.340, 0.787, 0.810, 0.350, 0.790, 0.803, 0.359,\n 0.793, 0.796, 0.367, 0.796, 0.789, 0.374, 0.798, 0.782, 0.381, 0.801,\n 0.774, 0.387, 0.803, 0.766, 0.393, 0.804, 0.757, 0.397, 0.806, 0.748,\n 0.402, 0.807, 0.739, 0.405, 0.808, 0.729, 0.408, 0.809, 0.719, 0.411,\n 0.809, 0.709, 0.413, 0.809, 0.698, 0.415, 0.808, 0.687, 0.416, 0.808,\n 0.675, 0.417, 0.807, 0.663, 0.417, 0.806, 0.650, 0.417, 0.804, 0.637,\n 0.418, 0.802, 0.623, 0.417, 0.800, 0.609, 0.417, 0.798, 0.594, 0.416,\n 0.795, 0.579, 0.416, 0.792, 0.564, 0.415, 0.789, 0.548, 0.414, 0.785,\n 0.532, 0.414, 0.781, 0.515, 0.413, 0.777, 0.499, 0.412, 0.773, 0.481,\n 0.412, 0.769, 0.464, 0.411, 0.764, 0.446, 0.410, 0.759, 0.428, 0.410,\n 0.754, 0.409, 0.409, 0.749, 0.390, 0.409, 0.743, 0.371, 0.409, 0.738,\n 0.351, 0.409, 0.732, 0.331, 0.408, 0.726, 0.310, 0.408, 0.720, 0.289,\n 0.408, 0.714, 0.268, 0.408, 0.708, 0.245, 0.409, 0.702, 0.222, 0.409,\n 0.695, 0.197, 0.409, 0.689, 0.170, 0.000, 0.681, 0.950, 0.000, 0.688,\n 0.943, 0.000, 0.694, 0.936, 0.000, 0.700, 0.929, 0.000, 0.706, 0.922,\n 0.000, 0.712, 0.915, 0.074, 0.718, 0.908, 0.124, 0.724, 0.902, 0.159,\n 0.730, 0.896, 0.188, 0.735, 0.890, 0.213, 0.740, 0.884, 0.235, 0.746,\n 0.878, 0.255, 0.751, 0.872, 0.273, 0.756, 0.866, 0.289, 0.761, 0.860,\n 0.305, 0.766, 0.854, 0.319, 0.770, 0.848, 0.332, 0.775, 0.842, 0.344,\n 0.779, 0.836, 0.356, 0.783, 0.830, 0.366, 0.787, 0.823, 0.376, 0.790,\n 0.817, 0.385, 0.794, 0.810, 0.394, 0.797, 0.803, 0.401, 0.800, 0.796,\n 0.408, 0.802, 0.789, 0.414, 0.805, 0.781, 0.420, 0.807, 0.773, 0.425,\n 0.809, 0.765, 0.430, 0.810, 0.756, 0.433, 0.812, 0.747, 0.437, 0.813,\n 0.738, 0.440, 0.813, 0.728, 0.442, 0.814, 0.717, 0.444, 0.813, 0.706,\n 0.445, 0.813, 0.695, 0.446, 0.812, 0.683, 0.446, 0.811, 0.671, 0.447,\n 0.810, 0.658, 0.447, 0.809, 0.645, 0.446, 0.807, 0.631, 0.446, 0.804,\n 0.617, 0.445, 0.802, 0.602, 0.444, 0.799, 0.587, 0.443, 0.796, 0.571,\n 0.442, 0.792, 0.555, 0.441, 0.789, 0.539, 0.440, 0.785, 0.522, 0.439,\n 0.781, 0.505, 0.438, 0.776, 0.488, 0.437, 0.772, 0.470, 0.436, 0.767,\n 0.452, 0.435, 0.762, 0.433, 0.435, 0.757, 0.415, 0.434, 0.751, 0.396,\n 0.433, 0.746, 0.376, 0.432, 0.740, 0.356, 0.432, 0.734, 0.336, 0.431,\n 0.728, 0.315, 0.431, 0.722, 0.294, 0.431, 0.716, 0.272, 0.430, 0.710,\n 0.250, 0.430, 0.703, 0.226, 0.430, 0.697, 0.201, 0.430, 0.690, 0.175,\n 0.000, 0.682, 0.953, 0.000, 0.689, 0.946, 0.000, 0.695, 0.938, 0.002,\n 0.701, 0.932, 0.086, 0.708, 0.925, 0.133, 0.714, 0.918, 0.167, 0.720,\n 0.912, 0.196, 0.726, 0.906, 0.221, 0.731, 0.900, 0.243, 0.737, 0.894,\n 0.263, 0.743, 0.888, 0.281, 0.748, 0.882, 0.298, 0.753, 0.876, 0.314,\n 0.759, 0.870, 0.329, 0.764, 0.865, 0.342, 0.768, 0.859, 0.355, 0.773,\n 0.853, 0.368, 0.778, 0.847, 0.379, 0.782, 0.842, 0.390, 0.786, 0.836,\n 0.400, 0.790, 0.830, 0.409, 0.794, 0.823, 0.417, 0.798, 0.817, 0.425,\n 0.801, 0.810, 0.433, 0.804, 0.803, 0.439, 0.807, 0.796, 0.445, 0.809,\n 0.789, 0.451, 0.811, 0.781, 0.456, 0.813, 0.773, 0.460, 0.815, 0.764,\n 0.463, 0.816, 0.755, 0.466, 0.817, 0.746, 0.469, 0.818, 0.736, 0.471,\n 0.818, 0.725, 0.472, 0.818, 0.715, 0.473, 0.818, 0.703, 0.474, 0.817,\n 0.691, 0.474, 0.816, 0.679, 0.474, 0.815, 0.666, 0.474, 0.813, 0.653,\n 0.473, 0.811, 0.639, 0.473, 0.809, 0.624, 0.472, 0.806, 0.610, 0.471,\n 0.803, 0.594, 0.469, 0.800, 0.579, 0.468, 0.796, 0.562, 0.467, 0.792,\n 0.546, 0.466, 0.788, 0.529, 0.464, 0.784, 0.512, 0.463, 0.780, 0.494,\n 0.462, 0.775, 0.476, 0.460, 0.770, 0.458, 0.459, 0.765, 0.439, 0.458,\n 0.759, 0.420, 0.457, 0.754, 0.401, 0.456, 0.748, 0.381, 0.455, 0.742,\n 0.361, 0.454, 0.736, 0.341, 0.453, 0.730, 0.320, 0.453, 0.724, 0.299,\n 0.452, 0.718, 0.277, 0.452, 0.711, 0.254, 0.451, 0.705, 0.231, 0.451,\n 0.698, 0.206, 0.450, 0.691, 0.179, 0.000, 0.683, 0.955, 0.013, 0.689,\n 0.948, 0.092, 0.696, 0.941, 0.137, 0.702, 0.935, 0.171, 0.709, 0.928,\n 0.200, 0.715, 0.922, 0.225, 0.721, 0.916, 0.247, 0.727, 0.909, 0.267,\n 0.733, 0.904, 0.286, 0.739, 0.898, 0.303, 0.745, 0.892, 0.320, 0.750,\n 0.886, 0.335, 0.756, 0.881, 0.350, 0.761, 0.875, 0.363, 0.766, 0.870,\n 0.376, 0.771, 0.864, 0.388, 0.776, 0.859, 0.400, 0.781, 0.853, 0.411,\n 0.785, 0.847, 0.421, 0.790, 0.842, 0.430, 0.794, 0.836, 0.439, 0.798,\n 0.830, 0.448, 0.802, 0.824, 0.455, 0.805, 0.817, 0.462, 0.808, 0.810,\n 0.469, 0.811, 0.804, 0.475, 0.814, 0.796, 0.480, 0.816, 0.789, 0.484,\n 0.818, 0.781, 0.488, 0.820, 0.772, 0.492, 0.821, 0.763, 0.495, 0.822,\n 0.754, 0.497, 0.823, 0.744, 0.499, 0.823, 0.734, 0.500, 0.823, 0.723,\n 0.501, 0.823, 0.712, 0.501, 0.822, 0.700, 0.501, 0.821, 0.687, 0.501,\n 0.819, 0.674, 0.500, 0.818, 0.661, 0.499, 0.815, 0.647, 0.498, 0.813,\n 0.632, 0.497, 0.810, 0.617, 0.496, 0.807, 0.602, 0.494, 0.804, 0.586,\n 0.493, 0.800, 0.569, 0.491, 0.796, 0.553, 0.490, 0.792, 0.536, 0.488,\n 0.787, 0.518, 0.486, 0.783, 0.500, 0.485, 0.778, 0.482, 0.483, 0.773,\n 0.463, 0.482, 0.767, 0.445, 0.480, 0.762, 0.425, 0.479, 0.756, 0.406,\n 0.478, 0.750, 0.386, 0.477, 0.744, 0.366, 0.476, 0.738, 0.345, 0.475,\n 0.732, 0.325, 0.474, 0.726, 0.303, 0.473, 0.719, 0.281, 0.472, 0.713,\n 0.258, 0.471, 0.706, 0.235, 0.470, 0.699, 0.210, 0.469, 0.692, 0.184,\n 0.095, 0.683, 0.958, 0.139, 0.690, 0.951, 0.173, 0.697, 0.944, 0.201,\n 0.703, 0.938, 0.226, 0.710, 0.931, 0.249, 0.716, 0.925, 0.269, 0.723,\n 0.919, 0.288, 0.729, 0.913, 0.306, 0.735, 0.907, 0.323, 0.741, 0.902,\n 0.339, 0.747, 0.896, 0.354, 0.752, 0.891, 0.368, 0.758, 0.885, 0.382,\n 0.764, 0.880, 0.394, 0.769, 0.875, 0.407, 0.774, 0.869, 0.418, 0.779,\n 0.864, 0.429, 0.784, 0.859, 0.440, 0.789, 0.853, 0.450, 0.793, 0.848,\n 0.459, 0.798, 0.842, 0.468, 0.802, 0.836, 0.476, 0.806, 0.830, 0.483,\n 0.809, 0.824, 0.490, 0.812, 0.818, 0.496, 0.815, 0.811, 0.502, 0.818,\n 0.804, 0.507, 0.821, 0.796, 0.512, 0.823, 0.789, 0.515, 0.825, 0.780,\n 0.519, 0.826, 0.772, 0.521, 0.827, 0.762, 0.524, 0.828, 0.753, 0.525,\n 0.828, 0.742, 0.526, 0.828, 0.732, 0.527, 0.828, 0.720, 0.527, 0.827,\n 0.708, 0.527, 0.826, 0.696, 0.526, 0.824, 0.683, 0.525, 0.822, 0.669,\n 0.524, 0.820, 0.655, 0.523, 0.817, 0.640, 0.522, 0.814, 0.625, 0.520,\n 0.811, 0.609, 0.518, 0.808, 0.593, 0.516, 0.804, 0.576, 0.515, 0.800,\n 0.559, 0.513, 0.795, 0.542, 0.511, 0.791, 0.524, 0.509, 0.786, 0.506,\n 0.507, 0.781, 0.488, 0.505, 0.775, 0.469, 0.504, 0.770, 0.450, 0.502,\n 0.764, 0.431, 0.500, 0.759, 0.411, 0.499, 0.753, 0.391, 0.497, 0.746,\n 0.371, 0.496, 0.740, 0.350, 0.495, 0.734, 0.329, 0.494, 0.727, 0.307,\n 0.492, 0.721, 0.285, 0.491, 0.714, 0.262, 0.490, 0.707, 0.239, 0.489,\n 0.700, 0.214, 0.488, 0.693, 0.188, 0.172, 0.684, 0.961, 0.201, 0.691,\n 0.954, 0.226, 0.698, 0.947, 0.248, 0.704, 0.941, 0.269, 0.711, 0.934,\n 0.289, 0.717, 0.928, 0.307, 0.724, 0.922, 0.324, 0.730, 0.917, 0.340,\n 0.736, 0.911, 0.356, 0.743, 0.906, 0.370, 0.749, 0.900, 0.384, 0.755,\n 0.895, 0.398, 0.760, 0.890, 0.411, 0.766, 0.885, 0.423, 0.772, 0.880,\n 0.435, 0.777, 0.874, 0.446, 0.782, 0.869, 0.457, 0.787, 0.864, 0.467,\n 0.792, 0.859, 0.477, 0.797, 0.854, 0.486, 0.801, 0.848, 0.494, 0.806,\n 0.843, 0.502, 0.810, 0.837, 0.510, 0.813, 0.831, 0.517, 0.817, 0.825,\n 0.523, 0.820, 0.818, 0.528, 0.823, 0.811, 0.533, 0.825, 0.804, 0.538,\n 0.828, 0.797, 0.542, 0.829, 0.788, 0.545, 0.831, 0.780, 0.547, 0.832,\n 0.771, 0.549, 0.833, 0.761, 0.551, 0.833, 0.751, 0.552, 0.833, 0.740,\n 0.552, 0.833, 0.729, 0.552, 0.832, 0.717, 0.551, 0.830, 0.704, 0.551,\n 0.829, 0.691, 0.550, 0.827, 0.677, 0.548, 0.824, 0.663, 0.547, 0.822,\n 0.648, 0.545, 0.819, 0.632, 0.543, 0.815, 0.617, 0.541, 0.812, 0.600,\n 0.539, 0.808, 0.583, 0.537, 0.803, 0.566, 0.535, 0.799, 0.549, 0.533,\n 0.794, 0.531, 0.531, 0.789, 0.512, 0.529, 0.784, 0.494, 0.527, 0.778,\n 0.475, 0.525, 0.773, 0.455, 0.523, 0.767, 0.436, 0.521, 0.761, 0.416,\n 0.519, 0.755, 0.396, 0.517, 0.748, 0.375, 0.516, 0.742, 0.354, 0.514,\n 0.735, 0.333, 0.513, 0.729, 0.311, 0.511, 0.722, 0.289, 0.510, 0.715,\n 0.266, 0.509, 0.708, 0.242, 0.507, 0.701, 0.218, 0.506, 0.694, 0.191,\n 0.224, 0.684, 0.963, 0.247, 0.691, 0.956, 0.268, 0.698, 0.950, 0.287,\n 0.705, 0.943, 0.305, 0.712, 0.937, 0.323, 0.719, 0.931, 0.339, 0.725,\n 0.926, 0.355, 0.732, 0.920, 0.370, 0.738, 0.915, 0.385, 0.744, 0.909,\n 0.399, 0.751, 0.904, 0.412, 0.757, 0.899, 0.425, 0.763, 0.894, 0.438,\n 0.768, 0.889, 0.450, 0.774, 0.884, 0.461, 0.780, 0.879, 0.472, 0.785,\n 0.875, 0.483, 0.790, 0.870, 0.493, 0.795, 0.865, 0.502, 0.800, 0.860,\n 0.511, 0.805, 0.855, 0.520, 0.809, 0.849, 0.528, 0.814, 0.844, 0.535,\n 0.818, 0.838, 0.542, 0.821, 0.832, 0.548, 0.824, 0.826, 0.554, 0.827,\n 0.819, 0.559, 0.830, 0.812, 0.563, 0.832, 0.805, 0.567, 0.834, 0.797,\n 0.570, 0.836, 0.788, 0.572, 0.837, 0.779, 0.574, 0.838, 0.770, 0.575,\n 0.838, 0.760, 0.576, 0.838, 0.749, 0.576, 0.838, 0.737, 0.576, 0.837,\n 0.725, 0.575, 0.835, 0.713, 0.574, 0.834, 0.699, 0.573, 0.831, 0.685,\n 0.571, 0.829, 0.671, 0.570, 0.826, 0.656, 0.568, 0.823, 0.640, 0.566,\n 0.819, 0.624, 0.563, 0.815, 0.607, 0.561, 0.811, 0.590, 0.559, 0.807,\n 0.573, 0.556, 0.802, 0.555, 0.554, 0.797, 0.537, 0.552, 0.792, 0.518,\n 0.549, 0.786, 0.499, 0.547, 0.781, 0.480, 0.545, 0.775, 0.460, 0.543,\n 0.769, 0.441, 0.541, 0.763, 0.420, 0.539, 0.756, 0.400, 0.537, 0.750,\n 0.379, 0.535, 0.743, 0.358, 0.533, 0.737, 0.337, 0.531, 0.730, 0.315,\n 0.530, 0.723, 0.293, 0.528, 0.716, 0.270, 0.527, 0.709, 0.246, 0.525,\n 0.702, 0.221, 0.524, 0.694, 0.195, 0.265, 0.685, 0.965, 0.284, 0.692,\n 0.959, 0.303, 0.699, 0.952, 0.320, 0.706, 0.946, 0.337, 0.713, 0.940,\n 0.353, 0.720, 0.935, 0.369, 0.726, 0.929, 0.384, 0.733, 0.924, 0.398,\n 0.739, 0.918, 0.412, 0.746, 0.913, 0.425, 0.752, 0.908, 0.438, 0.759,\n 0.903, 0.451, 0.765, 0.899, 0.463, 0.771, 0.894, 0.475, 0.777, 0.889,\n 0.486, 0.782, 0.884, 0.497, 0.788, 0.880, 0.507, 0.793, 0.875, 0.517,\n 0.799, 0.870, 0.527, 0.804, 0.866, 0.536, 0.809, 0.861, 0.544, 0.813,\n 0.856, 0.552, 0.818, 0.850, 0.560, 0.822, 0.845, 0.566, 0.826, 0.839,\n 0.573, 0.829, 0.833, 0.578, 0.832, 0.827, 0.583, 0.835, 0.820, 0.587,\n 0.837, 0.813, 0.591, 0.839, 0.805, 0.594, 0.841, 0.797, 0.596, 0.842,\n 0.788, 0.598, 0.843, 0.778, 0.599, 0.843, 0.768, 0.600, 0.843, 0.758,\n 0.600, 0.843, 0.746, 0.599, 0.842, 0.734, 0.599, 0.840, 0.721, 0.597,\n 0.838, 0.708, 0.596, 0.836, 0.694, 0.594, 0.834, 0.679, 0.592, 0.831,\n 0.663, 0.590, 0.827, 0.648, 0.587, 0.823, 0.631, 0.585, 0.819, 0.614,\n 0.582, 0.815, 0.597, 0.580, 0.810, 0.579, 0.577, 0.805, 0.561, 0.575,\n 0.800, 0.542, 0.572, 0.795, 0.524, 0.569, 0.789, 0.504, 0.567, 0.783,\n 0.485, 0.565, 0.777, 0.465, 0.562, 0.771, 0.445, 0.560, 0.765, 0.425,\n 0.558, 0.758, 0.404, 0.556, 0.752, 0.383, 0.554, 0.745, 0.362, 0.552,\n 0.738, 0.341, 0.550, 0.731, 0.319, 0.548, 0.724, 0.296, 0.546, 0.717,\n 0.273, 0.544, 0.709, 0.249, 0.542, 0.702, 0.224, 0.541, 0.695, 0.198,\n 0.299, 0.685, 0.968, 0.317, 0.692, 0.961, 0.334, 0.699, 0.955, 0.350,\n 0.706, 0.949, 0.366, 0.713, 0.943, 0.381, 0.720, 0.938, 0.395, 0.727,\n 0.932, 0.410, 0.734, 0.927, 0.423, 0.741, 0.922, 0.437, 0.747, 0.917,\n 0.450, 0.754, 0.912, 0.463, 0.760, 0.907, 0.475, 0.767, 0.903, 0.487,\n 0.773, 0.898, 0.498, 0.779, 0.894, 0.509, 0.785, 0.889, 0.520, 0.791,\n 0.885, 0.531, 0.796, 0.880, 0.540, 0.802, 0.876, 0.550, 0.807, 0.871,\n 0.559, 0.812, 0.867, 0.568, 0.817, 0.862, 0.576, 0.822, 0.857, 0.583,\n 0.826, 0.852, 0.590, 0.830, 0.847, 0.596, 0.834, 0.841, 0.602, 0.837,\n 0.835, 0.607, 0.840, 0.828, 0.611, 0.843, 0.821, 0.615, 0.845, 0.814,\n 0.618, 0.846, 0.805, 0.620, 0.848, 0.797, 0.622, 0.848, 0.787, 0.623,\n 0.849, 0.777, 0.623, 0.849, 0.766, 0.623, 0.848, 0.755, 0.622, 0.847,\n 0.743, 0.621, 0.845, 0.730, 0.620, 0.843, 0.716, 0.618, 0.841, 0.702,\n 0.616, 0.838, 0.687, 0.613, 0.835, 0.671, 0.611, 0.831, 0.655, 0.608,\n 0.827, 0.638, 0.606, 0.823, 0.621, 0.603, 0.818, 0.604, 0.600, 0.814,\n 0.585, 0.597, 0.808, 0.567, 0.594, 0.803, 0.548, 0.592, 0.797, 0.529,\n 0.589, 0.792, 0.510, 0.586, 0.785, 0.490, 0.584, 0.779, 0.470, 0.581,\n 0.773, 0.450, 0.579, 0.766, 0.429, 0.576, 0.760, 0.408, 0.574, 0.753,\n 0.387, 0.572, 0.746, 0.366, 0.569, 0.739, 0.344, 0.567, 0.732, 0.322,\n 0.565, 0.725, 0.299, 0.563, 0.717, 0.276, 0.561, 0.710, 0.252, 0.559,\n 0.703, 0.227, 0.557, 0.695, 0.201, 0.329, 0.685, 0.970, 0.346, 0.692,\n 0.964, 0.362, 0.699, 0.958, 0.377, 0.707, 0.952, 0.392, 0.714, 0.946,\n 0.406, 0.721, 0.941, 0.420, 0.728, 0.935, 0.434, 0.735, 0.930, 0.447,\n 0.742, 0.925, 0.460, 0.749, 0.920, 0.473, 0.756, 0.916, 0.485, 0.762,\n 0.911, 0.497, 0.769, 0.907, 0.509, 0.775, 0.903, 0.521, 0.781, 0.898,\n 0.532, 0.788, 0.894, 0.542, 0.794, 0.890, 0.553, 0.799, 0.886, 0.563,\n 0.805, 0.882, 0.572, 0.811, 0.877, 0.581, 0.816, 0.873, 0.590, 0.821,\n 0.868, 0.598, 0.826, 0.864, 0.606, 0.830, 0.859, 0.613, 0.834, 0.854,\n 0.619, 0.838, 0.848, 0.625, 0.842, 0.842, 0.630, 0.845, 0.836, 0.634,\n 0.848, 0.829, 0.638, 0.850, 0.822, 0.641, 0.852, 0.814, 0.643, 0.853,\n 0.805, 0.645, 0.854, 0.796, 0.645, 0.854, 0.786, 0.646, 0.854, 0.775,\n 0.645, 0.853, 0.764, 0.645, 0.852, 0.751, 0.643, 0.851, 0.738, 0.642,\n 0.848, 0.725, 0.639, 0.846, 0.710, 0.637, 0.843, 0.695, 0.635, 0.839,\n 0.679, 0.632, 0.836, 0.662, 0.629, 0.831, 0.645, 0.626, 0.827, 0.628,\n 0.623, 0.822, 0.610, 0.620, 0.817, 0.592, 0.617, 0.811, 0.573, 0.614,\n 0.806, 0.554, 0.611, 0.800, 0.534, 0.608, 0.794, 0.515, 0.605, 0.788,\n 0.495, 0.602, 0.781, 0.474, 0.599, 0.775, 0.454, 0.597, 0.768, 0.433,\n 0.594, 0.761, 0.412, 0.592, 0.754, 0.391, 0.589, 0.747, 0.369, 0.587,\n 0.740, 0.347, 0.584, 0.733, 0.325, 0.582, 0.725, 0.302, 0.580, 0.718,\n 0.279, 0.577, 0.710, 0.255, 0.575, 0.703, 0.230, 0.573, 0.695, 0.204,\n 0.357, 0.685, 0.972, 0.372, 0.692, 0.966, 0.387, 0.700, 0.960, 0.401,\n 0.707, 0.954, 0.416, 0.714, 0.949, 0.429, 0.722, 0.943, 0.443, 0.729,\n 0.938, 0.456, 0.736, 0.933, 0.469, 0.743, 0.929, 0.482, 0.750, 0.924,\n 0.494, 0.757, 0.919, 0.507, 0.764, 0.915, 0.519, 0.771, 0.911, 0.530,\n 0.777, 0.907, 0.542, 0.784, 0.903, 0.553, 0.790, 0.899, 0.563, 0.796,\n 0.895, 0.574, 0.802, 0.891, 0.584, 0.808, 0.887, 0.593, 0.814, 0.883,\n 0.603, 0.820, 0.879, 0.611, 0.825, 0.875, 0.620, 0.830, 0.870, 0.627,\n 0.835, 0.866, 0.635, 0.839, 0.861, 0.641, 0.843, 0.856, 0.647, 0.847,\n 0.850, 0.652, 0.850, 0.844, 0.657, 0.853, 0.838, 0.660, 0.855, 0.831,\n 0.663, 0.857, 0.823, 0.666, 0.859, 0.814, 0.667, 0.859, 0.805, 0.668,\n 0.860, 0.795, 0.668, 0.860, 0.784, 0.667, 0.859, 0.773, 0.666, 0.858,\n 0.760, 0.665, 0.856, 0.747, 0.663, 0.853, 0.733, 0.661, 0.851, 0.718,\n 0.658, 0.847, 0.703, 0.655, 0.844, 0.687, 0.652, 0.840, 0.670, 0.649,\n 0.835, 0.652, 0.646, 0.830, 0.635, 0.642, 0.825, 0.616, 0.639, 0.820,\n 0.598, 0.636, 0.814, 0.579, 0.633, 0.808, 0.559, 0.629, 0.802, 0.539,\n 0.626, 0.796, 0.519, 0.623, 0.790, 0.499, 0.620, 0.783, 0.479, 0.617,\n 0.776, 0.458, 0.614, 0.769, 0.437, 0.611, 0.762, 0.416, 0.609, 0.755,\n 0.394, 0.606, 0.748, 0.372, 0.603, 0.740, 0.350, 0.601, 0.733, 0.328,\n 0.598, 0.726, 0.305, 0.596, 0.718, 0.282, 0.593, 0.710, 0.257, 0.591,\n 0.703, 0.232, 0.589, 0.695, 0.206, 0.381, 0.684, 0.974, 0.396, 0.692,\n 0.968, 0.410, 0.700, 0.962, 0.424, 0.707, 0.957, 0.438, 0.715, 0.951,\n 0.451, 0.722, 0.946, 0.464, 0.729, 0.941, 0.477, 0.737, 0.936, 0.490,\n 0.744, 0.932, 0.503, 0.751, 0.927, 0.515, 0.758, 0.923, 0.527, 0.765,\n 0.919, 0.539, 0.772, 0.915, 0.550, 0.779, 0.911, 0.562, 0.786, 0.907,\n 0.573, 0.792, 0.903, 0.584, 0.799, 0.900, 0.594, 0.805, 0.896, 0.604,\n 0.811, 0.892, 0.614, 0.817, 0.889, 0.623, 0.823, 0.885, 0.632, 0.829,\n 0.881, 0.641, 0.834, 0.877, 0.649, 0.839, 0.873, 0.656, 0.844, 0.868,\n 0.663, 0.848, 0.863, 0.669, 0.852, 0.858, 0.674, 0.855, 0.852, 0.679,\n 0.858, 0.846, 0.682, 0.861, 0.839, 0.685, 0.863, 0.832, 0.688, 0.864,\n 0.823, 0.689, 0.865, 0.814, 0.690, 0.865, 0.804, 0.690, 0.865, 0.794,\n 0.689, 0.864, 0.782, 0.688, 0.863, 0.769, 0.686, 0.861, 0.756, 0.684,\n 0.858, 0.742, 0.681, 0.855, 0.726, 0.678, 0.852, 0.711, 0.675, 0.848,\n 0.694, 0.672, 0.844, 0.677, 0.668, 0.839, 0.659, 0.665, 0.834, 0.641,\n 0.662, 0.829, 0.622, 0.658, 0.823, 0.603, 0.655, 0.817, 0.584, 0.651,\n 0.811, 0.564, 0.648, 0.805, 0.544, 0.644, 0.798, 0.524, 0.641, 0.791,\n 0.503, 0.638, 0.785, 0.483, 0.635, 0.778, 0.462, 0.631, 0.770, 0.440,\n 0.628, 0.763, 0.419, 0.625, 0.756, 0.397, 0.623, 0.748, 0.375, 0.620,\n 0.741, 0.353, 0.617, 0.733, 0.330, 0.614, 0.726, 0.307, 0.612, 0.718,\n 0.284, 0.609, 0.710, 0.260, 0.606, 0.702, 0.235, 0.604, 0.694, 0.208,\n 0.404, 0.684, 0.977, 0.418, 0.692, 0.971, 0.432, 0.699, 0.965, 0.445,\n 0.707, 0.959, 0.458, 0.715, 0.954, 0.472, 0.722, 0.949, 0.484, 0.730,\n 0.944, 0.497, 0.737, 0.939, 0.510, 0.745, 0.935, 0.522, 0.752, 0.931,\n 0.534, 0.759, 0.926, 0.546, 0.767, 0.922, 0.558, 0.774, 0.919, 0.569,\n 0.781, 0.915, 0.581, 0.788, 0.911, 0.592, 0.794, 0.908, 0.603, 0.801,\n 0.904, 0.613, 0.808, 0.901, 0.624, 0.814, 0.897, 0.633, 0.820, 0.894,\n 0.643, 0.826, 0.891, 0.652, 0.832, 0.887, 0.661, 0.838, 0.883, 0.669,\n 0.843, 0.879, 0.677, 0.848, 0.875, 0.684, 0.853, 0.871, 0.690, 0.857,\n 0.866, 0.695, 0.860, 0.860, 0.700, 0.864, 0.855, 0.704, 0.866, 0.848,\n 0.707, 0.869, 0.841, 0.709, 0.870, 0.833, 0.711, 0.871, 0.824, 0.711,\n 0.871, 0.814, 0.711, 0.871, 0.803, 0.710, 0.870, 0.791, 0.709, 0.868,\n 0.778, 0.707, 0.866, 0.765, 0.704, 0.864, 0.750, 0.701, 0.860, 0.735,\n 0.698, 0.857, 0.718, 0.695, 0.852, 0.702, 0.691, 0.848, 0.684, 0.688,\n 0.843, 0.666, 0.684, 0.837, 0.647, 0.680, 0.832, 0.628, 0.676, 0.826,\n 0.609, 0.673, 0.820, 0.589, 0.669, 0.813, 0.569, 0.665, 0.807, 0.549,\n 0.662, 0.800, 0.528, 0.658, 0.793, 0.507, 0.655, 0.786, 0.486, 0.651,\n 0.779, 0.465, 0.648, 0.771, 0.444, 0.645, 0.764, 0.422, 0.642, 0.756,\n 0.400, 0.639, 0.749, 0.378, 0.636, 0.741, 0.356, 0.633, 0.733, 0.333,\n 0.630, 0.726, 0.310, 0.627, 0.718, 0.286, 0.624, 0.710, 0.262, 0.621,\n 0.702, 0.237, 0.619, 0.694, 0.210, 0.425, 0.683, 0.979, 0.439, 0.691,\n 0.973, 0.452, 0.699, 0.967, 0.465, 0.707, 0.962, 0.478, 0.715, 0.956,\n 0.491, 0.722, 0.951, 0.503, 0.730, 0.947, 0.516, 0.738, 0.942, 0.528,\n 0.745, 0.938, 0.540, 0.753, 0.934, 0.552, 0.760, 0.930, 0.564, 0.768,\n 0.926, 0.576, 0.775, 0.922, 0.588, 0.782, 0.919, 0.599, 0.789, 0.915,\n 0.610, 0.797, 0.912, 0.621, 0.803, 0.909, 0.632, 0.810, 0.906, 0.642,\n 0.817, 0.902, 0.652, 0.823, 0.899, 0.662, 0.830, 0.896, 0.671, 0.836,\n 0.893, 0.680, 0.842, 0.890, 0.689, 0.847, 0.886, 0.697, 0.853, 0.882,\n 0.704, 0.857, 0.878, 0.710, 0.862, 0.874, 0.716, 0.866, 0.869, 0.721,\n 0.869, 0.863, 0.725, 0.872, 0.857, 0.729, 0.874, 0.850, 0.731, 0.876,\n 0.842, 0.732, 0.877, 0.833, 0.733, 0.877, 0.823, 0.732, 0.877, 0.812,\n 0.731, 0.876, 0.800, 0.729, 0.874, 0.787, 0.727, 0.872, 0.773, 0.724,\n 0.869, 0.759, 0.721, 0.865, 0.743, 0.718, 0.861, 0.726, 0.714, 0.857,\n 0.709, 0.710, 0.852, 0.691, 0.706, 0.846, 0.672, 0.702, 0.841, 0.653,\n 0.698, 0.835, 0.634, 0.694, 0.828, 0.614, 0.690, 0.822, 0.594, 0.686,\n 0.815, 0.574, 0.683, 0.808, 0.553, 0.679, 0.801, 0.532, 0.675, 0.794,\n 0.511, 0.672, 0.787, 0.490, 0.668, 0.779, 0.468, 0.665, 0.772, 0.446,\n 0.661, 0.764, 0.425, 0.658, 0.757, 0.403, 0.654, 0.749, 0.380, 0.651,\n 0.741, 0.358, 0.648, 0.733, 0.335, 0.645, 0.725, 0.312, 0.642, 0.717,\n 0.288, 0.639, 0.709, 0.264, 0.636, 0.701, 0.238, 0.633, 0.693, 0.212,\n 0.445, 0.682, 0.981, 0.458, 0.691, 0.975, 0.471, 0.699, 0.969, 0.484,\n 0.707, 0.964, 0.496, 0.715, 0.959, 0.509, 0.722, 0.954, 0.521, 0.730,\n 0.949, 0.534, 0.738, 0.945, 0.546, 0.746, 0.941, 0.558, 0.753, 0.937,\n 0.570, 0.761, 0.933, 0.582, 0.769, 0.929, 0.593, 0.776, 0.926, 0.605,\n 0.784, 0.922, 0.616, 0.791, 0.919, 0.628, 0.798, 0.916, 0.639, 0.806,\n 0.913, 0.649, 0.813, 0.910, 0.660, 0.820, 0.907, 0.670, 0.826, 0.904,\n 0.680, 0.833, 0.902, 0.690, 0.839, 0.899, 0.699, 0.846, 0.896, 0.708,\n 0.851, 0.893, 0.716, 0.857, 0.889, 0.724, 0.862, 0.885, 0.731, 0.867,\n 0.881, 0.737, 0.871, 0.877, 0.742, 0.875, 0.872, 0.746, 0.878, 0.866,\n 0.750, 0.880, 0.859, 0.752, 0.882, 0.851, 0.753, 0.883, 0.843, 0.754,\n 0.883, 0.833, 0.753, 0.883, 0.822, 0.752, 0.882, 0.810, 0.750, 0.880,\n 0.797, 0.747, 0.877, 0.782, 0.744, 0.874, 0.767, 0.740, 0.870, 0.751,\n 0.737, 0.866, 0.734, 0.733, 0.861, 0.716, 0.729, 0.855, 0.697, 0.724,\n 0.850, 0.678, 0.720, 0.844, 0.659, 0.716, 0.837, 0.639, 0.712, 0.831,\n 0.619, 0.708, 0.824, 0.598, 0.704, 0.817, 0.578, 0.699, 0.810, 0.557,\n 0.696, 0.803, 0.535, 0.692, 0.795, 0.514, 0.688, 0.788, 0.493, 0.684,\n 0.780, 0.471, 0.680, 0.772, 0.449, 0.677, 0.765, 0.427, 0.673, 0.757,\n 0.405, 0.670, 0.749, 0.382, 0.666, 0.741, 0.360, 0.663, 0.733, 0.337,\n 0.660, 0.725, 0.313, 0.657, 0.716, 0.289, 0.653, 0.708, 0.265, 0.650,\n 0.700, 0.240, 0.647, 0.692, 0.213, 0.464, 0.681, 0.982, 0.476, 0.690,\n 0.977, 0.489, 0.698, 0.971, 0.501, 0.706, 0.966, 0.514, 0.714, 0.961,\n 0.526, 0.722, 0.956, 0.538, 0.730, 0.952, 0.550, 0.738, 0.947, 0.562,\n 0.746, 0.943, 0.574, 0.754, 0.939, 0.586, 0.762, 0.936, 0.598, 0.769,\n 0.932, 0.610, 0.777, 0.929, 0.621, 0.785, 0.926, 0.633, 0.792, 0.923,\n 0.644, 0.800, 0.920, 0.655, 0.807, 0.917, 0.666, 0.815, 0.915, 0.677,\n 0.822, 0.912, 0.688, 0.829, 0.909, 0.698, 0.836, 0.907, 0.708, 0.843,\n 0.904, 0.717, 0.849, 0.902, 0.727, 0.855, 0.899, 0.735, 0.861, 0.896,\n 0.743, 0.867, 0.893, 0.750, 0.872, 0.889, 0.757, 0.877, 0.885, 0.762,\n 0.881, 0.880, 0.767, 0.884, 0.875, 0.770, 0.887, 0.868, 0.773, 0.888,\n 0.861, 0.774, 0.889, 0.852, 0.774, 0.890, 0.842, 0.774, 0.889, 0.831,\n 0.772, 0.888, 0.819, 0.770, 0.885, 0.806, 0.767, 0.883, 0.791, 0.763,\n 0.879, 0.775, 0.759, 0.875, 0.759, 0.755, 0.870, 0.741, 0.751, 0.865,\n 0.723, 0.747, 0.859, 0.704, 0.742, 0.853, 0.684, 0.738, 0.847, 0.664,\n 0.733, 0.840, 0.644, 0.729, 0.833, 0.623, 0.724, 0.826, 0.603, 0.720,\n 0.819, 0.581, 0.716, 0.811, 0.560, 0.712, 0.804, 0.539, 0.708, 0.796,\n 0.517, 0.704, 0.788, 0.495, 0.700, 0.780, 0.473, 0.696, 0.772, 0.451,\n 0.692, 0.764, 0.429, 0.688, 0.756, 0.407, 0.685, 0.748, 0.384, 0.681,\n 0.740, 0.361, 0.678, 0.732, 0.338, 0.674, 0.724, 0.315, 0.671, 0.715,\n 0.291, 0.667, 0.707, 0.266, 0.664, 0.699, 0.241, 0.661, 0.691, 0.214,\n 0.481, 0.680, 0.984, 0.494, 0.689, 0.978, 0.506, 0.697, 0.973, 0.518,\n 0.705, 0.968, 0.530, 0.713, 0.963, 0.542, 0.722, 0.958, 0.554, 0.730,\n 0.954, 0.566, 0.738, 0.950, 0.578, 0.746, 0.946, 0.590, 0.754, 0.942,\n 0.602, 0.762, 0.939, 0.614, 0.770, 0.935, 0.626, 0.778, 0.932, 0.637,\n 0.786, 0.929, 0.649, 0.794, 0.926, 0.660, 0.801, 0.924, 0.671, 0.809,\n 0.921, 0.683, 0.817, 0.919, 0.694, 0.824, 0.916, 0.704, 0.832, 0.914,\n 0.715, 0.839, 0.912, 0.725, 0.846, 0.910, 0.735, 0.853, 0.908, 0.744,\n 0.859, 0.905, 0.753, 0.866, 0.903, 0.762, 0.872, 0.900, 0.770, 0.877,\n 0.897, 0.776, 0.882, 0.893, 0.782, 0.886, 0.889, 0.787, 0.890, 0.884,\n 0.791, 0.893, 0.878, 0.794, 0.895, 0.871, 0.795, 0.896, 0.862, 0.795,\n 0.896, 0.852, 0.794, 0.895, 0.841, 0.792, 0.894, 0.829, 0.789, 0.891,\n 0.815, 0.786, 0.888, 0.800, 0.782, 0.884, 0.783, 0.778, 0.879, 0.766,\n 0.774, 0.874, 0.748, 0.769, 0.868, 0.729, 0.764, 0.862, 0.710, 0.760,\n 0.856, 0.690, 0.755, 0.849, 0.669, 0.750, 0.842, 0.649, 0.745, 0.835,\n 0.628, 0.741, 0.827, 0.606, 0.736, 0.820, 0.585, 0.732, 0.812, 0.563,\n 0.728, 0.804, 0.542, 0.723, 0.796, 0.520, 0.719, 0.788, 0.498, 0.715,\n 0.780, 0.475, 0.711, 0.772, 0.453, 0.707, 0.764, 0.431, 0.703, 0.756,\n 0.408, 0.699, 0.748, 0.386, 0.696, 0.739, 0.363, 0.692, 0.731, 0.339,\n 0.688, 0.723, 0.316, 0.685, 0.714, 0.292, 0.681, 0.706, 0.267, 0.678,\n 0.697, 0.242, 0.674, 0.689, 0.215, 0.498, 0.679, 0.986, 0.510, 0.687,\n 0.980, 0.522, 0.696, 0.975, 0.534, 0.704, 0.970, 0.546, 0.712, 0.965,\n 0.558, 0.721, 0.961, 0.570, 0.729, 0.956, 0.581, 0.737, 0.952, 0.593,\n 0.746, 0.948, 0.605, 0.754, 0.945, 0.617, 0.762, 0.941, 0.629, 0.770,\n 0.938, 0.640, 0.778, 0.935, 0.652, 0.786, 0.932, 0.664, 0.794, 0.930,\n 0.675, 0.802, 0.927, 0.687, 0.810, 0.925, 0.698, 0.818, 0.923, 0.709,\n 0.826, 0.921, 0.720, 0.834, 0.919, 0.731, 0.841, 0.917, 0.742, 0.849,\n 0.915, 0.752, 0.856, 0.913, 0.762, 0.863, 0.911, 0.771, 0.870, 0.909,\n 0.780, 0.876, 0.907, 0.788, 0.882, 0.904, 0.796, 0.887, 0.901, 0.802,\n 0.892, 0.897, 0.807, 0.896, 0.893, 0.811, 0.899, 0.887, 0.814, 0.902,\n 0.880, 0.815, 0.903, 0.872, 0.815, 0.903, 0.862, 0.814, 0.902, 0.851,\n 0.812, 0.900, 0.838, 0.809, 0.897, 0.824, 0.805, 0.893, 0.808, 0.801,\n 0.889, 0.791, 0.796, 0.884, 0.774, 0.791, 0.878, 0.755, 0.786, 0.872,\n 0.735, 0.781, 0.865, 0.715, 0.776, 0.858, 0.695, 0.771, 0.851, 0.674,\n 0.767, 0.844, 0.653, 0.762, 0.836, 0.631, 0.757, 0.829, 0.610, 0.752,\n 0.821, 0.588, 0.748, 0.813, 0.566, 0.743, 0.805, 0.544, 0.739, 0.796,\n 0.522, 0.734, 0.788, 0.500, 0.730, 0.780, 0.477, 0.726, 0.772, 0.455,\n 0.722, 0.763, 0.432, 0.718, 0.755, 0.410, 0.714, 0.746, 0.387, 0.710,\n 0.738, 0.364, 0.706, 0.730, 0.340, 0.702, 0.721, 0.317, 0.698, 0.713,\n 0.293, 0.694, 0.704, 0.268, 0.691, 0.696, 0.243, 0.687, 0.687, 0.216,\n 0.513, 0.677, 0.987, 0.525, 0.686, 0.982, 0.537, 0.694, 0.977, 0.549,\n 0.703, 0.972, 0.561, 0.711, 0.967, 0.572, 0.720, 0.962, 0.584, 0.728,\n 0.958, 0.596, 0.737, 0.954, 0.608, 0.745, 0.951, 0.619, 0.753, 0.947,\n 0.631, 0.762, 0.944, 0.643, 0.770, 0.941, 0.655, 0.778, 0.938, 0.666,\n 0.787, 0.935, 0.678, 0.795, 0.933, 0.689, 0.803, 0.930, 0.701, 0.811,\n 0.928, 0.713, 0.820, 0.926, 0.724, 0.828, 0.925, 0.735, 0.836, 0.923,\n 0.746, 0.844, 0.921, 0.757, 0.852, 0.920, 0.768, 0.859, 0.918, 0.778,\n 0.867, 0.917, 0.788, 0.874, 0.915, 0.797, 0.881, 0.913, 0.806, 0.887,\n 0.911, 0.814, 0.893, 0.909, 0.821, 0.898, 0.906, 0.827, 0.902, 0.902,\n 0.831, 0.906, 0.897, 0.834, 0.908, 0.890, 0.836, 0.910, 0.882, 0.836,\n 0.910, 0.873, 0.834, 0.909, 0.861, 0.832, 0.906, 0.848, 0.828, 0.903,\n 0.833, 0.824, 0.899, 0.817, 0.819, 0.894, 0.799, 0.814, 0.888, 0.781,\n 0.809, 0.882, 0.761, 0.804, 0.875, 0.741, 0.798, 0.868, 0.720, 0.793,\n 0.861, 0.699, 0.788, 0.853, 0.678, 0.783, 0.845, 0.656, 0.777, 0.837,\n 0.635, 0.772, 0.829, 0.613, 0.768, 0.821, 0.590, 0.763, 0.813, 0.568,\n 0.758, 0.804, 0.546, 0.753, 0.796, 0.524, 0.749, 0.788, 0.501, 0.744,\n 0.779, 0.479, 0.740, 0.771, 0.456, 0.736, 0.762, 0.433, 0.731, 0.754,\n 0.411, 0.727, 0.745, 0.388, 0.723, 0.736, 0.365, 0.719, 0.728, 0.341,\n 0.715, 0.719, 0.317, 0.711, 0.711, 0.293, 0.707, 0.702, 0.268, 0.704,\n 0.694, 0.243, 0.700, 0.685, 0.216, 0.528, 0.675, 0.989, 0.540, 0.684,\n 0.983, 0.551, 0.693, 0.978, 0.563, 0.701, 0.973, 0.575, 0.710, 0.969,\n 0.586, 0.718, 0.964, 0.598, 0.727, 0.960, 0.610, 0.736, 0.956, 0.621,\n 0.744, 0.953, 0.633, 0.753, 0.949, 0.645, 0.761, 0.946, 0.656, 0.770,\n 0.943, 0.668, 0.778, 0.940, 0.680, 0.787, 0.938, 0.691, 0.795, 0.936,\n 0.703, 0.804, 0.933, 0.715, 0.812, 0.932, 0.726, 0.821, 0.930, 0.738,\n 0.829, 0.928, 0.749, 0.837, 0.927, 0.761, 0.846, 0.926, 0.772, 0.854,\n 0.924, 0.783, 0.862, 0.923, 0.794, 0.870, 0.922, 0.804, 0.877, 0.921,\n 0.814, 0.885, 0.920, 0.824, 0.892, 0.918, 0.832, 0.898, 0.917, 0.840,\n 0.904, 0.914, 0.846, 0.909, 0.911, 0.851, 0.913, 0.906, 0.855, 0.915,\n 0.901, 0.856, 0.917, 0.893, 0.856, 0.917, 0.883, 0.854, 0.915, 0.871,\n 0.851, 0.913, 0.858, 0.847, 0.909, 0.842, 0.842, 0.904, 0.825, 0.837,\n 0.898, 0.806, 0.831, 0.892, 0.787, 0.826, 0.885, 0.767, 0.820, 0.878,\n 0.746, 0.814, 0.870, 0.725, 0.809, 0.862, 0.703, 0.803, 0.854, 0.681,\n 0.798, 0.846, 0.659, 0.793, 0.838, 0.637, 0.788, 0.829, 0.615, 0.782,\n 0.821, 0.592, 0.777, 0.812, 0.570, 0.773, 0.804, 0.548, 0.768, 0.795,\n 0.525, 0.763, 0.787, 0.502, 0.758, 0.778, 0.480, 0.754, 0.769, 0.457,\n 0.749, 0.761, 0.434, 0.745, 0.752, 0.411, 0.741, 0.743, 0.388, 0.737,\n 0.735, 0.365, 0.732, 0.726, 0.342, 0.728, 0.717, 0.318, 0.724, 0.709,\n 0.293, 0.720, 0.700, 0.269, 0.716, 0.691, 0.243, 0.712, 0.683, 0.216,\n 0.542, 0.673, 0.990, 0.554, 0.682, 0.985, 0.565, 0.691, 0.980, 0.577,\n 0.700, 0.975, 0.588, 0.708, 0.970, 0.600, 0.717, 0.966, 0.611, 0.726,\n 0.962, 0.623, 0.734, 0.958, 0.634, 0.743, 0.955, 0.646, 0.752, 0.951,\n 0.657, 0.760, 0.948, 0.669, 0.769, 0.945, 0.681, 0.778, 0.943, 0.692,\n 0.786, 0.940, 0.704, 0.795, 0.938, 0.716, 0.804, 0.936, 0.728, 0.812,\n 0.934, 0.739, 0.821, 0.933, 0.751, 0.830, 0.932, 0.763, 0.838, 0.930,\n 0.774, 0.847, 0.929, 0.786, 0.856, 0.929, 0.797, 0.864, 0.928, 0.809,\n 0.873, 0.927, 0.819, 0.881, 0.927, 0.830, 0.889, 0.926, 0.840, 0.896,\n 0.925, 0.850, 0.903, 0.924, 0.858, 0.910, 0.922, 0.865, 0.915, 0.920,\n 0.871, 0.920, 0.916, 0.875, 0.923, 0.911, 0.876, 0.924, 0.903, 0.876,\n 0.924, 0.894, 0.873, 0.922, 0.882, 0.870, 0.919, 0.867, 0.865, 0.914,\n 0.851, 0.860, 0.909, 0.832, 0.854, 0.902, 0.813, 0.848, 0.895, 0.793,\n 0.842, 0.888, 0.772, 0.836, 0.880, 0.750, 0.830, 0.872, 0.729, 0.824,\n 0.864, 0.707, 0.819, 0.855, 0.684, 0.813, 0.847, 0.662, 0.808, 0.838,\n 0.639, 0.802, 0.829, 0.617, 0.797, 0.820, 0.594, 0.792, 0.812, 0.571,\n 0.787, 0.803, 0.549, 0.782, 0.794, 0.526, 0.777, 0.785, 0.503, 0.772,\n 0.776, 0.480, 0.767, 0.768, 0.458, 0.763, 0.759, 0.435, 0.758, 0.750,\n 0.412, 0.754, 0.741, 0.388, 0.749, 0.732, 0.365, 0.745, 0.724, 0.342,\n 0.741, 0.715, 0.318, 0.737, 0.706, 0.293, 0.732, 0.697, 0.269, 0.728,\n 0.689, 0.243, 0.724, 0.680, 0.216, 0.556, 0.671, 0.992, 0.567, 0.680,\n 0.986, 0.578, 0.689, 0.981, 0.590, 0.697, 0.976, 0.601, 0.706, 0.972,\n 0.612, 0.715, 0.968, 0.624, 0.724, 0.964, 0.635, 0.733, 0.960, 0.646,\n 0.741, 0.956, 0.658, 0.750, 0.953, 0.670, 0.759, 0.950, 0.681, 0.768,\n 0.947, 0.693, 0.777, 0.945, 0.704, 0.786, 0.943, 0.716, 0.794, 0.941,\n 0.728, 0.803, 0.939, 0.740, 0.812, 0.937, 0.752, 0.821, 0.936, 0.763,\n 0.830, 0.935, 0.775, 0.839, 0.934, 0.787, 0.848, 0.933, 0.799, 0.857,\n 0.932, 0.811, 0.866, 0.932, 0.822, 0.875, 0.932, 0.834, 0.883, 0.932,\n 0.845, 0.892, 0.931, 0.856, 0.900, 0.931, 0.866, 0.908, 0.931, 0.876,\n 0.915, 0.930, 0.884, 0.922, 0.929, 0.890, 0.927, 0.926, 0.895, 0.930,\n 0.921, 0.896, 0.932, 0.914, 0.896, 0.932, 0.905, 0.893, 0.929, 0.892,\n 0.888, 0.925, 0.876, 0.883, 0.920, 0.859, 0.877, 0.913, 0.840, 0.871,\n 0.906, 0.819, 0.864, 0.898, 0.798, 0.858, 0.890, 0.776, 0.852, 0.882,\n 0.754, 0.845, 0.873, 0.732, 0.839, 0.864, 0.709, 0.833, 0.855, 0.686,\n 0.828, 0.846, 0.664, 0.822, 0.837, 0.641, 0.816, 0.828, 0.618, 0.811,\n 0.819, 0.595, 0.806, 0.810, 0.572, 0.800, 0.801, 0.549, 0.795, 0.792,\n 0.526, 0.790, 0.783, 0.504, 0.785, 0.774, 0.481, 0.781, 0.765, 0.458,\n 0.776, 0.756, 0.435, 0.771, 0.748, 0.412, 0.766, 0.739, 0.388, 0.762,\n 0.730, 0.365, 0.757, 0.721, 0.341, 0.753, 0.712, 0.318, 0.749, 0.703,\n 0.293, 0.744, 0.695, 0.268, 0.740, 0.686, 0.243, 0.736, 0.677, 0.216,\n 0.569, 0.668, 0.993, 0.580, 0.677, 0.987, 0.591, 0.686, 0.982, 0.602,\n 0.695, 0.978, 0.613, 0.704, 0.973, 0.624, 0.713, 0.969, 0.635, 0.722,\n 0.965, 0.647, 0.731, 0.961, 0.658, 0.740, 0.958, 0.670, 0.748, 0.955,\n 0.681, 0.757, 0.952, 0.693, 0.766, 0.949, 0.704, 0.775, 0.947, 0.716,\n 0.784, 0.945, 0.728, 0.793, 0.943, 0.739, 0.802, 0.941, 0.751, 0.812,\n 0.939, 0.763, 0.821, 0.938, 0.775, 0.830, 0.937, 0.787, 0.839, 0.936,\n 0.799, 0.848, 0.936, 0.811, 0.858, 0.936, 0.823, 0.867, 0.935, 0.835,\n 0.876, 0.936, 0.847, 0.886, 0.936, 0.859, 0.895, 0.936, 0.870, 0.904,\n 0.937, 0.882, 0.912, 0.937, 0.892, 0.920, 0.937, 0.901, 0.928, 0.937,\n 0.909, 0.934, 0.936, 0.914, 0.938, 0.932, 0.917, 0.940, 0.926, 0.915,\n 0.940, 0.916, 0.912, 0.936, 0.902, 0.906, 0.931, 0.885, 0.900, 0.925,\n 0.866, 0.893, 0.917, 0.846, 0.887, 0.909, 0.824, 0.880, 0.900, 0.802,\n 0.873, 0.891, 0.780, 0.867, 0.882, 0.757, 0.860, 0.873, 0.734, 0.854,\n 0.864, 0.711, 0.848, 0.855, 0.688, 0.842, 0.845, 0.665, 0.836, 0.836,\n 0.642, 0.830, 0.827, 0.619, 0.824, 0.818, 0.596, 0.819, 0.808, 0.573,\n 0.814, 0.799, 0.549, 0.808, 0.790, 0.527, 0.803, 0.781, 0.504, 0.798,\n 0.772, 0.481, 0.793, 0.763, 0.458, 0.788, 0.754, 0.434, 0.783, 0.745,\n 0.411, 0.779, 0.736, 0.388, 0.774, 0.727, 0.365, 0.769, 0.718, 0.341,\n 0.765, 0.709, 0.317, 0.760, 0.700, 0.293, 0.756, 0.691, 0.268, 0.751,\n 0.683, 0.242, 0.747, 0.674, 0.215, 0.581, 0.665, 0.994, 0.592, 0.674,\n 0.989, 0.603, 0.683, 0.984, 0.614, 0.692, 0.979, 0.625, 0.701, 0.974,\n 0.636, 0.710, 0.970, 0.647, 0.719, 0.966, 0.658, 0.728, 0.963, 0.669,\n 0.737, 0.959, 0.681, 0.746, 0.956, 0.692, 0.755, 0.953, 0.703, 0.765,\n 0.951, 0.715, 0.774, 0.948, 0.727, 0.783, 0.946, 0.738, 0.792, 0.944,\n 0.750, 0.801, 0.943, 0.762, 0.810, 0.941, 0.774, 0.820, 0.940, 0.786,\n 0.829, 0.939, 0.798, 0.839, 0.939, 0.810, 0.848, 0.938, 0.822, 0.858,\n 0.938, 0.834, 0.867, 0.939, 0.847, 0.877, 0.939, 0.859, 0.887, 0.940,\n 0.871, 0.897, 0.940, 0.883, 0.906, 0.942, 0.896, 0.916, 0.943, 0.907,\n 0.925, 0.944, 0.918, 0.933, 0.945, 0.927, 0.941, 0.945, 0.934, 0.946,\n 0.943, 0.937, 0.949, 0.937, 0.935, 0.948, 0.927, 0.930, 0.943, 0.912,\n 0.924, 0.937, 0.893, 0.916, 0.929, 0.872, 0.909, 0.920, 0.850, 0.902,\n 0.911, 0.828, 0.895, 0.901, 0.805, 0.888, 0.892, 0.782, 0.881, 0.882,\n 0.759, 0.874, 0.872, 0.735, 0.868, 0.863, 0.712, 0.861, 0.853, 0.689,\n 0.855, 0.844, 0.665, 0.849, 0.834, 0.642, 0.843, 0.825, 0.619, 0.838,\n 0.815, 0.596, 0.832, 0.806, 0.572, 0.826, 0.797, 0.549, 0.821, 0.787,\n 0.526, 0.816, 0.778, 0.503, 0.811, 0.769, 0.480, 0.805, 0.760, 0.457,\n 0.800, 0.751, 0.434, 0.795, 0.742, 0.411, 0.791, 0.733, 0.387, 0.786,\n 0.724, 0.364, 0.781, 0.715, 0.340, 0.776, 0.706, 0.316, 0.772, 0.697,\n 0.292, 0.767, 0.688, 0.267, 0.762, 0.679, 0.241, 0.758, 0.670, 0.215,\n 0.593, 0.662, 0.995, 0.603, 0.671, 0.990, 0.614, 0.680, 0.985, 0.625,\n 0.689, 0.980, 0.636, 0.699, 0.975, 0.647, 0.708, 0.971, 0.658, 0.717,\n 0.967, 0.669, 0.726, 0.964, 0.680, 0.735, 0.960, 0.691, 0.744, 0.957,\n 0.702, 0.753, 0.955, 0.714, 0.762, 0.952, 0.725, 0.771, 0.950, 0.737,\n 0.781, 0.948, 0.748, 0.790, 0.946, 0.760, 0.799, 0.944, 0.772, 0.809,\n 0.943, 0.784, 0.818, 0.942, 0.796, 0.828, 0.941, 0.808, 0.837, 0.941,\n 0.820, 0.847, 0.940, 0.832, 0.857, 0.941, 0.844, 0.867, 0.941, 0.857,\n 0.877, 0.942, 0.869, 0.887, 0.943, 0.882, 0.897, 0.944, 0.895, 0.908,\n 0.945, 0.908, 0.918, 0.947, 0.920, 0.928, 0.949, 0.933, 0.938, 0.951,\n 0.944, 0.947, 0.953, 0.953, 0.955, 0.954, 0.957, 0.958, 0.950, 0.954,\n 0.956, 0.938, 0.948, 0.949, 0.920, 0.940, 0.941, 0.899, 0.932, 0.931,\n 0.877, 0.924, 0.921, 0.854, 0.916, 0.911, 0.830, 0.909, 0.901, 0.807,\n 0.901, 0.891, 0.783, 0.894, 0.881, 0.759, 0.887, 0.871, 0.736, 0.881,\n 0.861, 0.712, 0.874, 0.851, 0.688, 0.868, 0.841, 0.665, 0.862, 0.832,\n 0.642, 0.856, 0.822, 0.618, 0.850, 0.812, 0.595, 0.844, 0.803, 0.572,\n 0.839, 0.793, 0.549, 0.833, 0.784, 0.525, 0.828, 0.775, 0.502, 0.822,\n 0.766, 0.479, 0.817, 0.756, 0.456, 0.812, 0.747, 0.433, 0.807, 0.738,\n 0.410, 0.802, 0.729, 0.387, 0.797, 0.720, 0.363, 0.792, 0.711, 0.339,\n 0.787, 0.702, 0.315, 0.782, 0.693, 0.291, 0.778, 0.684, 0.266, 0.773,\n 0.675, 0.240, 0.768, 0.666, 0.214, 0.604, 0.659, 0.996, 0.614, 0.668,\n 0.990, 0.625, 0.677, 0.985, 0.636, 0.686, 0.981, 0.646, 0.695, 0.976,\n 0.657, 0.704, 0.972, 0.668, 0.714, 0.968, 0.679, 0.723, 0.965, 0.690,\n 0.732, 0.961, 0.701, 0.741, 0.958, 0.712, 0.750, 0.956, 0.723, 0.759,\n 0.953, 0.735, 0.769, 0.951, 0.746, 0.778, 0.949, 0.758, 0.787, 0.947,\n 0.769, 0.797, 0.945, 0.781, 0.806, 0.944, 0.793, 0.816, 0.943, 0.805,\n 0.826, 0.943, 0.817, 0.836, 0.942, 0.829, 0.845, 0.942, 0.841, 0.855,\n 0.942, 0.853, 0.866, 0.943, 0.866, 0.876, 0.943, 0.879, 0.886, 0.945,\n 0.892, 0.897, 0.946, 0.905, 0.907, 0.948, 0.918, 0.918, 0.950, 0.931,\n 0.930, 0.953, 0.945, 0.941, 0.956, 0.958, 0.952, 0.960, 0.971, 0.963,\n 0.963, 0.978, 0.968, 0.963, 0.972, 0.963, 0.948, 0.963, 0.954, 0.926,\n 0.954, 0.943, 0.903, 0.945, 0.931, 0.879, 0.937, 0.921, 0.855, 0.929,\n 0.910, 0.831, 0.921, 0.899, 0.807, 0.914, 0.889, 0.783, 0.907, 0.878,\n 0.759, 0.900, 0.868, 0.735, 0.893, 0.858, 0.711, 0.887, 0.848, 0.688,\n 0.880, 0.838, 0.664, 0.874, 0.828, 0.641, 0.868, 0.818, 0.617, 0.862,\n 0.809, 0.594, 0.856, 0.799, 0.571, 0.850, 0.790, 0.547, 0.845, 0.780,\n 0.524, 0.839, 0.771, 0.501, 0.834, 0.762, 0.478, 0.828, 0.752, 0.455,\n 0.823, 0.743, 0.432, 0.818, 0.734, 0.409, 0.813, 0.725, 0.385, 0.808,\n 0.716, 0.362, 0.803, 0.707, 0.338, 0.798, 0.698, 0.314, 0.793, 0.689,\n 0.290, 0.788, 0.680, 0.265, 0.783, 0.671, 0.239, 0.778, 0.662, 0.213,\n 0.615, 0.655, 0.996, 0.625, 0.664, 0.991, 0.635, 0.673, 0.986, 0.646,\n 0.683, 0.982, 0.656, 0.692, 0.977, 0.667, 0.701, 0.973, 0.678, 0.710,\n 0.969, 0.688, 0.719, 0.966, 0.699, 0.729, 0.962, 0.710, 0.738, 0.959,\n 0.721, 0.747, 0.956, 0.732, 0.756, 0.954, 0.744, 0.766, 0.952, 0.755,\n 0.775, 0.950, 0.766, 0.784, 0.948, 0.778, 0.794, 0.946, 0.789, 0.804,\n 0.945, 0.801, 0.813, 0.944, 0.813, 0.823, 0.943, 0.825, 0.833, 0.943,\n 0.837, 0.843, 0.943, 0.849, 0.853, 0.943, 0.861, 0.863, 0.944, 0.874,\n 0.873, 0.944, 0.886, 0.884, 0.946, 0.899, 0.895, 0.947, 0.912, 0.906,\n 0.949, 0.926, 0.917, 0.952, 0.939, 0.928, 0.955, 0.953, 0.940, 0.958,\n 0.967, 0.953, 0.963, 0.982, 0.966, 0.969, 0.994, 0.976, 0.972, 0.986,\n 0.966, 0.952, 0.976, 0.953, 0.928, 0.966, 0.941, 0.903, 0.957, 0.929,\n 0.878, 0.949, 0.918, 0.854, 0.941, 0.906, 0.830, 0.933, 0.896, 0.806,\n 0.926, 0.885, 0.782, 0.918, 0.874, 0.758, 0.911, 0.864, 0.734, 0.905,\n 0.854, 0.710, 0.898, 0.844, 0.686, 0.892, 0.834, 0.663, 0.885, 0.824,\n 0.639, 0.879, 0.814, 0.616, 0.873, 0.804, 0.592, 0.867, 0.795, 0.569,\n 0.861, 0.785, 0.546, 0.856, 0.776, 0.523, 0.850, 0.766, 0.500, 0.845,\n 0.757, 0.477, 0.839, 0.748, 0.454, 0.834, 0.739, 0.430, 0.829, 0.729,\n 0.407, 0.823, 0.720, 0.384, 0.818, 0.711, 0.361, 0.813, 0.702, 0.337,\n 0.808, 0.693, 0.313, 0.803, 0.684, 0.289, 0.798, 0.675, 0.264, 0.793,\n 0.666, 0.238, 0.788, 0.657, 0.211, 0.625, 0.651, 0.997, 0.635, 0.660,\n 0.992, 0.645, 0.669, 0.987, 0.656, 0.679, 0.982, 0.666, 0.688, 0.978,\n 0.676, 0.697, 0.974, 0.687, 0.706, 0.970, 0.698, 0.716, 0.966, 0.708,\n 0.725, 0.963, 0.719, 0.734, 0.960, 0.730, 0.743, 0.957, 0.741, 0.753,\n 0.954, 0.752, 0.762, 0.952, 0.763, 0.771, 0.950, 0.774, 0.781, 0.948,\n 0.786, 0.790, 0.947, 0.797, 0.800, 0.945, 0.809, 0.810, 0.945, 0.820,\n 0.819, 0.944, 0.832, 0.829, 0.943, 0.844, 0.839, 0.943, 0.856, 0.849,\n 0.943, 0.868, 0.860, 0.944, 0.880, 0.870, 0.945, 0.893, 0.880, 0.946,\n 0.905, 0.891, 0.947, 0.918, 0.902, 0.949, 0.931, 0.913, 0.951, 0.944,\n 0.924, 0.954, 0.957, 0.936, 0.957, 0.971, 0.947, 0.961, 0.983, 0.958,\n 0.964, 0.991, 0.963, 0.962, 0.990, 0.957, 0.946, 0.983, 0.946, 0.924,\n 0.975, 0.935, 0.900, 0.967, 0.923, 0.876, 0.959, 0.912, 0.851, 0.951,\n 0.901, 0.827, 0.943, 0.890, 0.803, 0.936, 0.880, 0.779, 0.929, 0.869,\n 0.755, 0.922, 0.859, 0.732, 0.915, 0.849, 0.708, 0.909, 0.839, 0.684,\n 0.902, 0.829, 0.661, 0.896, 0.819, 0.637, 0.890, 0.809, 0.614, 0.884,\n 0.800, 0.591, 0.878, 0.790, 0.567, 0.872, 0.780, 0.544, 0.866, 0.771,\n 0.521, 0.861, 0.762, 0.498, 0.855, 0.752, 0.475, 0.850, 0.743, 0.452,\n 0.844, 0.734, 0.429, 0.839, 0.725, 0.406, 0.834, 0.715, 0.382, 0.828,\n 0.706, 0.359, 0.823, 0.697, 0.335, 0.818, 0.688, 0.311, 0.813, 0.679,\n 0.287, 0.808, 0.670, 0.262, 0.803, 0.662, 0.236, 0.798, 0.653, 0.210,\n 0.635, 0.646, 0.998, 0.645, 0.656, 0.992, 0.655, 0.665, 0.987, 0.665,\n 0.674, 0.983, 0.675, 0.684, 0.978, 0.685, 0.693, 0.974, 0.696, 0.702,\n 0.970, 0.706, 0.711, 0.966, 0.717, 0.721, 0.963, 0.727, 0.730, 0.960,\n 0.738, 0.739, 0.957, 0.749, 0.748, 0.955, 0.760, 0.758, 0.952, 0.771,\n 0.767, 0.950, 0.782, 0.777, 0.948, 0.793, 0.786, 0.947, 0.804, 0.796,\n 0.946, 0.816, 0.805, 0.945, 0.827, 0.815, 0.944, 0.839, 0.825, 0.943,\n 0.850, 0.835, 0.943, 0.862, 0.845, 0.943, 0.874, 0.855, 0.943, 0.886,\n 0.865, 0.944, 0.898, 0.875, 0.945, 0.910, 0.886, 0.946, 0.923, 0.896,\n 0.948, 0.935, 0.907, 0.949, 0.947, 0.917, 0.951, 0.959, 0.927, 0.953,\n 0.970, 0.937, 0.955, 0.980, 0.944, 0.955, 0.987, 0.946, 0.949, 0.989,\n 0.942, 0.936, 0.985, 0.935, 0.916, 0.980, 0.925, 0.894, 0.973, 0.915,\n 0.871, 0.966, 0.904, 0.847, 0.959, 0.894, 0.824, 0.952, 0.883, 0.800,\n 0.945, 0.873, 0.776, 0.938, 0.863, 0.752, 0.932, 0.853, 0.729, 0.925,\n 0.843, 0.705, 0.919, 0.833, 0.682, 0.912, 0.823, 0.658, 0.906, 0.813,\n 0.635, 0.900, 0.803, 0.611, 0.894, 0.794, 0.588, 0.888, 0.784, 0.565,\n 0.882, 0.775, 0.542, 0.876, 0.765, 0.519, 0.871, 0.756, 0.496, 0.865,\n 0.747, 0.473, 0.859, 0.738, 0.450, 0.854, 0.728, 0.427, 0.848, 0.719,\n 0.404, 0.843, 0.710, 0.380, 0.838, 0.701, 0.357, 0.833, 0.692, 0.333,\n 0.827, 0.683, 0.310, 0.822, 0.674, 0.285, 0.817, 0.665, 0.260, 0.812,\n 0.656, 0.235, 0.807, 0.648, 0.208, 0.644, 0.642, 0.998, 0.654, 0.651,\n 0.993, 0.664, 0.660, 0.988, 0.674, 0.670, 0.983, 0.684, 0.679, 0.978,\n 0.694, 0.688, 0.974, 0.704, 0.697, 0.970, 0.715, 0.707, 0.967, 0.725,\n 0.716, 0.963, 0.735, 0.725, 0.960, 0.746, 0.735, 0.957, 0.757, 0.744,\n 0.955, 0.767, 0.753, 0.952, 0.778, 0.763, 0.950, 0.789, 0.772, 0.948,\n 0.800, 0.781, 0.947, 0.811, 0.791, 0.945, 0.822, 0.801, 0.944, 0.833,\n 0.810, 0.943, 0.845, 0.820, 0.943, 0.856, 0.830, 0.942, 0.868, 0.839,\n 0.942, 0.879, 0.849, 0.942, 0.891, 0.859, 0.943, 0.902, 0.869, 0.943,\n 0.914, 0.879, 0.944, 0.926, 0.889, 0.945, 0.937, 0.899, 0.946, 0.949,\n 0.908, 0.947, 0.959, 0.917, 0.948, 0.969, 0.924, 0.947, 0.978, 0.929,\n 0.944, 0.984, 0.930, 0.937, 0.986, 0.927, 0.924, 0.986, 0.921, 0.907,\n 0.982, 0.913, 0.887, 0.978, 0.904, 0.865, 0.972, 0.895, 0.842, 0.966,\n 0.885, 0.819, 0.959, 0.875, 0.795, 0.953, 0.865, 0.772, 0.946, 0.855,\n 0.749, 0.940, 0.846, 0.725, 0.934, 0.836, 0.702, 0.927, 0.826, 0.678,\n 0.921, 0.816, 0.655, 0.915, 0.807, 0.632, 0.909, 0.797, 0.609, 0.903,\n 0.788, 0.586, 0.897, 0.778, 0.562, 0.891, 0.769, 0.539, 0.886, 0.759,\n 0.516, 0.880, 0.750, 0.493, 0.874, 0.741, 0.471, 0.869, 0.732, 0.448,\n 0.863, 0.723, 0.425, 0.858, 0.713, 0.402, 0.852, 0.704, 0.378, 0.847,\n 0.695, 0.355, 0.842, 0.686, 0.331, 0.836, 0.677, 0.308, 0.831, 0.669,\n 0.283, 0.826, 0.660, 0.258, 0.821, 0.651, 0.233, 0.815, 0.642, 0.206,\n 0.653, 0.636, 0.998, 0.663, 0.646, 0.993, 0.673, 0.655, 0.988, 0.682,\n 0.665, 0.983, 0.692, 0.674, 0.979, 0.702, 0.683, 0.974, 0.712, 0.692,\n 0.970, 0.722, 0.702, 0.967, 0.733, 0.711, 0.963, 0.743, 0.720, 0.960,\n 0.753, 0.730, 0.957, 0.764, 0.739, 0.954, 0.774, 0.748, 0.952, 0.785,\n 0.757, 0.950, 0.796, 0.767, 0.948, 0.806, 0.776, 0.946, 0.817, 0.786,\n 0.945, 0.828, 0.795, 0.943, 0.839, 0.804, 0.942, 0.850, 0.814, 0.941,\n 0.861, 0.824, 0.941, 0.872, 0.833, 0.940, 0.884, 0.843, 0.940, 0.895,\n 0.852, 0.940, 0.906, 0.862, 0.940, 0.917, 0.871, 0.941, 0.928, 0.880,\n 0.941, 0.939, 0.889, 0.941, 0.949, 0.897, 0.941, 0.959, 0.904, 0.940,\n 0.968, 0.910, 0.938, 0.975, 0.914, 0.933, 0.981, 0.914, 0.925, 0.984,\n 0.912, 0.913, 0.985, 0.907, 0.897, 0.983, 0.900, 0.878, 0.980, 0.893,\n 0.857, 0.976, 0.884, 0.836, 0.971, 0.875, 0.813, 0.965, 0.866, 0.790,\n 0.959, 0.856, 0.767, 0.954, 0.847, 0.744, 0.947, 0.837, 0.721, 0.941,\n 0.828, 0.698, 0.935, 0.818, 0.675, 0.929, 0.809, 0.652, 0.923, 0.800,\n 0.629, 0.917, 0.790, 0.605, 0.912, 0.781, 0.582, 0.906, 0.771, 0.560,\n 0.900, 0.762, 0.537, 0.894, 0.753, 0.514, 0.889, 0.744, 0.491, 0.883,\n 0.735, 0.468, 0.877, 0.725, 0.445, 0.872, 0.716, 0.422, 0.866, 0.707,\n 0.399, 0.861, 0.698, 0.376, 0.856, 0.689, 0.353, 0.850, 0.680, 0.329,\n 0.845, 0.672, 0.305, 0.840, 0.663, 0.281, 0.834, 0.654, 0.256, 0.829,\n 0.645, 0.231, 0.824, 0.636, 0.204, 0.662, 0.631, 0.998, 0.672, 0.641,\n 0.993, 0.681, 0.650, 0.988, 0.691, 0.659, 0.983, 0.700, 0.669, 0.979,\n 0.710, 0.678, 0.974, 0.720, 0.687, 0.970, 0.730, 0.696, 0.966, 0.740,\n 0.706, 0.963, 0.750, 0.715, 0.960, 0.760, 0.724, 0.957, 0.771, 0.733,\n 0.954, 0.781, 0.742, 0.951, 0.791, 0.752, 0.949, 0.802, 0.761, 0.947,\n 0.812, 0.770, 0.945, 0.823, 0.779, 0.943, 0.834, 0.789, 0.942, 0.844,\n 0.798, 0.941, 0.855, 0.807, 0.940, 0.866, 0.817, 0.939, 0.877, 0.826,\n 0.938, 0.887, 0.835, 0.938, 0.898, 0.844, 0.937, 0.909, 0.853, 0.937,\n 0.919, 0.862, 0.937, 0.930, 0.870, 0.936, 0.940, 0.878, 0.936, 0.950,\n 0.885, 0.934, 0.958, 0.891, 0.932, 0.967, 0.896, 0.928, 0.974, 0.898,\n 0.922, 0.979, 0.899, 0.914, 0.982, 0.897, 0.902, 0.984, 0.893, 0.886,\n 0.984, 0.887, 0.869, 0.982, 0.880, 0.849, 0.979, 0.872, 0.828, 0.975,\n 0.864, 0.807, 0.970, 0.856, 0.785, 0.965, 0.847, 0.762, 0.959, 0.838,\n 0.739, 0.954, 0.829, 0.717, 0.948, 0.819, 0.694, 0.943, 0.810, 0.671,\n 0.937, 0.801, 0.648, 0.931, 0.792, 0.625, 0.925, 0.782, 0.602, 0.919,\n 0.773, 0.579, 0.914, 0.764, 0.556, 0.908, 0.755, 0.533, 0.902, 0.746,\n 0.511, 0.897, 0.737, 0.488, 0.891, 0.728, 0.465, 0.886, 0.719, 0.442,\n 0.880, 0.710, 0.420, 0.875, 0.701, 0.397, 0.869, 0.692, 0.374, 0.864,\n 0.683, 0.350, 0.858, 0.674, 0.327, 0.853, 0.665, 0.303, 0.848, 0.657,\n 0.279, 0.842, 0.648, 0.254, 0.837, 0.639, 0.229, 0.832, 0.630, 0.202,\n 0.671, 0.625, 0.998, 0.680, 0.635, 0.993, 0.689, 0.644, 0.988, 0.698,\n 0.654, 0.983, 0.708, 0.663, 0.978, 0.718, 0.672, 0.974, 0.727, 0.681,\n 0.970, 0.737, 0.691, 0.966, 0.747, 0.700, 0.962, 0.757, 0.709, 0.959,\n 0.767, 0.718, 0.956, 0.777, 0.727, 0.953, 0.787, 0.736, 0.950, 0.797,\n 0.745, 0.948, 0.807, 0.755, 0.946, 0.818, 0.764, 0.944, 0.828, 0.773,\n 0.942, 0.839, 0.782, 0.940, 0.849, 0.791, 0.939, 0.859, 0.800, 0.938,\n 0.870, 0.809, 0.937, 0.880, 0.818, 0.936, 0.891, 0.827, 0.935, 0.901,\n 0.835, 0.934, 0.911, 0.844, 0.933, 0.921, 0.852, 0.932, 0.931, 0.859,\n 0.931, 0.941, 0.866, 0.929, 0.950, 0.873, 0.927, 0.958, 0.878, 0.923,\n 0.966, 0.881, 0.919, 0.972, 0.883, 0.912, 0.977, 0.883, 0.903, 0.981,\n 0.882, 0.891, 0.983, 0.878, 0.876, 0.984, 0.873, 0.859, 0.983, 0.867,\n 0.841, 0.980, 0.860, 0.821, 0.977, 0.853, 0.800, 0.974, 0.845, 0.778,\n 0.969, 0.836, 0.756, 0.964, 0.828, 0.734, 0.959, 0.819, 0.712, 0.954,\n 0.810, 0.689, 0.949, 0.801, 0.666, 0.943, 0.792, 0.644, 0.938, 0.783,\n 0.621, 0.932, 0.774, 0.598, 0.927, 0.765, 0.575, 0.921, 0.756, 0.553,\n 0.916, 0.747, 0.530, 0.910, 0.738, 0.507, 0.904, 0.729, 0.485, 0.899,\n 0.721, 0.462, 0.893, 0.712, 0.439, 0.888, 0.703, 0.417, 0.882, 0.694,\n 0.394, 0.877, 0.685, 0.371, 0.871, 0.676, 0.348, 0.866, 0.668, 0.324,\n 0.861, 0.659, 0.301, 0.855, 0.650, 0.277, 0.850, 0.641, 0.252, 0.845,\n 0.633, 0.226, 0.839, 0.624, 0.200, 0.679, 0.619, 0.998, 0.688, 0.629,\n 0.993, 0.697, 0.638, 0.988, 0.706, 0.648, 0.983, 0.715, 0.657, 0.978,\n 0.725, 0.666, 0.974, 0.734, 0.675, 0.969, 0.744, 0.684, 0.965, 0.754,\n 0.693, 0.962, 0.763, 0.703, 0.958, 0.773, 0.712, 0.955, 0.783, 0.721,\n 0.952, 0.793, 0.730, 0.949, 0.803, 0.739, 0.947, 0.813, 0.748, 0.944,\n 0.823, 0.757, 0.942, 0.833, 0.766, 0.940, 0.843, 0.774, 0.938, 0.853,\n 0.783, 0.937, 0.863, 0.792, 0.935, 0.874, 0.801, 0.934, 0.884, 0.809,\n 0.932, 0.894, 0.818, 0.931, 0.904, 0.826, 0.930, 0.913, 0.833, 0.928,\n 0.923, 0.841, 0.927, 0.932, 0.848, 0.925, 0.941, 0.854, 0.922, 0.950,\n 0.859, 0.919, 0.957, 0.864, 0.915, 0.965, 0.867, 0.909, 0.971, 0.868,\n 0.901, 0.976, 0.868, 0.892, 0.980, 0.867, 0.880, 0.982, 0.863, 0.866,\n 0.983, 0.859, 0.849, 0.983, 0.854, 0.832, 0.982, 0.847, 0.812, 0.979,\n 0.840, 0.792, 0.976, 0.833, 0.771, 0.973, 0.825, 0.750, 0.969, 0.817,\n 0.728, 0.964, 0.809, 0.706, 0.959, 0.800, 0.684, 0.954, 0.792, 0.661,\n 0.949, 0.783, 0.639, 0.944, 0.774, 0.617, 0.939, 0.766, 0.594, 0.933,\n 0.757, 0.572, 0.928, 0.748, 0.549, 0.922, 0.739, 0.527, 0.917, 0.731,\n 0.504, 0.911, 0.722, 0.481, 0.906, 0.713, 0.459, 0.901, 0.704, 0.436,\n 0.895, 0.695, 0.414, 0.890, 0.687, 0.391, 0.884, 0.678, 0.368, 0.879,\n 0.669, 0.345, 0.873, 0.661, 0.322, 0.868, 0.652, 0.298, 0.863, 0.643,\n 0.274, 0.857, 0.635, 0.249, 0.852, 0.626, 0.224, 0.846, 0.617, 0.197,\n 0.686, 0.613, 0.998, 0.695, 0.622, 0.993, 0.704, 0.632, 0.987, 0.713,\n 0.641, 0.982, 0.722, 0.650, 0.977, 0.732, 0.660, 0.973, 0.741, 0.669,\n 0.969, 0.750, 0.678, 0.965, 0.760, 0.687, 0.961, 0.769, 0.696, 0.957,\n 0.779, 0.705, 0.954, 0.789, 0.714, 0.951, 0.798, 0.723, 0.948, 0.808,\n 0.731, 0.945, 0.818, 0.740, 0.943, 0.828, 0.749, 0.940, 0.838, 0.758,\n 0.938, 0.847, 0.766, 0.936, 0.857, 0.775, 0.934, 0.867, 0.783, 0.932,\n 0.877, 0.792, 0.930, 0.887, 0.800, 0.929, 0.896, 0.808, 0.927, 0.906,\n 0.815, 0.925, 0.915, 0.823, 0.923, 0.924, 0.829, 0.921, 0.933, 0.836,\n 0.918, 0.942, 0.841, 0.915, 0.950, 0.846, 0.911, 0.957, 0.850, 0.906,\n 0.964, 0.852, 0.899, 0.970, 0.853, 0.891, 0.975, 0.853, 0.881, 0.979,\n 0.852, 0.869, 0.981, 0.849, 0.855, 0.983, 0.845, 0.840, 0.983, 0.840,\n 0.822, 0.982, 0.834, 0.804, 0.981, 0.828, 0.784, 0.978, 0.821, 0.764,\n 0.975, 0.814, 0.743, 0.972, 0.806, 0.722, 0.968, 0.798, 0.700, 0.964,\n 0.790, 0.678, 0.959, 0.782, 0.656, 0.954, 0.773, 0.634, 0.949, 0.765,\n 0.612, 0.944, 0.757, 0.590, 0.939, 0.748, 0.567, 0.934, 0.739, 0.545,\n 0.929, 0.731, 0.523, 0.923, 0.722, 0.500, 0.918, 0.714, 0.478, 0.913,\n 0.705, 0.456, 0.907, 0.696, 0.433, 0.902, 0.688, 0.411, 0.896, 0.679,\n 0.388, 0.891, 0.670, 0.365, 0.886, 0.662, 0.342, 0.880, 0.653, 0.319,\n 0.875, 0.645, 0.295, 0.869, 0.636, 0.271, 0.864, 0.628, 0.247, 0.859,\n 0.619, 0.221, 0.853, 0.611, 0.195, 0.694, 0.606, 0.998, 0.703, 0.616,\n 0.992, 0.711, 0.625, 0.987, 0.720, 0.634, 0.982, 0.729, 0.644, 0.977,\n 0.738, 0.653, 0.972, 0.747, 0.662, 0.968, 0.757, 0.671, 0.964, 0.766,\n 0.680, 0.960, 0.775, 0.689, 0.956, 0.785, 0.698, 0.953, 0.794, 0.706,\n 0.949, 0.804, 0.715, 0.946, 0.813, 0.724, 0.943, 0.823, 0.732, 0.941,\n 0.832, 0.741, 0.938, 0.842, 0.749, 0.936, 0.851, 0.758, 0.933, 0.861,\n 0.766, 0.931, 0.870, 0.774, 0.929, 0.880, 0.782, 0.927, 0.889, 0.790,\n 0.924, 0.899, 0.797, 0.922, 0.908, 0.805, 0.920, 0.917, 0.811, 0.917,\n 0.925, 0.818, 0.914, 0.934, 0.823, 0.911, 0.942, 0.828, 0.907, 0.950,\n 0.832, 0.902, 0.957, 0.836, 0.896, 0.963, 0.838, 0.889, 0.969, 0.839,\n 0.881, 0.974, 0.838, 0.871, 0.978, 0.837, 0.859, 0.980, 0.834, 0.845,\n 0.982, 0.831, 0.830, 0.983, 0.826, 0.813, 0.983, 0.821, 0.795, 0.982,\n 0.815, 0.776, 0.980, 0.809, 0.757, 0.978, 0.802, 0.736, 0.975, 0.794,\n 0.715, 0.971, 0.787, 0.694, 0.967, 0.779, 0.673, 0.963, 0.771, 0.651,\n 0.959, 0.763, 0.629, 0.954, 0.755, 0.607, 0.949, 0.747, 0.585, 0.944,\n 0.739, 0.563, 0.939, 0.730, 0.541, 0.934, 0.722, 0.519, 0.929, 0.714,\n 0.496, 0.924, 0.705, 0.474, 0.919, 0.697, 0.452, 0.913, 0.688, 0.430,\n 0.908, 0.680, 0.407, 0.903, 0.671, 0.385, 0.897, 0.663, 0.362, 0.892,\n 0.654, 0.339, 0.887, 0.646, 0.316, 0.881, 0.637, 0.293, 0.876, 0.629,\n 0.269, 0.870, 0.620, 0.244, 0.865, 0.612, 0.219, 0.860, 0.604, 0.192,\n 0.701, 0.599, 0.997, 0.710, 0.609, 0.992, 0.718, 0.618, 0.986, 0.727,\n 0.627, 0.981, 0.736, 0.636, 0.976, 0.745, 0.645, 0.971, 0.754, 0.655,\n 0.967, 0.763, 0.663, 0.963, 0.772, 0.672, 0.959, 0.781, 0.681, 0.955,\n 0.790, 0.690, 0.951, 0.799, 0.699, 0.948, 0.808, 0.707, 0.944, 0.818,\n 0.716, 0.941, 0.827, 0.724, 0.938, 0.836, 0.732, 0.935, 0.846, 0.741,\n 0.933, 0.855, 0.749, 0.930, 0.864, 0.757, 0.928, 0.874, 0.765, 0.925,\n 0.883, 0.772, 0.923, 0.892, 0.780, 0.920, 0.901, 0.787, 0.917, 0.910,\n 0.793, 0.914, 0.918, 0.800, 0.911, 0.927, 0.805, 0.908, 0.935, 0.811,\n 0.904, 0.942, 0.815, 0.899, 0.950, 0.819, 0.894, 0.956, 0.821, 0.887,\n 0.963, 0.823, 0.880, 0.968, 0.824, 0.871, 0.973, 0.824, 0.860, 0.977,\n 0.822, 0.849, 0.980, 0.820, 0.835, 0.982, 0.817, 0.820, 0.983, 0.812,\n 0.804, 0.983, 0.808, 0.786, 0.983, 0.802, 0.768, 0.981, 0.796, 0.749,\n 0.979, 0.789, 0.729, 0.977, 0.783, 0.709, 0.974, 0.776, 0.688, 0.970,\n 0.768, 0.667, 0.967, 0.761, 0.645, 0.963, 0.753, 0.624, 0.958, 0.745,\n 0.602, 0.954, 0.737, 0.580, 0.949, 0.729, 0.558, 0.944, 0.721, 0.536,\n 0.939, 0.713, 0.514, 0.934, 0.704, 0.492, 0.929, 0.696, 0.470, 0.924,\n 0.688, 0.448, 0.919, 0.680, 0.426, 0.914, 0.671, 0.404, 0.908, 0.663,\n 0.381, 0.903, 0.655, 0.359, 0.898, 0.646, 0.336, 0.893, 0.638, 0.313,\n 0.887, 0.629, 0.290, 0.882, 0.621, 0.266, 0.876, 0.613, 0.241, 0.871,\n 0.604, 0.216, 0.866, 0.596, 0.189, 0.708, 0.592, 0.997, 0.716, 0.601,\n 0.991, 0.725, 0.611, 0.985, 0.733, 0.620, 0.980, 0.742, 0.629, 0.975,\n 0.751, 0.638, 0.970, 0.759, 0.647, 0.966, 0.768, 0.656, 0.961, 0.777,\n 0.665, 0.957, 0.786, 0.673, 0.953, 0.795, 0.682, 0.949, 0.804, 0.690,\n 0.946, 0.813, 0.699, 0.942, 0.822, 0.707, 0.939, 0.831, 0.715, 0.936,\n 0.840, 0.723, 0.933, 0.849, 0.731, 0.930, 0.859, 0.739, 0.927, 0.868,\n 0.747, 0.924, 0.876, 0.754, 0.921, 0.885, 0.762, 0.918, 0.894, 0.769,\n 0.915, 0.903, 0.775, 0.912, 0.911, 0.782, 0.909, 0.920, 0.787, 0.905,\n 0.928, 0.793, 0.901, 0.935, 0.798, 0.896, 0.943, 0.802, 0.891, 0.950,\n 0.805, 0.885, 0.956, 0.807, 0.878, 0.962, 0.809, 0.870, 0.967, 0.809,\n 0.861, 0.972, 0.809, 0.850, 0.976, 0.808, 0.838, 0.979, 0.805, 0.825,\n 0.981, 0.802, 0.810, 0.983, 0.799, 0.795, 0.983, 0.794, 0.778, 0.983,\n 0.789, 0.760, 0.982, 0.783, 0.741, 0.981, 0.777, 0.721, 0.979, 0.771,\n 0.701, 0.976, 0.764, 0.681, 0.973, 0.757, 0.660, 0.970, 0.750, 0.639,\n 0.966, 0.742, 0.618, 0.962, 0.735, 0.597, 0.958, 0.727, 0.575, 0.953,\n 0.719, 0.553, 0.949, 0.711, 0.532, 0.944, 0.703, 0.510, 0.939, 0.695,\n 0.488, 0.934, 0.687, 0.466, 0.929, 0.679, 0.444, 0.924, 0.671, 0.422,\n 0.919, 0.663, 0.400, 0.914, 0.654, 0.378, 0.909, 0.646, 0.355, 0.903,\n 0.638, 0.333, 0.898, 0.630, 0.310, 0.893, 0.621, 0.287, 0.887, 0.613,\n 0.263, 0.882, 0.605, 0.238, 0.877, 0.597, 0.213, 0.871, 0.589, 0.186,\n 0.715, 0.584, 0.996, 0.723, 0.593, 0.990, 0.731, 0.603, 0.984, 0.739,\n 0.612, 0.979, 0.748, 0.621, 0.974, 0.756, 0.630, 0.969, 0.765, 0.639,\n 0.964, 0.774, 0.648, 0.960, 0.782, 0.656, 0.955, 0.791, 0.665, 0.951,\n 0.800, 0.673, 0.947, 0.809, 0.682, 0.943, 0.818, 0.690, 0.940, 0.826,\n 0.698, 0.936, 0.835, 0.706, 0.933, 0.844, 0.714, 0.930, 0.853, 0.722,\n 0.926, 0.862, 0.729, 0.923, 0.871, 0.737, 0.920, 0.879, 0.744, 0.917,\n 0.888, 0.751, 0.913, 0.896, 0.758, 0.910, 0.905, 0.764, 0.906, 0.913,\n 0.770, 0.903, 0.921, 0.775, 0.898, 0.929, 0.780, 0.894, 0.936, 0.784,\n 0.889, 0.943, 0.788, 0.883, 0.950, 0.791, 0.877, 0.956, 0.793, 0.869,\n 0.962, 0.794, 0.861, 0.967, 0.795, 0.851, 0.971, 0.794, 0.841, 0.975,\n 0.793, 0.829, 0.978, 0.791, 0.815, 0.981, 0.788, 0.801, 0.982, 0.785,\n 0.785, 0.983, 0.780, 0.769, 0.983, 0.776, 0.751, 0.983, 0.770, 0.733,\n 0.982, 0.764, 0.714, 0.980, 0.758, 0.694, 0.978, 0.752, 0.674, 0.975,\n 0.745, 0.654, 0.972, 0.738, 0.633, 0.969, 0.731, 0.612, 0.965, 0.724,\n 0.591, 0.961, 0.716, 0.570, 0.957, 0.709, 0.548, 0.953, 0.701, 0.527,\n 0.948, 0.693, 0.505, 0.943, 0.685, 0.484, 0.939, 0.678, 0.462, 0.934,\n 0.670, 0.440, 0.929, 0.662, 0.418, 0.924, 0.654, 0.396, 0.919, 0.646,\n 0.374, 0.914, 0.637, 0.352, 0.908, 0.629, 0.329, 0.903, 0.621, 0.307,\n 0.898, 0.613, 0.283, 0.893, 0.605, 0.260, 0.887, 0.597, 0.235, 0.882,\n 0.589, 0.210, 0.876, 0.581, 0.183, 0.721, 0.576, 0.995, 0.729, 0.585,\n 0.989, 0.737, 0.595, 0.983, 0.745, 0.604, 0.978, 0.754, 0.613, 0.973,\n 0.762, 0.622, 0.968, 0.770, 0.631, 0.963, 0.779, 0.639, 0.958, 0.787,\n 0.648, 0.954, 0.796, 0.656, 0.949, 0.805, 0.665, 0.945, 0.813, 0.673,\n 0.941, 0.822, 0.681, 0.937, 0.830, 0.689, 0.933, 0.839, 0.697, 0.930,\n 0.848, 0.704, 0.926, 0.856, 0.712, 0.923, 0.865, 0.719, 0.919, 0.873,\n 0.726, 0.916, 0.882, 0.733, 0.912, 0.890, 0.740, 0.908, 0.898, 0.746,\n 0.905, 0.906, 0.752, 0.901, 0.914, 0.757, 0.896, 0.922, 0.762, 0.892,\n 0.929, 0.767, 0.887, 0.937, 0.771, 0.881, 0.943, 0.774, 0.875, 0.950,\n 0.777, 0.868, 0.956, 0.779, 0.860, 0.961, 0.780, 0.851, 0.966, 0.780,\n 0.842, 0.971, 0.780, 0.831, 0.975, 0.779, 0.819, 0.978, 0.777, 0.806,\n 0.980, 0.774, 0.791, 0.982, 0.771, 0.776, 0.983, 0.767, 0.760, 0.984,\n 0.762, 0.742, 0.983, 0.757, 0.725, 0.983, 0.752, 0.706, 0.981, 0.746,\n 0.687, 0.979, 0.740, 0.667, 0.977, 0.733, 0.647, 0.974, 0.727, 0.627,\n 0.971, 0.720, 0.606, 0.968, 0.713, 0.585, 0.964, 0.706, 0.564, 0.960,\n 0.698, 0.543, 0.956, 0.691, 0.522, 0.952, 0.683, 0.501, 0.947, 0.676,\n 0.479, 0.943, 0.668, 0.458, 0.938, 0.660, 0.436, 0.933, 0.652, 0.414,\n 0.928, 0.644, 0.392, 0.923, 0.636, 0.370, 0.918, 0.629, 0.348, 0.913,\n 0.621, 0.326, 0.908, 0.613, 0.303, 0.903, 0.605, 0.280, 0.897, 0.597,\n 0.257, 0.892, 0.589, 0.232, 0.887, 0.581, 0.207, 0.881, 0.573, 0.180,\n 0.727, 0.568, 0.994, 0.735, 0.577, 0.988, 0.743, 0.586, 0.982, 0.751,\n 0.595, 0.977, 0.759, 0.604, 0.971, 0.767, 0.613, 0.966, 0.776, 0.622,\n 0.961, 0.784, 0.630, 0.956, 0.792, 0.639, 0.951, 0.801, 0.647, 0.947,\n 0.809, 0.655, 0.943, 0.817, 0.663, 0.938, 0.826, 0.671, 0.934, 0.834,\n 0.679, 0.930, 0.843, 0.687, 0.927, 0.851, 0.694, 0.923, 0.859, 0.702,\n 0.919, 0.868, 0.709, 0.915, 0.876, 0.715, 0.911, 0.884, 0.722, 0.907,\n 0.892, 0.728, 0.903, 0.900, 0.734, 0.899, 0.908, 0.740, 0.895, 0.916,\n 0.745, 0.890, 0.923, 0.750, 0.885, 0.930, 0.754, 0.879, 0.937, 0.758,\n 0.873, 0.944, 0.761, 0.867, 0.950, 0.763, 0.859, 0.956, 0.765, 0.851,\n 0.961, 0.766, 0.842, 0.966, 0.766, 0.832, 0.970, 0.766, 0.821, 0.974,\n 0.764, 0.809, 0.977, 0.762, 0.796, 0.980, 0.760, 0.782, 0.982, 0.757,\n 0.767, 0.983, 0.753, 0.751, 0.984, 0.749, 0.734, 0.984, 0.744, 0.716,\n 0.983, 0.739, 0.698, 0.982, 0.733, 0.679, 0.980, 0.727, 0.660, 0.978,\n 0.721, 0.640, 0.976, 0.715, 0.620, 0.973, 0.708, 0.600, 0.970, 0.701,\n 0.579, 0.967, 0.694, 0.559, 0.963, 0.687, 0.538, 0.959, 0.680, 0.517,\n 0.955, 0.673, 0.496, 0.951, 0.665, 0.474, 0.946, 0.658, 0.453, 0.942,\n 0.650, 0.432, 0.937, 0.643, 0.410, 0.932, 0.635, 0.388, 0.927, 0.627,\n 0.367, 0.922, 0.619, 0.345, 0.917, 0.612, 0.322, 0.912, 0.604, 0.300,\n 0.907, 0.596, 0.277, 0.902, 0.588, 0.253, 0.897, 0.580, 0.229, 0.891,\n 0.572, 0.204, 0.886, 0.564, 0.177, 0.733, 0.559, 0.993, 0.741, 0.568,\n 0.987, 0.749, 0.577, 0.981, 0.757, 0.587, 0.975, 0.765, 0.595, 0.970,\n 0.773, 0.604, 0.964, 0.781, 0.613, 0.959, 0.789, 0.621, 0.954, 0.797,\n 0.630, 0.949, 0.805, 0.638, 0.945, 0.813, 0.646, 0.940, 0.821, 0.654,\n 0.936, 0.830, 0.662, 0.931, 0.838, 0.669, 0.927, 0.846, 0.677, 0.923,\n 0.854, 0.684, 0.919, 0.862, 0.691, 0.915, 0.870, 0.698, 0.911, 0.879,\n 0.704, 0.907, 0.886, 0.711, 0.902, 0.894, 0.717, 0.898, 0.902, 0.722,\n 0.893, 0.910, 0.727, 0.889, 0.917, 0.732, 0.883, 0.924, 0.737, 0.878,\n 0.931, 0.741, 0.872, 0.938, 0.744, 0.866, 0.944, 0.747, 0.859, 0.950,\n 0.749, 0.851, 0.956, 0.751, 0.842, 0.961, 0.751, 0.833, 0.966, 0.752,\n 0.823, 0.970, 0.751, 0.812, 0.974, 0.750, 0.800, 0.977, 0.748, 0.787,\n 0.979, 0.746, 0.773, 0.981, 0.743, 0.758, 0.983, 0.739, 0.742, 0.984,\n 0.735, 0.725, 0.984, 0.731, 0.708, 0.983, 0.726, 0.690, 0.983, 0.721,\n 0.672, 0.981, 0.715, 0.653, 0.980, 0.709, 0.633, 0.977, 0.703, 0.614,\n 0.975, 0.697, 0.594, 0.972, 0.690, 0.573, 0.969, 0.683, 0.553, 0.965,\n 0.676, 0.532, 0.962, 0.669, 0.512, 0.958, 0.662, 0.491, 0.954, 0.655,\n 0.470, 0.949, 0.648, 0.448, 0.945, 0.640, 0.427, 0.941, 0.633, 0.406,\n 0.936, 0.625, 0.384, 0.931, 0.618, 0.363, 0.926, 0.610, 0.341, 0.921,\n 0.602, 0.319, 0.916, 0.595, 0.296, 0.911, 0.587, 0.273, 0.906, 0.579,\n 0.250, 0.901, 0.571, 0.226, 0.896, 0.563, 0.201, 0.890, 0.556, 0.174,\n 0.739, 0.550, 0.992, 0.747, 0.559, 0.986, 0.754, 0.568, 0.980, 0.762,\n 0.577, 0.974, 0.770, 0.586, 0.968, 0.778, 0.595, 0.962, 0.785, 0.603,\n 0.957, 0.793, 0.612, 0.952, 0.801, 0.620, 0.947, 0.809, 0.628, 0.942,\n 0.817, 0.636, 0.937, 0.825, 0.644, 0.933, 0.833, 0.651, 0.928, 0.841,\n 0.659, 0.924, 0.849, 0.666, 0.919, 0.857, 0.673, 0.915, 0.865, 0.680,\n 0.911, 0.873, 0.686, 0.906, 0.881, 0.693, 0.902, 0.889, 0.699, 0.897,\n 0.896, 0.705, 0.892, 0.904, 0.710, 0.887, 0.911, 0.715, 0.882, 0.918,\n 0.720, 0.877, 0.925, 0.724, 0.871, 0.932, 0.727, 0.865, 0.938, 0.730,\n 0.858, 0.944, 0.733, 0.850, 0.950, 0.735, 0.842, 0.956, 0.736, 0.834,\n 0.961, 0.737, 0.824, 0.965, 0.737, 0.814, 0.970, 0.737, 0.802, 0.973,\n 0.736, 0.790, 0.976, 0.734, 0.777, 0.979, 0.732, 0.763, 0.981, 0.729,\n 0.749, 0.982, 0.726, 0.733, 0.983, 0.722, 0.717, 0.984, 0.717, 0.700,\n 0.984, 0.713, 0.682, 0.983, 0.708, 0.664, 0.982, 0.702, 0.645, 0.980,\n 0.697, 0.626, 0.979, 0.691, 0.607, 0.976, 0.685, 0.587, 0.974, 0.678,\n 0.567, 0.971, 0.672, 0.547, 0.967, 0.665, 0.527, 0.964, 0.658, 0.506,\n 0.960, 0.651, 0.485, 0.956, 0.644, 0.465, 0.952, 0.637, 0.444, 0.948,\n 0.630, 0.423, 0.944, 0.623, 0.401, 0.939, 0.615, 0.380, 0.934, 0.608,\n 0.358, 0.930, 0.600, 0.337, 0.925, 0.593, 0.315, 0.920, 0.585, 0.292,\n 0.915, 0.578, 0.270, 0.910, 0.570, 0.246, 0.905, 0.562, 0.222, 0.899,\n 0.555, 0.197, 0.894, 0.547, 0.171, 0.745, 0.540, 0.991, 0.752, 0.550,\n 0.984, 0.760, 0.559, 0.978, 0.767, 0.568, 0.972, 0.775, 0.577, 0.966,\n 0.782, 0.585, 0.960, 0.790, 0.594, 0.955, 0.798, 0.602, 0.950, 0.806,\n 0.610, 0.944, 0.813, 0.618, 0.939, 0.821, 0.626, 0.934, 0.829, 0.634,\n 0.930, 0.837, 0.641, 0.925, 0.845, 0.648, 0.920, 0.852, 0.655, 0.915,\n 0.860, 0.662, 0.911, 0.868, 0.669, 0.906, 0.876, 0.675, 0.901, 0.883,\n 0.681, 0.897, 0.891, 0.687, 0.892, 0.898, 0.692, 0.887, 0.905, 0.697,\n 0.881, 0.912, 0.702, 0.876, 0.919, 0.707, 0.870, 0.926, 0.710, 0.864,\n 0.932, 0.714, 0.857, 0.939, 0.717, 0.850, 0.945, 0.719, 0.842, 0.950,\n 0.721, 0.834, 0.956, 0.722, 0.825, 0.961, 0.723, 0.815, 0.965, 0.723,\n 0.804, 0.969, 0.723, 0.793, 0.973, 0.722, 0.781, 0.976, 0.720, 0.768,\n 0.978, 0.718, 0.754, 0.981, 0.715, 0.739, 0.982, 0.712, 0.724, 0.983,\n 0.708, 0.708, 0.984, 0.704, 0.691, 0.984, 0.700, 0.674, 0.983, 0.695,\n 0.656, 0.982, 0.690, 0.638, 0.981, 0.684, 0.619, 0.979, 0.679, 0.600,\n 0.977, 0.673, 0.581, 0.975, 0.666, 0.561, 0.972, 0.660, 0.541, 0.969,\n 0.654, 0.521, 0.966, 0.647, 0.501, 0.962, 0.640, 0.480, 0.959, 0.634,\n 0.459, 0.955, 0.627, 0.439, 0.951, 0.620, 0.418, 0.946, 0.612, 0.397,\n 0.942, 0.605, 0.376, 0.937, 0.598, 0.354, 0.933, 0.591, 0.333, 0.928,\n 0.583, 0.311, 0.923, 0.576, 0.289, 0.918, 0.568, 0.266, 0.913, 0.561,\n 0.243, 0.908, 0.553, 0.219, 0.903, 0.546, 0.194, 0.898, 0.538, 0.167,\n 0.750, 0.531, 0.989, 0.757, 0.540, 0.983, 0.765, 0.549, 0.976, 0.772,\n 0.558, 0.970, 0.779, 0.567, 0.964, 0.787, 0.575, 0.958, 0.794, 0.584,\n 0.953, 0.802, 0.592, 0.947, 0.810, 0.600, 0.942, 0.817, 0.608, 0.936,\n 0.825, 0.615, 0.931, 0.833, 0.623, 0.926, 0.840, 0.630, 0.921, 0.848,\n 0.637, 0.916, 0.855, 0.644, 0.911, 0.863, 0.651, 0.907, 0.870, 0.657,\n 0.902, 0.878, 0.663, 0.897, 0.885, 0.669, 0.891, 0.893, 0.675, 0.886,\n 0.900, 0.680, 0.881, 0.907, 0.685, 0.875, 0.914, 0.689, 0.869, 0.920,\n 0.693, 0.863, 0.927, 0.697, 0.857, 0.933, 0.700, 0.850, 0.939, 0.703,\n 0.842, 0.945, 0.705, 0.834, 0.950, 0.707, 0.825, 0.956, 0.708, 0.816,\n 0.960, 0.709, 0.806, 0.965, 0.709, 0.795, 0.969, 0.708, 0.784, 0.972,\n 0.707, 0.772, 0.975, 0.706, 0.759, 0.978, 0.704, 0.745, 0.980, 0.701,\n 0.731, 0.982, 0.698, 0.715, 0.983, 0.694, 0.699, 0.984, 0.691, 0.683,\n 0.984, 0.686, 0.666, 0.983, 0.682, 0.648, 0.983, 0.677, 0.630, 0.982,\n 0.672, 0.612, 0.980, 0.666, 0.593, 0.978, 0.660, 0.574, 0.976, 0.655,\n 0.554, 0.973, 0.648, 0.535, 0.971, 0.642, 0.515, 0.967, 0.636, 0.495,\n 0.964, 0.629, 0.475, 0.961, 0.623, 0.454, 0.957, 0.616, 0.434, 0.953,\n 0.609, 0.413, 0.949, 0.602, 0.392, 0.944, 0.595, 0.371, 0.940, 0.588,\n 0.350, 0.936, 0.580, 0.328, 0.931, 0.573, 0.307, 0.926, 0.566, 0.285,\n 0.921, 0.559, 0.262, 0.916, 0.551, 0.239, 0.911, 0.544, 0.215, 0.906,\n 0.536, 0.190, 0.901, 0.529, 0.164, 0.755, 0.521, 0.988, 0.762, 0.530,\n 0.981, 0.770, 0.539, 0.975, 0.777, 0.548, 0.968, 0.784, 0.557, 0.962,\n 0.791, 0.565, 0.956, 0.799, 0.573, 0.950, 0.806, 0.582, 0.944, 0.814,\n 0.589, 0.939, 0.821, 0.597, 0.933, 0.828, 0.605, 0.928, 0.836, 0.612,\n 0.923, 0.843, 0.619, 0.918, 0.851, 0.626, 0.912, 0.858, 0.633, 0.907,\n 0.866, 0.639, 0.902, 0.873, 0.645, 0.897, 0.880, 0.651, 0.892, 0.887,\n 0.657, 0.886, 0.894, 0.662, 0.881, 0.901, 0.667, 0.875, 0.908, 0.672,\n 0.869, 0.915, 0.676, 0.863, 0.921, 0.680, 0.856, 0.928, 0.684, 0.849,\n 0.934, 0.687, 0.842, 0.940, 0.689, 0.834, 0.945, 0.691, 0.826, 0.951,\n 0.693, 0.817, 0.956, 0.694, 0.807, 0.960, 0.695, 0.797, 0.964, 0.695,\n 0.787, 0.968, 0.694, 0.775, 0.972, 0.693, 0.763, 0.975, 0.692, 0.750,\n 0.977, 0.690, 0.736, 0.980, 0.687, 0.722, 0.981, 0.684, 0.707, 0.982,\n 0.681, 0.691, 0.983, 0.677, 0.675, 0.984, 0.673, 0.658, 0.983, 0.669,\n 0.641, 0.983, 0.664, 0.623, 0.982, 0.659, 0.605, 0.980, 0.654, 0.586,\n 0.979, 0.648, 0.567, 0.977, 0.642, 0.548, 0.974, 0.637, 0.529, 0.972,\n 0.630, 0.509, 0.969, 0.624, 0.489, 0.966, 0.618, 0.469, 0.962, 0.611,\n 0.449, 0.959, 0.605, 0.429, 0.955, 0.598, 0.408, 0.951, 0.591, 0.387,\n 0.947, 0.584, 0.367, 0.942, 0.577, 0.346, 0.938, 0.570, 0.324, 0.933,\n 0.563, 0.303, 0.929, 0.556, 0.281, 0.924, 0.549, 0.258, 0.919, 0.541,\n 0.235, 0.914, 0.534, 0.212, 0.909, 0.527, 0.187, 0.904, 0.519, 0.160,\n 0.760, 0.510, 0.986, 0.767, 0.520, 0.979, 0.774, 0.529, 0.973, 0.781,\n 0.538, 0.966, 0.788, 0.546, 0.960, 0.796, 0.555, 0.954, 0.803, 0.563,\n 0.948, 0.810, 0.571, 0.942, 0.817, 0.579, 0.936, 0.825, 0.586, 0.930,\n 0.832, 0.594, 0.925, 0.839, 0.601, 0.919, 0.846, 0.608, 0.914, 0.854,\n 0.615, 0.908, 0.861, 0.621, 0.903, 0.868, 0.627, 0.897, 0.875, 0.633,\n 0.892, 0.882, 0.639, 0.886, 0.889, 0.645, 0.881, 0.896, 0.650, 0.875,\n 0.903, 0.655, 0.869, 0.909, 0.659, 0.863, 0.916, 0.663, 0.856, 0.922,\n 0.667, 0.849, 0.928, 0.670, 0.842, 0.934, 0.673, 0.834, 0.940, 0.675,\n 0.826, 0.945, 0.677, 0.818, 0.951, 0.679, 0.809, 0.955, 0.680, 0.799,\n 0.960, 0.680, 0.789, 0.964, 0.680, 0.778, 0.968, 0.680, 0.766, 0.971,\n 0.679, 0.754, 0.974, 0.677, 0.741, 0.977, 0.676, 0.727, 0.979, 0.673,\n 0.713, 0.981, 0.670, 0.698, 0.982, 0.667, 0.682, 0.983, 0.664, 0.666,\n 0.983, 0.660, 0.650, 0.983, 0.655, 0.633, 0.983, 0.651, 0.615, 0.982,\n 0.646, 0.597, 0.981, 0.641, 0.579, 0.979, 0.636, 0.560, 0.977, 0.630,\n 0.541, 0.975, 0.625, 0.522, 0.973, 0.619, 0.503, 0.970, 0.613, 0.483,\n 0.967, 0.606, 0.463, 0.964, 0.600, 0.443, 0.960, 0.594, 0.423, 0.956,\n 0.587, 0.403, 0.953, 0.580, 0.383, 0.949, 0.574, 0.362, 0.944, 0.567,\n 0.341, 0.940, 0.560, 0.320, 0.936, 0.553, 0.298, 0.931, 0.546, 0.277,\n 0.926, 0.539, 0.254, 0.922, 0.532, 0.232, 0.917, 0.524, 0.208, 0.912,\n 0.517, 0.183, 0.906, 0.510, 0.156, 0.765, 0.499, 0.985, 0.772, 0.509,\n 0.978, 0.779, 0.518, 0.971, 0.786, 0.527, 0.964, 0.793, 0.535, 0.957,\n 0.800, 0.544, 0.951, 0.807, 0.552, 0.945, 0.814, 0.560, 0.939, 0.821,\n 0.568, 0.933, 0.828, 0.575, 0.927, 0.835, 0.582, 0.921, 0.842, 0.589,\n 0.915, 0.849, 0.596, 0.910, 0.856, 0.603, 0.904, 0.863, 0.609, 0.898,\n 0.870, 0.615, 0.893, 0.877, 0.621, 0.887, 0.884, 0.627, 0.881, 0.891,\n 0.632, 0.875, 0.898, 0.637, 0.869, 0.904, 0.642, 0.863, 0.911, 0.646,\n 0.856, 0.917, 0.650, 0.849, 0.923, 0.653, 0.842, 0.929, 0.657, 0.835,\n 0.935, 0.659, 0.827, 0.940, 0.662, 0.818, 0.946, 0.663, 0.810, 0.951,\n 0.665, 0.800, 0.955, 0.666, 0.790, 0.960, 0.666, 0.780, 0.964, 0.666,\n 0.769, 0.967, 0.666, 0.757, 0.971, 0.665, 0.745, 0.974, 0.663, 0.732,\n 0.976, 0.662, 0.718, 0.978, 0.659, 0.704, 0.980, 0.657, 0.689, 0.981,\n 0.654, 0.674, 0.982, 0.650, 0.658, 0.983, 0.646, 0.642, 0.983, 0.642,\n 0.625, 0.983, 0.638, 0.608, 0.982, 0.633, 0.590, 0.981, 0.628, 0.572,\n 0.979, 0.623, 0.553, 0.978, 0.618, 0.535, 0.976, 0.612, 0.516, 0.973,\n 0.607, 0.497, 0.971, 0.601, 0.477, 0.968, 0.595, 0.458, 0.965, 0.589,\n 0.438, 0.961, 0.582, 0.418, 0.958, 0.576, 0.398, 0.954, 0.569, 0.378,\n 0.950, 0.563, 0.357, 0.946, 0.556, 0.336, 0.942, 0.549, 0.315, 0.938,\n 0.542, 0.294, 0.933, 0.536, 0.273, 0.928, 0.529, 0.250, 0.924, 0.522,\n 0.228, 0.919, 0.514, 0.204, 0.914, 0.507, 0.179, 0.909, 0.500, 0.153,\n 0.770, 0.488, 0.983, 0.777, 0.498, 0.976, 0.783, 0.507, 0.969, 0.790,\n 0.516, 0.962, 0.797, 0.524, 0.955, 0.804, 0.533, 0.948, 0.811, 0.541,\n 0.942, 0.817, 0.549, 0.936, 0.824, 0.556, 0.930, 0.831, 0.564, 0.924,\n 0.838, 0.571, 0.918, 0.845, 0.578, 0.912, 0.852, 0.584, 0.906, 0.859,\n 0.591, 0.900, 0.866, 0.597, 0.894, 0.873, 0.603, 0.888, 0.879, 0.609,\n 0.882, 0.886, 0.614, 0.876, 0.893, 0.619, 0.869, 0.899, 0.624, 0.863,\n 0.906, 0.629, 0.856, 0.912, 0.633, 0.850, 0.918, 0.637, 0.843, 0.924,\n 0.640, 0.835, 0.930, 0.643, 0.827, 0.935, 0.646, 0.819, 0.941, 0.648,\n 0.811, 0.946, 0.649, 0.802, 0.951, 0.651, 0.792, 0.955, 0.652, 0.782,\n 0.959, 0.652, 0.771, 0.963, 0.652, 0.760, 0.967, 0.652, 0.749, 0.970,\n 0.651, 0.736, 0.973, 0.649, 0.723, 0.976, 0.647, 0.710, 0.978, 0.645,\n 0.696, 0.980, 0.643, 0.681, 0.981, 0.640, 0.666, 0.982, 0.637, 0.650,\n 0.982, 0.633, 0.634, 0.983, 0.629, 0.617, 0.982, 0.625, 0.600, 0.982,\n 0.620, 0.582, 0.981, 0.616, 0.565, 0.979, 0.611, 0.546, 0.978, 0.605,\n 0.528, 0.976, 0.600, 0.509, 0.974, 0.595, 0.490, 0.971, 0.589, 0.471,\n 0.969, 0.583, 0.452, 0.966, 0.577, 0.432, 0.962, 0.571, 0.413, 0.959,\n 0.565, 0.393, 0.955, 0.558, 0.373, 0.952, 0.552, 0.352, 0.948, 0.545,\n 0.332, 0.943, 0.539, 0.311, 0.939, 0.532, 0.290, 0.935, 0.525, 0.268,\n 0.930, 0.518, 0.246, 0.926, 0.511, 0.224, 0.921, 0.504, 0.200, 0.916,\n 0.497, 0.175, 0.911, 0.490, 0.149, 0.775, 0.477, 0.981, 0.781, 0.486,\n 0.974, 0.788, 0.495, 0.966, 0.794, 0.504, 0.959, 0.801, 0.513, 0.952,\n 0.808, 0.521, 0.946, 0.814, 0.529, 0.939, 0.821, 0.537, 0.933, 0.828,\n 0.545, 0.926, 0.835, 0.552, 0.920, 0.841, 0.559, 0.914, 0.848, 0.566,\n 0.908, 0.855, 0.572, 0.901, 0.862, 0.579, 0.895, 0.868, 0.585, 0.889,\n 0.875, 0.591, 0.883, 0.881, 0.596, 0.877, 0.888, 0.601, 0.870, 0.894,\n 0.606, 0.864, 0.901, 0.611, 0.857, 0.907, 0.615, 0.850, 0.913, 0.619,\n 0.843, 0.919, 0.623, 0.836, 0.925, 0.626, 0.828, 0.930, 0.629, 0.820,\n 0.936, 0.632, 0.812, 0.941, 0.634, 0.803, 0.946, 0.635, 0.794, 0.951,\n 0.637, 0.784, 0.955, 0.637, 0.774, 0.959, 0.638, 0.763, 0.963, 0.638,\n 0.752, 0.967, 0.637, 0.740, 0.970, 0.636, 0.728, 0.973, 0.635, 0.715,\n 0.975, 0.633, 0.701, 0.977, 0.631, 0.687, 0.979, 0.629, 0.672, 0.980,\n 0.626, 0.657, 0.981, 0.623, 0.642, 0.982, 0.619, 0.626, 0.982, 0.616,\n 0.609, 0.982, 0.612, 0.592, 0.981, 0.607, 0.575, 0.981, 0.603, 0.557,\n 0.979, 0.598, 0.540, 0.978, 0.593, 0.521, 0.976, 0.588, 0.503, 0.974,\n 0.582, 0.484, 0.972, 0.577, 0.465, 0.969, 0.571, 0.446, 0.966, 0.565,\n 0.427, 0.963, 0.559, 0.407, 0.960, 0.553, 0.387, 0.956, 0.547, 0.368,\n 0.953, 0.541, 0.347, 0.949, 0.534, 0.327, 0.945, 0.528, 0.306, 0.941,\n 0.521, 0.285, 0.936, 0.514, 0.264, 0.932, 0.508, 0.242, 0.927, 0.501,\n 0.220, 0.922, 0.494, 0.196, 0.918, 0.487, 0.172, 0.913, 0.480, 0.145,\n 0.779, 0.465, 0.979, 0.785, 0.474, 0.971, 0.792, 0.484, 0.964, 0.798,\n 0.492, 0.957, 0.805, 0.501, 0.950, 0.811, 0.509, 0.943, 0.818, 0.517,\n 0.936, 0.824, 0.525, 0.929, 0.831, 0.533, 0.923, 0.838, 0.540, 0.916,\n 0.844, 0.547, 0.910, 0.851, 0.554, 0.904, 0.857, 0.560, 0.897, 0.864,\n 0.566, 0.891, 0.870, 0.572, 0.884, 0.877, 0.578, 0.878, 0.883, 0.583,\n 0.871, 0.890, 0.589, 0.865, 0.896, 0.593, 0.858, 0.902, 0.598, 0.851,\n 0.908, 0.602, 0.844, 0.914, 0.606, 0.837, 0.920, 0.609, 0.829, 0.925,\n 0.613, 0.821, 0.931, 0.615, 0.813, 0.936, 0.618, 0.804, 0.941, 0.620,\n 0.795, 0.946, 0.621, 0.786, 0.950, 0.622, 0.776, 0.955, 0.623, 0.765,\n 0.959, 0.624, 0.755, 0.963, 0.624, 0.743, 0.966, 0.623, 0.731, 0.969,\n 0.622, 0.719, 0.972, 0.621, 0.706, 0.974, 0.619, 0.693, 0.976, 0.617,\n 0.679, 0.978, 0.615, 0.664, 0.979, 0.612, 0.649, 0.980, 0.609, 0.634,\n 0.981, 0.606, 0.618, 0.981, 0.602, 0.601, 0.981, 0.598, 0.585, 0.981,\n 0.594, 0.568, 0.980, 0.590, 0.550, 0.979, 0.585, 0.533, 0.978, 0.580,\n 0.515, 0.976, 0.575, 0.496, 0.974, 0.570, 0.478, 0.972, 0.565, 0.459,\n 0.969, 0.559, 0.440, 0.967, 0.553, 0.421, 0.964, 0.547, 0.402, 0.960,\n 0.542, 0.382, 0.957, 0.535, 0.362, 0.953, 0.529, 0.342, 0.950, 0.523,\n 0.322, 0.946, 0.517, 0.302, 0.942, 0.510, 0.281, 0.937, 0.504, 0.260,\n 0.933, 0.497, 0.238, 0.929, 0.490, 0.216, 0.924, 0.484, 0.192, 0.919,\n 0.477, 0.168, 0.914, 0.470, 0.141, 0.783, 0.453, 0.977, 0.789, 0.462,\n 0.969, 0.796, 0.471, 0.962, 0.802, 0.480, 0.954, 0.808, 0.489, 0.947,\n 0.815, 0.497, 0.940, 0.821, 0.505, 0.933, 0.828, 0.513, 0.926, 0.834,\n 0.520, 0.919, 0.840, 0.527, 0.913, 0.847, 0.534, 0.906, 0.853, 0.541,\n 0.899, 0.860, 0.548, 0.893, 0.866, 0.554, 0.886, 0.873, 0.560, 0.880,\n 0.879, 0.565, 0.873, 0.885, 0.570, 0.866, 0.891, 0.575, 0.859, 0.897,\n 0.580, 0.852, 0.903, 0.585, 0.845, 0.909, 0.589, 0.838, 0.915, 0.592,\n 0.830, 0.921, 0.596, 0.822, 0.926, 0.599, 0.814, 0.931, 0.601, 0.805,\n 0.936, 0.604, 0.797, 0.941, 0.606, 0.787, 0.946, 0.607, 0.778, 0.950,\n 0.608, 0.768, 0.955, 0.609, 0.757, 0.958, 0.609, 0.746, 0.962, 0.609,\n 0.735, 0.965, 0.609, 0.723, 0.968, 0.608, 0.710, 0.971, 0.607, 0.698,\n 0.974, 0.605, 0.684, 0.976, 0.603, 0.670, 0.977, 0.601, 0.656, 0.979,\n 0.598, 0.641, 0.980, 0.596, 0.626, 0.980, 0.592, 0.610, 0.981, 0.589,\n 0.594, 0.981, 0.585, 0.577, 0.980, 0.581, 0.560, 0.980, 0.577, 0.543,\n 0.979, 0.572, 0.526, 0.977, 0.568, 0.508, 0.976, 0.563, 0.490, 0.974,\n 0.558, 0.471, 0.972, 0.552, 0.453, 0.969, 0.547, 0.434, 0.967, 0.541,\n 0.415, 0.964, 0.536, 0.396, 0.961, 0.530, 0.377, 0.958, 0.524, 0.357,\n 0.954, 0.518, 0.337, 0.950, 0.512, 0.317, 0.947, 0.505, 0.297, 0.943,\n 0.499, 0.276, 0.938, 0.493, 0.255, 0.934, 0.486, 0.234, 0.930, 0.480,\n 0.211, 0.925, 0.473, 0.188, 0.920, 0.466, 0.164, 0.916, 0.459, 0.137,\n 0.787, 0.440, 0.975, 0.793, 0.450, 0.967, 0.799, 0.459, 0.959, 0.806,\n 0.468, 0.952, 0.812, 0.476, 0.944, 0.818, 0.485, 0.937, 0.824, 0.493,\n 0.930, 0.831, 0.500, 0.923, 0.837, 0.508, 0.916, 0.843, 0.515, 0.909,\n 0.850, 0.522, 0.902, 0.856, 0.528, 0.895, 0.862, 0.535, 0.888, 0.868,\n 0.541, 0.881, 0.874, 0.547, 0.875, 0.881, 0.552, 0.868, 0.887, 0.557,\n 0.861, 0.893, 0.562, 0.853, 0.899, 0.567, 0.846, 0.904, 0.571, 0.839,\n 0.910, 0.575, 0.831, 0.916, 0.579, 0.823, 0.921, 0.582, 0.815, 0.926,\n 0.585, 0.807, 0.932, 0.587, 0.798, 0.937, 0.590, 0.789, 0.941, 0.591,\n 0.780, 0.946, 0.593, 0.770, 0.950, 0.594, 0.760, 0.954, 0.595, 0.749,\n 0.958, 0.595, 0.738, 0.962, 0.595, 0.727, 0.965, 0.595, 0.715, 0.968,\n 0.594, 0.702, 0.970, 0.593, 0.689, 0.973, 0.591, 0.676, 0.975, 0.589,\n 0.662, 0.976, 0.587, 0.648, 0.978, 0.585, 0.633, 0.979, 0.582, 0.618,\n 0.980, 0.579, 0.602, 0.980, 0.575, 0.586, 0.980, 0.572, 0.570, 0.980,\n 0.568, 0.553, 0.979, 0.564, 0.536, 0.978, 0.559, 0.518, 0.977, 0.555,\n 0.501, 0.975, 0.550, 0.483, 0.974, 0.545, 0.465, 0.972, 0.540, 0.447,\n 0.969, 0.535, 0.428, 0.967, 0.529, 0.409, 0.964, 0.524, 0.390, 0.961,\n 0.518, 0.371, 0.958, 0.512, 0.352, 0.954, 0.506, 0.332, 0.951, 0.500,\n 0.312, 0.947, 0.494, 0.292, 0.943, 0.488, 0.272, 0.939, 0.481, 0.251,\n 0.935, 0.475, 0.229, 0.931, 0.469, 0.207, 0.926, 0.462, 0.184, 0.921,\n 0.455, 0.159, 0.917, 0.449, 0.133, 0.791, 0.427, 0.973, 0.797, 0.437,\n 0.964, 0.803, 0.446, 0.957, 0.809, 0.455, 0.949, 0.815, 0.464, 0.941,\n 0.821, 0.472, 0.934, 0.827, 0.480, 0.926, 0.834, 0.488, 0.919, 0.840,\n 0.495, 0.912, 0.846, 0.502, 0.905, 0.852, 0.509, 0.898, 0.858, 0.515,\n 0.891, 0.864, 0.522, 0.884, 0.870, 0.528, 0.877, 0.876, 0.533, 0.870,\n 0.882, 0.539, 0.862, 0.888, 0.544, 0.855, 0.894, 0.549, 0.848, 0.900,\n 0.553, 0.840, 0.906, 0.557, 0.833, 0.911, 0.561, 0.825, 0.916, 0.565,\n 0.817, 0.922, 0.568, 0.808, 0.927, 0.571, 0.800, 0.932, 0.573, 0.791,\n 0.937, 0.575, 0.782, 0.941, 0.577, 0.772, 0.946, 0.579, 0.762, 0.950,\n 0.580, 0.752, 0.954, 0.580, 0.741, 0.958, 0.581, 0.730, 0.961, 0.581,\n 0.718, 0.964, 0.580, 0.706, 0.967, 0.580, 0.694, 0.970, 0.578, 0.681,\n 0.972, 0.577, 0.667, 0.974, 0.575, 0.654, 0.976, 0.573, 0.639, 0.977,\n 0.571, 0.625, 0.978, 0.568, 0.610, 0.979, 0.565, 0.594, 0.979, 0.562,\n 0.578, 0.979, 0.558, 0.562, 0.979, 0.554, 0.545, 0.978, 0.550, 0.529,\n 0.977, 0.546, 0.511, 0.976, 0.542, 0.494, 0.975, 0.537, 0.476, 0.973,\n 0.532, 0.458, 0.971, 0.527, 0.440, 0.969, 0.522, 0.422, 0.967, 0.517,\n 0.403, 0.964, 0.511, 0.385, 0.961, 0.506, 0.366, 0.958, 0.500, 0.347,\n 0.955, 0.494, 0.327, 0.951, 0.488, 0.307, 0.947, 0.482, 0.287, 0.944,\n 0.476, 0.267, 0.940, 0.470, 0.246, 0.935, 0.464, 0.225, 0.931, 0.458,\n 0.203, 0.927, 0.451, 0.180, 0.922, 0.445, 0.155, 0.917, 0.438, 0.129,\n 0.795, 0.413, 0.970, 0.801, 0.423, 0.962, 0.807, 0.433, 0.954, 0.813,\n 0.442, 0.946, 0.818, 0.450, 0.938, 0.824, 0.459, 0.930, 0.830, 0.467,\n 0.923, 0.836, 0.474, 0.915, 0.842, 0.482, 0.908, 0.848, 0.489, 0.901,\n 0.854, 0.496, 0.894, 0.860, 0.502, 0.886, 0.866, 0.508, 0.879, 0.872,\n 0.514, 0.872, 0.878, 0.520, 0.864, 0.884, 0.525, 0.857, 0.890, 0.530,\n 0.850, 0.895, 0.535, 0.842, 0.901, 0.539, 0.834, 0.906, 0.543, 0.826,\n 0.912, 0.547, 0.818, 0.917, 0.551, 0.810, 0.922, 0.554, 0.801, 0.927,\n 0.557, 0.793, 0.932, 0.559, 0.783, 0.937, 0.561, 0.774, 0.941, 0.563,\n 0.764, 0.946, 0.564, 0.754, 0.950, 0.565, 0.744, 0.953, 0.566, 0.733,\n 0.957, 0.566, 0.722, 0.960, 0.566, 0.710, 0.963, 0.566, 0.698, 0.966,\n 0.565, 0.685, 0.969, 0.564, 0.673, 0.971, 0.563, 0.659, 0.973, 0.561,\n 0.645, 0.975, 0.559, 0.631, 0.976, 0.557, 0.617, 0.977, 0.554, 0.602,\n 0.978, 0.551, 0.586, 0.978, 0.548, 0.571, 0.978, 0.545, 0.554, 0.978,\n 0.541, 0.538, 0.977, 0.537, 0.521, 0.977, 0.533, 0.504, 0.976, 0.529,\n 0.487, 0.974, 0.524, 0.470, 0.973, 0.519, 0.452, 0.971, 0.515, 0.434,\n 0.969, 0.510, 0.416, 0.966, 0.504, 0.398, 0.964, 0.499, 0.379, 0.961,\n 0.494, 0.360, 0.958, 0.488, 0.341, 0.955, 0.482, 0.322, 0.951, 0.477,\n 0.302, 0.948, 0.471, 0.283, 0.944, 0.465, 0.262, 0.940, 0.459, 0.242,\n 0.936, 0.452, 0.220, 0.932, 0.446, 0.198, 0.927, 0.440, 0.175, 0.923,\n 0.434, 0.151, 0.918, 0.427, 0.124, 0.799, 0.399, 0.968, 0.804, 0.409,\n 0.959, 0.810, 0.419, 0.951, 0.816, 0.428, 0.943, 0.822, 0.437, 0.935,\n 0.827, 0.445, 0.927, 0.833, 0.453, 0.919, 0.839, 0.461, 0.912, 0.845,\n 0.468, 0.904, 0.851, 0.475, 0.897, 0.857, 0.482, 0.889, 0.862, 0.489,\n 0.882, 0.868, 0.495, 0.874, 0.874, 0.501, 0.867, 0.880, 0.506, 0.859,\n 0.885, 0.511, 0.852, 0.891, 0.516, 0.844, 0.897, 0.521, 0.836, 0.902,\n 0.525, 0.828, 0.907, 0.529, 0.820, 0.913, 0.533, 0.812, 0.918, 0.537,\n 0.803, 0.923, 0.540, 0.794, 0.928, 0.542, 0.785, 0.932, 0.545, 0.776,\n 0.937, 0.547, 0.767, 0.941, 0.549, 0.757, 0.945, 0.550, 0.747, 0.949,\n 0.551, 0.736, 0.953, 0.552, 0.725, 0.956, 0.552, 0.714, 0.960, 0.552,\n 0.702, 0.963, 0.552, 0.690, 0.965, 0.551, 0.677, 0.968, 0.550, 0.664,\n 0.970, 0.549, 0.651, 0.972, 0.547, 0.637, 0.974, 0.545, 0.623, 0.975,\n 0.543, 0.609, 0.976, 0.540, 0.594, 0.977, 0.537, 0.578, 0.977, 0.534,\n 0.563, 0.977, 0.531, 0.547, 0.977, 0.527, 0.531, 0.976, 0.524, 0.514,\n 0.976, 0.520, 0.497, 0.975, 0.516, 0.480, 0.973, 0.511, 0.463, 0.972,\n 0.507, 0.446, 0.970, 0.502, 0.428, 0.968, 0.497, 0.410, 0.966, 0.492,\n 0.392, 0.963, 0.487, 0.373, 0.960, 0.481, 0.355, 0.957, 0.476, 0.336,\n 0.954, 0.470, 0.317, 0.951, 0.465, 0.297, 0.947, 0.459, 0.278, 0.944,\n 0.453, 0.258, 0.940, 0.447, 0.237, 0.936, 0.441, 0.216, 0.932, 0.435,\n 0.194, 0.927, 0.429, 0.171, 0.923, 0.422, 0.147, 0.918, 0.416, 0.120,\n 0.802, 0.385, 0.965, 0.808, 0.395, 0.957, 0.813, 0.405, 0.948, 0.819,\n 0.414, 0.940, 0.825, 0.423, 0.932, 0.830, 0.431, 0.924, 0.836, 0.439,\n 0.916, 0.842, 0.447, 0.908, 0.847, 0.454, 0.900, 0.853, 0.462, 0.892,\n 0.859, 0.468, 0.885, 0.864, 0.475, 0.877, 0.870, 0.481, 0.869, 0.876,\n 0.487, 0.862, 0.881, 0.492, 0.854, 0.887, 0.498, 0.846, 0.892, 0.502,\n 0.838, 0.898, 0.507, 0.830, 0.903, 0.511, 0.822, 0.908, 0.515, 0.814,\n 0.913, 0.519, 0.805, 0.918, 0.522, 0.797, 0.923, 0.525, 0.788, 0.928,\n 0.528, 0.778, 0.932, 0.530, 0.769, 0.937, 0.532, 0.759, 0.941, 0.534,\n 0.749, 0.945, 0.535, 0.739, 0.949, 0.536, 0.728, 0.952, 0.537, 0.717,\n 0.956, 0.537, 0.706, 0.959, 0.537, 0.694, 0.962, 0.537, 0.682, 0.964,\n 0.536, 0.669, 0.967, 0.536, 0.656, 0.969, 0.534, 0.643, 0.971, 0.533,\n 0.629, 0.972, 0.531, 0.615, 0.974, 0.529, 0.601, 0.975, 0.526, 0.586,\n 0.975, 0.523, 0.571, 0.976, 0.521, 0.555, 0.976, 0.517, 0.540, 0.976,\n 0.514, 0.523, 0.975, 0.510, 0.507, 0.975, 0.506, 0.490, 0.974, 0.502,\n 0.474, 0.972, 0.498, 0.456, 0.971, 0.494, 0.439, 0.969, 0.489, 0.421,\n 0.967, 0.484, 0.404, 0.965, 0.479, 0.386, 0.963, 0.474, 0.367, 0.960,\n 0.469, 0.349, 0.957, 0.464, 0.330, 0.954, 0.458, 0.311, 0.951, 0.453,\n 0.292, 0.947, 0.447, 0.273, 0.944, 0.441, 0.253, 0.940, 0.435, 0.232,\n 0.936, 0.429, 0.211, 0.932, 0.423, 0.190, 0.927, 0.417, 0.167, 0.923,\n 0.411, 0.142, 0.919, 0.405, 0.116, 0.806, 0.370, 0.963, 0.811, 0.380,\n 0.954, 0.816, 0.390, 0.945, 0.822, 0.399, 0.937, 0.827, 0.408, 0.929,\n 0.833, 0.417, 0.920, 0.838, 0.425, 0.912, 0.844, 0.433, 0.904, 0.850,\n 0.440, 0.896, 0.855, 0.447, 0.888, 0.861, 0.454, 0.880, 0.866, 0.461,\n 0.872, 0.872, 0.467, 0.865, 0.877, 0.473, 0.857, 0.883, 0.478, 0.849,\n 0.888, 0.483, 0.841, 0.893, 0.488, 0.833, 0.899, 0.493, 0.824, 0.904,\n 0.497, 0.816, 0.909, 0.501, 0.807, 0.914, 0.505, 0.799, 0.919, 0.508,\n 0.790, 0.923, 0.511, 0.781, 0.928, 0.514, 0.771, 0.932, 0.516, 0.762,\n 0.937, 0.518, 0.752, 0.941, 0.520, 0.742, 0.945, 0.521, 0.731, 0.948,\n 0.522, 0.720, 0.952, 0.523, 0.709, 0.955, 0.523, 0.698, 0.958, 0.523,\n 0.686, 0.961, 0.523, 0.674, 0.964, 0.522, 0.661, 0.966, 0.521, 0.648,\n 0.968, 0.520, 0.635, 0.970, 0.518, 0.621, 0.971, 0.517, 0.607, 0.972,\n 0.514, 0.593, 0.973, 0.512, 0.578, 0.974, 0.509, 0.563, 0.975, 0.507,\n 0.548, 0.975, 0.503, 0.532, 0.975, 0.500, 0.516, 0.974, 0.497, 0.500,\n 0.974, 0.493, 0.483, 0.973, 0.489, 0.467, 0.971, 0.485, 0.450, 0.970,\n 0.480, 0.433, 0.968, 0.476, 0.415, 0.966, 0.471, 0.397, 0.964, 0.466,\n 0.380, 0.962, 0.461, 0.362, 0.959, 0.456, 0.343, 0.956, 0.451, 0.325,\n 0.953, 0.446, 0.306, 0.950, 0.440, 0.287, 0.947, 0.435, 0.268, 0.943,\n 0.429, 0.248, 0.939, 0.423, 0.228, 0.936, 0.417, 0.207, 0.931, 0.411,\n 0.185, 0.927, 0.405, 0.162, 0.923, 0.399, 0.138, 0.918, 0.393, 0.111,\n 0.809, 0.354, 0.960, 0.814, 0.364, 0.951, 0.819, 0.375, 0.942, 0.825,\n 0.384, 0.934, 0.830, 0.393, 0.925, 0.835, 0.402, 0.917, 0.841, 0.410,\n 0.908, 0.846, 0.418, 0.900, 0.852, 0.426, 0.892, 0.857, 0.433, 0.884,\n 0.863, 0.440, 0.876, 0.868, 0.446, 0.868, 0.873, 0.452, 0.860, 0.879,\n 0.458, 0.852, 0.884, 0.464, 0.843, 0.889, 0.469, 0.835, 0.894, 0.474,\n 0.827, 0.899, 0.478, 0.818, 0.904, 0.483, 0.810, 0.909, 0.486, 0.801,\n 0.914, 0.490, 0.792, 0.919, 0.493, 0.783, 0.923, 0.496, 0.774, 0.928,\n 0.499, 0.764, 0.932, 0.501, 0.755, 0.936, 0.503, 0.745, 0.940, 0.505,\n 0.734, 0.944, 0.506, 0.724, 0.948, 0.507, 0.713, 0.951, 0.508, 0.701,\n 0.954, 0.508, 0.690, 0.957, 0.508, 0.678, 0.960, 0.508, 0.666, 0.962,\n 0.507, 0.653, 0.965, 0.507, 0.640, 0.967, 0.505, 0.627, 0.968, 0.504,\n 0.613, 0.970, 0.502, 0.599, 0.971, 0.500, 0.585, 0.972, 0.498, 0.570,\n 0.973, 0.495, 0.555, 0.973, 0.493, 0.540, 0.973, 0.490, 0.525, 0.973,\n 0.486, 0.509, 0.973, 0.483, 0.493, 0.972, 0.479, 0.476, 0.971, 0.475,\n 0.460, 0.970, 0.471, 0.443, 0.969, 0.467, 0.426, 0.967, 0.463, 0.409,\n 0.965, 0.458, 0.391, 0.963, 0.453, 0.374, 0.961, 0.449, 0.356, 0.958,\n 0.444, 0.338, 0.956, 0.438, 0.319, 0.953, 0.433, 0.301, 0.949, 0.428,\n 0.282, 0.946, 0.422, 0.263, 0.943, 0.417, 0.243, 0.939, 0.411, 0.223,\n 0.935, 0.405, 0.202, 0.931, 0.399, 0.181, 0.927, 0.393, 0.158, 0.923,\n 0.387, 0.134, 0.918, 0.381, 0.107,\n ]).reshape((65, 65, 3))\n\nBiOrangeBlue = np.array(\n [0.000, 0.000, 0.000, 0.000, 0.062, 0.125, 0.000, 0.125, 0.250, 0.000,\n 0.188, 0.375, 0.000, 0.250, 0.500, 0.000, 0.312, 0.625, 0.000, 0.375,\n 0.750, 0.000, 0.438, 0.875, 0.000, 0.500, 1.000, 0.125, 0.062, 0.000,\n 0.125, 0.125, 0.125, 0.125, 0.188, 0.250, 0.125, 0.250, 0.375, 0.125,\n 0.312, 0.500, 0.125, 0.375, 0.625, 0.125, 0.438, 0.750, 0.125, 0.500,\n 0.875, 0.125, 0.562, 1.000, 0.250, 0.125, 0.000, 0.250, 0.188, 0.125,\n 0.250, 0.250, 0.250, 0.250, 0.312, 0.375, 0.250, 0.375, 0.500, 0.250,\n 0.438, 0.625, 0.250, 0.500, 0.750, 0.250, 0.562, 0.875, 0.250, 0.625,\n 1.000, 0.375, 0.188, 0.000, 0.375, 0.250, 0.125, 0.375, 0.312, 0.250,\n 0.375, 0.375, 0.375, 0.375, 0.438, 0.500, 0.375, 0.500, 0.625, 0.375,\n 0.562, 0.750, 0.375, 0.625, 0.875, 0.375, 0.688, 1.000, 0.500, 0.250,\n 0.000, 0.500, 0.312, 0.125, 0.500, 0.375, 0.250, 0.500, 0.438, 0.375,\n 0.500, 0.500, 0.500, 0.500, 0.562, 0.625, 0.500, 0.625, 0.750, 0.500,\n 0.688, 0.875, 0.500, 0.750, 1.000, 0.625, 0.312, 0.000, 0.625, 0.375,\n 0.125, 0.625, 0.438, 0.250, 0.625, 0.500, 0.375, 0.625, 0.562, 0.500,\n 0.625, 0.625, 0.625, 0.625, 0.688, 0.750, 0.625, 0.750, 0.875, 0.625,\n 0.812, 1.000, 0.750, 0.375, 0.000, 0.750, 0.438, 0.125, 0.750, 0.500,\n 0.250, 0.750, 0.562, 0.375, 0.750, 0.625, 0.500, 0.750, 0.688, 0.625,\n 0.750, 0.750, 0.750, 0.750, 0.812, 0.875, 0.750, 0.875, 1.000, 0.875,\n 0.438, 0.000, 0.875, 0.500, 0.125, 0.875, 0.562, 0.250, 0.875, 0.625,\n 0.375, 0.875, 0.688, 0.500, 0.875, 0.750, 0.625, 0.875, 0.812, 0.750,\n 0.875, 0.875, 0.875, 0.875, 0.938, 1.000, 1.000, 0.500, 0.000, 1.000,\n 0.562, 0.125, 1.000, 0.625, 0.250, 1.000, 0.688, 0.375, 1.000, 0.750,\n 0.500, 1.000, 0.812, 0.625, 1.000, 0.875, 0.750, 1.000, 0.938, 0.875,\n 1.000, 1.000, 1.000,\n ]).reshape((9, 9, 3))\n\ncmaps = {\n "BiPeak": SegmentedBivarColormap(\n BiPeak, 256, "square", (.5, .5), name="BiPeak"),\n "BiOrangeBlue": SegmentedBivarColormap(\n BiOrangeBlue, 256, "square", (0, 0), name="BiOrangeBlue"),\n "BiCone": SegmentedBivarColormap(BiPeak, 256, "circle", (.5, .5), name="BiCone"),\n}\n
.venv\Lib\site-packages\matplotlib\_cm_bivar.py
_cm_bivar.py
Python
97,461
0.75
0
0.001529
react-lib
885
2025-05-17T21:17:40.120771
Apache-2.0
false
6f98eb963a21bdaa54832d5bc9e8c714
# auto-generated by https://github.com/trygvrad/multivariate_colormaps\n# date: 2024-05-28\n\nfrom .colors import LinearSegmentedColormap, MultivarColormap\nimport matplotlib as mpl\n_LUTSIZE = mpl.rcParams['image.lut']\n\n_2VarAddA0_data = [[0.000, 0.000, 0.000],\n [0.020, 0.026, 0.031],\n [0.049, 0.068, 0.085],\n [0.075, 0.107, 0.135],\n [0.097, 0.144, 0.183],\n [0.116, 0.178, 0.231],\n [0.133, 0.212, 0.279],\n [0.148, 0.244, 0.326],\n [0.161, 0.276, 0.374],\n [0.173, 0.308, 0.422],\n [0.182, 0.339, 0.471],\n [0.190, 0.370, 0.521],\n [0.197, 0.400, 0.572],\n [0.201, 0.431, 0.623],\n [0.204, 0.461, 0.675],\n [0.204, 0.491, 0.728],\n [0.202, 0.520, 0.783],\n [0.197, 0.549, 0.838],\n [0.187, 0.577, 0.895]]\n\n_2VarAddA1_data = [[0.000, 0.000, 0.000],\n [0.030, 0.023, 0.018],\n [0.079, 0.060, 0.043],\n [0.125, 0.093, 0.065],\n [0.170, 0.123, 0.083],\n [0.213, 0.151, 0.098],\n [0.255, 0.177, 0.110],\n [0.298, 0.202, 0.120],\n [0.341, 0.226, 0.128],\n [0.384, 0.249, 0.134],\n [0.427, 0.271, 0.138],\n [0.472, 0.292, 0.141],\n [0.517, 0.313, 0.142],\n [0.563, 0.333, 0.141],\n [0.610, 0.353, 0.139],\n [0.658, 0.372, 0.134],\n [0.708, 0.390, 0.127],\n [0.759, 0.407, 0.118],\n [0.813, 0.423, 0.105]]\n\n_2VarSubA0_data = [[1.000, 1.000, 1.000],\n [0.959, 0.973, 0.986],\n [0.916, 0.948, 0.974],\n [0.874, 0.923, 0.965],\n [0.832, 0.899, 0.956],\n [0.790, 0.875, 0.948],\n [0.748, 0.852, 0.940],\n [0.707, 0.829, 0.934],\n [0.665, 0.806, 0.927],\n [0.624, 0.784, 0.921],\n [0.583, 0.762, 0.916],\n [0.541, 0.740, 0.910],\n [0.500, 0.718, 0.905],\n [0.457, 0.697, 0.901],\n [0.414, 0.675, 0.896],\n [0.369, 0.652, 0.892],\n [0.320, 0.629, 0.888],\n [0.266, 0.604, 0.884],\n [0.199, 0.574, 0.881]]\n\n_2VarSubA1_data = [[1.000, 1.000, 1.000],\n [0.982, 0.967, 0.955],\n [0.966, 0.935, 0.908],\n [0.951, 0.902, 0.860],\n [0.937, 0.870, 0.813],\n [0.923, 0.838, 0.765],\n [0.910, 0.807, 0.718],\n [0.898, 0.776, 0.671],\n [0.886, 0.745, 0.624],\n [0.874, 0.714, 0.577],\n [0.862, 0.683, 0.530],\n [0.851, 0.653, 0.483],\n [0.841, 0.622, 0.435],\n [0.831, 0.592, 0.388],\n [0.822, 0.561, 0.340],\n [0.813, 0.530, 0.290],\n [0.806, 0.498, 0.239],\n [0.802, 0.464, 0.184],\n [0.801, 0.426, 0.119]]\n\n_3VarAddA0_data = [[0.000, 0.000, 0.000],\n [0.018, 0.023, 0.028],\n [0.040, 0.056, 0.071],\n [0.059, 0.087, 0.110],\n [0.074, 0.114, 0.147],\n [0.086, 0.139, 0.183],\n [0.095, 0.163, 0.219],\n [0.101, 0.187, 0.255],\n [0.105, 0.209, 0.290],\n [0.107, 0.230, 0.326],\n [0.105, 0.251, 0.362],\n [0.101, 0.271, 0.398],\n [0.091, 0.291, 0.434],\n [0.075, 0.309, 0.471],\n [0.046, 0.325, 0.507],\n [0.021, 0.341, 0.546],\n [0.021, 0.363, 0.584],\n [0.022, 0.385, 0.622],\n [0.023, 0.408, 0.661]]\n\n_3VarAddA1_data = [[0.000, 0.000, 0.000],\n [0.020, 0.024, 0.016],\n [0.047, 0.058, 0.034],\n [0.072, 0.088, 0.048],\n [0.093, 0.116, 0.059],\n [0.113, 0.142, 0.067],\n [0.131, 0.167, 0.071],\n [0.149, 0.190, 0.074],\n [0.166, 0.213, 0.074],\n [0.182, 0.235, 0.072],\n [0.198, 0.256, 0.068],\n [0.215, 0.276, 0.061],\n [0.232, 0.296, 0.051],\n [0.249, 0.314, 0.037],\n [0.270, 0.330, 0.018],\n [0.288, 0.347, 0.000],\n [0.302, 0.369, 0.000],\n [0.315, 0.391, 0.000],\n [0.328, 0.414, 0.000]]\n\n_3VarAddA2_data = [[0.000, 0.000, 0.000],\n [0.029, 0.020, 0.023],\n [0.072, 0.045, 0.055],\n [0.111, 0.067, 0.084],\n [0.148, 0.085, 0.109],\n [0.184, 0.101, 0.133],\n [0.219, 0.115, 0.155],\n [0.254, 0.127, 0.176],\n [0.289, 0.138, 0.195],\n [0.323, 0.147, 0.214],\n [0.358, 0.155, 0.232],\n [0.393, 0.161, 0.250],\n [0.429, 0.166, 0.267],\n [0.467, 0.169, 0.283],\n [0.507, 0.168, 0.298],\n [0.546, 0.168, 0.313],\n [0.580, 0.172, 0.328],\n [0.615, 0.175, 0.341],\n [0.649, 0.178, 0.355]]\n\ncmaps = {\n name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [\n ('2VarAddA0', _2VarAddA0_data),\n ('2VarAddA1', _2VarAddA1_data),\n ('2VarSubA0', _2VarSubA0_data),\n ('2VarSubA1', _2VarSubA1_data),\n ('3VarAddA0', _3VarAddA0_data),\n ('3VarAddA1', _3VarAddA1_data),\n ('3VarAddA2', _3VarAddA2_data),\n ]}\n\ncmap_families = {\n '2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],\n 'sRGB_add', name='2VarAddA'),\n '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],\n 'sRGB_sub', name='2VarSubA'),\n '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],\n 'sRGB_add', name='3VarAddA'),\n}\n
.venv\Lib\site-packages\matplotlib\_cm_multivar.py
_cm_multivar.py
Python
6,630
0.95
0.024096
0.012821
node-utils
194
2024-07-06T22:08:43.446771
MIT
false
3412fefac07bd863f427896b538cea27
BASE_COLORS = {\n 'b': (0, 0, 1), # blue\n 'g': (0, 0.5, 0), # green\n 'r': (1, 0, 0), # red\n 'c': (0, 0.75, 0.75), # cyan\n 'm': (0.75, 0, 0.75), # magenta\n 'y': (0.75, 0.75, 0), # yellow\n 'k': (0, 0, 0), # black\n 'w': (1, 1, 1), # white\n}\n\n\n# These colors are from Tableau\nTABLEAU_COLORS = {\n 'tab:blue': '#1f77b4',\n 'tab:orange': '#ff7f0e',\n 'tab:green': '#2ca02c',\n 'tab:red': '#d62728',\n 'tab:purple': '#9467bd',\n 'tab:brown': '#8c564b',\n 'tab:pink': '#e377c2',\n 'tab:gray': '#7f7f7f',\n 'tab:olive': '#bcbd22',\n 'tab:cyan': '#17becf',\n}\n\n\n# This mapping of color names -> hex values is taken from\n# a survey run by Randall Munroe see:\n# https://blog.xkcd.com/2010/05/03/color-survey-results/\n# for more details. The results are hosted at\n# https://xkcd.com/color/rgb/\n# and also available as a text file at\n# https://xkcd.com/color/rgb.txt\n#\n# License: https://creativecommons.org/publicdomain/zero/1.0/\nXKCD_COLORS = {\n 'cloudy blue': '#acc2d9',\n 'dark pastel green': '#56ae57',\n 'dust': '#b2996e',\n 'electric lime': '#a8ff04',\n 'fresh green': '#69d84f',\n 'light eggplant': '#894585',\n 'nasty green': '#70b23f',\n 'really light blue': '#d4ffff',\n 'tea': '#65ab7c',\n 'warm purple': '#952e8f',\n 'yellowish tan': '#fcfc81',\n 'cement': '#a5a391',\n 'dark grass green': '#388004',\n 'dusty teal': '#4c9085',\n 'grey teal': '#5e9b8a',\n 'macaroni and cheese': '#efb435',\n 'pinkish tan': '#d99b82',\n 'spruce': '#0a5f38',\n 'strong blue': '#0c06f7',\n 'toxic green': '#61de2a',\n 'windows blue': '#3778bf',\n 'blue blue': '#2242c7',\n 'blue with a hint of purple': '#533cc6',\n 'booger': '#9bb53c',\n 'bright sea green': '#05ffa6',\n 'dark green blue': '#1f6357',\n 'deep turquoise': '#017374',\n 'green teal': '#0cb577',\n 'strong pink': '#ff0789',\n 'bland': '#afa88b',\n 'deep aqua': '#08787f',\n 'lavender pink': '#dd85d7',\n 'light moss green': '#a6c875',\n 'light seafoam green': '#a7ffb5',\n 'olive yellow': '#c2b709',\n 'pig pink': '#e78ea5',\n 'deep lilac': '#966ebd',\n 'desert': '#ccad60',\n 'dusty lavender': '#ac86a8',\n 'purpley grey': '#947e94',\n 'purply': '#983fb2',\n 'candy pink': '#ff63e9',\n 'light pastel green': '#b2fba5',\n 'boring green': '#63b365',\n 'kiwi green': '#8ee53f',\n 'light grey green': '#b7e1a1',\n 'orange pink': '#ff6f52',\n 'tea green': '#bdf8a3',\n 'very light brown': '#d3b683',\n 'egg shell': '#fffcc4',\n 'eggplant purple': '#430541',\n 'powder pink': '#ffb2d0',\n 'reddish grey': '#997570',\n 'baby shit brown': '#ad900d',\n 'liliac': '#c48efd',\n 'stormy blue': '#507b9c',\n 'ugly brown': '#7d7103',\n 'custard': '#fffd78',\n 'darkish pink': '#da467d',\n 'deep brown': '#410200',\n 'greenish beige': '#c9d179',\n 'manilla': '#fffa86',\n 'off blue': '#5684ae',\n 'battleship grey': '#6b7c85',\n 'browny green': '#6f6c0a',\n 'bruise': '#7e4071',\n 'kelley green': '#009337',\n 'sickly yellow': '#d0e429',\n 'sunny yellow': '#fff917',\n 'azul': '#1d5dec',\n 'darkgreen': '#054907',\n 'green/yellow': '#b5ce08',\n 'lichen': '#8fb67b',\n 'light light green': '#c8ffb0',\n 'pale gold': '#fdde6c',\n 'sun yellow': '#ffdf22',\n 'tan green': '#a9be70',\n 'burple': '#6832e3',\n 'butterscotch': '#fdb147',\n 'toupe': '#c7ac7d',\n 'dark cream': '#fff39a',\n 'indian red': '#850e04',\n 'light lavendar': '#efc0fe',\n 'poison green': '#40fd14',\n 'baby puke green': '#b6c406',\n 'bright yellow green': '#9dff00',\n 'charcoal grey': '#3c4142',\n 'squash': '#f2ab15',\n 'cinnamon': '#ac4f06',\n 'light pea green': '#c4fe82',\n 'radioactive green': '#2cfa1f',\n 'raw sienna': '#9a6200',\n 'baby purple': '#ca9bf7',\n 'cocoa': '#875f42',\n 'light royal blue': '#3a2efe',\n 'orangeish': '#fd8d49',\n 'rust brown': '#8b3103',\n 'sand brown': '#cba560',\n 'swamp': '#698339',\n 'tealish green': '#0cdc73',\n 'burnt siena': '#b75203',\n 'camo': '#7f8f4e',\n 'dusk blue': '#26538d',\n 'fern': '#63a950',\n 'old rose': '#c87f89',\n 'pale light green': '#b1fc99',\n 'peachy pink': '#ff9a8a',\n 'rosy pink': '#f6688e',\n 'light bluish green': '#76fda8',\n 'light bright green': '#53fe5c',\n 'light neon green': '#4efd54',\n 'light seafoam': '#a0febf',\n 'tiffany blue': '#7bf2da',\n 'washed out green': '#bcf5a6',\n 'browny orange': '#ca6b02',\n 'nice blue': '#107ab0',\n 'sapphire': '#2138ab',\n 'greyish teal': '#719f91',\n 'orangey yellow': '#fdb915',\n 'parchment': '#fefcaf',\n 'straw': '#fcf679',\n 'very dark brown': '#1d0200',\n 'terracota': '#cb6843',\n 'ugly blue': '#31668a',\n 'clear blue': '#247afd',\n 'creme': '#ffffb6',\n 'foam green': '#90fda9',\n 'grey/green': '#86a17d',\n 'light gold': '#fddc5c',\n 'seafoam blue': '#78d1b6',\n 'topaz': '#13bbaf',\n 'violet pink': '#fb5ffc',\n 'wintergreen': '#20f986',\n 'yellow tan': '#ffe36e',\n 'dark fuchsia': '#9d0759',\n 'indigo blue': '#3a18b1',\n 'light yellowish green': '#c2ff89',\n 'pale magenta': '#d767ad',\n 'rich purple': '#720058',\n 'sunflower yellow': '#ffda03',\n 'green/blue': '#01c08d',\n 'leather': '#ac7434',\n 'racing green': '#014600',\n 'vivid purple': '#9900fa',\n 'dark royal blue': '#02066f',\n 'hazel': '#8e7618',\n 'muted pink': '#d1768f',\n 'booger green': '#96b403',\n 'canary': '#fdff63',\n 'cool grey': '#95a3a6',\n 'dark taupe': '#7f684e',\n 'darkish purple': '#751973',\n 'true green': '#089404',\n 'coral pink': '#ff6163',\n 'dark sage': '#598556',\n 'dark slate blue': '#214761',\n 'flat blue': '#3c73a8',\n 'mushroom': '#ba9e88',\n 'rich blue': '#021bf9',\n 'dirty purple': '#734a65',\n 'greenblue': '#23c48b',\n 'icky green': '#8fae22',\n 'light khaki': '#e6f2a2',\n 'warm blue': '#4b57db',\n 'dark hot pink': '#d90166',\n 'deep sea blue': '#015482',\n 'carmine': '#9d0216',\n 'dark yellow green': '#728f02',\n 'pale peach': '#ffe5ad',\n 'plum purple': '#4e0550',\n 'golden rod': '#f9bc08',\n 'neon red': '#ff073a',\n 'old pink': '#c77986',\n 'very pale blue': '#d6fffe',\n 'blood orange': '#fe4b03',\n 'grapefruit': '#fd5956',\n 'sand yellow': '#fce166',\n 'clay brown': '#b2713d',\n 'dark blue grey': '#1f3b4d',\n 'flat green': '#699d4c',\n 'light green blue': '#56fca2',\n 'warm pink': '#fb5581',\n 'dodger blue': '#3e82fc',\n 'gross green': '#a0bf16',\n 'ice': '#d6fffa',\n 'metallic blue': '#4f738e',\n 'pale salmon': '#ffb19a',\n 'sap green': '#5c8b15',\n 'algae': '#54ac68',\n 'bluey grey': '#89a0b0',\n 'greeny grey': '#7ea07a',\n 'highlighter green': '#1bfc06',\n 'light light blue': '#cafffb',\n 'light mint': '#b6ffbb',\n 'raw umber': '#a75e09',\n 'vivid blue': '#152eff',\n 'deep lavender': '#8d5eb7',\n 'dull teal': '#5f9e8f',\n 'light greenish blue': '#63f7b4',\n 'mud green': '#606602',\n 'pinky': '#fc86aa',\n 'red wine': '#8c0034',\n 'shit green': '#758000',\n 'tan brown': '#ab7e4c',\n 'darkblue': '#030764',\n 'rosa': '#fe86a4',\n 'lipstick': '#d5174e',\n 'pale mauve': '#fed0fc',\n 'claret': '#680018',\n 'dandelion': '#fedf08',\n 'orangered': '#fe420f',\n 'poop green': '#6f7c00',\n 'ruby': '#ca0147',\n 'dark': '#1b2431',\n 'greenish turquoise': '#00fbb0',\n 'pastel red': '#db5856',\n 'piss yellow': '#ddd618',\n 'bright cyan': '#41fdfe',\n 'dark coral': '#cf524e',\n 'algae green': '#21c36f',\n 'darkish red': '#a90308',\n 'reddy brown': '#6e1005',\n 'blush pink': '#fe828c',\n 'camouflage green': '#4b6113',\n 'lawn green': '#4da409',\n 'putty': '#beae8a',\n 'vibrant blue': '#0339f8',\n 'dark sand': '#a88f59',\n 'purple/blue': '#5d21d0',\n 'saffron': '#feb209',\n 'twilight': '#4e518b',\n 'warm brown': '#964e02',\n 'bluegrey': '#85a3b2',\n 'bubble gum pink': '#ff69af',\n 'duck egg blue': '#c3fbf4',\n 'greenish cyan': '#2afeb7',\n 'petrol': '#005f6a',\n 'royal': '#0c1793',\n 'butter': '#ffff81',\n 'dusty orange': '#f0833a',\n 'off yellow': '#f1f33f',\n 'pale olive green': '#b1d27b',\n 'orangish': '#fc824a',\n 'leaf': '#71aa34',\n 'light blue grey': '#b7c9e2',\n 'dried blood': '#4b0101',\n 'lightish purple': '#a552e6',\n 'rusty red': '#af2f0d',\n 'lavender blue': '#8b88f8',\n 'light grass green': '#9af764',\n 'light mint green': '#a6fbb2',\n 'sunflower': '#ffc512',\n 'velvet': '#750851',\n 'brick orange': '#c14a09',\n 'lightish red': '#fe2f4a',\n 'pure blue': '#0203e2',\n 'twilight blue': '#0a437a',\n 'violet red': '#a50055',\n 'yellowy brown': '#ae8b0c',\n 'carnation': '#fd798f',\n 'muddy yellow': '#bfac05',\n 'dark seafoam green': '#3eaf76',\n 'deep rose': '#c74767',\n 'dusty red': '#b9484e',\n 'grey/blue': '#647d8e',\n 'lemon lime': '#bffe28',\n 'purple/pink': '#d725de',\n 'brown yellow': '#b29705',\n 'purple brown': '#673a3f',\n 'wisteria': '#a87dc2',\n 'banana yellow': '#fafe4b',\n 'lipstick red': '#c0022f',\n 'water blue': '#0e87cc',\n 'brown grey': '#8d8468',\n 'vibrant purple': '#ad03de',\n 'baby green': '#8cff9e',\n 'barf green': '#94ac02',\n 'eggshell blue': '#c4fff7',\n 'sandy yellow': '#fdee73',\n 'cool green': '#33b864',\n 'pale': '#fff9d0',\n 'blue/grey': '#758da3',\n 'hot magenta': '#f504c9',\n 'greyblue': '#77a1b5',\n 'purpley': '#8756e4',\n 'baby shit green': '#889717',\n 'brownish pink': '#c27e79',\n 'dark aquamarine': '#017371',\n 'diarrhea': '#9f8303',\n 'light mustard': '#f7d560',\n 'pale sky blue': '#bdf6fe',\n 'turtle green': '#75b84f',\n 'bright olive': '#9cbb04',\n 'dark grey blue': '#29465b',\n 'greeny brown': '#696006',\n 'lemon green': '#adf802',\n 'light periwinkle': '#c1c6fc',\n 'seaweed green': '#35ad6b',\n 'sunshine yellow': '#fffd37',\n 'ugly purple': '#a442a0',\n 'medium pink': '#f36196',\n 'puke brown': '#947706',\n 'very light pink': '#fff4f2',\n 'viridian': '#1e9167',\n 'bile': '#b5c306',\n 'faded yellow': '#feff7f',\n 'very pale green': '#cffdbc',\n 'vibrant green': '#0add08',\n 'bright lime': '#87fd05',\n 'spearmint': '#1ef876',\n 'light aquamarine': '#7bfdc7',\n 'light sage': '#bcecac',\n 'yellowgreen': '#bbf90f',\n 'baby poo': '#ab9004',\n 'dark seafoam': '#1fb57a',\n 'deep teal': '#00555a',\n 'heather': '#a484ac',\n 'rust orange': '#c45508',\n 'dirty blue': '#3f829d',\n 'fern green': '#548d44',\n 'bright lilac': '#c95efb',\n 'weird green': '#3ae57f',\n 'peacock blue': '#016795',\n 'avocado green': '#87a922',\n 'faded orange': '#f0944d',\n 'grape purple': '#5d1451',\n 'hot green': '#25ff29',\n 'lime yellow': '#d0fe1d',\n 'mango': '#ffa62b',\n 'shamrock': '#01b44c',\n 'bubblegum': '#ff6cb5',\n 'purplish brown': '#6b4247',\n 'vomit yellow': '#c7c10c',\n 'pale cyan': '#b7fffa',\n 'key lime': '#aeff6e',\n 'tomato red': '#ec2d01',\n 'lightgreen': '#76ff7b',\n 'merlot': '#730039',\n 'night blue': '#040348',\n 'purpleish pink': '#df4ec8',\n 'apple': '#6ecb3c',\n 'baby poop green': '#8f9805',\n 'green apple': '#5edc1f',\n 'heliotrope': '#d94ff5',\n 'yellow/green': '#c8fd3d',\n 'almost black': '#070d0d',\n 'cool blue': '#4984b8',\n 'leafy green': '#51b73b',\n 'mustard brown': '#ac7e04',\n 'dusk': '#4e5481',\n 'dull brown': '#876e4b',\n 'frog green': '#58bc08',\n 'vivid green': '#2fef10',\n 'bright light green': '#2dfe54',\n 'fluro green': '#0aff02',\n 'kiwi': '#9cef43',\n 'seaweed': '#18d17b',\n 'navy green': '#35530a',\n 'ultramarine blue': '#1805db',\n 'iris': '#6258c4',\n 'pastel orange': '#ff964f',\n 'yellowish orange': '#ffab0f',\n 'perrywinkle': '#8f8ce7',\n 'tealish': '#24bca8',\n 'dark plum': '#3f012c',\n 'pear': '#cbf85f',\n 'pinkish orange': '#ff724c',\n 'midnight purple': '#280137',\n 'light urple': '#b36ff6',\n 'dark mint': '#48c072',\n 'greenish tan': '#bccb7a',\n 'light burgundy': '#a8415b',\n 'turquoise blue': '#06b1c4',\n 'ugly pink': '#cd7584',\n 'sandy': '#f1da7a',\n 'electric pink': '#ff0490',\n 'muted purple': '#805b87',\n 'mid green': '#50a747',\n 'greyish': '#a8a495',\n 'neon yellow': '#cfff04',\n 'banana': '#ffff7e',\n 'carnation pink': '#ff7fa7',\n 'tomato': '#ef4026',\n 'sea': '#3c9992',\n 'muddy brown': '#886806',\n 'turquoise green': '#04f489',\n 'buff': '#fef69e',\n 'fawn': '#cfaf7b',\n 'muted blue': '#3b719f',\n 'pale rose': '#fdc1c5',\n 'dark mint green': '#20c073',\n 'amethyst': '#9b5fc0',\n 'blue/green': '#0f9b8e',\n 'chestnut': '#742802',\n 'sick green': '#9db92c',\n 'pea': '#a4bf20',\n 'rusty orange': '#cd5909',\n 'stone': '#ada587',\n 'rose red': '#be013c',\n 'pale aqua': '#b8ffeb',\n 'deep orange': '#dc4d01',\n 'earth': '#a2653e',\n 'mossy green': '#638b27',\n 'grassy green': '#419c03',\n 'pale lime green': '#b1ff65',\n 'light grey blue': '#9dbcd4',\n 'pale grey': '#fdfdfe',\n 'asparagus': '#77ab56',\n 'blueberry': '#464196',\n 'purple red': '#990147',\n 'pale lime': '#befd73',\n 'greenish teal': '#32bf84',\n 'caramel': '#af6f09',\n 'deep magenta': '#a0025c',\n 'light peach': '#ffd8b1',\n 'milk chocolate': '#7f4e1e',\n 'ocher': '#bf9b0c',\n 'off green': '#6ba353',\n 'purply pink': '#f075e6',\n 'lightblue': '#7bc8f6',\n 'dusky blue': '#475f94',\n 'golden': '#f5bf03',\n 'light beige': '#fffeb6',\n 'butter yellow': '#fffd74',\n 'dusky purple': '#895b7b',\n 'french blue': '#436bad',\n 'ugly yellow': '#d0c101',\n 'greeny yellow': '#c6f808',\n 'orangish red': '#f43605',\n 'shamrock green': '#02c14d',\n 'orangish brown': '#b25f03',\n 'tree green': '#2a7e19',\n 'deep violet': '#490648',\n 'gunmetal': '#536267',\n 'blue/purple': '#5a06ef',\n 'cherry': '#cf0234',\n 'sandy brown': '#c4a661',\n 'warm grey': '#978a84',\n 'dark indigo': '#1f0954',\n 'midnight': '#03012d',\n 'bluey green': '#2bb179',\n 'grey pink': '#c3909b',\n 'soft purple': '#a66fb5',\n 'blood': '#770001',\n 'brown red': '#922b05',\n 'medium grey': '#7d7f7c',\n 'berry': '#990f4b',\n 'poo': '#8f7303',\n 'purpley pink': '#c83cb9',\n 'light salmon': '#fea993',\n 'snot': '#acbb0d',\n 'easter purple': '#c071fe',\n 'light yellow green': '#ccfd7f',\n 'dark navy blue': '#00022e',\n 'drab': '#828344',\n 'light rose': '#ffc5cb',\n 'rouge': '#ab1239',\n 'purplish red': '#b0054b',\n 'slime green': '#99cc04',\n 'baby poop': '#937c00',\n 'irish green': '#019529',\n 'pink/purple': '#ef1de7',\n 'dark navy': '#000435',\n 'greeny blue': '#42b395',\n 'light plum': '#9d5783',\n 'pinkish grey': '#c8aca9',\n 'dirty orange': '#c87606',\n 'rust red': '#aa2704',\n 'pale lilac': '#e4cbff',\n 'orangey red': '#fa4224',\n 'primary blue': '#0804f9',\n 'kermit green': '#5cb200',\n 'brownish purple': '#76424e',\n 'murky green': '#6c7a0e',\n 'wheat': '#fbdd7e',\n 'very dark purple': '#2a0134',\n 'bottle green': '#044a05',\n 'watermelon': '#fd4659',\n 'deep sky blue': '#0d75f8',\n 'fire engine red': '#fe0002',\n 'yellow ochre': '#cb9d06',\n 'pumpkin orange': '#fb7d07',\n 'pale olive': '#b9cc81',\n 'light lilac': '#edc8ff',\n 'lightish green': '#61e160',\n 'carolina blue': '#8ab8fe',\n 'mulberry': '#920a4e',\n 'shocking pink': '#fe02a2',\n 'auburn': '#9a3001',\n 'bright lime green': '#65fe08',\n 'celadon': '#befdb7',\n 'pinkish brown': '#b17261',\n 'poo brown': '#885f01',\n 'bright sky blue': '#02ccfe',\n 'celery': '#c1fd95',\n 'dirt brown': '#836539',\n 'strawberry': '#fb2943',\n 'dark lime': '#84b701',\n 'copper': '#b66325',\n 'medium brown': '#7f5112',\n 'muted green': '#5fa052',\n "robin's egg": '#6dedfd',\n 'bright aqua': '#0bf9ea',\n 'bright lavender': '#c760ff',\n 'ivory': '#ffffcb',\n 'very light purple': '#f6cefc',\n 'light navy': '#155084',\n 'pink red': '#f5054f',\n 'olive brown': '#645403',\n 'poop brown': '#7a5901',\n 'mustard green': '#a8b504',\n 'ocean green': '#3d9973',\n 'very dark blue': '#000133',\n 'dusty green': '#76a973',\n 'light navy blue': '#2e5a88',\n 'minty green': '#0bf77d',\n 'adobe': '#bd6c48',\n 'barney': '#ac1db8',\n 'jade green': '#2baf6a',\n 'bright light blue': '#26f7fd',\n 'light lime': '#aefd6c',\n 'dark khaki': '#9b8f55',\n 'orange yellow': '#ffad01',\n 'ocre': '#c69c04',\n 'maize': '#f4d054',\n 'faded pink': '#de9dac',\n 'british racing green': '#05480d',\n 'sandstone': '#c9ae74',\n 'mud brown': '#60460f',\n 'light sea green': '#98f6b0',\n 'robin egg blue': '#8af1fe',\n 'aqua marine': '#2ee8bb',\n 'dark sea green': '#11875d',\n 'soft pink': '#fdb0c0',\n 'orangey brown': '#b16002',\n 'cherry red': '#f7022a',\n 'burnt yellow': '#d5ab09',\n 'brownish grey': '#86775f',\n 'camel': '#c69f59',\n 'purplish grey': '#7a687f',\n 'marine': '#042e60',\n 'greyish pink': '#c88d94',\n 'pale turquoise': '#a5fbd5',\n 'pastel yellow': '#fffe71',\n 'bluey purple': '#6241c7',\n 'canary yellow': '#fffe40',\n 'faded red': '#d3494e',\n 'sepia': '#985e2b',\n 'coffee': '#a6814c',\n 'bright magenta': '#ff08e8',\n 'mocha': '#9d7651',\n 'ecru': '#feffca',\n 'purpleish': '#98568d',\n 'cranberry': '#9e003a',\n 'darkish green': '#287c37',\n 'brown orange': '#b96902',\n 'dusky rose': '#ba6873',\n 'melon': '#ff7855',\n 'sickly green': '#94b21c',\n 'silver': '#c5c9c7',\n 'purply blue': '#661aee',\n 'purpleish blue': '#6140ef',\n 'hospital green': '#9be5aa',\n 'shit brown': '#7b5804',\n 'mid blue': '#276ab3',\n 'amber': '#feb308',\n 'easter green': '#8cfd7e',\n 'soft blue': '#6488ea',\n 'cerulean blue': '#056eee',\n 'golden brown': '#b27a01',\n 'bright turquoise': '#0ffef9',\n 'red pink': '#fa2a55',\n 'red purple': '#820747',\n 'greyish brown': '#7a6a4f',\n 'vermillion': '#f4320c',\n 'russet': '#a13905',\n 'steel grey': '#6f828a',\n 'lighter purple': '#a55af4',\n 'bright violet': '#ad0afd',\n 'prussian blue': '#004577',\n 'slate green': '#658d6d',\n 'dirty pink': '#ca7b80',\n 'dark blue green': '#005249',\n 'pine': '#2b5d34',\n 'yellowy green': '#bff128',\n 'dark gold': '#b59410',\n 'bluish': '#2976bb',\n 'darkish blue': '#014182',\n 'dull red': '#bb3f3f',\n 'pinky red': '#fc2647',\n 'bronze': '#a87900',\n 'pale teal': '#82cbb2',\n 'military green': '#667c3e',\n 'barbie pink': '#fe46a5',\n 'bubblegum pink': '#fe83cc',\n 'pea soup green': '#94a617',\n 'dark mustard': '#a88905',\n 'shit': '#7f5f00',\n 'medium purple': '#9e43a2',\n 'very dark green': '#062e03',\n 'dirt': '#8a6e45',\n 'dusky pink': '#cc7a8b',\n 'red violet': '#9e0168',\n 'lemon yellow': '#fdff38',\n 'pistachio': '#c0fa8b',\n 'dull yellow': '#eedc5b',\n 'dark lime green': '#7ebd01',\n 'denim blue': '#3b5b92',\n 'teal blue': '#01889f',\n 'lightish blue': '#3d7afd',\n 'purpley blue': '#5f34e7',\n 'light indigo': '#6d5acf',\n 'swamp green': '#748500',\n 'brown green': '#706c11',\n 'dark maroon': '#3c0008',\n 'hot purple': '#cb00f5',\n 'dark forest green': '#002d04',\n 'faded blue': '#658cbb',\n 'drab green': '#749551',\n 'light lime green': '#b9ff66',\n 'snot green': '#9dc100',\n 'yellowish': '#faee66',\n 'light blue green': '#7efbb3',\n 'bordeaux': '#7b002c',\n 'light mauve': '#c292a1',\n 'ocean': '#017b92',\n 'marigold': '#fcc006',\n 'muddy green': '#657432',\n 'dull orange': '#d8863b',\n 'steel': '#738595',\n 'electric purple': '#aa23ff',\n 'fluorescent green': '#08ff08',\n 'yellowish brown': '#9b7a01',\n 'blush': '#f29e8e',\n 'soft green': '#6fc276',\n 'bright orange': '#ff5b00',\n 'lemon': '#fdff52',\n 'purple grey': '#866f85',\n 'acid green': '#8ffe09',\n 'pale lavender': '#eecffe',\n 'violet blue': '#510ac9',\n 'light forest green': '#4f9153',\n 'burnt red': '#9f2305',\n 'khaki green': '#728639',\n 'cerise': '#de0c62',\n 'faded purple': '#916e99',\n 'apricot': '#ffb16d',\n 'dark olive green': '#3c4d03',\n 'grey brown': '#7f7053',\n 'green grey': '#77926f',\n 'true blue': '#010fcc',\n 'pale violet': '#ceaefa',\n 'periwinkle blue': '#8f99fb',\n 'light sky blue': '#c6fcff',\n 'blurple': '#5539cc',\n 'green brown': '#544e03',\n 'bluegreen': '#017a79',\n 'bright teal': '#01f9c6',\n 'brownish yellow': '#c9b003',\n 'pea soup': '#929901',\n 'forest': '#0b5509',\n 'barney purple': '#a00498',\n 'ultramarine': '#2000b1',\n 'purplish': '#94568c',\n 'puke yellow': '#c2be0e',\n 'bluish grey': '#748b97',\n 'dark periwinkle': '#665fd1',\n 'dark lilac': '#9c6da5',\n 'reddish': '#c44240',\n 'light maroon': '#a24857',\n 'dusty purple': '#825f87',\n 'terra cotta': '#c9643b',\n 'avocado': '#90b134',\n 'marine blue': '#01386a',\n 'teal green': '#25a36f',\n 'slate grey': '#59656d',\n 'lighter green': '#75fd63',\n 'electric green': '#21fc0d',\n 'dusty blue': '#5a86ad',\n 'golden yellow': '#fec615',\n 'bright yellow': '#fffd01',\n 'light lavender': '#dfc5fe',\n 'umber': '#b26400',\n 'poop': '#7f5e00',\n 'dark peach': '#de7e5d',\n 'jungle green': '#048243',\n 'eggshell': '#ffffd4',\n 'denim': '#3b638c',\n 'yellow brown': '#b79400',\n 'dull purple': '#84597e',\n 'chocolate brown': '#411900',\n 'wine red': '#7b0323',\n 'neon blue': '#04d9ff',\n 'dirty green': '#667e2c',\n 'light tan': '#fbeeac',\n 'ice blue': '#d7fffe',\n 'cadet blue': '#4e7496',\n 'dark mauve': '#874c62',\n 'very light blue': '#d5ffff',\n 'grey purple': '#826d8c',\n 'pastel pink': '#ffbacd',\n 'very light green': '#d1ffbd',\n 'dark sky blue': '#448ee4',\n 'evergreen': '#05472a',\n 'dull pink': '#d5869d',\n 'aubergine': '#3d0734',\n 'mahogany': '#4a0100',\n 'reddish orange': '#f8481c',\n 'deep green': '#02590f',\n 'vomit green': '#89a203',\n 'purple pink': '#e03fd8',\n 'dusty pink': '#d58a94',\n 'faded green': '#7bb274',\n 'camo green': '#526525',\n 'pinky purple': '#c94cbe',\n 'pink purple': '#db4bda',\n 'brownish red': '#9e3623',\n 'dark rose': '#b5485d',\n 'mud': '#735c12',\n 'brownish': '#9c6d57',\n 'emerald green': '#028f1e',\n 'pale brown': '#b1916e',\n 'dull blue': '#49759c',\n 'burnt umber': '#a0450e',\n 'medium green': '#39ad48',\n 'clay': '#b66a50',\n 'light aqua': '#8cffdb',\n 'light olive green': '#a4be5c',\n 'brownish orange': '#cb7723',\n 'dark aqua': '#05696b',\n 'purplish pink': '#ce5dae',\n 'dark salmon': '#c85a53',\n 'greenish grey': '#96ae8d',\n 'jade': '#1fa774',\n 'ugly green': '#7a9703',\n 'dark beige': '#ac9362',\n 'emerald': '#01a049',\n 'pale red': '#d9544d',\n 'light magenta': '#fa5ff7',\n 'sky': '#82cafc',\n 'light cyan': '#acfffc',\n 'yellow orange': '#fcb001',\n 'reddish purple': '#910951',\n 'reddish pink': '#fe2c54',\n 'orchid': '#c875c4',\n 'dirty yellow': '#cdc50a',\n 'orange red': '#fd411e',\n 'deep red': '#9a0200',\n 'orange brown': '#be6400',\n 'cobalt blue': '#030aa7',\n 'neon pink': '#fe019a',\n 'rose pink': '#f7879a',\n 'greyish purple': '#887191',\n 'raspberry': '#b00149',\n 'aqua green': '#12e193',\n 'salmon pink': '#fe7b7c',\n 'tangerine': '#ff9408',\n 'brownish green': '#6a6e09',\n 'red brown': '#8b2e16',\n 'greenish brown': '#696112',\n 'pumpkin': '#e17701',\n 'pine green': '#0a481e',\n 'charcoal': '#343837',\n 'baby pink': '#ffb7ce',\n 'cornflower': '#6a79f7',\n 'blue violet': '#5d06e9',\n 'chocolate': '#3d1c02',\n 'greyish green': '#82a67d',\n 'scarlet': '#be0119',\n 'green yellow': '#c9ff27',\n 'dark olive': '#373e02',\n 'sienna': '#a9561e',\n 'pastel purple': '#caa0ff',\n 'terracotta': '#ca6641',\n 'aqua blue': '#02d8e9',\n 'sage green': '#88b378',\n 'blood red': '#980002',\n 'deep pink': '#cb0162',\n 'grass': '#5cac2d',\n 'moss': '#769958',\n 'pastel blue': '#a2bffe',\n 'bluish green': '#10a674',\n 'green blue': '#06b48b',\n 'dark tan': '#af884a',\n 'greenish blue': '#0b8b87',\n 'pale orange': '#ffa756',\n 'vomit': '#a2a415',\n 'forrest green': '#154406',\n 'dark lavender': '#856798',\n 'dark violet': '#34013f',\n 'purple blue': '#632de9',\n 'dark cyan': '#0a888a',\n 'olive drab': '#6f7632',\n 'pinkish': '#d46a7e',\n 'cobalt': '#1e488f',\n 'neon purple': '#bc13fe',\n 'light turquoise': '#7ef4cc',\n 'apple green': '#76cd26',\n 'dull green': '#74a662',\n 'wine': '#80013f',\n 'powder blue': '#b1d1fc',\n 'off white': '#ffffe4',\n 'electric blue': '#0652ff',\n 'dark turquoise': '#045c5a',\n 'blue purple': '#5729ce',\n 'azure': '#069af3',\n 'bright red': '#ff000d',\n 'pinkish red': '#f10c45',\n 'cornflower blue': '#5170d7',\n 'light olive': '#acbf69',\n 'grape': '#6c3461',\n 'greyish blue': '#5e819d',\n 'purplish blue': '#601ef9',\n 'yellowish green': '#b0dd16',\n 'greenish yellow': '#cdfd02',\n 'medium blue': '#2c6fbb',\n 'dusty rose': '#c0737a',\n 'light violet': '#d6b4fc',\n 'midnight blue': '#020035',\n 'bluish purple': '#703be7',\n 'red orange': '#fd3c06',\n 'dark magenta': '#960056',\n 'greenish': '#40a368',\n 'ocean blue': '#03719c',\n 'coral': '#fc5a50',\n 'cream': '#ffffc2',\n 'reddish brown': '#7f2b0a',\n 'burnt sienna': '#b04e0f',\n 'brick': '#a03623',\n 'sage': '#87ae73',\n 'grey green': '#789b73',\n 'white': '#ffffff',\n "robin's egg blue": '#98eff9',\n 'moss green': '#658b38',\n 'steel blue': '#5a7d9a',\n 'eggplant': '#380835',\n 'light yellow': '#fffe7a',\n 'leaf green': '#5ca904',\n 'light grey': '#d8dcd6',\n 'puke': '#a5a502',\n 'pinkish purple': '#d648d7',\n 'sea blue': '#047495',\n 'pale purple': '#b790d4',\n 'slate blue': '#5b7c99',\n 'blue grey': '#607c8e',\n 'hunter green': '#0b4008',\n 'fuchsia': '#ed0dd9',\n 'crimson': '#8c000f',\n 'pale yellow': '#ffff84',\n 'ochre': '#bf9005',\n 'mustard yellow': '#d2bd0a',\n 'light red': '#ff474c',\n 'cerulean': '#0485d1',\n 'pale pink': '#ffcfdc',\n 'deep blue': '#040273',\n 'rust': '#a83c09',\n 'light teal': '#90e4c1',\n 'slate': '#516572',\n 'goldenrod': '#fac205',\n 'dark yellow': '#d5b60a',\n 'dark grey': '#363737',\n 'army green': '#4b5d16',\n 'grey blue': '#6b8ba4',\n 'seafoam': '#80f9ad',\n 'puce': '#a57e52',\n 'spring green': '#a9f971',\n 'dark orange': '#c65102',\n 'sand': '#e2ca76',\n 'pastel green': '#b0ff9d',\n 'mint': '#9ffeb0',\n 'light orange': '#fdaa48',\n 'bright pink': '#fe01b1',\n 'chartreuse': '#c1f80a',\n 'deep purple': '#36013f',\n 'dark brown': '#341c02',\n 'taupe': '#b9a281',\n 'pea green': '#8eab12',\n 'puke green': '#9aae07',\n 'kelly green': '#02ab2e',\n 'seafoam green': '#7af9ab',\n 'blue green': '#137e6d',\n 'khaki': '#aaa662',\n 'burgundy': '#610023',\n 'dark teal': '#014d4e',\n 'brick red': '#8f1402',\n 'royal purple': '#4b006e',\n 'plum': '#580f41',\n 'mint green': '#8fff9f',\n 'gold': '#dbb40c',\n 'baby blue': '#a2cffe',\n 'yellow green': '#c0fb2d',\n 'bright purple': '#be03fd',\n 'dark red': '#840000',\n 'pale blue': '#d0fefe',\n 'grass green': '#3f9b0b',\n 'navy': '#01153e',\n 'aquamarine': '#04d8b2',\n 'burnt orange': '#c04e01',\n 'neon green': '#0cff0c',\n 'bright blue': '#0165fc',\n 'rose': '#cf6275',\n 'light pink': '#ffd1df',\n 'mustard': '#ceb301',\n 'indigo': '#380282',\n 'lime': '#aaff32',\n 'sea green': '#53fca1',\n 'periwinkle': '#8e82fe',\n 'dark pink': '#cb416b',\n 'olive green': '#677a04',\n 'peach': '#ffb07c',\n 'pale green': '#c7fdb5',\n 'light brown': '#ad8150',\n 'hot pink': '#ff028d',\n 'black': '#000000',\n 'lilac': '#cea2fd',\n 'navy blue': '#001146',\n 'royal blue': '#0504aa',\n 'beige': '#e6daa6',\n 'salmon': '#ff796c',\n 'olive': '#6e750e',\n 'maroon': '#650021',\n 'bright green': '#01ff07',\n 'dark purple': '#35063e',\n 'mauve': '#ae7181',\n 'forest green': '#06470c',\n 'aqua': '#13eac9',\n 'cyan': '#00ffff',\n 'tan': '#d1b26f',\n 'dark blue': '#00035b',\n 'lavender': '#c79fef',\n 'turquoise': '#06c2ac',\n 'dark green': '#033500',\n 'violet': '#9a0eea',\n 'light purple': '#bf77f6',\n 'lime green': '#89fe05',\n 'grey': '#929591',\n 'sky blue': '#75bbfd',\n 'yellow': '#ffff14',\n 'magenta': '#c20078',\n 'light green': '#96f97b',\n 'orange': '#f97306',\n 'teal': '#029386',\n 'light blue': '#95d0fc',\n 'red': '#e50000',\n 'brown': '#653700',\n 'pink': '#ff81c0',\n 'blue': '#0343df',\n 'green': '#15b01a',\n 'purple': '#7e1e9c'}\n\n# Normalize name to "xkcd:<name>" to avoid name collisions.\nXKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}\n\n\n# https://drafts.csswg.org/css-color-4/#named-colors\nCSS4_COLORS = {\n 'aliceblue': '#F0F8FF',\n 'antiquewhite': '#FAEBD7',\n 'aqua': '#00FFFF',\n 'aquamarine': '#7FFFD4',\n 'azure': '#F0FFFF',\n 'beige': '#F5F5DC',\n 'bisque': '#FFE4C4',\n 'black': '#000000',\n 'blanchedalmond': '#FFEBCD',\n 'blue': '#0000FF',\n 'blueviolet': '#8A2BE2',\n 'brown': '#A52A2A',\n 'burlywood': '#DEB887',\n 'cadetblue': '#5F9EA0',\n 'chartreuse': '#7FFF00',\n 'chocolate': '#D2691E',\n 'coral': '#FF7F50',\n 'cornflowerblue': '#6495ED',\n 'cornsilk': '#FFF8DC',\n 'crimson': '#DC143C',\n 'cyan': '#00FFFF',\n 'darkblue': '#00008B',\n 'darkcyan': '#008B8B',\n 'darkgoldenrod': '#B8860B',\n 'darkgray': '#A9A9A9',\n 'darkgreen': '#006400',\n 'darkgrey': '#A9A9A9',\n 'darkkhaki': '#BDB76B',\n 'darkmagenta': '#8B008B',\n 'darkolivegreen': '#556B2F',\n 'darkorange': '#FF8C00',\n 'darkorchid': '#9932CC',\n 'darkred': '#8B0000',\n 'darksalmon': '#E9967A',\n 'darkseagreen': '#8FBC8F',\n 'darkslateblue': '#483D8B',\n 'darkslategray': '#2F4F4F',\n 'darkslategrey': '#2F4F4F',\n 'darkturquoise': '#00CED1',\n 'darkviolet': '#9400D3',\n 'deeppink': '#FF1493',\n 'deepskyblue': '#00BFFF',\n 'dimgray': '#696969',\n 'dimgrey': '#696969',\n 'dodgerblue': '#1E90FF',\n 'firebrick': '#B22222',\n 'floralwhite': '#FFFAF0',\n 'forestgreen': '#228B22',\n 'fuchsia': '#FF00FF',\n 'gainsboro': '#DCDCDC',\n 'ghostwhite': '#F8F8FF',\n 'gold': '#FFD700',\n 'goldenrod': '#DAA520',\n 'gray': '#808080',\n 'green': '#008000',\n 'greenyellow': '#ADFF2F',\n 'grey': '#808080',\n 'honeydew': '#F0FFF0',\n 'hotpink': '#FF69B4',\n 'indianred': '#CD5C5C',\n 'indigo': '#4B0082',\n 'ivory': '#FFFFF0',\n 'khaki': '#F0E68C',\n 'lavender': '#E6E6FA',\n 'lavenderblush': '#FFF0F5',\n 'lawngreen': '#7CFC00',\n 'lemonchiffon': '#FFFACD',\n 'lightblue': '#ADD8E6',\n 'lightcoral': '#F08080',\n 'lightcyan': '#E0FFFF',\n 'lightgoldenrodyellow': '#FAFAD2',\n 'lightgray': '#D3D3D3',\n 'lightgreen': '#90EE90',\n 'lightgrey': '#D3D3D3',\n 'lightpink': '#FFB6C1',\n 'lightsalmon': '#FFA07A',\n 'lightseagreen': '#20B2AA',\n 'lightskyblue': '#87CEFA',\n 'lightslategray': '#778899',\n 'lightslategrey': '#778899',\n 'lightsteelblue': '#B0C4DE',\n 'lightyellow': '#FFFFE0',\n 'lime': '#00FF00',\n 'limegreen': '#32CD32',\n 'linen': '#FAF0E6',\n 'magenta': '#FF00FF',\n 'maroon': '#800000',\n 'mediumaquamarine': '#66CDAA',\n 'mediumblue': '#0000CD',\n 'mediumorchid': '#BA55D3',\n 'mediumpurple': '#9370DB',\n 'mediumseagreen': '#3CB371',\n 'mediumslateblue': '#7B68EE',\n 'mediumspringgreen': '#00FA9A',\n 'mediumturquoise': '#48D1CC',\n 'mediumvioletred': '#C71585',\n 'midnightblue': '#191970',\n 'mintcream': '#F5FFFA',\n 'mistyrose': '#FFE4E1',\n 'moccasin': '#FFE4B5',\n 'navajowhite': '#FFDEAD',\n 'navy': '#000080',\n 'oldlace': '#FDF5E6',\n 'olive': '#808000',\n 'olivedrab': '#6B8E23',\n 'orange': '#FFA500',\n 'orangered': '#FF4500',\n 'orchid': '#DA70D6',\n 'palegoldenrod': '#EEE8AA',\n 'palegreen': '#98FB98',\n 'paleturquoise': '#AFEEEE',\n 'palevioletred': '#DB7093',\n 'papayawhip': '#FFEFD5',\n 'peachpuff': '#FFDAB9',\n 'peru': '#CD853F',\n 'pink': '#FFC0CB',\n 'plum': '#DDA0DD',\n 'powderblue': '#B0E0E6',\n 'purple': '#800080',\n 'rebeccapurple': '#663399',\n 'red': '#FF0000',\n 'rosybrown': '#BC8F8F',\n 'royalblue': '#4169E1',\n 'saddlebrown': '#8B4513',\n 'salmon': '#FA8072',\n 'sandybrown': '#F4A460',\n 'seagreen': '#2E8B57',\n 'seashell': '#FFF5EE',\n 'sienna': '#A0522D',\n 'silver': '#C0C0C0',\n 'skyblue': '#87CEEB',\n 'slateblue': '#6A5ACD',\n 'slategray': '#708090',\n 'slategrey': '#708090',\n 'snow': '#FFFAFA',\n 'springgreen': '#00FF7F',\n 'steelblue': '#4682B4',\n 'tan': '#D2B48C',\n 'teal': '#008080',\n 'thistle': '#D8BFD8',\n 'tomato': '#FF6347',\n 'turquoise': '#40E0D0',\n 'violet': '#EE82EE',\n 'wheat': '#F5DEB3',\n 'white': '#FFFFFF',\n 'whitesmoke': '#F5F5F5',\n 'yellow': '#FFFF00',\n 'yellowgreen': '#9ACD32'}\n
.venv\Lib\site-packages\matplotlib\_color_data.py
_color_data.py
Python
34,780
0.8
0.001753
0.010582
awesome-app
756
2024-06-13T06:18:38.693390
BSD-3-Clause
false
6764929e6730c452b657f2b27b5e9554
from .typing import ColorType\n\nBASE_COLORS: dict[str, ColorType]\nTABLEAU_COLORS: dict[str, ColorType]\nXKCD_COLORS: dict[str, ColorType]\nCSS4_COLORS: dict[str, ColorType]\n
.venv\Lib\site-packages\matplotlib\_color_data.pyi
_color_data.pyi
Other
170
0.85
0
0
awesome-app
43
2024-03-18T21:49:51.618871
BSD-3-Clause
false
a264b19450e5497fdc1fd7be44fd4aa2
"""\nAdjust subplot layouts so that there are no overlapping Axes or Axes\ndecorations. All Axes decorations are dealt with (labels, ticks, titles,\nticklabels) and some dependent artists are also dealt with (colorbar,\nsuptitle).\n\nLayout is done via `~matplotlib.gridspec`, with one constraint per gridspec,\nso it is possible to have overlapping Axes if the gridspecs overlap (i.e.\nusing `~matplotlib.gridspec.GridSpecFromSubplotSpec`). Axes placed using\n``figure.subplots()`` or ``figure.add_subplots()`` will participate in the\nlayout. Axes manually placed via ``figure.add_axes()`` will not.\n\nSee Tutorial: :ref:`constrainedlayout_guide`\n\nGeneral idea:\n-------------\n\nFirst, a figure has a gridspec that divides the figure into nrows and ncols,\nwith heights and widths set by ``height_ratios`` and ``width_ratios``,\noften just set to 1 for an equal grid.\n\nSubplotspecs that are derived from this gridspec can contain either a\n``SubPanel``, a ``GridSpecFromSubplotSpec``, or an ``Axes``. The ``SubPanel``\nand ``GridSpecFromSubplotSpec`` are dealt with recursively and each contain an\nanalogous layout.\n\nEach ``GridSpec`` has a ``_layoutgrid`` attached to it. The ``_layoutgrid``\nhas the same logical layout as the ``GridSpec``. Each row of the grid spec\nhas a top and bottom "margin" and each column has a left and right "margin".\nThe "inner" height of each row is constrained to be the same (or as modified\nby ``height_ratio``), and the "inner" width of each column is\nconstrained to be the same (as modified by ``width_ratio``), where "inner"\nis the width or height of each column/row minus the size of the margins.\n\nThen the size of the margins for each row and column are determined as the\nmax width of the decorators on each Axes that has decorators in that margin.\nFor instance, a normal Axes would have a left margin that includes the\nleft ticklabels, and the ylabel if it exists. The right margin may include a\ncolorbar, the bottom margin the xaxis decorations, and the top margin the\ntitle.\n\nWith these constraints, the solver then finds appropriate bounds for the\ncolumns and rows. It's possible that the margins take up the whole figure,\nin which case the algorithm is not applied and a warning is raised.\n\nSee the tutorial :ref:`constrainedlayout_guide`\nfor more discussion of the algorithm with examples.\n"""\n\nimport logging\n\nimport numpy as np\n\nfrom matplotlib import _api, artist as martist\nimport matplotlib.transforms as mtransforms\nimport matplotlib._layoutgrid as mlayoutgrid\n\n\n_log = logging.getLogger(__name__)\n\n\n######################################################\ndef do_constrained_layout(fig, h_pad, w_pad,\n hspace=None, wspace=None, rect=(0, 0, 1, 1),\n compress=False):\n """\n Do the constrained_layout. Called at draw time in\n ``figure.constrained_layout()``\n\n Parameters\n ----------\n fig : `~matplotlib.figure.Figure`\n `.Figure` instance to do the layout in.\n\n h_pad, w_pad : float\n Padding around the Axes elements in figure-normalized units.\n\n hspace, wspace : float\n Fraction of the figure to dedicate to space between the\n Axes. These are evenly spread between the gaps between the Axes.\n A value of 0.2 for a three-column layout would have a space\n of 0.1 of the figure width between each column.\n If h/wspace < h/w_pad, then the pads are used instead.\n\n rect : tuple of 4 floats\n Rectangle in figure coordinates to perform constrained layout in\n [left, bottom, width, height], each from 0-1.\n\n compress : bool\n Whether to shift Axes so that white space in between them is\n removed. This is useful for simple grids of fixed-aspect Axes (e.g.\n a grid of images).\n\n Returns\n -------\n layoutgrid : private debugging structure\n """\n\n renderer = fig._get_renderer()\n # make layoutgrid tree...\n layoutgrids = make_layoutgrids(fig, None, rect=rect)\n if not layoutgrids['hasgrids']:\n _api.warn_external('There are no gridspecs with layoutgrids. '\n 'Possibly did not call parent GridSpec with the'\n ' "figure" keyword')\n return\n\n for _ in range(2):\n # do the algorithm twice. This has to be done because decorations\n # change size after the first re-position (i.e. x/yticklabels get\n # larger/smaller). This second reposition tends to be much milder,\n # so doing twice makes things work OK.\n\n # make margins for all the Axes and subfigures in the\n # figure. Add margins for colorbars...\n make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad,\n w_pad=w_pad, hspace=hspace, wspace=wspace)\n make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad,\n w_pad=w_pad)\n\n # if a layout is such that a columns (or rows) margin has no\n # constraints, we need to make all such instances in the grid\n # match in margin size.\n match_submerged_margins(layoutgrids, fig)\n\n # update all the variables in the layout.\n layoutgrids[fig].update_variables()\n\n warn_collapsed = ('constrained_layout not applied because '\n 'axes sizes collapsed to zero. Try making '\n 'figure larger or Axes decorations smaller.')\n if check_no_collapsed_axes(layoutgrids, fig):\n reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,\n w_pad=w_pad, hspace=hspace, wspace=wspace)\n if compress:\n layoutgrids = compress_fixed_aspect(layoutgrids, fig)\n layoutgrids[fig].update_variables()\n if check_no_collapsed_axes(layoutgrids, fig):\n reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,\n w_pad=w_pad, hspace=hspace, wspace=wspace)\n else:\n _api.warn_external(warn_collapsed)\n\n if ((suptitle := fig._suptitle) is not None and\n suptitle.get_in_layout() and suptitle._autopos):\n x, _ = suptitle.get_position()\n suptitle.set_position(\n (x, layoutgrids[fig].get_inner_bbox().y1 + h_pad))\n suptitle.set_verticalalignment('bottom')\n else:\n _api.warn_external(warn_collapsed)\n reset_margins(layoutgrids, fig)\n return layoutgrids\n\n\ndef make_layoutgrids(fig, layoutgrids, rect=(0, 0, 1, 1)):\n """\n Make the layoutgrid tree.\n\n (Sub)Figures get a layoutgrid so we can have figure margins.\n\n Gridspecs that are attached to Axes get a layoutgrid so Axes\n can have margins.\n """\n\n if layoutgrids is None:\n layoutgrids = dict()\n layoutgrids['hasgrids'] = False\n if not hasattr(fig, '_parent'):\n # top figure; pass rect as parent to allow user-specified\n # margins\n layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=rect, name='figlb')\n else:\n # subfigure\n gs = fig._subplotspec.get_gridspec()\n # it is possible the gridspec containing this subfigure hasn't\n # been added to the tree yet:\n layoutgrids = make_layoutgrids_gs(layoutgrids, gs)\n # add the layoutgrid for the subfigure:\n parentlb = layoutgrids[gs]\n layoutgrids[fig] = mlayoutgrid.LayoutGrid(\n parent=parentlb,\n name='panellb',\n parent_inner=True,\n nrows=1, ncols=1,\n parent_pos=(fig._subplotspec.rowspan,\n fig._subplotspec.colspan))\n # recursively do all subfigures in this figure...\n for sfig in fig.subfigs:\n layoutgrids = make_layoutgrids(sfig, layoutgrids)\n\n # for each Axes at the local level add its gridspec:\n for ax in fig._localaxes:\n gs = ax.get_gridspec()\n if gs is not None:\n layoutgrids = make_layoutgrids_gs(layoutgrids, gs)\n\n return layoutgrids\n\n\ndef make_layoutgrids_gs(layoutgrids, gs):\n """\n Make the layoutgrid for a gridspec (and anything nested in the gridspec)\n """\n\n if gs in layoutgrids or gs.figure is None:\n return layoutgrids\n # in order to do constrained_layout there has to be at least *one*\n # gridspec in the tree:\n layoutgrids['hasgrids'] = True\n if not hasattr(gs, '_subplot_spec'):\n # normal gridspec\n parent = layoutgrids[gs.figure]\n layoutgrids[gs] = mlayoutgrid.LayoutGrid(\n parent=parent,\n parent_inner=True,\n name='gridspec',\n ncols=gs._ncols, nrows=gs._nrows,\n width_ratios=gs.get_width_ratios(),\n height_ratios=gs.get_height_ratios())\n else:\n # this is a gridspecfromsubplotspec:\n subplot_spec = gs._subplot_spec\n parentgs = subplot_spec.get_gridspec()\n # if a nested gridspec it is possible the parent is not in there yet:\n if parentgs not in layoutgrids:\n layoutgrids = make_layoutgrids_gs(layoutgrids, parentgs)\n subspeclb = layoutgrids[parentgs]\n # gridspecfromsubplotspec need an outer container:\n # get a unique representation:\n rep = (gs, 'top')\n if rep not in layoutgrids:\n layoutgrids[rep] = mlayoutgrid.LayoutGrid(\n parent=subspeclb,\n name='top',\n nrows=1, ncols=1,\n parent_pos=(subplot_spec.rowspan, subplot_spec.colspan))\n layoutgrids[gs] = mlayoutgrid.LayoutGrid(\n parent=layoutgrids[rep],\n name='gridspec',\n nrows=gs._nrows, ncols=gs._ncols,\n width_ratios=gs.get_width_ratios(),\n height_ratios=gs.get_height_ratios())\n return layoutgrids\n\n\ndef check_no_collapsed_axes(layoutgrids, fig):\n """\n Check that no Axes have collapsed to zero size.\n """\n for sfig in fig.subfigs:\n ok = check_no_collapsed_axes(layoutgrids, sfig)\n if not ok:\n return False\n for ax in fig.axes:\n gs = ax.get_gridspec()\n if gs in layoutgrids: # also implies gs is not None.\n lg = layoutgrids[gs]\n for i in range(gs.nrows):\n for j in range(gs.ncols):\n bb = lg.get_inner_bbox(i, j)\n if bb.width <= 0 or bb.height <= 0:\n return False\n return True\n\n\ndef compress_fixed_aspect(layoutgrids, fig):\n gs = None\n for ax in fig.axes:\n if ax.get_subplotspec() is None:\n continue\n ax.apply_aspect()\n sub = ax.get_subplotspec()\n _gs = sub.get_gridspec()\n if gs is None:\n gs = _gs\n extraw = np.zeros(gs.ncols)\n extrah = np.zeros(gs.nrows)\n elif _gs != gs:\n raise ValueError('Cannot do compressed layout if Axes are not'\n 'all from the same gridspec')\n orig = ax.get_position(original=True)\n actual = ax.get_position(original=False)\n dw = orig.width - actual.width\n if dw > 0:\n extraw[sub.colspan] = np.maximum(extraw[sub.colspan], dw)\n dh = orig.height - actual.height\n if dh > 0:\n extrah[sub.rowspan] = np.maximum(extrah[sub.rowspan], dh)\n\n if gs is None:\n raise ValueError('Cannot do compressed layout if no Axes '\n 'are part of a gridspec.')\n w = np.sum(extraw) / 2\n layoutgrids[fig].edit_margin_min('left', w)\n layoutgrids[fig].edit_margin_min('right', w)\n\n h = np.sum(extrah) / 2\n layoutgrids[fig].edit_margin_min('top', h)\n layoutgrids[fig].edit_margin_min('bottom', h)\n return layoutgrids\n\n\ndef get_margin_from_padding(obj, *, w_pad=0, h_pad=0,\n hspace=0, wspace=0):\n\n ss = obj._subplotspec\n gs = ss.get_gridspec()\n\n if hasattr(gs, 'hspace'):\n _hspace = (gs.hspace if gs.hspace is not None else hspace)\n _wspace = (gs.wspace if gs.wspace is not None else wspace)\n else:\n _hspace = (gs._hspace if gs._hspace is not None else hspace)\n _wspace = (gs._wspace if gs._wspace is not None else wspace)\n\n _wspace = _wspace / 2\n _hspace = _hspace / 2\n\n nrows, ncols = gs.get_geometry()\n # there are two margins for each direction. The "cb"\n # margins are for pads and colorbars, the non-"cb" are\n # for the Axes decorations (labels etc).\n margin = {'leftcb': w_pad, 'rightcb': w_pad,\n 'bottomcb': h_pad, 'topcb': h_pad,\n 'left': 0, 'right': 0,\n 'top': 0, 'bottom': 0}\n if _wspace / ncols > w_pad:\n if ss.colspan.start > 0:\n margin['leftcb'] = _wspace / ncols\n if ss.colspan.stop < ncols:\n margin['rightcb'] = _wspace / ncols\n if _hspace / nrows > h_pad:\n if ss.rowspan.stop < nrows:\n margin['bottomcb'] = _hspace / nrows\n if ss.rowspan.start > 0:\n margin['topcb'] = _hspace / nrows\n\n return margin\n\n\ndef make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,\n hspace=0, wspace=0):\n """\n For each Axes, make a margin between the *pos* layoutbox and the\n *axes* layoutbox be a minimum size that can accommodate the\n decorations on the axis.\n\n Then make room for colorbars.\n\n Parameters\n ----------\n layoutgrids : dict\n fig : `~matplotlib.figure.Figure`\n `.Figure` instance to do the layout in.\n renderer : `~matplotlib.backend_bases.RendererBase` subclass.\n The renderer to use.\n w_pad, h_pad : float, default: 0\n Width and height padding (in fraction of figure).\n hspace, wspace : float, default: 0\n Width and height padding as fraction of figure size divided by\n number of columns or rows.\n """\n for sfig in fig.subfigs: # recursively make child panel margins\n ss = sfig._subplotspec\n gs = ss.get_gridspec()\n\n make_layout_margins(layoutgrids, sfig, renderer,\n w_pad=w_pad, h_pad=h_pad,\n hspace=hspace, wspace=wspace)\n\n margins = get_margin_from_padding(sfig, w_pad=0, h_pad=0,\n hspace=hspace, wspace=wspace)\n layoutgrids[gs].edit_outer_margin_mins(margins, ss)\n\n for ax in fig._localaxes:\n if not ax.get_subplotspec() or not ax.get_in_layout():\n continue\n\n ss = ax.get_subplotspec()\n gs = ss.get_gridspec()\n\n if gs not in layoutgrids:\n return\n\n margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad,\n hspace=hspace, wspace=wspace)\n pos, bbox = get_pos_and_bbox(ax, renderer)\n # the margin is the distance between the bounding box of the Axes\n # and its position (plus the padding from above)\n margin['left'] += pos.x0 - bbox.x0\n margin['right'] += bbox.x1 - pos.x1\n # remember that rows are ordered from top:\n margin['bottom'] += pos.y0 - bbox.y0\n margin['top'] += bbox.y1 - pos.y1\n\n # make margin for colorbars. These margins go in the\n # padding margin, versus the margin for Axes decorators.\n for cbax in ax._colorbars:\n # note pad is a fraction of the parent width...\n pad = colorbar_get_pad(layoutgrids, cbax)\n # colorbars can be child of more than one subplot spec:\n cbp_rspan, cbp_cspan = get_cb_parent_spans(cbax)\n loc = cbax._colorbar_info['location']\n cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)\n if loc == 'right':\n if cbp_cspan.stop == ss.colspan.stop:\n # only increase if the colorbar is on the right edge\n margin['rightcb'] += cbbbox.width + pad\n elif loc == 'left':\n if cbp_cspan.start == ss.colspan.start:\n # only increase if the colorbar is on the left edge\n margin['leftcb'] += cbbbox.width + pad\n elif loc == 'top':\n if cbp_rspan.start == ss.rowspan.start:\n margin['topcb'] += cbbbox.height + pad\n else:\n if cbp_rspan.stop == ss.rowspan.stop:\n margin['bottomcb'] += cbbbox.height + pad\n # If the colorbars are wider than the parent box in the\n # cross direction\n if loc in ['top', 'bottom']:\n if (cbp_cspan.start == ss.colspan.start and\n cbbbox.x0 < bbox.x0):\n margin['left'] += bbox.x0 - cbbbox.x0\n if (cbp_cspan.stop == ss.colspan.stop and\n cbbbox.x1 > bbox.x1):\n margin['right'] += cbbbox.x1 - bbox.x1\n # or taller:\n if loc in ['left', 'right']:\n if (cbp_rspan.stop == ss.rowspan.stop and\n cbbbox.y0 < bbox.y0):\n margin['bottom'] += bbox.y0 - cbbbox.y0\n if (cbp_rspan.start == ss.rowspan.start and\n cbbbox.y1 > bbox.y1):\n margin['top'] += cbbbox.y1 - bbox.y1\n # pass the new margins down to the layout grid for the solution...\n layoutgrids[gs].edit_outer_margin_mins(margin, ss)\n\n # make margins for figure-level legends:\n for leg in fig.legends:\n inv_trans_fig = None\n if leg._outside_loc and leg._bbox_to_anchor is None:\n if inv_trans_fig is None:\n inv_trans_fig = fig.transFigure.inverted().transform_bbox\n bbox = inv_trans_fig(leg.get_tightbbox(renderer))\n w = bbox.width + 2 * w_pad\n h = bbox.height + 2 * h_pad\n legendloc = leg._outside_loc\n if legendloc == 'lower':\n layoutgrids[fig].edit_margin_min('bottom', h)\n elif legendloc == 'upper':\n layoutgrids[fig].edit_margin_min('top', h)\n if legendloc == 'right':\n layoutgrids[fig].edit_margin_min('right', w)\n elif legendloc == 'left':\n layoutgrids[fig].edit_margin_min('left', w)\n\n\ndef make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):\n # Figure out how large the suptitle is and make the\n # top level figure margin larger.\n\n inv_trans_fig = fig.transFigure.inverted().transform_bbox\n # get the h_pad and w_pad as distances in the local subfigure coordinates:\n padbox = mtransforms.Bbox([[0, 0], [w_pad, h_pad]])\n padbox = (fig.transFigure -\n fig.transSubfigure).transform_bbox(padbox)\n h_pad_local = padbox.height\n w_pad_local = padbox.width\n\n for sfig in fig.subfigs:\n make_margin_suptitles(layoutgrids, sfig, renderer,\n w_pad=w_pad, h_pad=h_pad)\n\n if fig._suptitle is not None and fig._suptitle.get_in_layout():\n p = fig._suptitle.get_position()\n if getattr(fig._suptitle, '_autopos', False):\n fig._suptitle.set_position((p[0], 1 - h_pad_local))\n bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer))\n layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad)\n\n if fig._supxlabel is not None and fig._supxlabel.get_in_layout():\n p = fig._supxlabel.get_position()\n if getattr(fig._supxlabel, '_autopos', False):\n fig._supxlabel.set_position((p[0], h_pad_local))\n bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer))\n layoutgrids[fig].edit_margin_min('bottom',\n bbox.height + 2 * h_pad)\n\n if fig._supylabel is not None and fig._supylabel.get_in_layout():\n p = fig._supylabel.get_position()\n if getattr(fig._supylabel, '_autopos', False):\n fig._supylabel.set_position((w_pad_local, p[1]))\n bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer))\n layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad)\n\n\ndef match_submerged_margins(layoutgrids, fig):\n """\n Make the margins that are submerged inside an Axes the same size.\n\n This allows Axes that span two columns (or rows) that are offset\n from one another to have the same size.\n\n This gives the proper layout for something like::\n fig = plt.figure(constrained_layout=True)\n axs = fig.subplot_mosaic("AAAB\nCCDD")\n\n Without this routine, the Axes D will be wider than C, because the\n margin width between the two columns in C has no width by default,\n whereas the margins between the two columns of D are set by the\n width of the margin between A and B. However, obviously the user would\n like C and D to be the same size, so we need to add constraints to these\n "submerged" margins.\n\n This routine makes all the interior margins the same, and the spacing\n between the three columns in A and the two column in C are all set to the\n margins between the two columns of D.\n\n See test_constrained_layout::test_constrained_layout12 for an example.\n """\n\n for sfig in fig.subfigs:\n match_submerged_margins(layoutgrids, sfig)\n\n axs = [a for a in fig.get_axes()\n if a.get_subplotspec() is not None and a.get_in_layout()]\n\n for ax1 in axs:\n ss1 = ax1.get_subplotspec()\n if ss1.get_gridspec() not in layoutgrids:\n axs.remove(ax1)\n continue\n lg1 = layoutgrids[ss1.get_gridspec()]\n\n # interior columns:\n if len(ss1.colspan) > 1:\n maxsubl = np.max(\n lg1.margin_vals['left'][ss1.colspan[1:]] +\n lg1.margin_vals['leftcb'][ss1.colspan[1:]]\n )\n maxsubr = np.max(\n lg1.margin_vals['right'][ss1.colspan[:-1]] +\n lg1.margin_vals['rightcb'][ss1.colspan[:-1]]\n )\n for ax2 in axs:\n ss2 = ax2.get_subplotspec()\n lg2 = layoutgrids[ss2.get_gridspec()]\n if lg2 is not None and len(ss2.colspan) > 1:\n maxsubl2 = np.max(\n lg2.margin_vals['left'][ss2.colspan[1:]] +\n lg2.margin_vals['leftcb'][ss2.colspan[1:]])\n if maxsubl2 > maxsubl:\n maxsubl = maxsubl2\n maxsubr2 = np.max(\n lg2.margin_vals['right'][ss2.colspan[:-1]] +\n lg2.margin_vals['rightcb'][ss2.colspan[:-1]])\n if maxsubr2 > maxsubr:\n maxsubr = maxsubr2\n for i in ss1.colspan[1:]:\n lg1.edit_margin_min('left', maxsubl, cell=i)\n for i in ss1.colspan[:-1]:\n lg1.edit_margin_min('right', maxsubr, cell=i)\n\n # interior rows:\n if len(ss1.rowspan) > 1:\n maxsubt = np.max(\n lg1.margin_vals['top'][ss1.rowspan[1:]] +\n lg1.margin_vals['topcb'][ss1.rowspan[1:]]\n )\n maxsubb = np.max(\n lg1.margin_vals['bottom'][ss1.rowspan[:-1]] +\n lg1.margin_vals['bottomcb'][ss1.rowspan[:-1]]\n )\n\n for ax2 in axs:\n ss2 = ax2.get_subplotspec()\n lg2 = layoutgrids[ss2.get_gridspec()]\n if lg2 is not None:\n if len(ss2.rowspan) > 1:\n maxsubt = np.max([np.max(\n lg2.margin_vals['top'][ss2.rowspan[1:]] +\n lg2.margin_vals['topcb'][ss2.rowspan[1:]]\n ), maxsubt])\n maxsubb = np.max([np.max(\n lg2.margin_vals['bottom'][ss2.rowspan[:-1]] +\n lg2.margin_vals['bottomcb'][ss2.rowspan[:-1]]\n ), maxsubb])\n for i in ss1.rowspan[1:]:\n lg1.edit_margin_min('top', maxsubt, cell=i)\n for i in ss1.rowspan[:-1]:\n lg1.edit_margin_min('bottom', maxsubb, cell=i)\n\n\ndef get_cb_parent_spans(cbax):\n """\n Figure out which subplotspecs this colorbar belongs to.\n\n Parameters\n ----------\n cbax : `~matplotlib.axes.Axes`\n Axes for the colorbar.\n """\n rowstart = np.inf\n rowstop = -np.inf\n colstart = np.inf\n colstop = -np.inf\n for parent in cbax._colorbar_info['parents']:\n ss = parent.get_subplotspec()\n rowstart = min(ss.rowspan.start, rowstart)\n rowstop = max(ss.rowspan.stop, rowstop)\n colstart = min(ss.colspan.start, colstart)\n colstop = max(ss.colspan.stop, colstop)\n\n rowspan = range(rowstart, rowstop)\n colspan = range(colstart, colstop)\n return rowspan, colspan\n\n\ndef get_pos_and_bbox(ax, renderer):\n """\n Get the position and the bbox for the Axes.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n renderer : `~matplotlib.backend_bases.RendererBase` subclass.\n\n Returns\n -------\n pos : `~matplotlib.transforms.Bbox`\n Position in figure coordinates.\n bbox : `~matplotlib.transforms.Bbox`\n Tight bounding box in figure coordinates.\n """\n fig = ax.get_figure(root=False)\n pos = ax.get_position(original=True)\n # pos is in panel co-ords, but we need in figure for the layout\n pos = pos.transformed(fig.transSubfigure - fig.transFigure)\n tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer)\n if tightbbox is None:\n bbox = pos\n else:\n bbox = tightbbox.transformed(fig.transFigure.inverted())\n return pos, bbox\n\n\ndef reposition_axes(layoutgrids, fig, renderer, *,\n w_pad=0, h_pad=0, hspace=0, wspace=0):\n """\n Reposition all the Axes based on the new inner bounding box.\n """\n trans_fig_to_subfig = fig.transFigure - fig.transSubfigure\n for sfig in fig.subfigs:\n bbox = layoutgrids[sfig].get_outer_bbox()\n sfig._redo_transform_rel_fig(\n bbox=bbox.transformed(trans_fig_to_subfig))\n reposition_axes(layoutgrids, sfig, renderer,\n w_pad=w_pad, h_pad=h_pad,\n wspace=wspace, hspace=hspace)\n\n for ax in fig._localaxes:\n if ax.get_subplotspec() is None or not ax.get_in_layout():\n continue\n\n # grid bbox is in Figure coordinates, but we specify in panel\n # coordinates...\n ss = ax.get_subplotspec()\n gs = ss.get_gridspec()\n if gs not in layoutgrids:\n return\n\n bbox = layoutgrids[gs].get_inner_bbox(rows=ss.rowspan,\n cols=ss.colspan)\n\n # transform from figure to panel for set_position:\n newbbox = trans_fig_to_subfig.transform_bbox(bbox)\n ax._set_position(newbbox)\n\n # move the colorbars:\n # we need to keep track of oldw and oldh if there is more than\n # one colorbar:\n offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0}\n for nn, cbax in enumerate(ax._colorbars[::-1]):\n if ax == cbax._colorbar_info['parents'][0]:\n reposition_colorbar(layoutgrids, cbax, renderer,\n offset=offset)\n\n\ndef reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):\n """\n Place the colorbar in its new place.\n\n Parameters\n ----------\n layoutgrids : dict\n cbax : `~matplotlib.axes.Axes`\n Axes for the colorbar.\n renderer : `~matplotlib.backend_bases.RendererBase` subclass.\n The renderer to use.\n offset : array-like\n Offset the colorbar needs to be pushed to in order to\n account for multiple colorbars.\n """\n\n parents = cbax._colorbar_info['parents']\n gs = parents[0].get_gridspec()\n fig = cbax.get_figure(root=False)\n trans_fig_to_subfig = fig.transFigure - fig.transSubfigure\n\n cb_rspans, cb_cspans = get_cb_parent_spans(cbax)\n bboxparent = layoutgrids[gs].get_bbox_for_cb(rows=cb_rspans,\n cols=cb_cspans)\n pb = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)\n\n location = cbax._colorbar_info['location']\n anchor = cbax._colorbar_info['anchor']\n fraction = cbax._colorbar_info['fraction']\n aspect = cbax._colorbar_info['aspect']\n shrink = cbax._colorbar_info['shrink']\n\n cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)\n\n # Colorbar gets put at extreme edge of outer bbox of the subplotspec\n # It needs to be moved in by: 1) a pad 2) its "margin" 3) by\n # any colorbars already added at this location:\n cbpad = colorbar_get_pad(layoutgrids, cbax)\n if location in ('left', 'right'):\n # fraction and shrink are fractions of parent\n pbcb = pb.shrunk(fraction, shrink).anchored(anchor, pb)\n # The colorbar is at the left side of the parent. Need\n # to translate to right (or left)\n if location == 'right':\n lmargin = cbpos.x0 - cbbbox.x0\n dx = bboxparent.x1 - pbcb.x0 + offset['right']\n dx += cbpad + lmargin\n offset['right'] += cbbbox.width + cbpad\n pbcb = pbcb.translated(dx, 0)\n else:\n lmargin = cbpos.x0 - cbbbox.x0\n dx = bboxparent.x0 - pbcb.x0 # edge of parent\n dx += -cbbbox.width - cbpad + lmargin - offset['left']\n offset['left'] += cbbbox.width + cbpad\n pbcb = pbcb.translated(dx, 0)\n else: # horizontal axes:\n pbcb = pb.shrunk(shrink, fraction).anchored(anchor, pb)\n if location == 'top':\n bmargin = cbpos.y0 - cbbbox.y0\n dy = bboxparent.y1 - pbcb.y0 + offset['top']\n dy += cbpad + bmargin\n offset['top'] += cbbbox.height + cbpad\n pbcb = pbcb.translated(0, dy)\n else:\n bmargin = cbpos.y0 - cbbbox.y0\n dy = bboxparent.y0 - pbcb.y0\n dy += -cbbbox.height - cbpad + bmargin - offset['bottom']\n offset['bottom'] += cbbbox.height + cbpad\n pbcb = pbcb.translated(0, dy)\n\n pbcb = trans_fig_to_subfig.transform_bbox(pbcb)\n cbax.set_transform(fig.transSubfigure)\n cbax._set_position(pbcb)\n cbax.set_anchor(anchor)\n if location in ['bottom', 'top']:\n aspect = 1 / aspect\n cbax.set_box_aspect(aspect)\n cbax.set_aspect('auto')\n return offset\n\n\ndef reset_margins(layoutgrids, fig):\n """\n Reset the margins in the layoutboxes of *fig*.\n\n Margins are usually set as a minimum, so if the figure gets smaller\n the minimum needs to be zero in order for it to grow again.\n """\n for sfig in fig.subfigs:\n reset_margins(layoutgrids, sfig)\n for ax in fig.axes:\n if ax.get_in_layout():\n gs = ax.get_gridspec()\n if gs in layoutgrids: # also implies gs is not None.\n layoutgrids[gs].reset_margins()\n layoutgrids[fig].reset_margins()\n\n\ndef colorbar_get_pad(layoutgrids, cax):\n parents = cax._colorbar_info['parents']\n gs = parents[0].get_gridspec()\n\n cb_rspans, cb_cspans = get_cb_parent_spans(cax)\n bboxouter = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans)\n\n if cax._colorbar_info['location'] in ['right', 'left']:\n size = bboxouter.width\n else:\n size = bboxouter.height\n\n return cax._colorbar_info['pad'] * size\n
.venv\Lib\site-packages\matplotlib\_constrained_layout.py
_constrained_layout.py
Python
31,403
0.95
0.193508
0.091971
python-kit
881
2024-10-11T22:17:27.042586
MIT
false
b37a501de582c8095f7aee90261a9435
MZ
.venv\Lib\site-packages\matplotlib\_c_internal_utils.cp313-win_amd64.pyd
_c_internal_utils.cp313-win_amd64.pyd
Other
138,240
0.75
0.017038
0.005115
vue-tools
849
2024-12-23T20:28:06.428147
GPL-3.0
false
45822b5609fb5538893256e809d2aa74
def display_is_valid() -> bool: ...\ndef xdisplay_is_valid() -> bool: ...\n\ndef Win32_GetForegroundWindow() -> int | None: ...\ndef Win32_SetForegroundWindow(hwnd: int) -> None: ...\ndef Win32_SetProcessDpiAwareness_max() -> None: ...\ndef Win32_SetCurrentProcessExplicitAppUserModelID(appid: str) -> None: ...\ndef Win32_GetCurrentProcessExplicitAppUserModelID() -> str | None: ...\n
.venv\Lib\site-packages\matplotlib\_c_internal_utils.pyi
_c_internal_utils.pyi
Other
377
0.85
0.875
0
node-utils
753
2023-10-30T23:43:49.507791
BSD-3-Clause
false
059aadce977a7a19da1f18a86a48e746
import inspect\n\nfrom . import _api\n\n\ndef kwarg_doc(text):\n """\n Decorator for defining the kwdoc documentation of artist properties.\n\n This decorator can be applied to artist property setter methods.\n The given text is stored in a private attribute ``_kwarg_doc`` on\n the method. It is used to overwrite auto-generated documentation\n in the *kwdoc list* for artists. The kwdoc list is used to document\n ``**kwargs`` when they are properties of an artist. See e.g. the\n ``**kwargs`` section in `.Axes.text`.\n\n The text should contain the supported types, as well as the default\n value if applicable, e.g.:\n\n @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")\n def set_usetex(self, usetex):\n\n See Also\n --------\n matplotlib.artist.kwdoc\n\n """\n def decorator(func):\n func._kwarg_doc = text\n return func\n return decorator\n\n\nclass Substitution:\n """\n A decorator that performs %-substitution on an object's docstring.\n\n This decorator should be robust even if ``obj.__doc__`` is None (for\n example, if -OO was passed to the interpreter).\n\n Usage: construct a docstring.Substitution with a sequence or dictionary\n suitable for performing substitution; then decorate a suitable function\n with the constructed object, e.g.::\n\n sub_author_name = Substitution(author='Jason')\n\n @sub_author_name\n def some_function(x):\n "%(author)s wrote this function"\n\n # note that some_function.__doc__ is now "Jason wrote this function"\n\n One can also use positional arguments::\n\n sub_first_last_names = Substitution('Edgar Allen', 'Poe')\n\n @sub_first_last_names\n def some_function(x):\n "%s %s wrote the Raven"\n """\n def __init__(self, *args, **kwargs):\n if args and kwargs:\n raise TypeError("Only positional or keyword args are allowed")\n self.params = args or kwargs\n\n def __call__(self, func):\n if func.__doc__:\n func.__doc__ = inspect.cleandoc(func.__doc__) % self.params\n return func\n\n\nclass _ArtistKwdocLoader(dict):\n def __missing__(self, key):\n if not key.endswith(":kwdoc"):\n raise KeyError(key)\n name = key[:-len(":kwdoc")]\n from matplotlib.artist import Artist, kwdoc\n try:\n cls, = (cls for cls in _api.recursive_subclasses(Artist)\n if cls.__name__ == name)\n except ValueError as e:\n raise KeyError(key) from e\n return self.setdefault(key, kwdoc(cls))\n\n\nclass _ArtistPropertiesSubstitution:\n """\n A class to substitute formatted placeholders in docstrings.\n\n This is realized in a single instance ``_docstring.interpd``.\n\n Use `~._ArtistPropertiesSubstition.register` to define placeholders and\n their substitution, e.g. ``_docstring.interpd.register(name="some value")``.\n\n Use this as a decorator to apply the substitution::\n\n @_docstring.interpd\n def some_func():\n '''Replace %(name)s.'''\n\n Decorating a class triggers substitution both on the class docstring and\n on the class' ``__init__`` docstring (which is a commonly required\n pattern for Artist subclasses).\n\n Substitutions of the form ``%(classname:kwdoc)s`` (ending with the\n literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the\n given *classname*, and are substituted with the `.kwdoc` of that class.\n """\n\n def __init__(self):\n self.params = _ArtistKwdocLoader()\n\n def register(self, **kwargs):\n """\n Register substitutions.\n\n ``_docstring.interpd.register(name="some value")`` makes "name" available\n as a named parameter that will be replaced by "some value".\n """\n self.params.update(**kwargs)\n\n def __call__(self, obj):\n if obj.__doc__:\n obj.__doc__ = inspect.cleandoc(obj.__doc__) % self.params\n if isinstance(obj, type) and obj.__init__ != object.__init__:\n self(obj.__init__)\n return obj\n\n\ndef copy(source):\n """Copy a docstring from another source function (if present)."""\n def do_copy(target):\n if source.__doc__:\n target.__doc__ = source.__doc__\n return target\n return do_copy\n\n\n# Create a decorator that will house the various docstring snippets reused\n# throughout Matplotlib.\ninterpd = _ArtistPropertiesSubstitution()\n
.venv\Lib\site-packages\matplotlib\_docstring.py
_docstring.py
Python
4,435
0.95
0.312057
0.028846
node-utils
351
2024-06-26T21:55:17.514375
BSD-3-Clause
false
5a8e00b4fd60a39233ec5a2505f2a867
from collections.abc import Callable\nfrom typing import Any, TypeVar, overload\n\n\n_T = TypeVar('_T')\n\n\ndef kwarg_doc(text: str) -> Callable[[_T], _T]: ...\n\n\nclass Substitution:\n @overload\n def __init__(self, *args: str): ...\n @overload\n def __init__(self, **kwargs: str): ...\n def __call__(self, func: _T) -> _T: ...\n def update(self, *args, **kwargs): ... # type: ignore[no-untyped-def]\n\n\nclass _ArtistKwdocLoader(dict[str, str]):\n def __missing__(self, key: str) -> str: ...\n\n\nclass _ArtistPropertiesSubstitution:\n def __init__(self) -> None: ...\n def register(self, **kwargs) -> None: ...\n def __call__(self, obj: _T) -> _T: ...\n\n\ndef copy(source: Any) -> Callable[[_T], _T]: ...\n\n\ndedent_interpd: _ArtistPropertiesSubstitution\ninterpd: _ArtistPropertiesSubstitution\n
.venv\Lib\site-packages\matplotlib\_docstring.pyi
_docstring.pyi
Other
800
0.95
0.411765
0
react-lib
487
2025-03-13T08:53:48.122965
MIT
false
9a902423085d37c0f8a3ebc4cc15f235
"""\nEnums representing sets of strings that Matplotlib uses as input parameters.\n\nMatplotlib often uses simple data types like strings or tuples to define a\nconcept; e.g. the line capstyle can be specified as one of 'butt', 'round',\nor 'projecting'. The classes in this module are used internally and serve to\ndocument these concepts formally.\n\nAs an end-user you will not use these classes directly, but only the values\nthey define.\n"""\n\nfrom enum import Enum\nfrom matplotlib import _docstring\n\n\nclass JoinStyle(str, Enum):\n """\n Define how the connection between two line segments is drawn.\n\n For a visual impression of each *JoinStyle*, `view these docs online\n <JoinStyle>`, or run `JoinStyle.demo`.\n\n Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a\n finite ``linewidth``, where the underlying 1D `~.path.Path` represents the\n center of the stroked line.\n\n By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of\n a stroked line to simply be every point within some radius,\n ``linewidth/2``, away from any point of the center line. However, this\n results in corners appearing "rounded", which may not be the desired\n behavior if you are drawing, for example, a polygon or pointed star.\n\n **Supported values:**\n\n .. rst-class:: value-list\n\n 'miter'\n the "arrow-tip" style. Each boundary of the filled-in area will\n extend in a straight line parallel to the tangent vector of the\n centerline at the point it meets the corner, until they meet in a\n sharp point.\n 'round'\n stokes every point within a radius of ``linewidth/2`` of the center\n lines.\n 'bevel'\n the "squared-off" style. It can be thought of as a rounded corner\n where the "circular" part of the corner has been cut off.\n\n .. note::\n\n Very long miter tips are cut off (to form a *bevel*) after a\n backend-dependent limit called the "miter limit", which specifies the\n maximum allowed ratio of miter length to line width. For example, the\n PDF backend uses the default value of 10 specified by the PDF standard,\n while the SVG backend does not even specify the miter limit, resulting\n in a default value of 4 per the SVG specification. Matplotlib does not\n currently allow the user to adjust this parameter.\n\n A more detailed description of the effect of a miter limit can be found\n in the `Mozilla Developer Docs\n <https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit>`_\n\n .. plot::\n :alt: Demo of possible JoinStyle's\n\n from matplotlib._enums import JoinStyle\n JoinStyle.demo()\n\n """\n\n miter = "miter"\n round = "round"\n bevel = "bevel"\n\n @staticmethod\n def demo():\n """Demonstrate how each JoinStyle looks for various join angles."""\n import numpy as np\n import matplotlib.pyplot as plt\n\n def plot_angle(ax, x, y, angle, style):\n phi = np.radians(angle)\n xx = [x + .5, x, x + .5*np.cos(phi)]\n yy = [y, y, y + .5*np.sin(phi)]\n ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style)\n ax.plot(xx, yy, lw=1, color='black')\n ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3)\n\n fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True)\n ax.set_title('Join style')\n for x, style in enumerate(['miter', 'round', 'bevel']):\n ax.text(x, 5, style)\n for y, angle in enumerate([20, 45, 60, 90, 120]):\n plot_angle(ax, x, y, angle, style)\n if x == 0:\n ax.text(-1.3, y, f'{angle} degrees')\n ax.set_xlim(-1.5, 2.75)\n ax.set_ylim(-.5, 5.5)\n ax.set_axis_off()\n fig.show()\n\n\nJoinStyle.input_description = "{" \\n + ", ".join([f"'{js.name}'" for js in JoinStyle]) \\n + "}"\n\n\nclass CapStyle(str, Enum):\n r"""\n Define how the two endpoints (caps) of an unclosed line are drawn.\n\n How to draw the start and end points of lines that represent a closed curve\n (i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's\n `JoinStyle`. For all other lines, how the start and end points are drawn is\n controlled by the *CapStyle*.\n\n For a visual impression of each *CapStyle*, `view these docs online\n <CapStyle>` or run `CapStyle.demo`.\n\n By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as\n squared off at its endpoints.\n\n **Supported values:**\n\n .. rst-class:: value-list\n\n 'butt'\n the line is squared off at its endpoint.\n 'projecting'\n the line is squared off as in *butt*, but the filled in area\n extends beyond the endpoint a distance of ``linewidth/2``.\n 'round'\n like *butt*, but a semicircular cap is added to the end of the\n line, of radius ``linewidth/2``.\n\n .. plot::\n :alt: Demo of possible CapStyle's\n\n from matplotlib._enums import CapStyle\n CapStyle.demo()\n\n """\n butt = "butt"\n projecting = "projecting"\n round = "round"\n\n @staticmethod\n def demo():\n """Demonstrate how each CapStyle looks for a thick line segment."""\n import matplotlib.pyplot as plt\n\n fig = plt.figure(figsize=(4, 1.2))\n ax = fig.add_axes([0, 0, 1, 0.8])\n ax.set_title('Cap style')\n\n for x, style in enumerate(['butt', 'round', 'projecting']):\n ax.text(x+0.25, 0.85, style, ha='center')\n xx = [x, x+0.5]\n yy = [0, 0]\n ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style)\n ax.plot(xx, yy, lw=1, color='black')\n ax.plot(xx, yy, 'o', color='tab:red', markersize=3)\n\n ax.set_ylim(-.5, 1.5)\n ax.set_axis_off()\n fig.show()\n\n\nCapStyle.input_description = "{" \\n + ", ".join([f"'{cs.name}'" for cs in CapStyle]) \\n + "}"\n\n_docstring.interpd.register(\n JoinStyle=JoinStyle.input_description,\n CapStyle=CapStyle.input_description,\n)\n
.venv\Lib\site-packages\matplotlib\_enums.py
_enums.py
Python
6,175
0.95
0.101695
0.014706
python-kit
514
2025-05-27T21:27:30.813286
MIT
false
da56826f3216481f520d518c6993024b
from typing import cast\nfrom enum import Enum\n\n\nclass JoinStyle(str, Enum):\n miter = "miter"\n round = "round"\n bevel = "bevel"\n @staticmethod\n def demo() -> None: ...\n\n\nclass CapStyle(str, Enum):\n butt = "butt"\n projecting = "projecting"\n round = "round"\n\n @staticmethod\n def demo() -> None: ...\n
.venv\Lib\site-packages\matplotlib\_enums.pyi
_enums.pyi
Other
326
0.85
0.210526
0
react-lib
352
2024-05-07T05:14:05.237018
MIT
false
02ec47046f024815234ce4564a528e76
"""\nA module for parsing and generating `fontconfig patterns`_.\n\n.. _fontconfig patterns:\n https://www.freedesktop.org/software/fontconfig/fontconfig-user.html\n"""\n\n# This class logically belongs in `matplotlib.font_manager`, but placing it\n# there would have created cyclical dependency problems, because it also needs\n# to be available from `matplotlib.rcsetup` (for parsing matplotlibrc files).\n\nfrom functools import lru_cache, partial\nimport re\n\nfrom pyparsing import (\n Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore, oneOf)\n\n\n_family_punc = r'\\\-:,'\n_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '')\n_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\')\n_value_punc = r'\\=_:,'\n_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '')\n_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\')\n\n\n_CONSTANTS = {\n 'thin': ('weight', 'light'),\n 'extralight': ('weight', 'light'),\n 'ultralight': ('weight', 'light'),\n 'light': ('weight', 'light'),\n 'book': ('weight', 'book'),\n 'regular': ('weight', 'regular'),\n 'normal': ('weight', 'normal'),\n 'medium': ('weight', 'medium'),\n 'demibold': ('weight', 'demibold'),\n 'semibold': ('weight', 'semibold'),\n 'bold': ('weight', 'bold'),\n 'extrabold': ('weight', 'extra bold'),\n 'black': ('weight', 'black'),\n 'heavy': ('weight', 'heavy'),\n 'roman': ('slant', 'normal'),\n 'italic': ('slant', 'italic'),\n 'oblique': ('slant', 'oblique'),\n 'ultracondensed': ('width', 'ultra-condensed'),\n 'extracondensed': ('width', 'extra-condensed'),\n 'condensed': ('width', 'condensed'),\n 'semicondensed': ('width', 'semi-condensed'),\n 'expanded': ('width', 'expanded'),\n 'extraexpanded': ('width', 'extra-expanded'),\n 'ultraexpanded': ('width', 'ultra-expanded'),\n}\n\n\n@lru_cache # The parser instance is a singleton.\ndef _make_fontconfig_parser():\n def comma_separated(elem):\n return elem + ZeroOrMore(Suppress(",") + elem)\n\n family = Regex(fr"([^{_family_punc}]|(\\[{_family_punc}]))*")\n size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)")\n name = Regex(r"[a-z]+")\n value = Regex(fr"([^{_value_punc}]|(\\[{_value_punc}]))*")\n prop = Group((name + Suppress("=") + comma_separated(value)) | oneOf(_CONSTANTS))\n return (\n Optional(comma_separated(family)("families"))\n + Optional("-" + comma_separated(size)("sizes"))\n + ZeroOrMore(":" + prop("properties*"))\n + StringEnd()\n )\n\n\n# `parse_fontconfig_pattern` is a bottleneck during the tests because it is\n# repeatedly called when the rcParams are reset (to validate the default\n# fonts). In practice, the cache size doesn't grow beyond a few dozen entries\n# during the test suite.\n@lru_cache\ndef parse_fontconfig_pattern(pattern):\n """\n Parse a fontconfig *pattern* into a dict that can initialize a\n `.font_manager.FontProperties` object.\n """\n parser = _make_fontconfig_parser()\n try:\n parse = parser.parseString(pattern)\n except ParseException as err:\n # explain becomes a plain method on pyparsing 3 (err.explain(0)).\n raise ValueError("\n" + ParseException.explain(err, 0)) from None\n parser.resetCache()\n props = {}\n if "families" in parse:\n props["family"] = [*map(_family_unescape, parse["families"])]\n if "sizes" in parse:\n props["size"] = [*parse["sizes"]]\n for prop in parse.get("properties", []):\n if len(prop) == 1:\n prop = _CONSTANTS[prop[0]]\n k, *v = prop\n props.setdefault(k, []).extend(map(_value_unescape, v))\n return props\n\n\ndef generate_fontconfig_pattern(d):\n """Convert a `.FontProperties` to a fontconfig pattern string."""\n kvs = [(k, getattr(d, f"get_{k}")())\n for k in ["style", "variant", "weight", "stretch", "file", "size"]]\n # Families is given first without a leading keyword. Other entries (which\n # are necessarily scalar) are given as key=value, skipping Nones.\n return (",".join(_family_escape(f) for f in d.get_family())\n + "".join(f":{k}={_value_escape(str(v))}"\n for k, v in kvs if v is not None))\n
.venv\Lib\site-packages\matplotlib\_fontconfig_pattern.py
_fontconfig_pattern.py
Python
4,361
0.95
0.144144
0.104167
node-utils
576
2024-12-28T07:31:54.482662
BSD-3-Clause
false
a20bb600119329b53624232c31fe6e95
"""\nInternal debugging utilities, that are not expected to be used in the rest of\nthe codebase.\n\nWARNING: Code in this module may change without prior notice!\n"""\n\nfrom io import StringIO\nfrom pathlib import Path\nimport subprocess\n\nfrom matplotlib.transforms import TransformNode\n\n\ndef graphviz_dump_transform(transform, dest, *, highlight=None):\n """\n Generate a graphical representation of the transform tree for *transform*\n using the :program:`dot` program (which this function depends on). The\n output format (png, dot, etc.) is determined from the suffix of *dest*.\n\n Parameters\n ----------\n transform : `~matplotlib.transform.Transform`\n The represented transform.\n dest : str\n Output filename. The extension must be one of the formats supported\n by :program:`dot`, e.g. png, svg, dot, ...\n (see https://www.graphviz.org/doc/info/output.html).\n highlight : list of `~matplotlib.transform.Transform` or None\n The transforms in the tree to be drawn in bold.\n If *None*, *transform* is highlighted.\n """\n\n if highlight is None:\n highlight = [transform]\n seen = set()\n\n def recurse(root, buf):\n if id(root) in seen:\n return\n seen.add(id(root))\n props = {}\n label = type(root).__name__\n if root._invalid:\n label = f'[{label}]'\n if root in highlight:\n props['style'] = 'bold'\n props['shape'] = 'box'\n props['label'] = '"%s"' % label\n props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))\n buf.write(f'{id(root)} [{props}];\n')\n for key, val in vars(root).items():\n if isinstance(val, TransformNode) and id(root) in val._parents:\n buf.write(f'"{id(root)}" -> "{id(val)}" '\n f'[label="{key}", fontsize=10];\n')\n recurse(val, buf)\n\n buf = StringIO()\n buf.write('digraph G {\n')\n recurse(transform, buf)\n buf.write('}\n')\n subprocess.run(\n ['dot', '-T', Path(dest).suffix[1:], '-o', dest],\n input=buf.getvalue().encode('utf-8'), check=True)\n
.venv\Lib\site-packages\matplotlib\_internal_utils.py
_internal_utils.py
Python
2,140
0.95
0.15625
0
vue-tools
649
2025-01-27T17:54:33.857979
Apache-2.0
false
950a9ccda36505fde9782f2a31d57c9d
"""\nA layoutgrid is a nrows by ncols set of boxes, meant to be used by\n`._constrained_layout`, each box is analogous to a subplotspec element of\na gridspec.\n\nEach box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],\nand by two editable margins for each side. The main margin gets its value\nset by the size of ticklabels, titles, etc on each Axes that is in the figure.\nThe outer margin is the padding around the Axes, and space for any\ncolorbars.\n\nThe "inner" widths and heights of these boxes are then constrained to be the\nsame (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).\n\nThe layoutgrid is then constrained to be contained within a parent layoutgrid,\nits column(s) and row(s) specified when it is created.\n"""\n\nimport itertools\nimport kiwisolver as kiwi\nimport logging\nimport numpy as np\n\nimport matplotlib as mpl\nimport matplotlib.patches as mpatches\nfrom matplotlib.transforms import Bbox\n\n_log = logging.getLogger(__name__)\n\n\nclass LayoutGrid:\n """\n Analogous to a gridspec, and contained in another LayoutGrid.\n """\n\n def __init__(self, parent=None, parent_pos=(0, 0),\n parent_inner=False, name='', ncols=1, nrows=1,\n h_pad=None, w_pad=None, width_ratios=None,\n height_ratios=None):\n Variable = kiwi.Variable\n self.parent_pos = parent_pos\n self.parent_inner = parent_inner\n self.name = name + seq_id()\n if isinstance(parent, LayoutGrid):\n self.name = f'{parent.name}.{self.name}'\n self.nrows = nrows\n self.ncols = ncols\n self.height_ratios = np.atleast_1d(height_ratios)\n if height_ratios is None:\n self.height_ratios = np.ones(nrows)\n self.width_ratios = np.atleast_1d(width_ratios)\n if width_ratios is None:\n self.width_ratios = np.ones(ncols)\n\n sn = self.name + '_'\n if not isinstance(parent, LayoutGrid):\n # parent can be a rect if not a LayoutGrid\n # allows specifying a rectangle to contain the layout.\n self.solver = kiwi.Solver()\n else:\n parent.add_child(self, *parent_pos)\n self.solver = parent.solver\n # keep track of artist associated w/ this layout. Can be none\n self.artists = np.empty((nrows, ncols), dtype=object)\n self.children = np.empty((nrows, ncols), dtype=object)\n\n self.margins = {}\n self.margin_vals = {}\n # all the boxes in each column share the same left/right margins:\n for todo in ['left', 'right', 'leftcb', 'rightcb']:\n # track the value so we can change only if a margin is larger\n # than the current value\n self.margin_vals[todo] = np.zeros(ncols)\n\n sol = self.solver\n\n self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)]\n self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)]\n for todo in ['left', 'right', 'leftcb', 'rightcb']:\n self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')\n for i in range(ncols)]\n for i in range(ncols):\n sol.addEditVariable(self.margins[todo][i], 'strong')\n\n for todo in ['bottom', 'top', 'bottomcb', 'topcb']:\n self.margins[todo] = np.empty((nrows), dtype=object)\n self.margin_vals[todo] = np.zeros(nrows)\n\n self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)]\n self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)]\n for todo in ['bottom', 'top', 'bottomcb', 'topcb']:\n self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')\n for i in range(nrows)]\n for i in range(nrows):\n sol.addEditVariable(self.margins[todo][i], 'strong')\n\n # set these margins to zero by default. They will be edited as\n # children are filled.\n self.reset_margins()\n self.add_constraints(parent)\n\n self.h_pad = h_pad\n self.w_pad = w_pad\n\n def __repr__(self):\n str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n'\n for i in range(self.nrows):\n for j in range(self.ncols):\n str += f'{i}, {j}: '\\n f'L{self.lefts[j].value():1.3f}, ' \\n f'B{self.bottoms[i].value():1.3f}, ' \\n f'R{self.rights[j].value():1.3f}, ' \\n f'T{self.tops[i].value():1.3f}, ' \\n f'ML{self.margins["left"][j].value():1.3f}, ' \\n f'MR{self.margins["right"][j].value():1.3f}, ' \\n f'MB{self.margins["bottom"][i].value():1.3f}, ' \\n f'MT{self.margins["top"][i].value():1.3f}, \n'\n return str\n\n def reset_margins(self):\n """\n Reset all the margins to zero. Must do this after changing\n figure size, for instance, because the relative size of the\n axes labels etc changes.\n """\n for todo in ['left', 'right', 'bottom', 'top',\n 'leftcb', 'rightcb', 'bottomcb', 'topcb']:\n self.edit_margins(todo, 0.0)\n\n def add_constraints(self, parent):\n # define self-consistent constraints\n self.hard_constraints()\n # define relationship with parent layoutgrid:\n self.parent_constraints(parent)\n # define relative widths of the grid cells to each other\n # and stack horizontally and vertically.\n self.grid_constraints()\n\n def hard_constraints(self):\n """\n These are the redundant constraints, plus ones that make the\n rest of the code easier.\n """\n for i in range(self.ncols):\n hc = [self.rights[i] >= self.lefts[i],\n (self.rights[i] - self.margins['right'][i] -\n self.margins['rightcb'][i] >=\n self.lefts[i] - self.margins['left'][i] -\n self.margins['leftcb'][i])\n ]\n for c in hc:\n self.solver.addConstraint(c | 'required')\n\n for i in range(self.nrows):\n hc = [self.tops[i] >= self.bottoms[i],\n (self.tops[i] - self.margins['top'][i] -\n self.margins['topcb'][i] >=\n self.bottoms[i] - self.margins['bottom'][i] -\n self.margins['bottomcb'][i])\n ]\n for c in hc:\n self.solver.addConstraint(c | 'required')\n\n def add_child(self, child, i=0, j=0):\n # np.ix_ returns the cross product of i and j indices\n self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child\n\n def parent_constraints(self, parent):\n # constraints that are due to the parent...\n # i.e. the first column's left is equal to the\n # parent's left, the last column right equal to the\n # parent's right...\n if not isinstance(parent, LayoutGrid):\n # specify a rectangle in figure coordinates\n hc = [self.lefts[0] == parent[0],\n self.rights[-1] == parent[0] + parent[2],\n # top and bottom reversed order...\n self.tops[0] == parent[1] + parent[3],\n self.bottoms[-1] == parent[1]]\n else:\n rows, cols = self.parent_pos\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n left = parent.lefts[cols[0]]\n right = parent.rights[cols[-1]]\n top = parent.tops[rows[0]]\n bottom = parent.bottoms[rows[-1]]\n if self.parent_inner:\n # the layout grid is contained inside the inner\n # grid of the parent.\n left += parent.margins['left'][cols[0]]\n left += parent.margins['leftcb'][cols[0]]\n right -= parent.margins['right'][cols[-1]]\n right -= parent.margins['rightcb'][cols[-1]]\n top -= parent.margins['top'][rows[0]]\n top -= parent.margins['topcb'][rows[0]]\n bottom += parent.margins['bottom'][rows[-1]]\n bottom += parent.margins['bottomcb'][rows[-1]]\n hc = [self.lefts[0] == left,\n self.rights[-1] == right,\n # from top to bottom\n self.tops[0] == top,\n self.bottoms[-1] == bottom]\n for c in hc:\n self.solver.addConstraint(c | 'required')\n\n def grid_constraints(self):\n # constrain the ratio of the inner part of the grids\n # to be the same (relative to width_ratios)\n\n # constrain widths:\n w = (self.rights[0] - self.margins['right'][0] -\n self.margins['rightcb'][0])\n w = (w - self.lefts[0] - self.margins['left'][0] -\n self.margins['leftcb'][0])\n w0 = w / self.width_ratios[0]\n # from left to right\n for i in range(1, self.ncols):\n w = (self.rights[i] - self.margins['right'][i] -\n self.margins['rightcb'][i])\n w = (w - self.lefts[i] - self.margins['left'][i] -\n self.margins['leftcb'][i])\n c = (w == w0 * self.width_ratios[i])\n self.solver.addConstraint(c | 'strong')\n # constrain the grid cells to be directly next to each other.\n c = (self.rights[i - 1] == self.lefts[i])\n self.solver.addConstraint(c | 'strong')\n\n # constrain heights:\n h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0]\n h = (h - self.bottoms[0] - self.margins['bottom'][0] -\n self.margins['bottomcb'][0])\n h0 = h / self.height_ratios[0]\n # from top to bottom:\n for i in range(1, self.nrows):\n h = (self.tops[i] - self.margins['top'][i] -\n self.margins['topcb'][i])\n h = (h - self.bottoms[i] - self.margins['bottom'][i] -\n self.margins['bottomcb'][i])\n c = (h == h0 * self.height_ratios[i])\n self.solver.addConstraint(c | 'strong')\n # constrain the grid cells to be directly above each other.\n c = (self.bottoms[i - 1] == self.tops[i])\n self.solver.addConstraint(c | 'strong')\n\n # Margin editing: The margins are variable and meant to\n # contain things of a fixed size like axes labels, tick labels, titles\n # etc\n def edit_margin(self, todo, size, cell):\n """\n Change the size of the margin for one cell.\n\n Parameters\n ----------\n todo : string (one of 'left', 'right', 'bottom', 'top')\n margin to alter.\n\n size : float\n Size of the margin. If it is larger than the existing minimum it\n updates the margin size. Fraction of figure size.\n\n cell : int\n Cell column or row to edit.\n """\n self.solver.suggestValue(self.margins[todo][cell], size)\n self.margin_vals[todo][cell] = size\n\n def edit_margin_min(self, todo, size, cell=0):\n """\n Change the minimum size of the margin for one cell.\n\n Parameters\n ----------\n todo : string (one of 'left', 'right', 'bottom', 'top')\n margin to alter.\n\n size : float\n Minimum size of the margin . If it is larger than the\n existing minimum it updates the margin size. Fraction of\n figure size.\n\n cell : int\n Cell column or row to edit.\n """\n\n if size > self.margin_vals[todo][cell]:\n self.edit_margin(todo, size, cell)\n\n def edit_margins(self, todo, size):\n """\n Change the size of all the margin of all the cells in the layout grid.\n\n Parameters\n ----------\n todo : string (one of 'left', 'right', 'bottom', 'top')\n margin to alter.\n\n size : float\n Size to set the margins. Fraction of figure size.\n """\n\n for i in range(len(self.margin_vals[todo])):\n self.edit_margin(todo, size, i)\n\n def edit_all_margins_min(self, todo, size):\n """\n Change the minimum size of all the margin of all\n the cells in the layout grid.\n\n Parameters\n ----------\n todo : {'left', 'right', 'bottom', 'top'}\n The margin to alter.\n\n size : float\n Minimum size of the margin. If it is larger than the\n existing minimum it updates the margin size. Fraction of\n figure size.\n """\n\n for i in range(len(self.margin_vals[todo])):\n self.edit_margin_min(todo, size, i)\n\n def edit_outer_margin_mins(self, margin, ss):\n """\n Edit all four margin minimums in one statement.\n\n Parameters\n ----------\n margin : dict\n size of margins in a dict with keys 'left', 'right', 'bottom',\n 'top'\n\n ss : SubplotSpec\n defines the subplotspec these margins should be applied to\n """\n\n self.edit_margin_min('left', margin['left'], ss.colspan.start)\n self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start)\n self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1)\n self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1)\n # rows are from the top down:\n self.edit_margin_min('top', margin['top'], ss.rowspan.start)\n self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start)\n self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1)\n self.edit_margin_min('bottomcb', margin['bottomcb'],\n ss.rowspan.stop - 1)\n\n def get_margins(self, todo, col):\n """Return the margin at this position"""\n return self.margin_vals[todo][col]\n\n def get_outer_bbox(self, rows=0, cols=0):\n """\n Return the outer bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n self.lefts[cols[0]].value(),\n self.bottoms[rows[-1]].value(),\n self.rights[cols[-1]].value(),\n self.tops[rows[0]].value())\n return bbox\n\n def get_inner_bbox(self, rows=0, cols=0):\n """\n Return the inner bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.lefts[cols[0]].value() +\n self.margins['left'][cols[0]].value() +\n self.margins['leftcb'][cols[0]].value()),\n (self.bottoms[rows[-1]].value() +\n self.margins['bottom'][rows[-1]].value() +\n self.margins['bottomcb'][rows[-1]].value()),\n (self.rights[cols[-1]].value() -\n self.margins['right'][cols[-1]].value() -\n self.margins['rightcb'][cols[-1]].value()),\n (self.tops[rows[0]].value() -\n self.margins['top'][rows[0]].value() -\n self.margins['topcb'][rows[0]].value())\n )\n return bbox\n\n def get_bbox_for_cb(self, rows=0, cols=0):\n """\n Return the bounding box that includes the\n decorations but, *not* the colorbar...\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.lefts[cols[0]].value() +\n self.margins['leftcb'][cols[0]].value()),\n (self.bottoms[rows[-1]].value() +\n self.margins['bottomcb'][rows[-1]].value()),\n (self.rights[cols[-1]].value() -\n self.margins['rightcb'][cols[-1]].value()),\n (self.tops[rows[0]].value() -\n self.margins['topcb'][rows[0]].value())\n )\n return bbox\n\n def get_left_margin_bbox(self, rows=0, cols=0):\n """\n Return the left margin bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.lefts[cols[0]].value() +\n self.margins['leftcb'][cols[0]].value()),\n (self.bottoms[rows[-1]].value()),\n (self.lefts[cols[0]].value() +\n self.margins['leftcb'][cols[0]].value() +\n self.margins['left'][cols[0]].value()),\n (self.tops[rows[0]].value()))\n return bbox\n\n def get_bottom_margin_bbox(self, rows=0, cols=0):\n """\n Return the left margin bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.lefts[cols[0]].value()),\n (self.bottoms[rows[-1]].value() +\n self.margins['bottomcb'][rows[-1]].value()),\n (self.rights[cols[-1]].value()),\n (self.bottoms[rows[-1]].value() +\n self.margins['bottom'][rows[-1]].value() +\n self.margins['bottomcb'][rows[-1]].value()\n ))\n return bbox\n\n def get_right_margin_bbox(self, rows=0, cols=0):\n """\n Return the left margin bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.rights[cols[-1]].value() -\n self.margins['right'][cols[-1]].value() -\n self.margins['rightcb'][cols[-1]].value()),\n (self.bottoms[rows[-1]].value()),\n (self.rights[cols[-1]].value() -\n self.margins['rightcb'][cols[-1]].value()),\n (self.tops[rows[0]].value()))\n return bbox\n\n def get_top_margin_bbox(self, rows=0, cols=0):\n """\n Return the left margin bounding box of the subplot specs\n given by rows and cols. rows and cols can be spans.\n """\n rows = np.atleast_1d(rows)\n cols = np.atleast_1d(cols)\n\n bbox = Bbox.from_extents(\n (self.lefts[cols[0]].value()),\n (self.tops[rows[0]].value() -\n self.margins['topcb'][rows[0]].value()),\n (self.rights[cols[-1]].value()),\n (self.tops[rows[0]].value() -\n self.margins['topcb'][rows[0]].value() -\n self.margins['top'][rows[0]].value()))\n return bbox\n\n def update_variables(self):\n """\n Update the variables for the solver attached to this layoutgrid.\n """\n self.solver.updateVariables()\n\n_layoutboxobjnum = itertools.count()\n\n\ndef seq_id():\n """Generate a short sequential id for layoutbox objects."""\n return '%06d' % next(_layoutboxobjnum)\n\n\ndef plot_children(fig, lg=None, level=0):\n """Simple plotting to show where boxes are."""\n if lg is None:\n _layoutgrids = fig.get_layout_engine().execute(fig)\n lg = _layoutgrids[fig]\n colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"]\n col = colors[level]\n for i in range(lg.nrows):\n for j in range(lg.ncols):\n bb = lg.get_outer_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1,\n edgecolor='0.7', facecolor='0.7',\n alpha=0.2, transform=fig.transFigure,\n zorder=-3))\n bbi = lg.get_inner_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2,\n edgecolor=col, facecolor='none',\n transform=fig.transFigure, zorder=-2))\n\n bbi = lg.get_left_margin_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,\n edgecolor='none', alpha=0.2,\n facecolor=[0.5, 0.7, 0.5],\n transform=fig.transFigure, zorder=-2))\n bbi = lg.get_right_margin_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,\n edgecolor='none', alpha=0.2,\n facecolor=[0.7, 0.5, 0.5],\n transform=fig.transFigure, zorder=-2))\n bbi = lg.get_bottom_margin_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,\n edgecolor='none', alpha=0.2,\n facecolor=[0.5, 0.5, 0.7],\n transform=fig.transFigure, zorder=-2))\n bbi = lg.get_top_margin_bbox(rows=i, cols=j)\n fig.add_artist(\n mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,\n edgecolor='none', alpha=0.2,\n facecolor=[0.7, 0.2, 0.7],\n transform=fig.transFigure, zorder=-2))\n for ch in lg.children.flat:\n if ch is not None:\n plot_children(fig, ch, level=level+1)\n
.venv\Lib\site-packages\matplotlib\_layoutgrid.py
_layoutgrid.py
Python
21,676
0.95
0.127971
0.071429
node-utils
901
2024-01-07T23:37:24.690940
BSD-3-Clause
false
5f1583b56803d2af7bb1e25e9ec2506a
"""\nfont data tables for truetype and afm computer modern fonts\n"""\n\nfrom __future__ import annotations\nfrom typing import overload\n\nlatex_to_bakoma = {\n '\\__sqrt__' : ('cmex10', 0x70),\n '\\bigcap' : ('cmex10', 0x5c),\n '\\bigcup' : ('cmex10', 0x5b),\n '\\bigodot' : ('cmex10', 0x4b),\n '\\bigoplus' : ('cmex10', 0x4d),\n '\\bigotimes' : ('cmex10', 0x4f),\n '\\biguplus' : ('cmex10', 0x5d),\n '\\bigvee' : ('cmex10', 0x5f),\n '\\bigwedge' : ('cmex10', 0x5e),\n '\\coprod' : ('cmex10', 0x61),\n '\\int' : ('cmex10', 0x5a),\n '\\langle' : ('cmex10', 0xad),\n '\\leftangle' : ('cmex10', 0xad),\n '\\leftbrace' : ('cmex10', 0xa9),\n '\\oint' : ('cmex10', 0x49),\n '\\prod' : ('cmex10', 0x59),\n '\\rangle' : ('cmex10', 0xae),\n '\\rightangle' : ('cmex10', 0xae),\n '\\rightbrace' : ('cmex10', 0xaa),\n '\\sum' : ('cmex10', 0x58),\n '\\widehat' : ('cmex10', 0x62),\n '\\widetilde' : ('cmex10', 0x65),\n '\\{' : ('cmex10', 0xa9),\n '\\}' : ('cmex10', 0xaa),\n '{' : ('cmex10', 0xa9),\n '}' : ('cmex10', 0xaa),\n\n ',' : ('cmmi10', 0x3b),\n '.' : ('cmmi10', 0x3a),\n '/' : ('cmmi10', 0x3d),\n '<' : ('cmmi10', 0x3c),\n '>' : ('cmmi10', 0x3e),\n '\\alpha' : ('cmmi10', 0xae),\n '\\beta' : ('cmmi10', 0xaf),\n '\\chi' : ('cmmi10', 0xc2),\n '\\combiningrightarrowabove' : ('cmmi10', 0x7e),\n '\\delta' : ('cmmi10', 0xb1),\n '\\ell' : ('cmmi10', 0x60),\n '\\epsilon' : ('cmmi10', 0xb2),\n '\\eta' : ('cmmi10', 0xb4),\n '\\flat' : ('cmmi10', 0x5b),\n '\\frown' : ('cmmi10', 0x5f),\n '\\gamma' : ('cmmi10', 0xb0),\n '\\imath' : ('cmmi10', 0x7b),\n '\\iota' : ('cmmi10', 0xb6),\n '\\jmath' : ('cmmi10', 0x7c),\n '\\kappa' : ('cmmi10', 0x2219),\n '\\lambda' : ('cmmi10', 0xb8),\n '\\leftharpoondown' : ('cmmi10', 0x29),\n '\\leftharpoonup' : ('cmmi10', 0x28),\n '\\mu' : ('cmmi10', 0xb9),\n '\\natural' : ('cmmi10', 0x5c),\n '\\nu' : ('cmmi10', 0xba),\n '\\omega' : ('cmmi10', 0x21),\n '\\phi' : ('cmmi10', 0xc1),\n '\\pi' : ('cmmi10', 0xbc),\n '\\psi' : ('cmmi10', 0xc3),\n '\\rho' : ('cmmi10', 0xbd),\n '\\rightharpoondown' : ('cmmi10', 0x2b),\n '\\rightharpoonup' : ('cmmi10', 0x2a),\n '\\sharp' : ('cmmi10', 0x5d),\n '\\sigma' : ('cmmi10', 0xbe),\n '\\smile' : ('cmmi10', 0x5e),\n '\\tau' : ('cmmi10', 0xbf),\n '\\theta' : ('cmmi10', 0xb5),\n '\\triangleleft' : ('cmmi10', 0x2f),\n '\\triangleright' : ('cmmi10', 0x2e),\n '\\upsilon' : ('cmmi10', 0xc0),\n '\\varepsilon' : ('cmmi10', 0x22),\n '\\varphi' : ('cmmi10', 0x27),\n '\\varrho' : ('cmmi10', 0x25),\n '\\varsigma' : ('cmmi10', 0x26),\n '\\vartheta' : ('cmmi10', 0x23),\n '\\wp' : ('cmmi10', 0x7d),\n '\\xi' : ('cmmi10', 0xbb),\n '\\zeta' : ('cmmi10', 0xb3),\n\n '!' : ('cmr10', 0x21),\n '%' : ('cmr10', 0x25),\n '&' : ('cmr10', 0x26),\n '(' : ('cmr10', 0x28),\n ')' : ('cmr10', 0x29),\n '+' : ('cmr10', 0x2b),\n '0' : ('cmr10', 0x30),\n '1' : ('cmr10', 0x31),\n '2' : ('cmr10', 0x32),\n '3' : ('cmr10', 0x33),\n '4' : ('cmr10', 0x34),\n '5' : ('cmr10', 0x35),\n '6' : ('cmr10', 0x36),\n '7' : ('cmr10', 0x37),\n '8' : ('cmr10', 0x38),\n '9' : ('cmr10', 0x39),\n ':' : ('cmr10', 0x3a),\n ';' : ('cmr10', 0x3b),\n '=' : ('cmr10', 0x3d),\n '?' : ('cmr10', 0x3f),\n '@' : ('cmr10', 0x40),\n '[' : ('cmr10', 0x5b),\n '\\#' : ('cmr10', 0x23),\n '\\$' : ('cmr10', 0x24),\n '\\%' : ('cmr10', 0x25),\n '\\Delta' : ('cmr10', 0xa2),\n '\\Gamma' : ('cmr10', 0xa1),\n '\\Lambda' : ('cmr10', 0xa4),\n '\\Omega' : ('cmr10', 0xad),\n '\\Phi' : ('cmr10', 0xa9),\n '\\Pi' : ('cmr10', 0xa6),\n '\\Psi' : ('cmr10', 0xaa),\n '\\Sigma' : ('cmr10', 0xa7),\n '\\Theta' : ('cmr10', 0xa3),\n '\\Upsilon' : ('cmr10', 0xa8),\n '\\Xi' : ('cmr10', 0xa5),\n '\\circumflexaccent' : ('cmr10', 0x5e),\n '\\combiningacuteaccent' : ('cmr10', 0xb6),\n '\\combiningbreve' : ('cmr10', 0xb8),\n '\\combiningdiaeresis' : ('cmr10', 0xc4),\n '\\combiningdotabove' : ('cmr10', 0x5f),\n '\\combininggraveaccent' : ('cmr10', 0xb5),\n '\\combiningoverline' : ('cmr10', 0xb9),\n '\\combiningtilde' : ('cmr10', 0x7e),\n '\\leftbracket' : ('cmr10', 0x5b),\n '\\leftparen' : ('cmr10', 0x28),\n '\\rightbracket' : ('cmr10', 0x5d),\n '\\rightparen' : ('cmr10', 0x29),\n '\\widebar' : ('cmr10', 0xb9),\n ']' : ('cmr10', 0x5d),\n\n '*' : ('cmsy10', 0xa4),\n '\N{MINUS SIGN}' : ('cmsy10', 0xa1),\n '\\Downarrow' : ('cmsy10', 0x2b),\n '\\Im' : ('cmsy10', 0x3d),\n '\\Leftarrow' : ('cmsy10', 0x28),\n '\\Leftrightarrow' : ('cmsy10', 0x2c),\n '\\P' : ('cmsy10', 0x7b),\n '\\Re' : ('cmsy10', 0x3c),\n '\\Rightarrow' : ('cmsy10', 0x29),\n '\\S' : ('cmsy10', 0x78),\n '\\Uparrow' : ('cmsy10', 0x2a),\n '\\Updownarrow' : ('cmsy10', 0x6d),\n '\\Vert' : ('cmsy10', 0x6b),\n '\\aleph' : ('cmsy10', 0x40),\n '\\approx' : ('cmsy10', 0xbc),\n '\\ast' : ('cmsy10', 0xa4),\n '\\asymp' : ('cmsy10', 0xb3),\n '\\backslash' : ('cmsy10', 0x6e),\n '\\bigcirc' : ('cmsy10', 0xb0),\n '\\bigtriangledown' : ('cmsy10', 0x35),\n '\\bigtriangleup' : ('cmsy10', 0x34),\n '\\bot' : ('cmsy10', 0x3f),\n '\\bullet' : ('cmsy10', 0xb2),\n '\\cap' : ('cmsy10', 0x5c),\n '\\cdot' : ('cmsy10', 0xa2),\n '\\circ' : ('cmsy10', 0xb1),\n '\\clubsuit' : ('cmsy10', 0x7c),\n '\\cup' : ('cmsy10', 0x5b),\n '\\dag' : ('cmsy10', 0x79),\n '\\dashv' : ('cmsy10', 0x61),\n '\\ddag' : ('cmsy10', 0x7a),\n '\\diamond' : ('cmsy10', 0xa6),\n '\\diamondsuit' : ('cmsy10', 0x7d),\n '\\div' : ('cmsy10', 0xa5),\n '\\downarrow' : ('cmsy10', 0x23),\n '\\emptyset' : ('cmsy10', 0x3b),\n '\\equiv' : ('cmsy10', 0xb4),\n '\\exists' : ('cmsy10', 0x39),\n '\\forall' : ('cmsy10', 0x38),\n '\\geq' : ('cmsy10', 0xb8),\n '\\gg' : ('cmsy10', 0xc0),\n '\\heartsuit' : ('cmsy10', 0x7e),\n '\\in' : ('cmsy10', 0x32),\n '\\infty' : ('cmsy10', 0x31),\n '\\lbrace' : ('cmsy10', 0x66),\n '\\lceil' : ('cmsy10', 0x64),\n '\\leftarrow' : ('cmsy10', 0xc3),\n '\\leftrightarrow' : ('cmsy10', 0x24),\n '\\leq' : ('cmsy10', 0x2219),\n '\\lfloor' : ('cmsy10', 0x62),\n '\\ll' : ('cmsy10', 0xbf),\n '\\mid' : ('cmsy10', 0x6a),\n '\\mp' : ('cmsy10', 0xa8),\n '\\nabla' : ('cmsy10', 0x72),\n '\\nearrow' : ('cmsy10', 0x25),\n '\\neg' : ('cmsy10', 0x3a),\n '\\ni' : ('cmsy10', 0x33),\n '\\nwarrow' : ('cmsy10', 0x2d),\n '\\odot' : ('cmsy10', 0xaf),\n '\\ominus' : ('cmsy10', 0xaa),\n '\\oplus' : ('cmsy10', 0xa9),\n '\\oslash' : ('cmsy10', 0xae),\n '\\otimes' : ('cmsy10', 0xad),\n '\\pm' : ('cmsy10', 0xa7),\n '\\prec' : ('cmsy10', 0xc1),\n '\\preceq' : ('cmsy10', 0xb9),\n '\\prime' : ('cmsy10', 0x30),\n '\\propto' : ('cmsy10', 0x2f),\n '\\rbrace' : ('cmsy10', 0x67),\n '\\rceil' : ('cmsy10', 0x65),\n '\\rfloor' : ('cmsy10', 0x63),\n '\\rightarrow' : ('cmsy10', 0x21),\n '\\searrow' : ('cmsy10', 0x26),\n '\\sim' : ('cmsy10', 0xbb),\n '\\simeq' : ('cmsy10', 0x27),\n '\\slash' : ('cmsy10', 0x36),\n '\\spadesuit' : ('cmsy10', 0xc4),\n '\\sqcap' : ('cmsy10', 0x75),\n '\\sqcup' : ('cmsy10', 0x74),\n '\\sqsubseteq' : ('cmsy10', 0x76),\n '\\sqsupseteq' : ('cmsy10', 0x77),\n '\\subset' : ('cmsy10', 0xbd),\n '\\subseteq' : ('cmsy10', 0xb5),\n '\\succ' : ('cmsy10', 0xc2),\n '\\succeq' : ('cmsy10', 0xba),\n '\\supset' : ('cmsy10', 0xbe),\n '\\supseteq' : ('cmsy10', 0xb6),\n '\\swarrow' : ('cmsy10', 0x2e),\n '\\times' : ('cmsy10', 0xa3),\n '\\to' : ('cmsy10', 0x21),\n '\\top' : ('cmsy10', 0x3e),\n '\\uparrow' : ('cmsy10', 0x22),\n '\\updownarrow' : ('cmsy10', 0x6c),\n '\\uplus' : ('cmsy10', 0x5d),\n '\\vdash' : ('cmsy10', 0x60),\n '\\vee' : ('cmsy10', 0x5f),\n '\\vert' : ('cmsy10', 0x6a),\n '\\wedge' : ('cmsy10', 0x5e),\n '\\wr' : ('cmsy10', 0x6f),\n '\\|' : ('cmsy10', 0x6b),\n '|' : ('cmsy10', 0x6a),\n\n '\\_' : ('cmtt10', 0x5f)\n}\n\n# Automatically generated.\n\ntype12uni = {\n 'aring' : 229,\n 'quotedblright' : 8221,\n 'V' : 86,\n 'dollar' : 36,\n 'four' : 52,\n 'Yacute' : 221,\n 'P' : 80,\n 'underscore' : 95,\n 'p' : 112,\n 'Otilde' : 213,\n 'perthousand' : 8240,\n 'zero' : 48,\n 'dotlessi' : 305,\n 'Scaron' : 352,\n 'zcaron' : 382,\n 'egrave' : 232,\n 'section' : 167,\n 'Icircumflex' : 206,\n 'ntilde' : 241,\n 'ampersand' : 38,\n 'dotaccent' : 729,\n 'degree' : 176,\n 'K' : 75,\n 'acircumflex' : 226,\n 'Aring' : 197,\n 'k' : 107,\n 'smalltilde' : 732,\n 'Agrave' : 192,\n 'divide' : 247,\n 'ocircumflex' : 244,\n 'asciitilde' : 126,\n 'two' : 50,\n 'E' : 69,\n 'scaron' : 353,\n 'F' : 70,\n 'bracketleft' : 91,\n 'asciicircum' : 94,\n 'f' : 102,\n 'ordmasculine' : 186,\n 'mu' : 181,\n 'paragraph' : 182,\n 'nine' : 57,\n 'v' : 118,\n 'guilsinglleft' : 8249,\n 'backslash' : 92,\n 'six' : 54,\n 'A' : 65,\n 'icircumflex' : 238,\n 'a' : 97,\n 'ogonek' : 731,\n 'q' : 113,\n 'oacute' : 243,\n 'ograve' : 242,\n 'edieresis' : 235,\n 'comma' : 44,\n 'otilde' : 245,\n 'guillemotright' : 187,\n 'ecircumflex' : 234,\n 'greater' : 62,\n 'uacute' : 250,\n 'L' : 76,\n 'bullet' : 8226,\n 'cedilla' : 184,\n 'ydieresis' : 255,\n 'l' : 108,\n 'logicalnot' : 172,\n 'exclamdown' : 161,\n 'endash' : 8211,\n 'agrave' : 224,\n 'Adieresis' : 196,\n 'germandbls' : 223,\n 'Odieresis' : 214,\n 'space' : 32,\n 'quoteright' : 8217,\n 'ucircumflex' : 251,\n 'G' : 71,\n 'quoteleft' : 8216,\n 'W' : 87,\n 'Q' : 81,\n 'g' : 103,\n 'w' : 119,\n 'question' : 63,\n 'one' : 49,\n 'ring' : 730,\n 'figuredash' : 8210,\n 'B' : 66,\n 'iacute' : 237,\n 'Ydieresis' : 376,\n 'R' : 82,\n 'b' : 98,\n 'r' : 114,\n 'Ccedilla' : 199,\n 'minus' : 8722,\n 'Lslash' : 321,\n 'Uacute' : 218,\n 'yacute' : 253,\n 'Ucircumflex' : 219,\n 'quotedbl' : 34,\n 'onehalf' : 189,\n 'Thorn' : 222,\n 'M' : 77,\n 'eight' : 56,\n 'multiply' : 215,\n 'grave' : 96,\n 'Ocircumflex' : 212,\n 'm' : 109,\n 'Ugrave' : 217,\n 'guilsinglright' : 8250,\n 'Ntilde' : 209,\n 'questiondown' : 191,\n 'Atilde' : 195,\n 'ccedilla' : 231,\n 'Z' : 90,\n 'copyright' : 169,\n 'yen' : 165,\n 'Eacute' : 201,\n 'H' : 72,\n 'X' : 88,\n 'Idieresis' : 207,\n 'bar' : 124,\n 'h' : 104,\n 'x' : 120,\n 'udieresis' : 252,\n 'ordfeminine' : 170,\n 'braceleft' : 123,\n 'macron' : 175,\n 'atilde' : 227,\n 'Acircumflex' : 194,\n 'Oslash' : 216,\n 'C' : 67,\n 'quotedblleft' : 8220,\n 'S' : 83,\n 'exclam' : 33,\n 'Zcaron' : 381,\n 'equal' : 61,\n 's' : 115,\n 'eth' : 240,\n 'Egrave' : 200,\n 'hyphen' : 45,\n 'period' : 46,\n 'igrave' : 236,\n 'colon' : 58,\n 'Ecircumflex' : 202,\n 'trademark' : 8482,\n 'Aacute' : 193,\n 'cent' : 162,\n 'lslash' : 322,\n 'c' : 99,\n 'N' : 78,\n 'breve' : 728,\n 'Oacute' : 211,\n 'guillemotleft' : 171,\n 'n' : 110,\n 'idieresis' : 239,\n 'braceright' : 125,\n 'seven' : 55,\n 'brokenbar' : 166,\n 'ugrave' : 249,\n 'periodcentered' : 183,\n 'sterling' : 163,\n 'I' : 73,\n 'Y' : 89,\n 'Eth' : 208,\n 'emdash' : 8212,\n 'i' : 105,\n 'daggerdbl' : 8225,\n 'y' : 121,\n 'plusminus' : 177,\n 'less' : 60,\n 'Udieresis' : 220,\n 'D' : 68,\n 'five' : 53,\n 'T' : 84,\n 'oslash' : 248,\n 'acute' : 180,\n 'd' : 100,\n 'OE' : 338,\n 'Igrave' : 204,\n 't' : 116,\n 'parenright' : 41,\n 'adieresis' : 228,\n 'quotesingle' : 39,\n 'twodotenleader' : 8229,\n 'slash' : 47,\n 'ellipsis' : 8230,\n 'numbersign' : 35,\n 'odieresis' : 246,\n 'O' : 79,\n 'oe' : 339,\n 'o' : 111,\n 'Edieresis' : 203,\n 'plus' : 43,\n 'dagger' : 8224,\n 'three' : 51,\n 'hungarumlaut' : 733,\n 'parenleft' : 40,\n 'fraction' : 8260,\n 'registered' : 174,\n 'J' : 74,\n 'dieresis' : 168,\n 'Ograve' : 210,\n 'j' : 106,\n 'z' : 122,\n 'ae' : 230,\n 'semicolon' : 59,\n 'at' : 64,\n 'Iacute' : 205,\n 'percent' : 37,\n 'bracketright' : 93,\n 'AE' : 198,\n 'asterisk' : 42,\n 'aacute' : 225,\n 'U' : 85,\n 'eacute' : 233,\n 'e' : 101,\n 'thorn' : 254,\n 'u' : 117,\n}\n\nuni2type1 = {v: k for k, v in type12uni.items()}\n\n# The script below is to sort and format the tex2uni dict\n\n## For decimal values: int(hex(v), 16)\n# newtex = {k: hex(v) for k, v in tex2uni.items()}\n# sd = dict(sorted(newtex.items(), key=lambda item: item[0]))\n#\n## For formatting the sorted dictionary with proper spacing\n## the value '24' comes from finding the longest string in\n## the newtex keys with len(max(newtex, key=len))\n# for key in sd:\n# print("{0:24} : {1: <s},".format("'" + key + "'", sd[key]))\n\ntex2uni = {\n '#' : 0x23,\n '$' : 0x24,\n '%' : 0x25,\n 'AA' : 0xc5,\n 'AE' : 0xc6,\n 'BbbC' : 0x2102,\n 'BbbN' : 0x2115,\n 'BbbP' : 0x2119,\n 'BbbQ' : 0x211a,\n 'BbbR' : 0x211d,\n 'BbbZ' : 0x2124,\n 'Bumpeq' : 0x224e,\n 'Cap' : 0x22d2,\n 'Colon' : 0x2237,\n 'Cup' : 0x22d3,\n 'DH' : 0xd0,\n 'Delta' : 0x394,\n 'Doteq' : 0x2251,\n 'Downarrow' : 0x21d3,\n 'Equiv' : 0x2263,\n 'Finv' : 0x2132,\n 'Game' : 0x2141,\n 'Gamma' : 0x393,\n 'H' : 0x30b,\n 'Im' : 0x2111,\n 'Join' : 0x2a1d,\n 'L' : 0x141,\n 'Lambda' : 0x39b,\n 'Ldsh' : 0x21b2,\n 'Leftarrow' : 0x21d0,\n 'Leftrightarrow' : 0x21d4,\n 'Lleftarrow' : 0x21da,\n 'Longleftarrow' : 0x27f8,\n 'Longleftrightarrow' : 0x27fa,\n 'Longrightarrow' : 0x27f9,\n 'Lsh' : 0x21b0,\n 'Nearrow' : 0x21d7,\n 'Nwarrow' : 0x21d6,\n 'O' : 0xd8,\n 'OE' : 0x152,\n 'Omega' : 0x3a9,\n 'P' : 0xb6,\n 'Phi' : 0x3a6,\n 'Pi' : 0x3a0,\n 'Psi' : 0x3a8,\n 'QED' : 0x220e,\n 'Rdsh' : 0x21b3,\n 'Re' : 0x211c,\n 'Rightarrow' : 0x21d2,\n 'Rrightarrow' : 0x21db,\n 'Rsh' : 0x21b1,\n 'S' : 0xa7,\n 'Searrow' : 0x21d8,\n 'Sigma' : 0x3a3,\n 'Subset' : 0x22d0,\n 'Supset' : 0x22d1,\n 'Swarrow' : 0x21d9,\n 'Theta' : 0x398,\n 'Thorn' : 0xde,\n 'Uparrow' : 0x21d1,\n 'Updownarrow' : 0x21d5,\n 'Upsilon' : 0x3a5,\n 'Vdash' : 0x22a9,\n 'Vert' : 0x2016,\n 'Vvdash' : 0x22aa,\n 'Xi' : 0x39e,\n '_' : 0x5f,\n '__sqrt__' : 0x221a,\n 'aa' : 0xe5,\n 'ac' : 0x223e,\n 'acute' : 0x301,\n 'acwopencirclearrow' : 0x21ba,\n 'adots' : 0x22f0,\n 'ae' : 0xe6,\n 'aleph' : 0x2135,\n 'alpha' : 0x3b1,\n 'amalg' : 0x2a3f,\n 'angle' : 0x2220,\n 'approx' : 0x2248,\n 'approxeq' : 0x224a,\n 'approxident' : 0x224b,\n 'arceq' : 0x2258,\n 'ast' : 0x2217,\n 'asterisk' : 0x2a,\n 'asymp' : 0x224d,\n 'backcong' : 0x224c,\n 'backepsilon' : 0x3f6,\n 'backprime' : 0x2035,\n 'backsim' : 0x223d,\n 'backsimeq' : 0x22cd,\n 'backslash' : 0x5c,\n 'bagmember' : 0x22ff,\n 'bar' : 0x304,\n 'barleftarrow' : 0x21e4,\n 'barvee' : 0x22bd,\n 'barwedge' : 0x22bc,\n 'because' : 0x2235,\n 'beta' : 0x3b2,\n 'beth' : 0x2136,\n 'between' : 0x226c,\n 'bigcap' : 0x22c2,\n 'bigcirc' : 0x25cb,\n 'bigcup' : 0x22c3,\n 'bigodot' : 0x2a00,\n 'bigoplus' : 0x2a01,\n 'bigotimes' : 0x2a02,\n 'bigsqcup' : 0x2a06,\n 'bigstar' : 0x2605,\n 'bigtriangledown' : 0x25bd,\n 'bigtriangleup' : 0x25b3,\n 'biguplus' : 0x2a04,\n 'bigvee' : 0x22c1,\n 'bigwedge' : 0x22c0,\n 'blacksquare' : 0x25a0,\n 'blacktriangle' : 0x25b4,\n 'blacktriangledown' : 0x25be,\n 'blacktriangleleft' : 0x25c0,\n 'blacktriangleright' : 0x25b6,\n 'bot' : 0x22a5,\n 'bowtie' : 0x22c8,\n 'boxbar' : 0x25eb,\n 'boxdot' : 0x22a1,\n 'boxminus' : 0x229f,\n 'boxplus' : 0x229e,\n 'boxtimes' : 0x22a0,\n 'breve' : 0x306,\n 'bullet' : 0x2219,\n 'bumpeq' : 0x224f,\n 'c' : 0x327,\n 'candra' : 0x310,\n 'cap' : 0x2229,\n 'carriagereturn' : 0x21b5,\n 'cdot' : 0x22c5,\n 'cdotp' : 0xb7,\n 'cdots' : 0x22ef,\n 'cent' : 0xa2,\n 'check' : 0x30c,\n 'checkmark' : 0x2713,\n 'chi' : 0x3c7,\n 'circ' : 0x2218,\n 'circeq' : 0x2257,\n 'circlearrowleft' : 0x21ba,\n 'circlearrowright' : 0x21bb,\n 'circledR' : 0xae,\n 'circledS' : 0x24c8,\n 'circledast' : 0x229b,\n 'circledcirc' : 0x229a,\n 'circleddash' : 0x229d,\n 'circumflexaccent' : 0x302,\n 'clubsuit' : 0x2663,\n 'clubsuitopen' : 0x2667,\n 'colon' : 0x3a,\n 'coloneq' : 0x2254,\n 'combiningacuteaccent' : 0x301,\n 'combiningbreve' : 0x306,\n 'combiningdiaeresis' : 0x308,\n 'combiningdotabove' : 0x307,\n 'combiningfourdotsabove' : 0x20dc,\n 'combininggraveaccent' : 0x300,\n 'combiningoverline' : 0x304,\n 'combiningrightarrowabove' : 0x20d7,\n 'combiningthreedotsabove' : 0x20db,\n 'combiningtilde' : 0x303,\n 'complement' : 0x2201,\n 'cong' : 0x2245,\n 'coprod' : 0x2210,\n 'copyright' : 0xa9,\n 'cup' : 0x222a,\n 'cupdot' : 0x228d,\n 'cupleftarrow' : 0x228c,\n 'curlyeqprec' : 0x22de,\n 'curlyeqsucc' : 0x22df,\n 'curlyvee' : 0x22ce,\n 'curlywedge' : 0x22cf,\n 'curvearrowleft' : 0x21b6,\n 'curvearrowright' : 0x21b7,\n 'cwopencirclearrow' : 0x21bb,\n 'd' : 0x323,\n 'dag' : 0x2020,\n 'dagger' : 0x2020,\n 'daleth' : 0x2138,\n 'danger' : 0x2621,\n 'dashleftarrow' : 0x290e,\n 'dashrightarrow' : 0x290f,\n 'dashv' : 0x22a3,\n 'ddag' : 0x2021,\n 'ddagger' : 0x2021,\n 'ddddot' : 0x20dc,\n 'dddot' : 0x20db,\n 'ddot' : 0x308,\n 'ddots' : 0x22f1,\n 'degree' : 0xb0,\n 'delta' : 0x3b4,\n 'dh' : 0xf0,\n 'diamond' : 0x22c4,\n 'diamondsuit' : 0x2662,\n 'digamma' : 0x3dd,\n 'disin' : 0x22f2,\n 'div' : 0xf7,\n 'divideontimes' : 0x22c7,\n 'dot' : 0x307,\n 'doteq' : 0x2250,\n 'doteqdot' : 0x2251,\n 'dotminus' : 0x2238,\n 'dotplus' : 0x2214,\n 'dots' : 0x2026,\n 'dotsminusdots' : 0x223a,\n 'doublebarwedge' : 0x2306,\n 'downarrow' : 0x2193,\n 'downdownarrows' : 0x21ca,\n 'downharpoonleft' : 0x21c3,\n 'downharpoonright' : 0x21c2,\n 'downzigzagarrow' : 0x21af,\n 'ell' : 0x2113,\n 'emdash' : 0x2014,\n 'emptyset' : 0x2205,\n 'endash' : 0x2013,\n 'epsilon' : 0x3b5,\n 'eqcirc' : 0x2256,\n 'eqcolon' : 0x2255,\n 'eqdef' : 0x225d,\n 'eqgtr' : 0x22dd,\n 'eqless' : 0x22dc,\n 'eqsim' : 0x2242,\n 'eqslantgtr' : 0x2a96,\n 'eqslantless' : 0x2a95,\n 'equal' : 0x3d,\n 'equalparallel' : 0x22d5,\n 'equiv' : 0x2261,\n 'eta' : 0x3b7,\n 'eth' : 0xf0,\n 'exists' : 0x2203,\n 'fallingdotseq' : 0x2252,\n 'flat' : 0x266d,\n 'forall' : 0x2200,\n 'frakC' : 0x212d,\n 'frakZ' : 0x2128,\n 'frown' : 0x2322,\n 'gamma' : 0x3b3,\n 'geq' : 0x2265,\n 'geqq' : 0x2267,\n 'geqslant' : 0x2a7e,\n 'gg' : 0x226b,\n 'ggg' : 0x22d9,\n 'gimel' : 0x2137,\n 'gnapprox' : 0x2a8a,\n 'gneqq' : 0x2269,\n 'gnsim' : 0x22e7,\n 'grave' : 0x300,\n 'greater' : 0x3e,\n 'gtrapprox' : 0x2a86,\n 'gtrdot' : 0x22d7,\n 'gtreqless' : 0x22db,\n 'gtreqqless' : 0x2a8c,\n 'gtrless' : 0x2277,\n 'gtrsim' : 0x2273,\n 'guillemotleft' : 0xab,\n 'guillemotright' : 0xbb,\n 'guilsinglleft' : 0x2039,\n 'guilsinglright' : 0x203a,\n 'hat' : 0x302,\n 'hbar' : 0x127,\n 'heartsuit' : 0x2661,\n 'hermitmatrix' : 0x22b9,\n 'hookleftarrow' : 0x21a9,\n 'hookrightarrow' : 0x21aa,\n 'hslash' : 0x210f,\n 'i' : 0x131,\n 'iiiint' : 0x2a0c,\n 'iiint' : 0x222d,\n 'iint' : 0x222c,\n 'imageof' : 0x22b7,\n 'imath' : 0x131,\n 'in' : 0x2208,\n 'increment' : 0x2206,\n 'infty' : 0x221e,\n 'int' : 0x222b,\n 'intercal' : 0x22ba,\n 'invnot' : 0x2310,\n 'iota' : 0x3b9,\n 'isinE' : 0x22f9,\n 'isindot' : 0x22f5,\n 'isinobar' : 0x22f7,\n 'isins' : 0x22f4,\n 'isinvb' : 0x22f8,\n 'jmath' : 0x237,\n 'k' : 0x328,\n 'kappa' : 0x3ba,\n 'kernelcontraction' : 0x223b,\n 'l' : 0x142,\n 'lambda' : 0x3bb,\n 'lambdabar' : 0x19b,\n 'langle' : 0x27e8,\n 'lasp' : 0x2bd,\n 'lbrace' : 0x7b,\n 'lbrack' : 0x5b,\n 'lceil' : 0x2308,\n 'ldots' : 0x2026,\n 'leadsto' : 0x21dd,\n 'leftarrow' : 0x2190,\n 'leftarrowtail' : 0x21a2,\n 'leftbrace' : 0x7b,\n 'leftharpoonaccent' : 0x20d0,\n 'leftharpoondown' : 0x21bd,\n 'leftharpoonup' : 0x21bc,\n 'leftleftarrows' : 0x21c7,\n 'leftparen' : 0x28,\n 'leftrightarrow' : 0x2194,\n 'leftrightarrows' : 0x21c6,\n 'leftrightharpoons' : 0x21cb,\n 'leftrightsquigarrow' : 0x21ad,\n 'leftsquigarrow' : 0x219c,\n 'leftthreetimes' : 0x22cb,\n 'leq' : 0x2264,\n 'leqq' : 0x2266,\n 'leqslant' : 0x2a7d,\n 'less' : 0x3c,\n 'lessapprox' : 0x2a85,\n 'lessdot' : 0x22d6,\n 'lesseqgtr' : 0x22da,\n 'lesseqqgtr' : 0x2a8b,\n 'lessgtr' : 0x2276,\n 'lesssim' : 0x2272,\n 'lfloor' : 0x230a,\n 'lgroup' : 0x27ee,\n 'lhd' : 0x25c1,\n 'll' : 0x226a,\n 'llcorner' : 0x231e,\n 'lll' : 0x22d8,\n 'lnapprox' : 0x2a89,\n 'lneqq' : 0x2268,\n 'lnsim' : 0x22e6,\n 'longleftarrow' : 0x27f5,\n 'longleftrightarrow' : 0x27f7,\n 'longmapsto' : 0x27fc,\n 'longrightarrow' : 0x27f6,\n 'looparrowleft' : 0x21ab,\n 'looparrowright' : 0x21ac,\n 'lq' : 0x2018,\n 'lrcorner' : 0x231f,\n 'ltimes' : 0x22c9,\n 'macron' : 0xaf,\n 'maltese' : 0x2720,\n 'mapsdown' : 0x21a7,\n 'mapsfrom' : 0x21a4,\n 'mapsto' : 0x21a6,\n 'mapsup' : 0x21a5,\n 'measeq' : 0x225e,\n 'measuredangle' : 0x2221,\n 'measuredrightangle' : 0x22be,\n 'merge' : 0x2a55,\n 'mho' : 0x2127,\n 'mid' : 0x2223,\n 'minus' : 0x2212,\n 'minuscolon' : 0x2239,\n 'models' : 0x22a7,\n 'mp' : 0x2213,\n 'mu' : 0x3bc,\n 'multimap' : 0x22b8,\n 'nLeftarrow' : 0x21cd,\n 'nLeftrightarrow' : 0x21ce,\n 'nRightarrow' : 0x21cf,\n 'nVDash' : 0x22af,\n 'nVdash' : 0x22ae,\n 'nabla' : 0x2207,\n 'napprox' : 0x2249,\n 'natural' : 0x266e,\n 'ncong' : 0x2247,\n 'ne' : 0x2260,\n 'nearrow' : 0x2197,\n 'neg' : 0xac,\n 'neq' : 0x2260,\n 'nequiv' : 0x2262,\n 'nexists' : 0x2204,\n 'ngeq' : 0x2271,\n 'ngtr' : 0x226f,\n 'ngtrless' : 0x2279,\n 'ngtrsim' : 0x2275,\n 'ni' : 0x220b,\n 'niobar' : 0x22fe,\n 'nis' : 0x22fc,\n 'nisd' : 0x22fa,\n 'nleftarrow' : 0x219a,\n 'nleftrightarrow' : 0x21ae,\n 'nleq' : 0x2270,\n 'nless' : 0x226e,\n 'nlessgtr' : 0x2278,\n 'nlesssim' : 0x2274,\n 'nmid' : 0x2224,\n 'not' : 0x338,\n 'notin' : 0x2209,\n 'notsmallowns' : 0x220c,\n 'nparallel' : 0x2226,\n 'nprec' : 0x2280,\n 'npreccurlyeq' : 0x22e0,\n 'nrightarrow' : 0x219b,\n 'nsim' : 0x2241,\n 'nsimeq' : 0x2244,\n 'nsqsubseteq' : 0x22e2,\n 'nsqsupseteq' : 0x22e3,\n 'nsubset' : 0x2284,\n 'nsubseteq' : 0x2288,\n 'nsucc' : 0x2281,\n 'nsucccurlyeq' : 0x22e1,\n 'nsupset' : 0x2285,\n 'nsupseteq' : 0x2289,\n 'ntriangleleft' : 0x22ea,\n 'ntrianglelefteq' : 0x22ec,\n 'ntriangleright' : 0x22eb,\n 'ntrianglerighteq' : 0x22ed,\n 'nu' : 0x3bd,\n 'nvDash' : 0x22ad,\n 'nvdash' : 0x22ac,\n 'nwarrow' : 0x2196,\n 'o' : 0xf8,\n 'obar' : 0x233d,\n 'ocirc' : 0x30a,\n 'odot' : 0x2299,\n 'oe' : 0x153,\n 'oequal' : 0x229c,\n 'oiiint' : 0x2230,\n 'oiint' : 0x222f,\n 'oint' : 0x222e,\n 'omega' : 0x3c9,\n 'ominus' : 0x2296,\n 'oplus' : 0x2295,\n 'origof' : 0x22b6,\n 'oslash' : 0x2298,\n 'otimes' : 0x2297,\n 'overarc' : 0x311,\n 'overleftarrow' : 0x20d6,\n 'overleftrightarrow' : 0x20e1,\n 'parallel' : 0x2225,\n 'partial' : 0x2202,\n 'perp' : 0x27c2,\n 'perthousand' : 0x2030,\n 'phi' : 0x3d5,\n 'pi' : 0x3c0,\n 'pitchfork' : 0x22d4,\n 'plus' : 0x2b,\n 'pm' : 0xb1,\n 'prec' : 0x227a,\n 'precapprox' : 0x2ab7,\n 'preccurlyeq' : 0x227c,\n 'preceq' : 0x227c,\n 'precnapprox' : 0x2ab9,\n 'precnsim' : 0x22e8,\n 'precsim' : 0x227e,\n 'prime' : 0x2032,\n 'prod' : 0x220f,\n 'propto' : 0x221d,\n 'prurel' : 0x22b0,\n 'psi' : 0x3c8,\n 'quad' : 0x2003,\n 'questeq' : 0x225f,\n 'rangle' : 0x27e9,\n 'rasp' : 0x2bc,\n 'ratio' : 0x2236,\n 'rbrace' : 0x7d,\n 'rbrack' : 0x5d,\n 'rceil' : 0x2309,\n 'rfloor' : 0x230b,\n 'rgroup' : 0x27ef,\n 'rhd' : 0x25b7,\n 'rho' : 0x3c1,\n 'rightModels' : 0x22ab,\n 'rightangle' : 0x221f,\n 'rightarrow' : 0x2192,\n 'rightarrowbar' : 0x21e5,\n 'rightarrowtail' : 0x21a3,\n 'rightassert' : 0x22a6,\n 'rightbrace' : 0x7d,\n 'rightharpoonaccent' : 0x20d1,\n 'rightharpoondown' : 0x21c1,\n 'rightharpoonup' : 0x21c0,\n 'rightleftarrows' : 0x21c4,\n 'rightleftharpoons' : 0x21cc,\n 'rightparen' : 0x29,\n 'rightrightarrows' : 0x21c9,\n 'rightsquigarrow' : 0x219d,\n 'rightthreetimes' : 0x22cc,\n 'rightzigzagarrow' : 0x21dd,\n 'ring' : 0x2da,\n 'risingdotseq' : 0x2253,\n 'rq' : 0x2019,\n 'rtimes' : 0x22ca,\n 'scrB' : 0x212c,\n 'scrE' : 0x2130,\n 'scrF' : 0x2131,\n 'scrH' : 0x210b,\n 'scrI' : 0x2110,\n 'scrL' : 0x2112,\n 'scrM' : 0x2133,\n 'scrR' : 0x211b,\n 'scre' : 0x212f,\n 'scrg' : 0x210a,\n 'scro' : 0x2134,\n 'scurel' : 0x22b1,\n 'searrow' : 0x2198,\n 'setminus' : 0x2216,\n 'sharp' : 0x266f,\n 'sigma' : 0x3c3,\n 'sim' : 0x223c,\n 'simeq' : 0x2243,\n 'simneqq' : 0x2246,\n 'sinewave' : 0x223f,\n 'slash' : 0x2215,\n 'smallin' : 0x220a,\n 'smallintclockwise' : 0x2231,\n 'smallointctrcclockwise' : 0x2233,\n 'smallowns' : 0x220d,\n 'smallsetminus' : 0x2216,\n 'smallvarointclockwise' : 0x2232,\n 'smile' : 0x2323,\n 'solbar' : 0x233f,\n 'spadesuit' : 0x2660,\n 'spadesuitopen' : 0x2664,\n 'sphericalangle' : 0x2222,\n 'sqcap' : 0x2293,\n 'sqcup' : 0x2294,\n 'sqsubset' : 0x228f,\n 'sqsubseteq' : 0x2291,\n 'sqsubsetneq' : 0x22e4,\n 'sqsupset' : 0x2290,\n 'sqsupseteq' : 0x2292,\n 'sqsupsetneq' : 0x22e5,\n 'ss' : 0xdf,\n 'star' : 0x22c6,\n 'stareq' : 0x225b,\n 'sterling' : 0xa3,\n 'subset' : 0x2282,\n 'subseteq' : 0x2286,\n 'subseteqq' : 0x2ac5,\n 'subsetneq' : 0x228a,\n 'subsetneqq' : 0x2acb,\n 'succ' : 0x227b,\n 'succapprox' : 0x2ab8,\n 'succcurlyeq' : 0x227d,\n 'succeq' : 0x227d,\n 'succnapprox' : 0x2aba,\n 'succnsim' : 0x22e9,\n 'succsim' : 0x227f,\n 'sum' : 0x2211,\n 'supset' : 0x2283,\n 'supseteq' : 0x2287,\n 'supseteqq' : 0x2ac6,\n 'supsetneq' : 0x228b,\n 'supsetneqq' : 0x2acc,\n 'swarrow' : 0x2199,\n 't' : 0x361,\n 'tau' : 0x3c4,\n 'textasciiacute' : 0xb4,\n 'textasciicircum' : 0x5e,\n 'textasciigrave' : 0x60,\n 'textasciitilde' : 0x7e,\n 'textexclamdown' : 0xa1,\n 'textquestiondown' : 0xbf,\n 'textquotedblleft' : 0x201c,\n 'textquotedblright' : 0x201d,\n 'therefore' : 0x2234,\n 'theta' : 0x3b8,\n 'thickspace' : 0x2005,\n 'thorn' : 0xfe,\n 'tilde' : 0x303,\n 'times' : 0xd7,\n 'to' : 0x2192,\n 'top' : 0x22a4,\n 'triangle' : 0x25b3,\n 'triangledown' : 0x25bf,\n 'triangleeq' : 0x225c,\n 'triangleleft' : 0x25c1,\n 'trianglelefteq' : 0x22b4,\n 'triangleq' : 0x225c,\n 'triangleright' : 0x25b7,\n 'trianglerighteq' : 0x22b5,\n 'turnednot' : 0x2319,\n 'twoheaddownarrow' : 0x21a1,\n 'twoheadleftarrow' : 0x219e,\n 'twoheadrightarrow' : 0x21a0,\n 'twoheaduparrow' : 0x219f,\n 'ulcorner' : 0x231c,\n 'underbar' : 0x331,\n 'unlhd' : 0x22b4,\n 'unrhd' : 0x22b5,\n 'uparrow' : 0x2191,\n 'updownarrow' : 0x2195,\n 'updownarrowbar' : 0x21a8,\n 'updownarrows' : 0x21c5,\n 'upharpoonleft' : 0x21bf,\n 'upharpoonright' : 0x21be,\n 'uplus' : 0x228e,\n 'upsilon' : 0x3c5,\n 'upuparrows' : 0x21c8,\n 'urcorner' : 0x231d,\n 'vDash' : 0x22a8,\n 'varepsilon' : 0x3b5,\n 'varisinobar' : 0x22f6,\n 'varisins' : 0x22f3,\n 'varkappa' : 0x3f0,\n 'varlrtriangle' : 0x22bf,\n 'varniobar' : 0x22fd,\n 'varnis' : 0x22fb,\n 'varnothing' : 0x2205,\n 'varphi' : 0x3c6,\n 'varpi' : 0x3d6,\n 'varpropto' : 0x221d,\n 'varrho' : 0x3f1,\n 'varsigma' : 0x3c2,\n 'vartheta' : 0x3d1,\n 'vartriangle' : 0x25b5,\n 'vartriangleleft' : 0x22b2,\n 'vartriangleright' : 0x22b3,\n 'vdash' : 0x22a2,\n 'vdots' : 0x22ee,\n 'vec' : 0x20d7,\n 'vee' : 0x2228,\n 'veebar' : 0x22bb,\n 'veeeq' : 0x225a,\n 'vert' : 0x7c,\n 'wedge' : 0x2227,\n 'wedgeq' : 0x2259,\n 'widebar' : 0x305,\n 'widehat' : 0x302,\n 'widetilde' : 0x303,\n 'wp' : 0x2118,\n 'wr' : 0x2240,\n 'xi' : 0x3be,\n 'yen' : 0xa5,\n 'zeta' : 0x3b6,\n '{' : 0x7b,\n '|' : 0x2016,\n '}' : 0x7d,\n}\n\n# Each element is a 4-tuple of the form:\n# src_start, src_end, dst_font, dst_start\n\n_EntryTypeIn = tuple[str, str, str, str | int]\n_EntryTypeOut = tuple[int, int, str, int]\n\n_stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeIn]] | list[_EntryTypeIn]] = {\n 'bb': {\n "rm": [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER B}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL A}"),\n ("\N{LATIN CAPITAL LETTER C}",\n "\N{LATIN CAPITAL LETTER C}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL C}"),\n ("\N{LATIN CAPITAL LETTER D}",\n "\N{LATIN CAPITAL LETTER G}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL D}"),\n ("\N{LATIN CAPITAL LETTER H}",\n "\N{LATIN CAPITAL LETTER H}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL H}"),\n ("\N{LATIN CAPITAL LETTER I}",\n "\N{LATIN CAPITAL LETTER M}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}"),\n ("\N{LATIN CAPITAL LETTER N}",\n "\N{LATIN CAPITAL LETTER N}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL N}"),\n ("\N{LATIN CAPITAL LETTER O}",\n "\N{LATIN CAPITAL LETTER O}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL O}"),\n ("\N{LATIN CAPITAL LETTER P}",\n "\N{LATIN CAPITAL LETTER Q}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL P}"),\n ("\N{LATIN CAPITAL LETTER R}",\n "\N{LATIN CAPITAL LETTER R}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL R}"),\n ("\N{LATIN CAPITAL LETTER S}",\n "\N{LATIN CAPITAL LETTER Y}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL S}"),\n ("\N{LATIN CAPITAL LETTER Z}",\n "\N{LATIN CAPITAL LETTER Z}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL Z}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK SMALL A}"),\n ("\N{GREEK CAPITAL LETTER GAMMA}",\n "\N{GREEK CAPITAL LETTER GAMMA}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL GAMMA}"),\n ("\N{GREEK CAPITAL LETTER PI}",\n "\N{GREEK CAPITAL LETTER PI}",\n "rm",\n "\N{DOUBLE-STRUCK CAPITAL PI}"),\n ("\N{GREEK CAPITAL LETTER SIGMA}",\n "\N{GREEK CAPITAL LETTER SIGMA}",\n "rm",\n "\N{DOUBLE-STRUCK N-ARY SUMMATION}"),\n ("\N{GREEK SMALL LETTER GAMMA}",\n "\N{GREEK SMALL LETTER GAMMA}",\n "rm",\n "\N{DOUBLE-STRUCK SMALL GAMMA}"),\n ("\N{GREEK SMALL LETTER PI}",\n "\N{GREEK SMALL LETTER PI}",\n "rm",\n "\N{DOUBLE-STRUCK SMALL PI}"),\n ],\n "it": [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER B}",\n "it",\n 0xe154),\n ("\N{LATIN CAPITAL LETTER C}",\n "\N{LATIN CAPITAL LETTER C}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL C}"),\n ("\N{LATIN CAPITAL LETTER D}",\n "\N{LATIN CAPITAL LETTER D}",\n "it",\n "\N{DOUBLE-STRUCK ITALIC CAPITAL D}"),\n ("\N{LATIN CAPITAL LETTER E}",\n "\N{LATIN CAPITAL LETTER G}",\n "it",\n 0xe156),\n ("\N{LATIN CAPITAL LETTER H}",\n "\N{LATIN CAPITAL LETTER H}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL H}"),\n ("\N{LATIN CAPITAL LETTER I}",\n "\N{LATIN CAPITAL LETTER M}",\n "it",\n 0xe159),\n ("\N{LATIN CAPITAL LETTER N}",\n "\N{LATIN CAPITAL LETTER N}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL N}"),\n ("\N{LATIN CAPITAL LETTER O}",\n "\N{LATIN CAPITAL LETTER O}",\n "it",\n 0xe15e),\n ("\N{LATIN CAPITAL LETTER P}",\n "\N{LATIN CAPITAL LETTER Q}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL P}"),\n ("\N{LATIN CAPITAL LETTER R}",\n "\N{LATIN CAPITAL LETTER R}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL R}"),\n ("\N{LATIN CAPITAL LETTER S}",\n "\N{LATIN CAPITAL LETTER Y}",\n "it",\n 0xe15f),\n ("\N{LATIN CAPITAL LETTER Z}",\n "\N{LATIN CAPITAL LETTER Z}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL Z}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER C}",\n "it",\n 0xe166),\n ("\N{LATIN SMALL LETTER D}",\n "\N{LATIN SMALL LETTER E}",\n "it",\n "\N{DOUBLE-STRUCK ITALIC SMALL D}"),\n ("\N{LATIN SMALL LETTER F}",\n "\N{LATIN SMALL LETTER H}",\n "it",\n 0xe169),\n ("\N{LATIN SMALL LETTER I}",\n "\N{LATIN SMALL LETTER J}",\n "it",\n "\N{DOUBLE-STRUCK ITALIC SMALL I}"),\n ("\N{LATIN SMALL LETTER K}",\n "\N{LATIN SMALL LETTER Z}",\n "it",\n 0xe16c),\n ("\N{GREEK CAPITAL LETTER GAMMA}",\n "\N{GREEK CAPITAL LETTER GAMMA}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL GAMMA}"), # \Gamma (not in beta STIX fonts)\n ("\N{GREEK CAPITAL LETTER PI}",\n "\N{GREEK CAPITAL LETTER PI}",\n "it",\n "\N{DOUBLE-STRUCK CAPITAL PI}"),\n ("\N{GREEK CAPITAL LETTER SIGMA}",\n "\N{GREEK CAPITAL LETTER SIGMA}",\n "it",\n "\N{DOUBLE-STRUCK N-ARY SUMMATION}"), # \Sigma (not in beta STIX fonts)\n ("\N{GREEK SMALL LETTER GAMMA}",\n "\N{GREEK SMALL LETTER GAMMA}",\n "it",\n "\N{DOUBLE-STRUCK SMALL GAMMA}"), # \gamma (not in beta STIX fonts)\n ("\N{GREEK SMALL LETTER PI}",\n "\N{GREEK SMALL LETTER PI}",\n "it",\n "\N{DOUBLE-STRUCK SMALL PI}"),\n ],\n "bf": [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER B}",\n "bf",\n 0xe38a),\n ("\N{LATIN CAPITAL LETTER C}",\n "\N{LATIN CAPITAL LETTER C}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL C}"),\n ("\N{LATIN CAPITAL LETTER D}",\n "\N{LATIN CAPITAL LETTER D}",\n "bf",\n "\N{DOUBLE-STRUCK ITALIC CAPITAL D}"),\n ("\N{LATIN CAPITAL LETTER E}",\n "\N{LATIN CAPITAL LETTER G}",\n "bf",\n 0xe38d),\n ("\N{LATIN CAPITAL LETTER H}",\n "\N{LATIN CAPITAL LETTER H}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL H}"),\n ("\N{LATIN CAPITAL LETTER I}",\n "\N{LATIN CAPITAL LETTER M}",\n "bf",\n 0xe390),\n ("\N{LATIN CAPITAL LETTER N}",\n "\N{LATIN CAPITAL LETTER N}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL N}"),\n ("\N{LATIN CAPITAL LETTER O}",\n "\N{LATIN CAPITAL LETTER O}",\n "bf",\n 0xe395),\n ("\N{LATIN CAPITAL LETTER P}",\n "\N{LATIN CAPITAL LETTER Q}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL P}"),\n ("\N{LATIN CAPITAL LETTER R}",\n "\N{LATIN CAPITAL LETTER R}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL R}"),\n ("\N{LATIN CAPITAL LETTER S}",\n "\N{LATIN CAPITAL LETTER Y}",\n "bf",\n 0xe396),\n ("\N{LATIN CAPITAL LETTER Z}",\n "\N{LATIN CAPITAL LETTER Z}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL Z}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER C}",\n "bf",\n 0xe39d),\n ("\N{LATIN SMALL LETTER D}",\n "\N{LATIN SMALL LETTER E}",\n "bf",\n "\N{DOUBLE-STRUCK ITALIC SMALL D}"),\n ("\N{LATIN SMALL LETTER F}",\n "\N{LATIN SMALL LETTER H}",\n "bf",\n 0xe3a2),\n ("\N{LATIN SMALL LETTER I}",\n "\N{LATIN SMALL LETTER J}",\n "bf",\n "\N{DOUBLE-STRUCK ITALIC SMALL I}"),\n ("\N{LATIN SMALL LETTER K}",\n "\N{LATIN SMALL LETTER Z}",\n "bf",\n 0xe3a7),\n ("\N{GREEK CAPITAL LETTER GAMMA}",\n "\N{GREEK CAPITAL LETTER GAMMA}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL GAMMA}"),\n ("\N{GREEK CAPITAL LETTER PI}",\n "\N{GREEK CAPITAL LETTER PI}",\n "bf",\n "\N{DOUBLE-STRUCK CAPITAL PI}"),\n ("\N{GREEK CAPITAL LETTER SIGMA}",\n "\N{GREEK CAPITAL LETTER SIGMA}",\n "bf",\n "\N{DOUBLE-STRUCK N-ARY SUMMATION}"),\n ("\N{GREEK SMALL LETTER GAMMA}",\n "\N{GREEK SMALL LETTER GAMMA}",\n "bf",\n "\N{DOUBLE-STRUCK SMALL GAMMA}"),\n ("\N{GREEK SMALL LETTER PI}",\n "\N{GREEK SMALL LETTER PI}",\n "bf",\n "\N{DOUBLE-STRUCK SMALL PI}"),\n ],\n },\n 'cal': [\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "it",\n 0xe22d),\n ],\n 'frak': {\n "rm": [\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER B}",\n "rm",\n "\N{MATHEMATICAL FRAKTUR CAPITAL A}"),\n ("\N{LATIN CAPITAL LETTER C}",\n "\N{LATIN CAPITAL LETTER C}",\n "rm",\n "\N{BLACK-LETTER CAPITAL C}"),\n ("\N{LATIN CAPITAL LETTER D}",\n "\N{LATIN CAPITAL LETTER G}",\n "rm",\n "\N{MATHEMATICAL FRAKTUR CAPITAL D}"),\n ("\N{LATIN CAPITAL LETTER H}",\n "\N{LATIN CAPITAL LETTER H}",\n "rm",\n "\N{BLACK-LETTER CAPITAL H}"),\n ("\N{LATIN CAPITAL LETTER I}",\n "\N{LATIN CAPITAL LETTER I}",\n "rm",\n "\N{BLACK-LETTER CAPITAL I}"),\n ("\N{LATIN CAPITAL LETTER J}",\n "\N{LATIN CAPITAL LETTER Q}",\n "rm",\n "\N{MATHEMATICAL FRAKTUR CAPITAL J}"),\n ("\N{LATIN CAPITAL LETTER R}",\n "\N{LATIN CAPITAL LETTER R}",\n "rm",\n "\N{BLACK-LETTER CAPITAL R}"),\n ("\N{LATIN CAPITAL LETTER S}",\n "\N{LATIN CAPITAL LETTER Y}",\n "rm",\n "\N{MATHEMATICAL FRAKTUR CAPITAL S}"),\n ("\N{LATIN CAPITAL LETTER Z}",\n "\N{LATIN CAPITAL LETTER Z}",\n "rm",\n "\N{BLACK-LETTER CAPITAL Z}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL FRAKTUR SMALL A}"),\n ],\n "bf": [\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "bf",\n "\N{MATHEMATICAL BOLD FRAKTUR CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "bf",\n "\N{MATHEMATICAL BOLD FRAKTUR SMALL A}"),\n ],\n },\n 'scr': [\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER A}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL A}"),\n ("\N{LATIN CAPITAL LETTER B}",\n "\N{LATIN CAPITAL LETTER B}",\n "it",\n "\N{SCRIPT CAPITAL B}"),\n ("\N{LATIN CAPITAL LETTER C}",\n "\N{LATIN CAPITAL LETTER D}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL C}"),\n ("\N{LATIN CAPITAL LETTER E}",\n "\N{LATIN CAPITAL LETTER F}",\n "it",\n "\N{SCRIPT CAPITAL E}"),\n ("\N{LATIN CAPITAL LETTER G}",\n "\N{LATIN CAPITAL LETTER G}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL G}"),\n ("\N{LATIN CAPITAL LETTER H}",\n "\N{LATIN CAPITAL LETTER H}",\n "it",\n "\N{SCRIPT CAPITAL H}"),\n ("\N{LATIN CAPITAL LETTER I}",\n "\N{LATIN CAPITAL LETTER I}",\n "it",\n "\N{SCRIPT CAPITAL I}"),\n ("\N{LATIN CAPITAL LETTER J}",\n "\N{LATIN CAPITAL LETTER K}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL J}"),\n ("\N{LATIN CAPITAL LETTER L}",\n "\N{LATIN CAPITAL LETTER L}",\n "it",\n "\N{SCRIPT CAPITAL L}"),\n ("\N{LATIN CAPITAL LETTER M}",\n "\N{LATIN CAPITAL LETTER M}",\n "it",\n "\N{SCRIPT CAPITAL M}"),\n ("\N{LATIN CAPITAL LETTER N}",\n "\N{LATIN CAPITAL LETTER Q}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL N}"),\n ("\N{LATIN CAPITAL LETTER R}",\n "\N{LATIN CAPITAL LETTER R}",\n "it",\n "\N{SCRIPT CAPITAL R}"),\n ("\N{LATIN CAPITAL LETTER S}",\n "\N{LATIN CAPITAL LETTER Z}",\n "it",\n "\N{MATHEMATICAL SCRIPT CAPITAL S}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER D}",\n "it",\n "\N{MATHEMATICAL SCRIPT SMALL A}"),\n ("\N{LATIN SMALL LETTER E}",\n "\N{LATIN SMALL LETTER E}",\n "it",\n "\N{SCRIPT SMALL E}"),\n ("\N{LATIN SMALL LETTER F}",\n "\N{LATIN SMALL LETTER F}",\n "it",\n "\N{MATHEMATICAL SCRIPT SMALL F}"),\n ("\N{LATIN SMALL LETTER G}",\n "\N{LATIN SMALL LETTER G}",\n "it",\n "\N{SCRIPT SMALL G}"),\n ("\N{LATIN SMALL LETTER H}",\n "\N{LATIN SMALL LETTER N}",\n "it",\n "\N{MATHEMATICAL SCRIPT SMALL H}"),\n ("\N{LATIN SMALL LETTER O}",\n "\N{LATIN SMALL LETTER O}",\n "it",\n "\N{SCRIPT SMALL O}"),\n ("\N{LATIN SMALL LETTER P}",\n "\N{LATIN SMALL LETTER Z}",\n "it",\n "\N{MATHEMATICAL SCRIPT SMALL P}"),\n ],\n 'sf': {\n "rm": [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL SANS-SERIF DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL SANS-SERIF CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL SANS-SERIF SMALL A}"),\n ("\N{GREEK CAPITAL LETTER ALPHA}",\n "\N{GREEK CAPITAL LETTER OMEGA}",\n "rm",\n 0xe17d),\n ("\N{GREEK SMALL LETTER ALPHA}",\n "\N{GREEK SMALL LETTER OMEGA}",\n "rm",\n 0xe196),\n ("\N{GREEK THETA SYMBOL}",\n "\N{GREEK THETA SYMBOL}",\n "rm",\n 0xe1b0),\n ("\N{GREEK PHI SYMBOL}",\n "\N{GREEK PHI SYMBOL}",\n "rm",\n 0xe1b1),\n ("\N{GREEK PI SYMBOL}",\n "\N{GREEK PI SYMBOL}",\n "rm",\n 0xe1b3),\n ("\N{GREEK RHO SYMBOL}",\n "\N{GREEK RHO SYMBOL}",\n "rm",\n 0xe1b2),\n ("\N{GREEK LUNATE EPSILON SYMBOL}",\n "\N{GREEK LUNATE EPSILON SYMBOL}",\n "rm",\n 0xe1af),\n ("\N{PARTIAL DIFFERENTIAL}",\n "\N{PARTIAL DIFFERENTIAL}",\n "rm",\n 0xe17c),\n ],\n "it": [\n # These numerals are actually upright. We don't actually\n # want italic numerals ever.\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL SANS-SERIF DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "it",\n "\N{MATHEMATICAL SANS-SERIF ITALIC CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "it",\n "\N{MATHEMATICAL SANS-SERIF ITALIC SMALL A}"),\n ("\N{GREEK CAPITAL LETTER ALPHA}",\n "\N{GREEK CAPITAL LETTER OMEGA}",\n "rm",\n 0xe17d),\n ("\N{GREEK SMALL LETTER ALPHA}",\n "\N{GREEK SMALL LETTER OMEGA}",\n "it",\n 0xe1d8),\n ("\N{GREEK THETA SYMBOL}",\n "\N{GREEK THETA SYMBOL}",\n "it",\n 0xe1f2),\n ("\N{GREEK PHI SYMBOL}",\n "\N{GREEK PHI SYMBOL}",\n "it",\n 0xe1f3),\n ("\N{GREEK PI SYMBOL}",\n "\N{GREEK PI SYMBOL}",\n "it",\n 0xe1f5),\n ("\N{GREEK RHO SYMBOL}",\n "\N{GREEK RHO SYMBOL}",\n "it",\n 0xe1f4),\n ("\N{GREEK LUNATE EPSILON SYMBOL}",\n "\N{GREEK LUNATE EPSILON SYMBOL}",\n "it",\n 0xe1f1),\n ],\n "bf": [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD SMALL A}"),\n ("\N{GREEK CAPITAL LETTER ALPHA}",\n "\N{GREEK CAPITAL LETTER OMEGA}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA}"),\n ("\N{GREEK SMALL LETTER ALPHA}",\n "\N{GREEK SMALL LETTER OMEGA}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA}"),\n ("\N{GREEK THETA SYMBOL}",\n "\N{GREEK THETA SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL}"),\n ("\N{GREEK PHI SYMBOL}",\n "\N{GREEK PHI SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL}"),\n ("\N{GREEK PI SYMBOL}",\n "\N{GREEK PI SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD PI SYMBOL}"),\n ("\N{GREEK KAPPA SYMBOL}",\n "\N{GREEK KAPPA SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL}"),\n ("\N{GREEK RHO SYMBOL}",\n "\N{GREEK RHO SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL}"),\n ("\N{GREEK LUNATE EPSILON SYMBOL}",\n "\N{GREEK LUNATE EPSILON SYMBOL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL}"),\n ("\N{PARTIAL DIFFERENTIAL}",\n "\N{PARTIAL DIFFERENTIAL}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL}"),\n ("\N{NABLA}",\n "\N{NABLA}",\n "bf",\n "\N{MATHEMATICAL SANS-SERIF BOLD NABLA}"),\n ],\n "bfit": [\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "bfit",\n "\N{MATHEMATICAL BOLD ITALIC CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "bfit",\n "\N{MATHEMATICAL BOLD ITALIC SMALL A}"),\n ("\N{GREEK CAPITAL LETTER GAMMA}",\n "\N{GREEK CAPITAL LETTER OMEGA}",\n "bfit",\n "\N{MATHEMATICAL BOLD ITALIC CAPITAL GAMMA}"),\n ("\N{GREEK SMALL LETTER ALPHA}",\n "\N{GREEK SMALL LETTER OMEGA}",\n "bfit",\n "\N{MATHEMATICAL BOLD ITALIC SMALL ALPHA}"),\n ],\n },\n 'tt': [\n ("\N{DIGIT ZERO}",\n "\N{DIGIT NINE}",\n "rm",\n "\N{MATHEMATICAL MONOSPACE DIGIT ZERO}"),\n ("\N{LATIN CAPITAL LETTER A}",\n "\N{LATIN CAPITAL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL MONOSPACE CAPITAL A}"),\n ("\N{LATIN SMALL LETTER A}",\n "\N{LATIN SMALL LETTER Z}",\n "rm",\n "\N{MATHEMATICAL MONOSPACE SMALL A}")\n ],\n}\n\n\n@overload\ndef _normalize_stix_fontcodes(d: _EntryTypeIn) -> _EntryTypeOut: ...\n\n\n@overload\ndef _normalize_stix_fontcodes(d: list[_EntryTypeIn]) -> list[_EntryTypeOut]: ...\n\n\n@overload\ndef _normalize_stix_fontcodes(d: dict[str, list[_EntryTypeIn] |\n dict[str, list[_EntryTypeIn]]]\n ) -> dict[str, list[_EntryTypeOut] |\n dict[str, list[_EntryTypeOut]]]: ...\n\n\ndef _normalize_stix_fontcodes(d):\n if isinstance(d, tuple):\n return tuple(ord(x) if isinstance(x, str) and len(x) == 1 else x for x in d)\n elif isinstance(d, list):\n return [_normalize_stix_fontcodes(x) for x in d]\n elif isinstance(d, dict):\n return {k: _normalize_stix_fontcodes(v) for k, v in d.items()}\n\n\nstix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]]\nstix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts)\n\n# Free redundant list now that it has been normalized\ndel _stix_virtual_fonts\n\n# Fix some incorrect glyphs.\nstix_glyph_fixes = {\n # Cap and Cup glyphs are swapped.\n 0x22d2: 0x22d3,\n 0x22d3: 0x22d2,\n}\n
.venv\Lib\site-packages\matplotlib\_mathtext_data.py
_mathtext_data.py
Python
65,067
0.75
0.007463
0.010496
node-utils
72
2024-08-01T01:27:01.571391
MIT
false
f1579db547a0405f85954d4ec37774a0
from collections.abc import Sequence\n\nimport numpy as np\n\nfrom .transforms import BboxBase\n\ndef affine_transform(points: np.ndarray, trans: np.ndarray) -> np.ndarray: ...\ndef count_bboxes_overlapping_bbox(bbox: BboxBase, bboxes: Sequence[BboxBase]) -> int: ...\ndef update_path_extents(path, trans, rect, minpos, ignore): ...\n
.venv\Lib\site-packages\matplotlib\_path.pyi
_path.pyi
Other
325
0.85
0.333333
0
awesome-app
249
2025-04-13T23:31:51.722053
Apache-2.0
false
7b377a4bfcc21529904e2a7f24d31b66
"""\nManage figures for the pyplot interface.\n"""\n\nimport atexit\nfrom collections import OrderedDict\n\n\nclass Gcf:\n """\n Singleton to maintain the relation between figures and their managers, and\n keep track of and "active" figure and manager.\n\n The canvas of a figure created through pyplot is associated with a figure\n manager, which handles the interaction between the figure and the backend.\n pyplot keeps track of figure managers using an identifier, the "figure\n number" or "manager number" (which can actually be any hashable value);\n this number is available as the :attr:`number` attribute of the manager.\n\n This class is never instantiated; it consists of an `OrderedDict` mapping\n figure/manager numbers to managers, and a set of class methods that\n manipulate this `OrderedDict`.\n\n Attributes\n ----------\n figs : OrderedDict\n `OrderedDict` mapping numbers to managers; the active manager is at the\n end.\n """\n\n figs = OrderedDict()\n\n @classmethod\n def get_fig_manager(cls, num):\n """\n If manager number *num* exists, make it the active one and return it;\n otherwise return *None*.\n """\n manager = cls.figs.get(num, None)\n if manager is not None:\n cls.set_active(manager)\n return manager\n\n @classmethod\n def destroy(cls, num):\n """\n Destroy manager *num* -- either a manager instance or a manager number.\n\n In the interactive backends, this is bound to the window "destroy" and\n "delete" events.\n\n It is recommended to pass a manager instance, to avoid confusion when\n two managers share the same number.\n """\n if all(hasattr(num, attr) for attr in ["num", "destroy"]):\n manager = num\n if cls.figs.get(manager.num) is manager:\n cls.figs.pop(manager.num)\n else:\n try:\n manager = cls.figs.pop(num)\n except KeyError:\n return\n if hasattr(manager, "_cidgcf"):\n manager.canvas.mpl_disconnect(manager._cidgcf)\n manager.destroy()\n\n @classmethod\n def destroy_fig(cls, fig):\n """Destroy figure *fig*."""\n num = next((manager.num for manager in cls.figs.values()\n if manager.canvas.figure == fig), None)\n if num is not None:\n cls.destroy(num)\n\n @classmethod\n def destroy_all(cls):\n """Destroy all figures."""\n for manager in list(cls.figs.values()):\n manager.canvas.mpl_disconnect(manager._cidgcf)\n manager.destroy()\n cls.figs.clear()\n\n @classmethod\n def has_fignum(cls, num):\n """Return whether figure number *num* exists."""\n return num in cls.figs\n\n @classmethod\n def get_all_fig_managers(cls):\n """Return a list of figure managers."""\n return list(cls.figs.values())\n\n @classmethod\n def get_num_fig_managers(cls):\n """Return the number of figures being managed."""\n return len(cls.figs)\n\n @classmethod\n def get_active(cls):\n """Return the active manager, or *None* if there is no manager."""\n return next(reversed(cls.figs.values())) if cls.figs else None\n\n @classmethod\n def _set_new_active_manager(cls, manager):\n """Adopt *manager* into pyplot and make it the active manager."""\n if not hasattr(manager, "_cidgcf"):\n manager._cidgcf = manager.canvas.mpl_connect(\n "button_press_event", lambda event: cls.set_active(manager))\n fig = manager.canvas.figure\n fig._number = manager.num\n label = fig.get_label()\n if label:\n manager.set_window_title(label)\n cls.set_active(manager)\n\n @classmethod\n def set_active(cls, manager):\n """Make *manager* the active manager."""\n cls.figs[manager.num] = manager\n cls.figs.move_to_end(manager.num)\n\n @classmethod\n def draw_all(cls, force=False):\n """\n Redraw all stale managed figures, or, if *force* is True, all managed\n figures.\n """\n for manager in cls.get_all_fig_managers():\n if force or manager.canvas.figure.stale:\n manager.canvas.draw_idle()\n\n\natexit.register(Gcf.destroy_all)\n
.venv\Lib\site-packages\matplotlib\_pylab_helpers.py
_pylab_helpers.py
Python
4,307
0.85
0.238806
0
react-lib
499
2025-01-01T09:25:31.932380
BSD-3-Clause
false
5ba79962e544b7012ece8205244202d4
from collections import OrderedDict\n\nfrom matplotlib.backend_bases import FigureManagerBase\nfrom matplotlib.figure import Figure\n\nclass Gcf:\n figs: OrderedDict[int, FigureManagerBase]\n @classmethod\n def get_fig_manager(cls, num: int) -> FigureManagerBase | None: ...\n @classmethod\n def destroy(cls, num: int | FigureManagerBase) -> None: ...\n @classmethod\n def destroy_fig(cls, fig: Figure) -> None: ...\n @classmethod\n def destroy_all(cls) -> None: ...\n @classmethod\n def has_fignum(cls, num: int) -> bool: ...\n @classmethod\n def get_all_fig_managers(cls) -> list[FigureManagerBase]: ...\n @classmethod\n def get_num_fig_managers(cls) -> int: ...\n @classmethod\n def get_active(cls) -> FigureManagerBase | None: ...\n @classmethod\n def _set_new_active_manager(cls, manager: FigureManagerBase) -> None: ...\n @classmethod\n def set_active(cls, manager: FigureManagerBase) -> None: ...\n @classmethod\n def draw_all(cls, force: bool = ...) -> None: ...\n
.venv\Lib\site-packages\matplotlib\_pylab_helpers.pyi
_pylab_helpers.pyi
Other
1,012
0.85
0.413793
0
python-kit
821
2025-05-23T00:59:55.487942
MIT
false
2688278901c5ab1285b10c533cf58d8f
"""\nLow-level text helper utilities.\n"""\n\nfrom __future__ import annotations\n\nimport dataclasses\n\nfrom . import _api\nfrom .ft2font import FT2Font, Kerning, LoadFlags\n\n\n@dataclasses.dataclass(frozen=True)\nclass LayoutItem:\n ft_object: FT2Font\n char: str\n glyph_idx: int\n x: float\n prev_kern: float\n\n\ndef warn_on_missing_glyph(codepoint, fontnames):\n _api.warn_external(\n f"Glyph {codepoint} "\n f"({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) "\n f"missing from font(s) {fontnames}.")\n\n block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else\n "Arabic" if 0x0600 <= codepoint <= 0x06ff else\n "Devanagari" if 0x0900 <= codepoint <= 0x097f else\n "Bengali" if 0x0980 <= codepoint <= 0x09ff else\n "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else\n "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else\n "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else\n "Tamil" if 0x0b80 <= codepoint <= 0x0bff else\n "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else\n "Kannada" if 0x0c80 <= codepoint <= 0x0cff else\n "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else\n "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else\n None)\n if block:\n _api.warn_external(\n f"Matplotlib currently does not support {block} natively.")\n\n\ndef layout(string, font, *, kern_mode=Kerning.DEFAULT):\n """\n Render *string* with *font*.\n\n For each character in *string*, yield a LayoutItem instance. When such an instance\n is yielded, the font's glyph is set to the corresponding character.\n\n Parameters\n ----------\n string : str\n The string to be rendered.\n font : FT2Font\n The font.\n kern_mode : Kerning\n A FreeType kerning mode.\n\n Yields\n ------\n LayoutItem\n """\n x = 0\n prev_glyph_idx = None\n char_to_font = font._get_fontmap(string)\n base_font = font\n for char in string:\n # This has done the fallback logic\n font = char_to_font.get(char, base_font)\n glyph_idx = font.get_char_index(ord(char))\n kern = (\n base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64\n if prev_glyph_idx is not None else 0.\n )\n x += kern\n glyph = font.load_glyph(glyph_idx, flags=LoadFlags.NO_HINTING)\n yield LayoutItem(font, char, glyph_idx, x, kern)\n x += glyph.linearHoriAdvance / 65536\n prev_glyph_idx = glyph_idx\n
.venv\Lib\site-packages\matplotlib\_text_helpers.py
_text_helpers.py
Python
2,538
0.95
0.219512
0.014493
vue-tools
498
2024-06-01T19:24:11.629738
Apache-2.0
false
d90cdc67380f9de1723d015c537a8f25
"""\nHelper module for the *bbox_inches* parameter in `.Figure.savefig`.\n"""\n\nfrom matplotlib.transforms import Bbox, TransformedBbox, Affine2D\n\n\ndef adjust_bbox(fig, bbox_inches, fixed_dpi=None):\n """\n Temporarily adjust the figure so that only the specified area\n (bbox_inches) is saved.\n\n It modifies fig.bbox, fig.bbox_inches,\n fig.transFigure._boxout, and fig.patch. While the figure size\n changes, the scale of the original figure is conserved. A\n function which restores the original values are returned.\n """\n origBbox = fig.bbox\n origBboxInches = fig.bbox_inches\n _boxout = fig.transFigure._boxout\n\n old_aspect = []\n locator_list = []\n sentinel = object()\n for ax in fig.axes:\n locator = ax.get_axes_locator()\n if locator is not None:\n ax.apply_aspect(locator(ax, None))\n locator_list.append(locator)\n current_pos = ax.get_position(original=False).frozen()\n ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)\n # override the method that enforces the aspect ratio on the Axes\n if 'apply_aspect' in ax.__dict__:\n old_aspect.append(ax.apply_aspect)\n else:\n old_aspect.append(sentinel)\n ax.apply_aspect = lambda pos=None: None\n\n def restore_bbox():\n for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):\n ax.set_axes_locator(loc)\n if aspect is sentinel:\n # delete our no-op function which un-hides the original method\n del ax.apply_aspect\n else:\n ax.apply_aspect = aspect\n\n fig.bbox = origBbox\n fig.bbox_inches = origBboxInches\n fig.transFigure._boxout = _boxout\n fig.transFigure.invalidate()\n fig.patch.set_bounds(0, 0, 1, 1)\n\n if fixed_dpi is None:\n fixed_dpi = fig.dpi\n tr = Affine2D().scale(fixed_dpi)\n dpi_scale = fixed_dpi / fig.dpi\n\n fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)\n x0, y0 = tr.transform(bbox_inches.p0)\n w1, h1 = fig.bbox.size * dpi_scale\n fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)\n fig.transFigure.invalidate()\n\n fig.bbox = TransformedBbox(fig.bbox_inches, tr)\n\n fig.patch.set_bounds(x0 / w1, y0 / h1,\n fig.bbox.width / w1, fig.bbox.height / h1)\n\n return restore_bbox\n\n\ndef process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):\n """\n A function that needs to be called when figure dpi changes during the\n drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with\n the new dpi.\n """\n\n bbox_inches, restore_bbox = bbox_inches_restore\n restore_bbox()\n r = adjust_bbox(fig, bbox_inches, fixed_dpi)\n\n return bbox_inches, r\n
.venv\Lib\site-packages\matplotlib\_tight_bbox.py
_tight_bbox.py
Python
2,787
0.95
0.154762
0.029412
vue-tools
309
2024-12-22T20:44:33.423930
MIT
false
035bf8e538b86d99e27eb755f896dc53
"""\nRoutines to adjust subplot params so that subplots are\nnicely fit in the figure. In doing so, only axis labels, tick labels, Axes\ntitles and offsetboxes that are anchored to Axes are currently considered.\n\nInternally, this module assumes that the margins (left margin, etc.) which are\ndifferences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of\nAxes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as\nsuch cases as when left or right margin are affected by xlabel.\n"""\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, artist as martist\nfrom matplotlib.font_manager import FontProperties\nfrom matplotlib.transforms import Bbox\n\n\ndef _auto_adjust_subplotpars(\n fig, renderer, shape, span_pairs, subplot_list,\n ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):\n """\n Return a dict of subplot parameters to adjust spacing between subplots\n or ``None`` if resulting Axes would have zero height or width.\n\n Note that this function ignores geometry information of subplot itself, but\n uses what is given by the *shape* and *subplot_list* parameters. Also, the\n results could be incorrect if some subplots have ``adjustable=datalim``.\n\n Parameters\n ----------\n shape : tuple[int, int]\n Number of rows and columns of the grid.\n span_pairs : list[tuple[slice, slice]]\n List of rowspans and colspans occupied by each subplot.\n subplot_list : list of subplots\n List of subplots that will be used to calculate optimal subplot_params.\n pad : float\n Padding between the figure edge and the edges of subplots, as a\n fraction of the font size.\n h_pad, w_pad : float\n Padding (height/width) between edges of adjacent subplots, as a\n fraction of the font size. Defaults to *pad*.\n rect : tuple\n (left, bottom, right, top), default: None.\n """\n rows, cols = shape\n\n font_size_inch = (FontProperties(\n size=mpl.rcParams["font.size"]).get_size_in_points() / 72)\n pad_inch = pad * font_size_inch\n vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch\n hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch\n\n if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0:\n raise ValueError\n\n if rect is None:\n margin_left = margin_bottom = margin_right = margin_top = None\n else:\n margin_left, margin_bottom, _right, _top = rect\n margin_right = 1 - _right if _right else None\n margin_top = 1 - _top if _top else None\n\n vspaces = np.zeros((rows + 1, cols))\n hspaces = np.zeros((rows, cols + 1))\n\n if ax_bbox_list is None:\n ax_bbox_list = [\n Bbox.union([ax.get_position(original=True) for ax in subplots])\n for subplots in subplot_list]\n\n for subplots, ax_bbox, (rowspan, colspan) in zip(\n subplot_list, ax_bbox_list, span_pairs):\n if all(not ax.get_visible() for ax in subplots):\n continue\n\n bb = []\n for ax in subplots:\n if ax.get_visible():\n bb += [martist._get_tightbbox_for_layout_only(ax, renderer)]\n\n tight_bbox_raw = Bbox.union(bb)\n tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw)\n\n hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l\n hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r\n vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t\n vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b\n\n fig_width_inch, fig_height_inch = fig.get_size_inches()\n\n # margins can be negative for Axes with aspect applied, so use max(, 0) to\n # make them nonnegative.\n if not margin_left:\n margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch\n suplabel = fig._supylabel\n if suplabel and suplabel.get_in_layout():\n rel_width = fig.transFigure.inverted().transform_bbox(\n suplabel.get_window_extent(renderer)).width\n margin_left += rel_width + pad_inch/fig_width_inch\n if not margin_right:\n margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch\n if not margin_top:\n margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch\n if fig._suptitle and fig._suptitle.get_in_layout():\n rel_height = fig.transFigure.inverted().transform_bbox(\n fig._suptitle.get_window_extent(renderer)).height\n margin_top += rel_height + pad_inch/fig_height_inch\n if not margin_bottom:\n margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch\n suplabel = fig._supxlabel\n if suplabel and suplabel.get_in_layout():\n rel_height = fig.transFigure.inverted().transform_bbox(\n suplabel.get_window_extent(renderer)).height\n margin_bottom += rel_height + pad_inch/fig_height_inch\n\n if margin_left + margin_right >= 1:\n _api.warn_external('Tight layout not applied. The left and right '\n 'margins cannot be made large enough to '\n 'accommodate all Axes decorations.')\n return None\n if margin_bottom + margin_top >= 1:\n _api.warn_external('Tight layout not applied. The bottom and top '\n 'margins cannot be made large enough to '\n 'accommodate all Axes decorations.')\n return None\n\n kwargs = dict(left=margin_left,\n right=1 - margin_right,\n bottom=margin_bottom,\n top=1 - margin_top)\n\n if cols > 1:\n hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch\n # axes widths:\n h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols\n if h_axes < 0:\n _api.warn_external('Tight layout not applied. tight_layout '\n 'cannot make Axes width small enough to '\n 'accommodate all Axes decorations')\n return None\n else:\n kwargs["wspace"] = hspace / h_axes\n if rows > 1:\n vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch\n v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows\n if v_axes < 0:\n _api.warn_external('Tight layout not applied. tight_layout '\n 'cannot make Axes height small enough to '\n 'accommodate all Axes decorations.')\n return None\n else:\n kwargs["hspace"] = vspace / v_axes\n\n return kwargs\n\n\ndef get_subplotspec_list(axes_list, grid_spec=None):\n """\n Return a list of subplotspec from the given list of Axes.\n\n For an instance of Axes that does not support subplotspec, None is inserted\n in the list.\n\n If grid_spec is given, None is inserted for those not from the given\n grid_spec.\n """\n subplotspec_list = []\n for ax in axes_list:\n axes_or_locator = ax.get_axes_locator()\n if axes_or_locator is None:\n axes_or_locator = ax\n\n if hasattr(axes_or_locator, "get_subplotspec"):\n subplotspec = axes_or_locator.get_subplotspec()\n if subplotspec is not None:\n subplotspec = subplotspec.get_topmost_subplotspec()\n gs = subplotspec.get_gridspec()\n if grid_spec is not None:\n if gs != grid_spec:\n subplotspec = None\n elif gs.locally_modified_subplot_params():\n subplotspec = None\n else:\n subplotspec = None\n\n subplotspec_list.append(subplotspec)\n\n return subplotspec_list\n\n\ndef get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,\n pad=1.08, h_pad=None, w_pad=None, rect=None):\n """\n Return subplot parameters for tight-layouted-figure with specified padding.\n\n Parameters\n ----------\n fig : Figure\n axes_list : list of Axes\n subplotspec_list : list of `.SubplotSpec`\n The subplotspecs of each Axes.\n renderer : renderer\n pad : float\n Padding between the figure edge and the edges of subplots, as a\n fraction of the font size.\n h_pad, w_pad : float\n Padding (height/width) between edges of adjacent subplots. Defaults to\n *pad*.\n rect : tuple (left, bottom, right, top), default: None.\n rectangle in normalized figure coordinates\n that the whole subplots area (including labels) will fit into.\n Defaults to using the entire figure.\n\n Returns\n -------\n subplotspec or None\n subplotspec kwargs to be passed to `.Figure.subplots_adjust` or\n None if tight_layout could not be accomplished.\n """\n\n # Multiple Axes can share same subplotspec (e.g., if using axes_grid1);\n # we need to group them together.\n ss_to_subplots = {ss: [] for ss in subplotspec_list}\n for ax, ss in zip(axes_list, subplotspec_list):\n ss_to_subplots[ss].append(ax)\n if ss_to_subplots.pop(None, None):\n _api.warn_external(\n "This figure includes Axes that are not compatible with "\n "tight_layout, so results might be incorrect.")\n if not ss_to_subplots:\n return {}\n subplot_list = list(ss_to_subplots.values())\n ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots]\n\n max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots)\n max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots)\n\n span_pairs = []\n for ss in ss_to_subplots:\n # The intent here is to support Axes from different gridspecs where\n # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4),\n # but this doesn't actually work because the computed wspace, in\n # relative-axes-height, corresponds to different physical spacings for\n # the 2-row grid and the 4-row grid. Still, this code is left, mostly\n # for backcompat.\n rows, cols = ss.get_gridspec().get_geometry()\n div_row, mod_row = divmod(max_nrows, rows)\n div_col, mod_col = divmod(max_ncols, cols)\n if mod_row != 0:\n _api.warn_external('tight_layout not applied: number of rows '\n 'in subplot specifications must be '\n 'multiples of one another.')\n return {}\n if mod_col != 0:\n _api.warn_external('tight_layout not applied: number of '\n 'columns in subplot specifications must be '\n 'multiples of one another.')\n return {}\n span_pairs.append((\n slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row),\n slice(ss.colspan.start * div_col, ss.colspan.stop * div_col)))\n\n kwargs = _auto_adjust_subplotpars(fig, renderer,\n shape=(max_nrows, max_ncols),\n span_pairs=span_pairs,\n subplot_list=subplot_list,\n ax_bbox_list=ax_bbox_list,\n pad=pad, h_pad=h_pad, w_pad=w_pad)\n\n # kwargs can be none if tight_layout fails...\n if rect is not None and kwargs is not None:\n # if rect is given, the whole subplots area (including\n # labels) will fit into the rect instead of the\n # figure. Note that the rect argument of\n # *auto_adjust_subplotpars* specify the area that will be\n # covered by the total area of axes.bbox. Thus we call\n # auto_adjust_subplotpars twice, where the second run\n # with adjusted rect parameters.\n\n left, bottom, right, top = rect\n if left is not None:\n left += kwargs["left"]\n if bottom is not None:\n bottom += kwargs["bottom"]\n if right is not None:\n right -= (1 - kwargs["right"])\n if top is not None:\n top -= (1 - kwargs["top"])\n\n kwargs = _auto_adjust_subplotpars(fig, renderer,\n shape=(max_nrows, max_ncols),\n span_pairs=span_pairs,\n subplot_list=subplot_list,\n ax_bbox_list=ax_bbox_list,\n pad=pad, h_pad=h_pad, w_pad=w_pad,\n rect=(left, bottom, right, top))\n\n return kwargs\n
.venv\Lib\site-packages\matplotlib\_tight_layout.py
_tight_layout.py
Python
12,675
0.95
0.212625
0.076923
vue-tools
758
2024-11-03T23:46:01.802989
Apache-2.0
false
53a5123b08150f7f624c2e1f10548eec
# This is a private module implemented in C++\nfrom typing import final\n\nimport numpy as np\nimport numpy.typing as npt\n\n@final\nclass TrapezoidMapTriFinder:\n def __init__(self, triangulation: Triangulation): ...\n def find_many(self, x: npt.NDArray[np.float64], y: npt.NDArray[np.float64]) -> npt.NDArray[np.int_]: ...\n def get_tree_stats(self) -> list[int | float]: ...\n def initialize(self) -> None: ...\n def print_tree(self) -> None: ...\n\n@final\nclass TriContourGenerator:\n def __init__(self, triangulation: Triangulation, z: npt.NDArray[np.float64]): ...\n def create_contour(self, level: float) -> tuple[list[float], list[int]]: ...\n def create_filled_contour(self, lower_level: float, upper_level: float) -> tuple[list[float], list[int]]: ...\n\n@final\nclass Triangulation:\n def __init__(\n self,\n x: npt.NDArray[np.float64],\n y: npt.NDArray[np.float64],\n triangles: npt.NDArray[np.int_],\n mask: npt.NDArray[np.bool_] | tuple[()],\n edges: npt.NDArray[np.int_] | tuple[()],\n neighbors: npt.NDArray[np.int_] | tuple[()],\n correct_triangle_orientation: bool,\n ): ...\n def calculate_plane_coefficients(self, z: npt.ArrayLike) -> npt.NDArray[np.float64]: ...\n def get_edges(self) -> npt.NDArray[np.int_]: ...\n def get_neighbors(self) -> npt.NDArray[np.int_]: ...\n def set_mask(self, mask: npt.NDArray[np.bool_] | tuple[()]) -> None: ...\n
.venv\Lib\site-packages\matplotlib\_tri.pyi
_tri.pyi
Other
1,429
0.95
0.444444
0.03125
node-utils
710
2024-06-25T14:08:16.126879
BSD-3-Clause
false
3db883d438ae6256b4467f47a2939169
"""\nA class representing a Type 1 font.\n\nThis version reads pfa and pfb files and splits them for embedding in\npdf files. It also supports SlantFont and ExtendFont transformations,\nsimilarly to pdfTeX and friends. There is no support yet for subsetting.\n\nUsage::\n\n font = Type1Font(filename)\n clear_part, encrypted_part, finale = font.parts\n slanted_font = font.transform({'slant': 0.167})\n extended_font = font.transform({'extend': 1.2})\n\nSources:\n\n* Adobe Technical Note #5040, Supporting Downloadable PostScript\n Language Fonts.\n\n* Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing,\n v1.1, 1993. ISBN 0-201-57044-0.\n"""\n\nfrom __future__ import annotations\n\nimport binascii\nimport functools\nimport logging\nimport re\nimport string\nimport struct\nimport typing as T\n\nimport numpy as np\n\nfrom matplotlib.cbook import _format_approx\nfrom . import _api\n\n_log = logging.getLogger(__name__)\n\n\nclass _Token:\n """\n A token in a PostScript stream.\n\n Attributes\n ----------\n pos : int\n Position, i.e. offset from the beginning of the data.\n raw : str\n Raw text of the token.\n kind : str\n Description of the token (for debugging or testing).\n """\n __slots__ = ('pos', 'raw')\n kind = '?'\n\n def __init__(self, pos, raw):\n _log.debug('type1font._Token %s at %d: %r', self.kind, pos, raw)\n self.pos = pos\n self.raw = raw\n\n def __str__(self):\n return f"<{self.kind} {self.raw} @{self.pos}>"\n\n def endpos(self):\n """Position one past the end of the token"""\n return self.pos + len(self.raw)\n\n def is_keyword(self, *names):\n """Is this a name token with one of the names?"""\n return False\n\n def is_slash_name(self):\n """Is this a name token that starts with a slash?"""\n return False\n\n def is_delim(self):\n """Is this a delimiter token?"""\n return False\n\n def is_number(self):\n """Is this a number token?"""\n return False\n\n def value(self):\n return self.raw\n\n\nclass _NameToken(_Token):\n kind = 'name'\n\n def is_slash_name(self):\n return self.raw.startswith('/')\n\n def value(self):\n return self.raw[1:]\n\n\nclass _BooleanToken(_Token):\n kind = 'boolean'\n\n def value(self):\n return self.raw == 'true'\n\n\nclass _KeywordToken(_Token):\n kind = 'keyword'\n\n def is_keyword(self, *names):\n return self.raw in names\n\n\nclass _DelimiterToken(_Token):\n kind = 'delimiter'\n\n def is_delim(self):\n return True\n\n def opposite(self):\n return {'[': ']', ']': '[',\n '{': '}', '}': '{',\n '<<': '>>', '>>': '<<'\n }[self.raw]\n\n\nclass _WhitespaceToken(_Token):\n kind = 'whitespace'\n\n\nclass _StringToken(_Token):\n kind = 'string'\n _escapes_re = re.compile(r'\\([\\()nrtbf]|[0-7]{1,3})')\n _replacements = {'\\': '\\', '(': '(', ')': ')', 'n': '\n',\n 'r': '\r', 't': '\t', 'b': '\b', 'f': '\f'}\n _ws_re = re.compile('[\0\t\r\f\n ]')\n\n @classmethod\n def _escape(cls, match):\n group = match.group(1)\n try:\n return cls._replacements[group]\n except KeyError:\n return chr(int(group, 8))\n\n @functools.lru_cache\n def value(self):\n if self.raw[0] == '(':\n return self._escapes_re.sub(self._escape, self.raw[1:-1])\n else:\n data = self._ws_re.sub('', self.raw[1:-1])\n if len(data) % 2 == 1:\n data += '0'\n return binascii.unhexlify(data)\n\n\nclass _BinaryToken(_Token):\n kind = 'binary'\n\n def value(self):\n return self.raw[1:]\n\n\nclass _NumberToken(_Token):\n kind = 'number'\n\n def is_number(self):\n return True\n\n def value(self):\n if '.' not in self.raw:\n return int(self.raw)\n else:\n return float(self.raw)\n\n\ndef _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]:\n """\n A generator that produces _Token instances from Type-1 font code.\n\n The consumer of the generator may send an integer to the tokenizer to\n indicate that the next token should be _BinaryToken of the given length.\n\n Parameters\n ----------\n data : bytes\n The data of the font to tokenize.\n\n skip_ws : bool\n If true, the generator will drop any _WhitespaceTokens from the output.\n """\n\n text = data.decode('ascii', 'replace')\n whitespace_or_comment_re = re.compile(r'[\0\t\r\f\n ]+|%[^\r\n]*')\n token_re = re.compile(r'/{0,2}[^]\0\t\r\f\n ()<>{}/%[]+')\n instring_re = re.compile(r'[()\\]')\n hex_re = re.compile(r'^<[0-9a-fA-F\0\t\r\f\n ]*>$')\n oct_re = re.compile(r'[0-7]{1,3}')\n pos = 0\n next_binary: int | None = None\n\n while pos < len(text):\n if next_binary is not None:\n n = next_binary\n next_binary = (yield _BinaryToken(pos, data[pos:pos+n]))\n pos += n\n continue\n match = whitespace_or_comment_re.match(text, pos)\n if match:\n if not skip_ws:\n next_binary = (yield _WhitespaceToken(pos, match.group()))\n pos = match.end()\n elif text[pos] == '(':\n # PostScript string rules:\n # - parentheses must be balanced\n # - backslashes escape backslashes and parens\n # - also codes \n\r\t\b\f and octal escapes are recognized\n # - other backslashes do not escape anything\n start = pos\n pos += 1\n depth = 1\n while depth:\n match = instring_re.search(text, pos)\n if match is None:\n raise ValueError(\n f'Unterminated string starting at {start}')\n pos = match.end()\n if match.group() == '(':\n depth += 1\n elif match.group() == ')':\n depth -= 1\n else: # a backslash\n char = text[pos]\n if char in r'\()nrtbf':\n pos += 1\n else:\n octal = oct_re.match(text, pos)\n if octal:\n pos = octal.end()\n else:\n pass # non-escaping backslash\n next_binary = (yield _StringToken(start, text[start:pos]))\n elif text[pos:pos + 2] in ('<<', '>>'):\n next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2]))\n pos += 2\n elif text[pos] == '<':\n start = pos\n try:\n pos = text.index('>', pos) + 1\n except ValueError as e:\n raise ValueError(f'Unterminated hex string starting at {start}'\n ) from e\n if not hex_re.match(text[start:pos]):\n raise ValueError(f'Malformed hex string starting at {start}')\n next_binary = (yield _StringToken(pos, text[start:pos]))\n else:\n match = token_re.match(text, pos)\n if match:\n raw = match.group()\n if raw.startswith('/'):\n next_binary = (yield _NameToken(pos, raw))\n elif match.group() in ('true', 'false'):\n next_binary = (yield _BooleanToken(pos, raw))\n else:\n try:\n float(raw)\n next_binary = (yield _NumberToken(pos, raw))\n except ValueError:\n next_binary = (yield _KeywordToken(pos, raw))\n pos = match.end()\n else:\n next_binary = (yield _DelimiterToken(pos, text[pos]))\n pos += 1\n\n\nclass _BalancedExpression(_Token):\n pass\n\n\ndef _expression(initial, tokens, data):\n """\n Consume some number of tokens and return a balanced PostScript expression.\n\n Parameters\n ----------\n initial : _Token\n The token that triggered parsing a balanced expression.\n tokens : iterator of _Token\n Following tokens.\n data : bytes\n Underlying data that the token positions point to.\n\n Returns\n -------\n _BalancedExpression\n """\n delim_stack = []\n token = initial\n while True:\n if token.is_delim():\n if token.raw in ('[', '{'):\n delim_stack.append(token)\n elif token.raw in (']', '}'):\n if not delim_stack:\n raise RuntimeError(f"unmatched closing token {token}")\n match = delim_stack.pop()\n if match.raw != token.opposite():\n raise RuntimeError(\n f"opening token {match} closed by {token}"\n )\n if not delim_stack:\n break\n else:\n raise RuntimeError(f'unknown delimiter {token}')\n elif not delim_stack:\n break\n token = next(tokens)\n return _BalancedExpression(\n initial.pos,\n data[initial.pos:token.endpos()].decode('ascii', 'replace')\n )\n\n\nclass Type1Font:\n """\n A class representing a Type-1 font, for use by backends.\n\n Attributes\n ----------\n parts : tuple\n A 3-tuple of the cleartext part, the encrypted part, and the finale of\n zeros.\n\n decrypted : bytes\n The decrypted form of ``parts[1]``.\n\n prop : dict[str, Any]\n A dictionary of font properties. Noteworthy keys include:\n\n - FontName: PostScript name of the font\n - Encoding: dict from numeric codes to glyph names\n - FontMatrix: bytes object encoding a matrix\n - UniqueID: optional font identifier, dropped when modifying the font\n - CharStrings: dict from glyph names to byte code\n - Subrs: array of byte code subroutines\n - OtherSubrs: bytes object encoding some PostScript code\n """\n __slots__ = ('parts', 'decrypted', 'prop', '_pos', '_abbr')\n # the _pos dict contains (begin, end) indices to parts[0] + decrypted\n # so that they can be replaced when transforming the font;\n # but since sometimes a definition appears in both parts[0] and decrypted,\n # _pos[name] is an array of such pairs\n #\n # _abbr maps three standard abbreviations to their particular names in\n # this font (e.g. 'RD' is named '-|' in some fonts)\n\n def __init__(self, input):\n """\n Initialize a Type-1 font.\n\n Parameters\n ----------\n input : str or 3-tuple\n Either a pfb file name, or a 3-tuple of already-decoded Type-1\n font `~.Type1Font.parts`.\n """\n if isinstance(input, tuple) and len(input) == 3:\n self.parts = input\n else:\n with open(input, 'rb') as file:\n data = self._read(file)\n self.parts = self._split(data)\n\n self.decrypted = self._decrypt(self.parts[1], 'eexec')\n self._abbr = {'RD': 'RD', 'ND': 'ND', 'NP': 'NP'}\n self._parse()\n\n def _read(self, file):\n """Read the font from a file, decoding into usable parts."""\n rawdata = file.read()\n if not rawdata.startswith(b'\x80'):\n return rawdata\n\n data = b''\n while rawdata:\n if not rawdata.startswith(b'\x80'):\n raise RuntimeError('Broken pfb file (expected byte 128, '\n 'got %d)' % rawdata[0])\n type = rawdata[1]\n if type in (1, 2):\n length, = struct.unpack('<i', rawdata[2:6])\n segment = rawdata[6:6 + length]\n rawdata = rawdata[6 + length:]\n\n if type == 1: # ASCII text: include verbatim\n data += segment\n elif type == 2: # binary data: encode in hexadecimal\n data += binascii.hexlify(segment)\n elif type == 3: # end of file\n break\n else:\n raise RuntimeError('Unknown segment type %d in pfb file' % type)\n\n return data\n\n def _split(self, data):\n """\n Split the Type 1 font into its three main parts.\n\n The three parts are: (1) the cleartext part, which ends in a\n eexec operator; (2) the encrypted part; (3) the fixed part,\n which contains 512 ASCII zeros possibly divided on various\n lines, a cleartomark operator, and possibly something else.\n """\n\n # Cleartext part: just find the eexec and skip whitespace\n idx = data.index(b'eexec')\n idx += len(b'eexec')\n while data[idx] in b' \t\r\n':\n idx += 1\n len1 = idx\n\n # Encrypted part: find the cleartomark operator and count\n # zeros backward\n idx = data.rindex(b'cleartomark') - 1\n zeros = 512\n while zeros and data[idx] in b'0' or data[idx] in b'\r\n':\n if data[idx] in b'0':\n zeros -= 1\n idx -= 1\n if zeros:\n # this may have been a problem on old implementations that\n # used the zeros as necessary padding\n _log.info('Insufficiently many zeros in Type 1 font')\n\n # Convert encrypted part to binary (if we read a pfb file, we may end\n # up converting binary to hexadecimal to binary again; but if we read\n # a pfa file, this part is already in hex, and I am not quite sure if\n # even the pfb format guarantees that it will be in binary).\n idx1 = len1 + ((idx - len1 + 2) & ~1) # ensure an even number of bytes\n binary = binascii.unhexlify(data[len1:idx1])\n\n return data[:len1], binary, data[idx+1:]\n\n @staticmethod\n def _decrypt(ciphertext, key, ndiscard=4):\n """\n Decrypt ciphertext using the Type-1 font algorithm.\n\n The algorithm is described in Adobe's "Adobe Type 1 Font Format".\n The key argument can be an integer, or one of the strings\n 'eexec' and 'charstring', which map to the key specified for the\n corresponding part of Type-1 fonts.\n\n The ndiscard argument should be an integer, usually 4.\n That number of bytes is discarded from the beginning of plaintext.\n """\n\n key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key)\n plaintext = []\n for byte in ciphertext:\n plaintext.append(byte ^ (key >> 8))\n key = ((key+byte) * 52845 + 22719) & 0xffff\n\n return bytes(plaintext[ndiscard:])\n\n @staticmethod\n def _encrypt(plaintext, key, ndiscard=4):\n """\n Encrypt plaintext using the Type-1 font algorithm.\n\n The algorithm is described in Adobe's "Adobe Type 1 Font Format".\n The key argument can be an integer, or one of the strings\n 'eexec' and 'charstring', which map to the key specified for the\n corresponding part of Type-1 fonts.\n\n The ndiscard argument should be an integer, usually 4. That\n number of bytes is prepended to the plaintext before encryption.\n This function prepends NUL bytes for reproducibility, even though\n the original algorithm uses random bytes, presumably to avoid\n cryptanalysis.\n """\n\n key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key)\n ciphertext = []\n for byte in b'\0' * ndiscard + plaintext:\n c = byte ^ (key >> 8)\n ciphertext.append(c)\n key = ((key + c) * 52845 + 22719) & 0xffff\n\n return bytes(ciphertext)\n\n def _parse(self):\n """\n Find the values of various font properties. This limited kind\n of parsing is described in Chapter 10 "Adobe Type Manager\n Compatibility" of the Type-1 spec.\n """\n # Start with reasonable defaults\n prop = {'Weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False,\n 'UnderlinePosition': -100, 'UnderlineThickness': 50}\n pos = {}\n data = self.parts[0] + self.decrypted\n\n source = _tokenize(data, True)\n while True:\n # See if there is a key to be assigned a value\n # e.g. /FontName in /FontName /Helvetica def\n try:\n token = next(source)\n except StopIteration:\n break\n if token.is_delim():\n # skip over this - we want top-level keys only\n _expression(token, source, data)\n if token.is_slash_name():\n key = token.value()\n keypos = token.pos\n else:\n continue\n\n # Some values need special parsing\n if key in ('Subrs', 'CharStrings', 'Encoding', 'OtherSubrs'):\n prop[key], endpos = {\n 'Subrs': self._parse_subrs,\n 'CharStrings': self._parse_charstrings,\n 'Encoding': self._parse_encoding,\n 'OtherSubrs': self._parse_othersubrs\n }[key](source, data)\n pos.setdefault(key, []).append((keypos, endpos))\n continue\n\n try:\n token = next(source)\n except StopIteration:\n break\n\n if isinstance(token, _KeywordToken):\n # constructs like\n # FontDirectory /Helvetica known {...} {...} ifelse\n # mean the key was not really a key\n continue\n\n if token.is_delim():\n value = _expression(token, source, data).raw\n else:\n value = token.value()\n\n # look for a 'def' possibly preceded by access modifiers\n try:\n kw = next(\n kw for kw in source\n if not kw.is_keyword('readonly', 'noaccess', 'executeonly')\n )\n except StopIteration:\n break\n\n # sometimes noaccess def and readonly def are abbreviated\n if kw.is_keyword('def', self._abbr['ND'], self._abbr['NP']):\n prop[key] = value\n pos.setdefault(key, []).append((keypos, kw.endpos()))\n\n # detect the standard abbreviations\n if value == '{noaccess def}':\n self._abbr['ND'] = key\n elif value == '{noaccess put}':\n self._abbr['NP'] = key\n elif value == '{string currentfile exch readstring pop}':\n self._abbr['RD'] = key\n\n # Fill in the various *Name properties\n if 'FontName' not in prop:\n prop['FontName'] = (prop.get('FullName') or\n prop.get('FamilyName') or\n 'Unknown')\n if 'FullName' not in prop:\n prop['FullName'] = prop['FontName']\n if 'FamilyName' not in prop:\n extras = ('(?i)([ -](regular|plain|italic|oblique|(semi)?bold|'\n '(ultra)?light|extra|condensed))+$')\n prop['FamilyName'] = re.sub(extras, '', prop['FullName'])\n # Decrypt the encrypted parts\n ndiscard = prop.get('lenIV', 4)\n cs = prop['CharStrings']\n for key, value in cs.items():\n cs[key] = self._decrypt(value, 'charstring', ndiscard)\n if 'Subrs' in prop:\n prop['Subrs'] = [\n self._decrypt(value, 'charstring', ndiscard)\n for value in prop['Subrs']\n ]\n\n self.prop = prop\n self._pos = pos\n\n def _parse_subrs(self, tokens, _data):\n count_token = next(tokens)\n if not count_token.is_number():\n raise RuntimeError(\n f"Token following /Subrs must be a number, was {count_token}"\n )\n count = count_token.value()\n array = [None] * count\n next(t for t in tokens if t.is_keyword('array'))\n for _ in range(count):\n next(t for t in tokens if t.is_keyword('dup'))\n index_token = next(tokens)\n if not index_token.is_number():\n raise RuntimeError(\n "Token following dup in Subrs definition must be a "\n f"number, was {index_token}"\n )\n nbytes_token = next(tokens)\n if not nbytes_token.is_number():\n raise RuntimeError(\n "Second token following dup in Subrs definition must "\n f"be a number, was {nbytes_token}"\n )\n token = next(tokens)\n if not token.is_keyword(self._abbr['RD']):\n raise RuntimeError(\n f"Token preceding subr must be {self._abbr['RD']}, "\n f"was {token}"\n )\n binary_token = tokens.send(1+nbytes_token.value())\n array[index_token.value()] = binary_token.value()\n\n return array, next(tokens).endpos()\n\n @staticmethod\n def _parse_charstrings(tokens, _data):\n count_token = next(tokens)\n if not count_token.is_number():\n raise RuntimeError(\n "Token following /CharStrings must be a number, "\n f"was {count_token}"\n )\n count = count_token.value()\n charstrings = {}\n next(t for t in tokens if t.is_keyword('begin'))\n while True:\n token = next(t for t in tokens\n if t.is_keyword('end') or t.is_slash_name())\n if token.raw == 'end':\n return charstrings, token.endpos()\n glyphname = token.value()\n nbytes_token = next(tokens)\n if not nbytes_token.is_number():\n raise RuntimeError(\n f"Token following /{glyphname} in CharStrings definition "\n f"must be a number, was {nbytes_token}"\n )\n next(tokens) # usually RD or |-\n binary_token = tokens.send(1+nbytes_token.value())\n charstrings[glyphname] = binary_token.value()\n\n @staticmethod\n def _parse_encoding(tokens, _data):\n # this only works for encodings that follow the Adobe manual\n # but some old fonts include non-compliant data - we log a warning\n # and return a possibly incomplete encoding\n encoding = {}\n while True:\n token = next(t for t in tokens\n if t.is_keyword('StandardEncoding', 'dup', 'def'))\n if token.is_keyword('StandardEncoding'):\n return _StandardEncoding, token.endpos()\n if token.is_keyword('def'):\n return encoding, token.endpos()\n index_token = next(tokens)\n if not index_token.is_number():\n _log.warning(\n f"Parsing encoding: expected number, got {index_token}"\n )\n continue\n name_token = next(tokens)\n if not name_token.is_slash_name():\n _log.warning(\n f"Parsing encoding: expected slash-name, got {name_token}"\n )\n continue\n encoding[index_token.value()] = name_token.value()\n\n @staticmethod\n def _parse_othersubrs(tokens, data):\n init_pos = None\n while True:\n token = next(tokens)\n if init_pos is None:\n init_pos = token.pos\n if token.is_delim():\n _expression(token, tokens, data)\n elif token.is_keyword('def', 'ND', '|-'):\n return data[init_pos:token.endpos()], token.endpos()\n\n def transform(self, effects):\n """\n Return a new font that is slanted and/or extended.\n\n Parameters\n ----------\n effects : dict\n A dict with optional entries:\n\n - 'slant' : float, default: 0\n Tangent of the angle that the font is to be slanted to the\n right. Negative values slant to the left.\n - 'extend' : float, default: 1\n Scaling factor for the font width. Values less than 1 condense\n the glyphs.\n\n Returns\n -------\n `Type1Font`\n """\n fontname = self.prop['FontName']\n italicangle = self.prop['ItalicAngle']\n\n array = [\n float(x) for x in (self.prop['FontMatrix']\n .lstrip('[').rstrip(']').split())\n ]\n oldmatrix = np.eye(3, 3)\n oldmatrix[0:3, 0] = array[::2]\n oldmatrix[0:3, 1] = array[1::2]\n modifier = np.eye(3, 3)\n\n if 'slant' in effects:\n slant = effects['slant']\n fontname += f'_Slant_{int(1000 * slant)}'\n italicangle = round(\n float(italicangle) - np.arctan(slant) / np.pi * 180,\n 5\n )\n modifier[1, 0] = slant\n\n if 'extend' in effects:\n extend = effects['extend']\n fontname += f'_Extend_{int(1000 * extend)}'\n modifier[0, 0] = extend\n\n newmatrix = np.dot(modifier, oldmatrix)\n array[::2] = newmatrix[0:3, 0]\n array[1::2] = newmatrix[0:3, 1]\n fontmatrix = (\n f"[{' '.join(_format_approx(x, 6) for x in array)}]"\n )\n replacements = (\n [(x, f'/FontName/{fontname} def')\n for x in self._pos['FontName']]\n + [(x, f'/ItalicAngle {italicangle} def')\n for x in self._pos['ItalicAngle']]\n + [(x, f'/FontMatrix {fontmatrix} readonly def')\n for x in self._pos['FontMatrix']]\n + [(x, '') for x in self._pos.get('UniqueID', [])]\n )\n\n data = bytearray(self.parts[0])\n data.extend(self.decrypted)\n len0 = len(self.parts[0])\n for (pos0, pos1), value in sorted(replacements, reverse=True):\n data[pos0:pos1] = value.encode('ascii', 'replace')\n if pos0 < len(self.parts[0]):\n if pos1 >= len(self.parts[0]):\n raise RuntimeError(\n f"text to be replaced with {value} spans "\n "the eexec boundary"\n )\n len0 += len(value) - pos1 + pos0\n\n data = bytes(data)\n return Type1Font((\n data[:len0],\n self._encrypt(data[len0:], 'eexec'),\n self.parts[2]\n ))\n\n\n_StandardEncoding = {\n **{ord(letter): letter for letter in string.ascii_letters},\n 0: '.notdef',\n 32: 'space',\n 33: 'exclam',\n 34: 'quotedbl',\n 35: 'numbersign',\n 36: 'dollar',\n 37: 'percent',\n 38: 'ampersand',\n 39: 'quoteright',\n 40: 'parenleft',\n 41: 'parenright',\n 42: 'asterisk',\n 43: 'plus',\n 44: 'comma',\n 45: 'hyphen',\n 46: 'period',\n 47: 'slash',\n 48: 'zero',\n 49: 'one',\n 50: 'two',\n 51: 'three',\n 52: 'four',\n 53: 'five',\n 54: 'six',\n 55: 'seven',\n 56: 'eight',\n 57: 'nine',\n 58: 'colon',\n 59: 'semicolon',\n 60: 'less',\n 61: 'equal',\n 62: 'greater',\n 63: 'question',\n 64: 'at',\n 91: 'bracketleft',\n 92: 'backslash',\n 93: 'bracketright',\n 94: 'asciicircum',\n 95: 'underscore',\n 96: 'quoteleft',\n 123: 'braceleft',\n 124: 'bar',\n 125: 'braceright',\n 126: 'asciitilde',\n 161: 'exclamdown',\n 162: 'cent',\n 163: 'sterling',\n 164: 'fraction',\n 165: 'yen',\n 166: 'florin',\n 167: 'section',\n 168: 'currency',\n 169: 'quotesingle',\n 170: 'quotedblleft',\n 171: 'guillemotleft',\n 172: 'guilsinglleft',\n 173: 'guilsinglright',\n 174: 'fi',\n 175: 'fl',\n 177: 'endash',\n 178: 'dagger',\n 179: 'daggerdbl',\n 180: 'periodcentered',\n 182: 'paragraph',\n 183: 'bullet',\n 184: 'quotesinglbase',\n 185: 'quotedblbase',\n 186: 'quotedblright',\n 187: 'guillemotright',\n 188: 'ellipsis',\n 189: 'perthousand',\n 191: 'questiondown',\n 193: 'grave',\n 194: 'acute',\n 195: 'circumflex',\n 196: 'tilde',\n 197: 'macron',\n 198: 'breve',\n 199: 'dotaccent',\n 200: 'dieresis',\n 202: 'ring',\n 203: 'cedilla',\n 205: 'hungarumlaut',\n 206: 'ogonek',\n 207: 'caron',\n 208: 'emdash',\n 225: 'AE',\n 227: 'ordfeminine',\n 232: 'Lslash',\n 233: 'Oslash',\n 234: 'OE',\n 235: 'ordmasculine',\n 241: 'ae',\n 245: 'dotlessi',\n 248: 'lslash',\n 249: 'oslash',\n 250: 'oe',\n 251: 'germandbls',\n}\n
.venv\Lib\site-packages\matplotlib\_type1font.py
_type1font.py
Python
28,409
0.95
0.188851
0.052632
vue-tools
448
2024-01-06T06:14:52.085977
BSD-3-Clause
false
4ef2206a9ee40c847285a52078cbe7e5
version = "3.10.3"\n
.venv\Lib\site-packages\matplotlib\_version.py
_version.py
Python
19
0.5
0
0
awesome-app
607
2024-05-15T12:50:44.898350
MIT
false
61441409c7d041db98382e654388f0bc
"""\nAn object-oriented plotting library.\n\nA procedural interface is provided by the companion pyplot module,\nwhich may be imported directly, e.g.::\n\n import matplotlib.pyplot as plt\n\nor using ipython::\n\n ipython\n\nat your terminal, followed by::\n\n In [1]: %matplotlib\n In [2]: import matplotlib.pyplot as plt\n\nat the ipython shell prompt.\n\nFor the most part, direct use of the explicit object-oriented library is\nencouraged when programming; the implicit pyplot interface is primarily for\nworking interactively. The exceptions to this suggestion are the pyplot\nfunctions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and\n`.pyplot.savefig`, which can greatly simplify scripting. See\n:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit\nand explicit interfaces.\n\nModules include:\n\n:mod:`matplotlib.axes`\n The `~.axes.Axes` class. Most pyplot functions are wrappers for\n `~.axes.Axes` methods. The axes module is the highest level of OO\n access to the library.\n\n:mod:`matplotlib.figure`\n The `.Figure` class.\n\n:mod:`matplotlib.artist`\n The `.Artist` base class for all classes that draw things.\n\n:mod:`matplotlib.lines`\n The `.Line2D` class for drawing lines and markers.\n\n:mod:`matplotlib.patches`\n Classes for drawing polygons.\n\n:mod:`matplotlib.text`\n The `.Text` and `.Annotation` classes.\n\n:mod:`matplotlib.image`\n The `.AxesImage` and `.FigureImage` classes.\n\n:mod:`matplotlib.collections`\n Classes for efficient drawing of groups of lines or polygons.\n\n:mod:`matplotlib.colors`\n Color specifications and making colormaps.\n\n:mod:`matplotlib.cm`\n Colormaps, and the `.ScalarMappable` mixin class for providing color\n mapping functionality to other classes.\n\n:mod:`matplotlib.ticker`\n Calculation of tick mark locations and formatting of tick labels.\n\n:mod:`matplotlib.backends`\n A subpackage with modules for various GUI libraries and output formats.\n\nThe base matplotlib namespace includes:\n\n`~matplotlib.rcParams`\n Default configuration settings; their defaults may be overridden using\n a :file:`matplotlibrc` file.\n\n`~matplotlib.use`\n Setting the Matplotlib backend. This should be called before any\n figure is created, because it is not possible to switch between\n different GUI backends after that.\n\nThe following environment variables can be used to customize the behavior:\n\n:envvar:`MPLBACKEND`\n This optional variable can be set to choose the Matplotlib backend. See\n :ref:`what-is-a-backend`.\n\n:envvar:`MPLCONFIGDIR`\n This is the directory used to store user customizations to\n Matplotlib, as well as some caches to improve performance. If\n :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`\n and :file:`{HOME}/.cache/matplotlib` are used on Linux, and\n :file:`{HOME}/.matplotlib` on other platforms, if they are\n writable. Otherwise, the Python standard library's `tempfile.gettempdir`\n is used to find a base directory in which the :file:`matplotlib`\n subdirectory is created.\n\nMatplotlib was initially written by John D. Hunter (1968-2012) and is now\ndeveloped and maintained by a host of others.\n\nOccasionally the internal documentation (python docstrings) will refer\nto MATLAB®, a registered trademark of The MathWorks, Inc.\n\n"""\n\n__all__ = [\n "__bibtex__",\n "__version__",\n "__version_info__",\n "set_loglevel",\n "ExecutableNotFoundError",\n "get_configdir",\n "get_cachedir",\n "get_data_path",\n "matplotlib_fname",\n "MatplotlibDeprecationWarning",\n "RcParams",\n "rc_params",\n "rc_params_from_file",\n "rcParamsDefault",\n "rcParams",\n "rcParamsOrig",\n "defaultParams",\n "rc",\n "rcdefaults",\n "rc_file_defaults",\n "rc_file",\n "rc_context",\n "use",\n "get_backend",\n "interactive",\n "is_interactive",\n "colormaps",\n "multivar_colormaps",\n "bivar_colormaps",\n "color_sequences",\n]\n\n\nimport atexit\nfrom collections import namedtuple\nfrom collections.abc import MutableMapping\nimport contextlib\nimport functools\nimport importlib\nimport inspect\nfrom inspect import Parameter\nimport locale\nimport logging\nimport os\nfrom pathlib import Path\nimport pprint\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\nfrom packaging.version import parse as parse_version\n\n# cbook must import matplotlib only within function\n# definitions, so it is safe to import from it here.\nfrom . import _api, _version, cbook, _docstring, rcsetup\nfrom matplotlib._api import MatplotlibDeprecationWarning\nfrom matplotlib.rcsetup import cycler # noqa: F401\n\n\n_log = logging.getLogger(__name__)\n\n__bibtex__ = r"""@Article{Hunter:2007,\n Author = {Hunter, J. D.},\n Title = {Matplotlib: A 2D graphics environment},\n Journal = {Computing in Science \& Engineering},\n Volume = {9},\n Number = {3},\n Pages = {90--95},\n abstract = {Matplotlib is a 2D graphics package used for Python\n for application development, interactive scripting, and\n publication-quality image generation across user\n interfaces and operating systems.},\n publisher = {IEEE COMPUTER SOC},\n year = 2007\n}"""\n\n# modelled after sys.version_info\n_VersionInfo = namedtuple('_VersionInfo',\n 'major, minor, micro, releaselevel, serial')\n\n\ndef _parse_to_version_info(version_str):\n """\n Parse a version string to a namedtuple analogous to sys.version_info.\n\n See:\n https://packaging.pypa.io/en/latest/version.html#packaging.version.parse\n https://docs.python.org/3/library/sys.html#sys.version_info\n """\n v = parse_version(version_str)\n if v.pre is None and v.post is None and v.dev is None:\n return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)\n elif v.dev is not None:\n return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)\n elif v.pre is not None:\n releaselevel = {\n 'a': 'alpha',\n 'b': 'beta',\n 'rc': 'candidate'}.get(v.pre[0], 'alpha')\n return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])\n else:\n # fallback for v.post: guess-next-dev scheme from setuptools_scm\n return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)\n\n\ndef _get_version():\n """Return the version string used for __version__."""\n # Only shell out to a git subprocess if really needed, i.e. when we are in\n # a matplotlib git repo but not in a shallow clone, such as those used by\n # CI, as the latter would trigger a warning from setuptools_scm.\n root = Path(__file__).resolve().parents[2]\n if ((root / ".matplotlib-repo").exists()\n and (root / ".git").exists()\n and not (root / ".git/shallow").exists()):\n try:\n import setuptools_scm\n except ImportError:\n pass\n else:\n return setuptools_scm.get_version(\n root=root,\n dist_name="matplotlib",\n version_scheme="release-branch-semver",\n local_scheme="node-and-date",\n fallback_version=_version.version,\n )\n # Get the version from the _version.py file if not in repo or setuptools_scm is\n # unavailable.\n return _version.version\n\n\n@_api.caching_module_getattr\nclass __getattr__:\n __version__ = property(lambda self: _get_version())\n __version_info__ = property(\n lambda self: _parse_to_version_info(self.__version__))\n\n\ndef _check_versions():\n\n # Quickfix to ensure Microsoft Visual C++ redistributable\n # DLLs are loaded before importing kiwisolver\n from . import ft2font # noqa: F401\n\n for modname, minver in [\n ("cycler", "0.10"),\n ("dateutil", "2.7"),\n ("kiwisolver", "1.3.1"),\n ("numpy", "1.23"),\n ("pyparsing", "2.3.1"),\n ]:\n module = importlib.import_module(modname)\n if parse_version(module.__version__) < parse_version(minver):\n raise ImportError(f"Matplotlib requires {modname}>={minver}; "\n f"you have {module.__version__}")\n\n\n_check_versions()\n\n\n# The decorator ensures this always returns the same handler (and it is only\n# attached once).\n@functools.cache\ndef _ensure_handler():\n """\n The first time this function is called, attach a `StreamHandler` using the\n same format as `logging.basicConfig` to the Matplotlib root logger.\n\n Return this handler every time this function is called.\n """\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))\n _log.addHandler(handler)\n return handler\n\n\ndef set_loglevel(level):\n """\n Configure Matplotlib's logging levels.\n\n Matplotlib uses the standard library `logging` framework under the root\n logger 'matplotlib'. This is a helper function to:\n\n - set Matplotlib's root logger level\n - set the root logger handler's level, creating the handler\n if it does not exist yet\n\n Typically, one should call ``set_loglevel("info")`` or\n ``set_loglevel("debug")`` to get additional debugging information.\n\n Users or applications that are installing their own logging handlers\n may want to directly manipulate ``logging.getLogger('matplotlib')`` rather\n than use this function.\n\n Parameters\n ----------\n level : {"notset", "debug", "info", "warning", "error", "critical"}\n The log level of the handler.\n\n Notes\n -----\n The first time this function is called, an additional handler is attached\n to Matplotlib's root handler; this handler is reused every time and this\n function simply manipulates the logger and handler's level.\n\n """\n _log.setLevel(level.upper())\n _ensure_handler().setLevel(level.upper())\n\n\ndef _logged_cached(fmt, func=None):\n """\n Decorator that logs a function's return value, and memoizes that value.\n\n After ::\n\n @_logged_cached(fmt)\n def func(): ...\n\n the first call to *func* will log its return value at the DEBUG level using\n %-format string *fmt*, and memoize it; later calls to *func* will directly\n return that value.\n """\n if func is None: # Return the actual decorator.\n return functools.partial(_logged_cached, fmt)\n\n called = False\n ret = None\n\n @functools.wraps(func)\n def wrapper(**kwargs):\n nonlocal called, ret\n if not called:\n ret = func(**kwargs)\n called = True\n _log.debug(fmt, ret)\n return ret\n\n return wrapper\n\n\n_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")\n\n\nclass ExecutableNotFoundError(FileNotFoundError):\n """\n Error raised when an executable that Matplotlib optionally\n depends on can't be found.\n """\n pass\n\n\n@functools.cache\ndef _get_executable_info(name):\n """\n Get the version of some executable that Matplotlib optionally depends on.\n\n .. warning::\n The list of executables that this function supports is set according to\n Matplotlib's internal needs, and may change without notice.\n\n Parameters\n ----------\n name : str\n The executable to query. The following values are currently supported:\n "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This\n list is subject to change without notice.\n\n Returns\n -------\n tuple\n A namedtuple with fields ``executable`` (`str`) and ``version``\n (`packaging.Version`, or ``None`` if the version cannot be determined).\n\n Raises\n ------\n ExecutableNotFoundError\n If the executable is not found or older than the oldest version\n supported by Matplotlib. For debugging purposes, it is also\n possible to "hide" an executable from Matplotlib by adding it to the\n :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated\n list), which must be set prior to any calls to this function.\n ValueError\n If the executable is not one that we know how to query.\n """\n\n def impl(args, regex, min_ver=None, ignore_exit_code=False):\n # Execute the subprocess specified by args; capture stdout and stderr.\n # Search for a regex match in the output; if the match succeeds, the\n # first group of the match is the version.\n # Return an _ExecInfo if the executable exists, and has a version of\n # at least min_ver (if set); else, raise ExecutableNotFoundError.\n try:\n output = subprocess.check_output(\n args, stderr=subprocess.STDOUT,\n text=True, errors="replace")\n except subprocess.CalledProcessError as _cpe:\n if ignore_exit_code:\n output = _cpe.output\n else:\n raise ExecutableNotFoundError(str(_cpe)) from _cpe\n except OSError as _ose:\n raise ExecutableNotFoundError(str(_ose)) from _ose\n match = re.search(regex, output)\n if match:\n raw_version = match.group(1)\n version = parse_version(raw_version)\n if min_ver is not None and version < parse_version(min_ver):\n raise ExecutableNotFoundError(\n f"You have {args[0]} version {version} but the minimum "\n f"version supported by Matplotlib is {min_ver}")\n return _ExecInfo(args[0], raw_version, version)\n else:\n raise ExecutableNotFoundError(\n f"Failed to determine the version of {args[0]} from "\n f"{' '.join(args)}, which output {output}")\n\n if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):\n raise ExecutableNotFoundError(f"{name} was hidden")\n\n if name == "dvipng":\n return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")\n elif name == "gs":\n execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.\n if sys.platform == "win32" else\n ["gs"])\n for e in execs:\n try:\n return impl([e, "--version"], "(.*)", "9")\n except ExecutableNotFoundError:\n pass\n message = "Failed to find a Ghostscript installation"\n raise ExecutableNotFoundError(message)\n elif name == "inkscape":\n try:\n # Try headless option first (needed for Inkscape version < 1.0):\n return impl(["inkscape", "--without-gui", "-V"],\n "Inkscape ([^ ]*)")\n except ExecutableNotFoundError:\n pass # Suppress exception chaining.\n # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so\n # try without it:\n return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")\n elif name == "magick":\n if sys.platform == "win32":\n # Check the registry to avoid confusing ImageMagick's convert with\n # Windows's builtin convert.exe.\n import winreg\n binpath = ""\n for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:\n try:\n with winreg.OpenKeyEx(\n winreg.HKEY_LOCAL_MACHINE,\n r"Software\Imagemagick\Current",\n 0, winreg.KEY_QUERY_VALUE | flag) as hkey:\n binpath = winreg.QueryValueEx(hkey, "BinPath")[0]\n except OSError:\n pass\n path = None\n if binpath:\n for name in ["convert.exe", "magick.exe"]:\n candidate = Path(binpath, name)\n if candidate.exists():\n path = str(candidate)\n break\n if path is None:\n raise ExecutableNotFoundError(\n "Failed to find an ImageMagick installation")\n else:\n path = "convert"\n info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")\n if info.raw_version == "7.0.10-34":\n # https://github.com/ImageMagick/ImageMagick/issues/2720\n raise ExecutableNotFoundError(\n f"You have ImageMagick {info.version}, which is unsupported")\n return info\n elif name == "pdftocairo":\n return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")\n elif name == "pdftops":\n info = impl(["pdftops", "-v"], "^pdftops version (.*)",\n ignore_exit_code=True)\n if info and not (\n 3 <= info.version.major or\n # poppler version numbers.\n parse_version("0.9") <= info.version < parse_version("1.0")):\n raise ExecutableNotFoundError(\n f"You have pdftops version {info.version} but the minimum "\n f"version supported by Matplotlib is 3.0")\n return info\n else:\n raise ValueError(f"Unknown executable: {name!r}")\n\n\ndef _get_xdg_config_dir():\n """\n Return the XDG configuration directory, according to the XDG base\n directory spec:\n\n https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html\n """\n return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")\n\n\ndef _get_xdg_cache_dir():\n """\n Return the XDG cache directory, according to the XDG base directory spec:\n\n https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html\n """\n return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")\n\n\ndef _get_config_or_cache_dir(xdg_base_getter):\n configdir = os.environ.get('MPLCONFIGDIR')\n if configdir:\n configdir = Path(configdir)\n elif sys.platform.startswith(('linux', 'freebsd')):\n # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,\n # as _xdg_base_getter can throw.\n configdir = Path(xdg_base_getter(), "matplotlib")\n else:\n configdir = Path.home() / ".matplotlib"\n # Resolve the path to handle potential issues with inaccessible symlinks.\n configdir = configdir.resolve()\n try:\n configdir.mkdir(parents=True, exist_ok=True)\n except OSError as exc:\n _log.warning("mkdir -p failed for path %s: %s", configdir, exc)\n else:\n if os.access(str(configdir), os.W_OK) and configdir.is_dir():\n return str(configdir)\n _log.warning("%s is not a writable directory", configdir)\n # If the config or cache directory cannot be created or is not a writable\n # directory, create a temporary one.\n try:\n tmpdir = tempfile.mkdtemp(prefix="matplotlib-")\n except OSError as exc:\n raise OSError(\n f"Matplotlib requires access to a writable cache directory, but there "\n f"was an issue with the default path ({configdir}), and a temporary "\n f"directory could not be created; set the MPLCONFIGDIR environment "\n f"variable to a writable directory") from exc\n os.environ["MPLCONFIGDIR"] = tmpdir\n atexit.register(shutil.rmtree, tmpdir)\n _log.warning(\n "Matplotlib created a temporary cache directory at %s because there was "\n "an issue with the default path (%s); it is highly recommended to set the "\n "MPLCONFIGDIR environment variable to a writable directory, in particular to "\n "speed up the import of Matplotlib and to better support multiprocessing.",\n tmpdir, configdir)\n return tmpdir\n\n\n@_logged_cached('CONFIGDIR=%s')\ndef get_configdir():\n """\n Return the string path of the configuration directory.\n\n The directory is chosen as follows:\n\n 1. If the MPLCONFIGDIR environment variable is supplied, choose that.\n 2. On Linux, follow the XDG specification and look first in\n ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other\n platforms, choose ``$HOME/.matplotlib``.\n 3. If the chosen directory exists and is writable, use that as the\n configuration directory.\n 4. Else, create a temporary directory, and use it as the configuration\n directory.\n """\n return _get_config_or_cache_dir(_get_xdg_config_dir)\n\n\n@_logged_cached('CACHEDIR=%s')\ndef get_cachedir():\n """\n Return the string path of the cache directory.\n\n The procedure used to find the directory is the same as for\n `get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.\n """\n return _get_config_or_cache_dir(_get_xdg_cache_dir)\n\n\n@_logged_cached('matplotlib data path: %s')\ndef get_data_path():\n """Return the path to Matplotlib data."""\n return str(Path(__file__).with_name("mpl-data"))\n\n\ndef matplotlib_fname():\n """\n Get the location of the config file.\n\n The file location is determined in the following order\n\n - ``$PWD/matplotlibrc``\n - ``$MATPLOTLIBRC`` if it is not a directory\n - ``$MATPLOTLIBRC/matplotlibrc``\n - ``$MPLCONFIGDIR/matplotlibrc``\n - On Linux,\n - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``\n is defined)\n - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``\n is not defined)\n - On other platforms,\n - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined\n - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always\n exist.\n """\n\n def gen_candidates():\n # rely on down-stream code to make absolute. This protects us\n # from having to directly get the current working directory\n # which can fail if the user has ended up with a cwd that is\n # non-existent.\n yield 'matplotlibrc'\n try:\n matplotlibrc = os.environ['MATPLOTLIBRC']\n except KeyError:\n pass\n else:\n yield matplotlibrc\n yield os.path.join(matplotlibrc, 'matplotlibrc')\n yield os.path.join(get_configdir(), 'matplotlibrc')\n yield os.path.join(get_data_path(), 'matplotlibrc')\n\n for fname in gen_candidates():\n if os.path.exists(fname) and not os.path.isdir(fname):\n return fname\n\n raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "\n "install is broken")\n\n\n# rcParams deprecated and automatically mapped to another key.\n# Values are tuples of (version, new_name, f_old2new, f_new2old).\n_deprecated_map = {}\n# rcParams deprecated; some can manually be mapped to another key.\n# Values are tuples of (version, new_name_or_None).\n_deprecated_ignore_map = {}\n# rcParams deprecated; can use None to suppress warnings; remain actually\n# listed in the rcParams.\n# Values are tuples of (version,)\n_deprecated_remain_as_none = {}\n\n\n@_docstring.Substitution(\n "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))\n)\nclass RcParams(MutableMapping, dict):\n """\n A dict-like key-value store for config parameters, including validation.\n\n Validating functions are defined and associated with rc parameters in\n :mod:`matplotlib.rcsetup`.\n\n The list of rcParams is:\n\n %s\n\n See Also\n --------\n :ref:`customizing-with-matplotlibrc-files`\n """\n\n validate = rcsetup._validators\n\n # validate values on the way in\n def __init__(self, *args, **kwargs):\n self.update(*args, **kwargs)\n\n def _set(self, key, val):\n """\n Directly write data bypassing deprecation and validation logic.\n\n Notes\n -----\n As end user or downstream library you almost always should use\n ``rcParams[key] = val`` and not ``_set()``.\n\n There are only very few special cases that need direct data access.\n These cases previously used ``dict.__setitem__(rcParams, key, val)``,\n which is now deprecated and replaced by ``rcParams._set(key, val)``.\n\n Even though private, we guarantee API stability for ``rcParams._set``,\n i.e. it is subject to Matplotlib's API and deprecation policy.\n\n :meta public:\n """\n dict.__setitem__(self, key, val)\n\n def _get(self, key):\n """\n Directly read data bypassing deprecation, backend and validation\n logic.\n\n Notes\n -----\n As end user or downstream library you almost always should use\n ``val = rcParams[key]`` and not ``_get()``.\n\n There are only very few special cases that need direct data access.\n These cases previously used ``dict.__getitem__(rcParams, key, val)``,\n which is now deprecated and replaced by ``rcParams._get(key)``.\n\n Even though private, we guarantee API stability for ``rcParams._get``,\n i.e. it is subject to Matplotlib's API and deprecation policy.\n\n :meta public:\n """\n return dict.__getitem__(self, key)\n\n def _update_raw(self, other_params):\n """\n Directly update the data from *other_params*, bypassing deprecation,\n backend and validation logic on both sides.\n\n This ``rcParams._update_raw(params)`` replaces the previous pattern\n ``dict.update(rcParams, params)``.\n\n Parameters\n ----------\n other_params : dict or `.RcParams`\n The input mapping from which to update.\n """\n if isinstance(other_params, RcParams):\n other_params = dict.items(other_params)\n dict.update(self, other_params)\n\n def _ensure_has_backend(self):\n """\n Ensure that a "backend" entry exists.\n\n Normally, the default matplotlibrc file contains *no* entry for "backend" (the\n corresponding line starts with ##, not #; we fill in _auto_backend_sentinel\n in that case. However, packagers can set a different default backend\n (resulting in a normal `#backend: foo` line) in which case we should *not*\n fill in _auto_backend_sentinel.\n """\n dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)\n\n def __setitem__(self, key, val):\n try:\n if key in _deprecated_map:\n version, alt_key, alt_val, inverse_alt = _deprecated_map[key]\n _api.warn_deprecated(\n version, name=key, obj_type="rcparam", alternative=alt_key)\n key = alt_key\n val = alt_val(val)\n elif key in _deprecated_remain_as_none and val is not None:\n version, = _deprecated_remain_as_none[key]\n _api.warn_deprecated(version, name=key, obj_type="rcparam")\n elif key in _deprecated_ignore_map:\n version, alt_key = _deprecated_ignore_map[key]\n _api.warn_deprecated(\n version, name=key, obj_type="rcparam", alternative=alt_key)\n return\n elif key == 'backend':\n if val is rcsetup._auto_backend_sentinel:\n if 'backend' in self:\n return\n try:\n cval = self.validate[key](val)\n except ValueError as ve:\n raise ValueError(f"Key {key}: {ve}") from None\n self._set(key, cval)\n except KeyError as err:\n raise KeyError(\n f"{key} is not a valid rc parameter (see rcParams.keys() for "\n f"a list of valid parameters)") from err\n\n def __getitem__(self, key):\n if key in _deprecated_map:\n version, alt_key, alt_val, inverse_alt = _deprecated_map[key]\n _api.warn_deprecated(\n version, name=key, obj_type="rcparam", alternative=alt_key)\n return inverse_alt(self._get(alt_key))\n\n elif key in _deprecated_ignore_map:\n version, alt_key = _deprecated_ignore_map[key]\n _api.warn_deprecated(\n version, name=key, obj_type="rcparam", alternative=alt_key)\n return self._get(alt_key) if alt_key else None\n\n # In theory, this should only ever be used after the global rcParams\n # has been set up, but better be safe e.g. in presence of breakpoints.\n elif key == "backend" and self is globals().get("rcParams"):\n val = self._get(key)\n if val is rcsetup._auto_backend_sentinel:\n from matplotlib import pyplot as plt\n plt.switch_backend(rcsetup._auto_backend_sentinel)\n\n return self._get(key)\n\n def _get_backend_or_none(self):\n """Get the requested backend, if any, without triggering resolution."""\n backend = self._get("backend")\n return None if backend is rcsetup._auto_backend_sentinel else backend\n\n def __repr__(self):\n class_name = self.__class__.__name__\n indent = len(class_name) + 1\n with _api.suppress_matplotlib_deprecation_warning():\n repr_split = pprint.pformat(dict(self), indent=1,\n width=80 - indent).split('\n')\n repr_indented = ('\n' + ' ' * indent).join(repr_split)\n return f'{class_name}({repr_indented})'\n\n def __str__(self):\n return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))\n\n def __iter__(self):\n """Yield sorted list of keys."""\n with _api.suppress_matplotlib_deprecation_warning():\n yield from sorted(dict.__iter__(self))\n\n def __len__(self):\n return dict.__len__(self)\n\n def find_all(self, pattern):\n """\n Return the subset of this RcParams dictionary whose keys match,\n using :func:`re.search`, the given ``pattern``.\n\n .. note::\n\n Changes to the returned dictionary are *not* propagated to\n the parent RcParams dictionary.\n\n """\n pattern_re = re.compile(pattern)\n return RcParams((key, value)\n for key, value in self.items()\n if pattern_re.search(key))\n\n def copy(self):\n """Copy this RcParams instance."""\n rccopy = RcParams()\n for k in self: # Skip deprecations and revalidation.\n rccopy._set(k, self._get(k))\n return rccopy\n\n\ndef rc_params(fail_on_error=False):\n """Construct a `RcParams` instance from the default Matplotlib rc file."""\n return rc_params_from_file(matplotlib_fname(), fail_on_error)\n\n\n@functools.cache\ndef _get_ssl_context():\n try:\n import certifi\n except ImportError:\n _log.debug("Could not import certifi.")\n return None\n import ssl\n return ssl.create_default_context(cafile=certifi.where())\n\n\n@contextlib.contextmanager\ndef _open_file_or_url(fname):\n if (isinstance(fname, str)\n and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):\n import urllib.request\n ssl_ctx = _get_ssl_context()\n if ssl_ctx is None:\n _log.debug(\n "Could not get certifi ssl context, https may not work."\n )\n with urllib.request.urlopen(fname, context=ssl_ctx) as f:\n yield (line.decode('utf-8') for line in f)\n else:\n fname = os.path.expanduser(fname)\n with open(fname, encoding='utf-8') as f:\n yield f\n\n\ndef _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):\n """\n Construct a `RcParams` instance from file *fname*.\n\n Unlike `rc_params_from_file`, the configuration class only contains the\n parameters specified in the file (i.e. default values are not filled in).\n\n Parameters\n ----------\n fname : path-like\n The loaded file.\n transform : callable, default: the identity function\n A function called on each individual line of the file to transform it,\n before further parsing.\n fail_on_error : bool, default: False\n Whether invalid entries should result in an exception or a warning.\n """\n import matplotlib as mpl\n rc_temp = {}\n with _open_file_or_url(fname) as fd:\n try:\n for line_no, line in enumerate(fd, 1):\n line = transform(line)\n strippedline = cbook._strip_comment(line)\n if not strippedline:\n continue\n tup = strippedline.split(':', 1)\n if len(tup) != 2:\n _log.warning('Missing colon in file %r, line %d (%r)',\n fname, line_no, line.rstrip('\n'))\n continue\n key, val = tup\n key = key.strip()\n val = val.strip()\n if val.startswith('"') and val.endswith('"'):\n val = val[1:-1] # strip double quotes\n if key in rc_temp:\n _log.warning('Duplicate key in file %r, line %d (%r)',\n fname, line_no, line.rstrip('\n'))\n rc_temp[key] = (val, line, line_no)\n except UnicodeDecodeError:\n _log.warning('Cannot decode configuration file %r as utf-8.',\n fname)\n raise\n\n config = RcParams()\n\n for key, (val, line, line_no) in rc_temp.items():\n if key in rcsetup._validators:\n if fail_on_error:\n config[key] = val # try to convert to proper type or raise\n else:\n try:\n config[key] = val # try to convert to proper type or skip\n except Exception as msg:\n _log.warning('Bad value in file %r, line %d (%r): %s',\n fname, line_no, line.rstrip('\n'), msg)\n elif key in _deprecated_ignore_map:\n version, alt_key = _deprecated_ignore_map[key]\n _api.warn_deprecated(\n version, name=key, alternative=alt_key, obj_type='rcparam',\n addendum="Please update your matplotlibrc.")\n else:\n # __version__ must be looked up as an attribute to trigger the\n # module-level __getattr__.\n version = ('main' if '.post' in mpl.__version__\n else f'v{mpl.__version__}')\n _log.warning("""\nBad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)\nYou probably need to get an updated matplotlibrc file from\nhttps://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc\nor from the matplotlib source distribution""",\n dict(key=key, fname=fname, line_no=line_no,\n line=line.rstrip('\n'), version=version))\n return config\n\n\ndef rc_params_from_file(fname, fail_on_error=False, use_default_template=True):\n """\n Construct a `RcParams` from file *fname*.\n\n Parameters\n ----------\n fname : str or path-like\n A file with Matplotlib rc settings.\n fail_on_error : bool\n If True, raise an error when the parser fails to convert a parameter.\n use_default_template : bool\n If True, initialize with default parameters before updating with those\n in the given file. If False, the configuration class only contains the\n parameters specified in the file. (Useful for updating dicts.)\n """\n config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)\n\n if not use_default_template:\n return config_from_file\n\n with _api.suppress_matplotlib_deprecation_warning():\n config = RcParams({**rcParamsDefault, **config_from_file})\n\n if "".join(config['text.latex.preamble']):\n _log.info("""\n*****************************************************************\nYou have the following UNSUPPORTED LaTeX preamble customizations:\n%s\nPlease do not ask for support with these customizations active.\n*****************************************************************\n""", '\n'.join(config['text.latex.preamble']))\n _log.debug('loaded rc file %s', fname)\n\n return config\n\n\nrcParamsDefault = _rc_params_in_file(\n cbook._get_data_path("matplotlibrc"),\n # Strip leading comment.\n transform=lambda line: line[1:] if line.startswith("#") else line,\n fail_on_error=True)\nrcParamsDefault._update_raw(rcsetup._hardcoded_defaults)\nrcParamsDefault._ensure_has_backend()\n\nrcParams = RcParams() # The global instance.\nrcParams._update_raw(rcParamsDefault)\nrcParams._update_raw(_rc_params_in_file(matplotlib_fname()))\nrcParamsOrig = rcParams.copy()\nwith _api.suppress_matplotlib_deprecation_warning():\n # This also checks that all rcParams are indeed listed in the template.\n # Assigning to rcsetup.defaultParams is left only for backcompat.\n defaultParams = rcsetup.defaultParams = {\n # We want to resolve deprecated rcParams, but not backend...\n key: [(rcsetup._auto_backend_sentinel if key == "backend" else\n rcParamsDefault[key]),\n validator]\n for key, validator in rcsetup._validators.items()}\nif rcParams['axes.formatter.use_locale']:\n locale.setlocale(locale.LC_ALL, '')\n\n\ndef rc(group, **kwargs):\n """\n Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,\n for ``lines.linewidth`` the group is ``lines``, for\n ``axes.facecolor``, the group is ``axes``, and so on. Group may\n also be a list or tuple of group names, e.g., (*xtick*, *ytick*).\n *kwargs* is a dictionary attribute name/value pairs, e.g.,::\n\n rc('lines', linewidth=2, color='r')\n\n sets the current `.rcParams` and is equivalent to::\n\n rcParams['lines.linewidth'] = 2\n rcParams['lines.color'] = 'r'\n\n The following aliases are available to save typing for interactive users:\n\n ===== =================\n Alias Property\n ===== =================\n 'lw' 'linewidth'\n 'ls' 'linestyle'\n 'c' 'color'\n 'fc' 'facecolor'\n 'ec' 'edgecolor'\n 'mew' 'markeredgewidth'\n 'aa' 'antialiased'\n ===== =================\n\n Thus you could abbreviate the above call as::\n\n rc('lines', lw=2, c='r')\n\n Note you can use python's kwargs dictionary facility to store\n dictionaries of default parameters. e.g., you can customize the\n font rc as follows::\n\n font = {'family' : 'monospace',\n 'weight' : 'bold',\n 'size' : 'larger'}\n rc('font', **font) # pass in the font dict as kwargs\n\n This enables you to easily switch between several configurations. Use\n ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to\n restore the default `.rcParams` after changes.\n\n Notes\n -----\n Similar functionality is available by using the normal dict interface, i.e.\n ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``\n does not support abbreviations or grouping).\n """\n\n aliases = {\n 'lw': 'linewidth',\n 'ls': 'linestyle',\n 'c': 'color',\n 'fc': 'facecolor',\n 'ec': 'edgecolor',\n 'mew': 'markeredgewidth',\n 'aa': 'antialiased',\n }\n\n if isinstance(group, str):\n group = (group,)\n for g in group:\n for k, v in kwargs.items():\n name = aliases.get(k) or k\n key = f'{g}.{name}'\n try:\n rcParams[key] = v\n except KeyError as err:\n raise KeyError(('Unrecognized key "%s" for group "%s" and '\n 'name "%s"') % (key, g, name)) from err\n\n\ndef rcdefaults():\n """\n Restore the `.rcParams` from Matplotlib's internal default style.\n\n Style-blacklisted `.rcParams` (defined in\n ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.\n\n See Also\n --------\n matplotlib.rc_file_defaults\n Restore the `.rcParams` from the rc file originally loaded by\n Matplotlib.\n matplotlib.style.use\n Use a specific style file. Call ``style.use('default')`` to restore\n the default style.\n """\n # Deprecation warnings were already handled when creating rcParamsDefault,\n # no need to reemit them here.\n with _api.suppress_matplotlib_deprecation_warning():\n from .style.core import STYLE_BLACKLIST\n rcParams.clear()\n rcParams.update({k: v for k, v in rcParamsDefault.items()\n if k not in STYLE_BLACKLIST})\n\n\ndef rc_file_defaults():\n """\n Restore the `.rcParams` from the original rc file loaded by Matplotlib.\n\n Style-blacklisted `.rcParams` (defined in\n ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.\n """\n # Deprecation warnings were already handled when creating rcParamsOrig, no\n # need to reemit them here.\n with _api.suppress_matplotlib_deprecation_warning():\n from .style.core import STYLE_BLACKLIST\n rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig\n if k not in STYLE_BLACKLIST})\n\n\ndef rc_file(fname, *, use_default_template=True):\n """\n Update `.rcParams` from file.\n\n Style-blacklisted `.rcParams` (defined in\n ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.\n\n Parameters\n ----------\n fname : str or path-like\n A file with Matplotlib rc settings.\n\n use_default_template : bool\n If True, initialize with default parameters before updating with those\n in the given file. If False, the current configuration persists\n and only the parameters specified in the file are updated.\n """\n # Deprecation warnings were already handled in rc_params_from_file, no need\n # to reemit them here.\n with _api.suppress_matplotlib_deprecation_warning():\n from .style.core import STYLE_BLACKLIST\n rc_from_file = rc_params_from_file(\n fname, use_default_template=use_default_template)\n rcParams.update({k: rc_from_file[k] for k in rc_from_file\n if k not in STYLE_BLACKLIST})\n\n\n@contextlib.contextmanager\ndef rc_context(rc=None, fname=None):\n """\n Return a context manager for temporarily changing rcParams.\n\n The :rc:`backend` will not be reset by the context manager.\n\n rcParams changed both through the context manager invocation and\n in the body of the context will be reset on context exit.\n\n Parameters\n ----------\n rc : dict\n The rcParams to temporarily set.\n fname : str or path-like\n A file with Matplotlib rc settings. If both *fname* and *rc* are given,\n settings from *rc* take precedence.\n\n See Also\n --------\n :ref:`customizing-with-matplotlibrc-files`\n\n Examples\n --------\n Passing explicit values via a dict::\n\n with mpl.rc_context({'interactive': False}):\n fig, ax = plt.subplots()\n ax.plot(range(3), range(3))\n fig.savefig('example.png')\n plt.close(fig)\n\n Loading settings from a file::\n\n with mpl.rc_context(fname='print.rc'):\n plt.plot(x, y) # uses 'print.rc'\n\n Setting in the context body::\n\n with mpl.rc_context():\n # will be reset\n mpl.rcParams['lines.linewidth'] = 5\n plt.plot(x, y)\n\n """\n orig = dict(rcParams.copy())\n del orig['backend']\n try:\n if fname:\n rc_file(fname)\n if rc:\n rcParams.update(rc)\n yield\n finally:\n rcParams._update_raw(orig) # Revert to the original rcs.\n\n\ndef use(backend, *, force=True):\n """\n Select the backend used for rendering and GUI integration.\n\n If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used\n and if the new backend is different than the current backend, all Figures\n will be closed.\n\n Parameters\n ----------\n backend : str\n The backend to switch to. This can either be one of the standard\n backend names, which are case-insensitive:\n\n - interactive backends:\n GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,\n QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo\n\n - non-interactive backends:\n agg, cairo, pdf, pgf, ps, svg, template\n\n or a string of the form: ``module://my.module.name``.\n\n notebook is a synonym for nbAgg.\n\n Switching to an interactive backend is not possible if an unrelated\n event loop has already been started (e.g., switching to GTK3Agg if a\n TkAgg window has already been opened). Switching to a non-interactive\n backend is always possible.\n\n force : bool, default: True\n If True (the default), raise an `ImportError` if the backend cannot be\n set up (either because it fails to import, or because an incompatible\n GUI interactive framework is already running); if False, silently\n ignore the failure.\n\n See Also\n --------\n :ref:`backends`\n matplotlib.get_backend\n matplotlib.pyplot.switch_backend\n\n """\n name = rcsetup.validate_backend(backend)\n # don't (prematurely) resolve the "auto" backend setting\n if rcParams._get_backend_or_none() == name:\n # Nothing to do if the requested backend is already set\n pass\n else:\n # if pyplot is not already imported, do not import it. Doing\n # so may trigger a `plt.switch_backend` to the _default_ backend\n # before we get a chance to change to the one the user just requested\n plt = sys.modules.get('matplotlib.pyplot')\n # if pyplot is imported, then try to change backends\n if plt is not None:\n try:\n # we need this import check here to re-raise if the\n # user does not have the libraries to support their\n # chosen backend installed.\n plt.switch_backend(name)\n except ImportError:\n if force:\n raise\n # if we have not imported pyplot, then we can set the rcParam\n # value which will be respected when the user finally imports\n # pyplot\n else:\n rcParams['backend'] = backend\n # if the user has asked for a given backend, do not helpfully\n # fallback\n rcParams['backend_fallback'] = False\n\n\nif os.environ.get('MPLBACKEND'):\n rcParams['backend'] = os.environ.get('MPLBACKEND')\n\n\ndef get_backend(*, auto_select=True):\n """\n Return the name of the current backend.\n\n Parameters\n ----------\n auto_select : bool, default: True\n Whether to trigger backend resolution if no backend has been\n selected so far. If True, this ensures that a valid backend\n is returned. If False, this returns None if no backend has been\n selected so far.\n\n .. versionadded:: 3.10\n\n .. admonition:: Provisional\n\n The *auto_select* flag is provisional. It may be changed or removed\n without prior warning.\n\n See Also\n --------\n matplotlib.use\n """\n if auto_select:\n return rcParams['backend']\n else:\n backend = rcParams._get('backend')\n if backend is rcsetup._auto_backend_sentinel:\n return None\n else:\n return backend\n\n\ndef interactive(b):\n """\n Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).\n """\n rcParams['interactive'] = b\n\n\ndef is_interactive():\n """\n Return whether to redraw after every plotting command.\n\n .. note::\n\n This function is only intended for use in backends. End users should\n use `.pyplot.isinteractive` instead.\n """\n return rcParams['interactive']\n\n\ndef _val_or_rc(val, rc_name):\n """\n If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val.\n """\n return val if val is not None else rcParams[rc_name]\n\n\ndef _init_tests():\n # The version of FreeType to install locally for running the tests. This must match\n # the value in `meson.build`.\n LOCAL_FREETYPE_VERSION = '2.6.1'\n\n from matplotlib import ft2font\n if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or\n ft2font.__freetype_build_type__ != 'local'):\n _log.warning(\n "Matplotlib is not built with the correct FreeType version to run tests. "\n "Rebuild without setting system-freetype=true in Meson setup options. "\n "Expect many image comparison failures below. "\n "Expected freetype version %s. "\n "Found freetype version %s. "\n "Freetype build type is %slocal.",\n LOCAL_FREETYPE_VERSION,\n ft2font.__freetype_version__,\n "" if ft2font.__freetype_build_type__ == 'local' else "not ")\n\n\ndef _replacer(data, value):\n """\n Either returns ``data[value]`` or passes ``data`` back, converts either to\n a sequence.\n """\n try:\n # if key isn't a string don't bother\n if isinstance(value, str):\n # try to use __getitem__\n value = data[value]\n except Exception:\n # key does not exist, silently fall back to key\n pass\n return cbook.sanitize_sequence(value)\n\n\ndef _label_from_arg(y, default_name):\n try:\n return y.name\n except AttributeError:\n if isinstance(default_name, str):\n return default_name\n return None\n\n\ndef _add_data_doc(docstring, replace_names):\n """\n Add documentation for a *data* field to the given docstring.\n\n Parameters\n ----------\n docstring : str\n The input docstring.\n replace_names : list of str or None\n The list of parameter names which arguments should be replaced by\n ``data[name]`` (if ``data[name]`` does not throw an exception). If\n None, replacement is attempted for all arguments.\n\n Returns\n -------\n str\n The augmented docstring.\n """\n if (docstring is None\n or replace_names is not None and len(replace_names) == 0):\n return docstring\n docstring = inspect.cleandoc(docstring)\n\n data_doc = ("""\\n If given, all parameters also accept a string ``s``, which is\n interpreted as ``data[s]`` if ``s`` is a key in ``data``."""\n if replace_names is None else f"""\\n If given, the following parameters also accept a string ``s``, which is\n interpreted as ``data[s]`` if ``s`` is a key in ``data``:\n\n {', '.join(map('*{}*'.format, replace_names))}""")\n # using string replacement instead of formatting has the advantages\n # 1) simpler indent handling\n # 2) prevent problems with formatting characters '{', '%' in the docstring\n if _log.level <= logging.DEBUG:\n # test_data_parameter_replacement() tests against these log messages\n # make sure to keep message and test in sync\n if "data : indexable object, optional" not in docstring:\n _log.debug("data parameter docstring error: no data parameter")\n if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:\n _log.debug("data parameter docstring error: missing placeholder")\n return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)\n\n\ndef _preprocess_data(func=None, *, replace_names=None, label_namer=None):\n """\n A decorator to add a 'data' kwarg to a function.\n\n When applied::\n\n @_preprocess_data()\n def func(ax, *args, **kwargs): ...\n\n the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``\n with the following behavior:\n\n - if called with ``data=None``, forward the other arguments to ``func``;\n - otherwise, *data* must be a mapping; for any argument passed in as a\n string ``name``, replace the argument by ``data[name]`` (if this does not\n throw an exception), then forward the arguments to ``func``.\n\n In either case, any argument that is a `MappingView` is also converted to a\n list.\n\n Parameters\n ----------\n replace_names : list of str or None, default: None\n The list of parameter names for which lookup into *data* should be\n attempted. If None, replacement is attempted for all arguments.\n label_namer : str, default: None\n If set e.g. to "namer" (which must be a kwarg in the function's\n signature -- not as ``**kwargs``), if the *namer* argument passed in is\n a (string) key of *data* and no *label* kwarg is passed, then use the\n (string) value of the *namer* as *label*. ::\n\n @_preprocess_data(label_namer="foo")\n def func(foo, label=None): ...\n\n func("key", data={"key": value})\n # is equivalent to\n func.__wrapped__(value, label="key")\n """\n\n if func is None: # Return the actual decorator.\n return functools.partial(\n _preprocess_data,\n replace_names=replace_names, label_namer=label_namer)\n\n sig = inspect.signature(func)\n varargs_name = None\n varkwargs_name = None\n arg_names = []\n params = list(sig.parameters.values())\n for p in params:\n if p.kind is Parameter.VAR_POSITIONAL:\n varargs_name = p.name\n elif p.kind is Parameter.VAR_KEYWORD:\n varkwargs_name = p.name\n else:\n arg_names.append(p.name)\n data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)\n if varkwargs_name:\n params.insert(-1, data_param)\n else:\n params.append(data_param)\n new_sig = sig.replace(parameters=params)\n arg_names = arg_names[1:] # remove the first "ax" / self arg\n\n assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (\n "Matplotlib internal error: invalid replace_names "\n f"({replace_names!r}) for {func.__name__!r}")\n assert label_namer is None or label_namer in arg_names, (\n "Matplotlib internal error: invalid label_namer "\n f"({label_namer!r}) for {func.__name__!r}")\n\n @functools.wraps(func)\n def inner(ax, *args, data=None, **kwargs):\n if data is None:\n return func(\n ax,\n *map(cbook.sanitize_sequence, args),\n **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})\n\n bound = new_sig.bind(ax, *args, **kwargs)\n auto_label = (bound.arguments.get(label_namer)\n or bound.kwargs.get(label_namer))\n\n for k, v in bound.arguments.items():\n if k == varkwargs_name:\n for k1, v1 in v.items():\n if replace_names is None or k1 in replace_names:\n v[k1] = _replacer(data, v1)\n elif k == varargs_name:\n if replace_names is None:\n bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)\n else:\n if replace_names is None or k in replace_names:\n bound.arguments[k] = _replacer(data, v)\n\n new_args = bound.args\n new_kwargs = bound.kwargs\n\n args_and_kwargs = {**bound.arguments, **bound.kwargs}\n if label_namer and "label" not in args_and_kwargs:\n new_kwargs["label"] = _label_from_arg(\n args_and_kwargs.get(label_namer), auto_label)\n\n return func(*new_args, **new_kwargs)\n\n inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)\n inner.__signature__ = new_sig\n return inner\n\n\n_log.debug('interactive is %s', is_interactive())\n_log.debug('platform is %s', sys.platform)\n\n\n@_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")\ndef sanitize_sequence(data):\n return cbook.sanitize_sequence(data)\n\n\n@_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")\ndef validate_backend(s):\n return rcsetup.validate_backend(s)\n\n\n# workaround: we must defer colormaps import to after loading rcParams, because\n# colormap creation depends on rcParams\nfrom matplotlib.cm import _colormaps as colormaps # noqa: E402\nfrom matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402\nfrom matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402\nfrom matplotlib.colors import _color_sequences as color_sequences # noqa: E402\n
.venv\Lib\site-packages\matplotlib\__init__.py
__init__.py
Python
55,633
0.75
0.178934
0.068726
awesome-app
153
2023-10-02T05:55:27.351300
BSD-3-Clause
false
c1c613aee4bf330de02f91d3a0b9d0cf
__all__ = [\n "__bibtex__",\n "__version__",\n "__version_info__",\n "set_loglevel",\n "ExecutableNotFoundError",\n "get_configdir",\n "get_cachedir",\n "get_data_path",\n "matplotlib_fname",\n "MatplotlibDeprecationWarning",\n "RcParams",\n "rc_params",\n "rc_params_from_file",\n "rcParamsDefault",\n "rcParams",\n "rcParamsOrig",\n "defaultParams",\n "rc",\n "rcdefaults",\n "rc_file_defaults",\n "rc_file",\n "rc_context",\n "use",\n "get_backend",\n "interactive",\n "is_interactive",\n "colormaps",\n "color_sequences",\n]\n\nimport os\nfrom pathlib import Path\n\nfrom collections.abc import Callable, Generator\nimport contextlib\nfrom packaging.version import Version\n\nfrom matplotlib._api import MatplotlibDeprecationWarning\nfrom typing import Any, Literal, NamedTuple, overload\n\nclass _VersionInfo(NamedTuple):\n major: int\n minor: int\n micro: int\n releaselevel: str\n serial: int\n\n__bibtex__: str\n__version__: str\n__version_info__: _VersionInfo\n\ndef set_loglevel(level: str) -> None: ...\n\nclass _ExecInfo(NamedTuple):\n executable: str\n raw_version: str\n version: Version\n\nclass ExecutableNotFoundError(FileNotFoundError): ...\n\ndef _get_executable_info(name: str) -> _ExecInfo: ...\ndef get_configdir() -> str: ...\ndef get_cachedir() -> str: ...\ndef get_data_path() -> str: ...\ndef matplotlib_fname() -> str: ...\n\nclass RcParams(dict[str, Any]):\n validate: dict[str, Callable]\n def __init__(self, *args, **kwargs) -> None: ...\n def _set(self, key: str, val: Any) -> None: ...\n def _get(self, key: str) -> Any: ...\n\n def _update_raw(self, other_params: dict | RcParams) -> None: ...\n\n def _ensure_has_backend(self) -> None: ...\n def __setitem__(self, key: str, val: Any) -> None: ...\n def __getitem__(self, key: str) -> Any: ...\n def __iter__(self) -> Generator[str, None, None]: ...\n def __len__(self) -> int: ...\n def find_all(self, pattern: str) -> RcParams: ...\n def copy(self) -> RcParams: ...\n\ndef rc_params(fail_on_error: bool = ...) -> RcParams: ...\ndef rc_params_from_file(\n fname: str | Path | os.PathLike,\n fail_on_error: bool = ...,\n use_default_template: bool = ...,\n) -> RcParams: ...\n\nrcParamsDefault: RcParams\nrcParams: RcParams\nrcParamsOrig: RcParams\ndefaultParams: dict[str, Any]\n\ndef rc(group: str, **kwargs) -> None: ...\ndef rcdefaults() -> None: ...\ndef rc_file_defaults() -> None: ...\ndef rc_file(\n fname: str | Path | os.PathLike, *, use_default_template: bool = ...\n) -> None: ...\n@contextlib.contextmanager\ndef rc_context(\n rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ...\n) -> Generator[None, None, None]: ...\ndef use(backend: str, *, force: bool = ...) -> None: ...\n@overload\ndef get_backend(*, auto_select: Literal[True] = True) -> str: ...\n@overload\ndef get_backend(*, auto_select: Literal[False]) -> str | None: ...\ndef interactive(b: bool) -> None: ...\ndef is_interactive() -> bool: ...\n\ndef _preprocess_data(\n func: Callable | None = ...,\n *,\n replace_names: list[str] | None = ...,\n label_namer: str | None = ...\n) -> Callable: ...\n\nfrom matplotlib.cm import _colormaps as colormaps # noqa: E402\nfrom matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402\nfrom matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402\nfrom matplotlib.colors import _color_sequences as color_sequences # noqa: E402\n
.venv\Lib\site-packages\matplotlib\__init__.pyi
__init__.pyi
Other
3,439
0.95
0.274194
0.009346
python-kit
0
2025-01-27T23:56:48.338831
Apache-2.0
false
a0428d3e1b91a8c7a4f573537cb44a99
from matplotlib.axes._base import _AxesBase\nfrom matplotlib.axes._secondary_axes import SecondaryAxis\n\nfrom matplotlib.artist import Artist\nfrom matplotlib.backend_bases import RendererBase\nfrom matplotlib.collections import (\n Collection,\n FillBetweenPolyCollection,\n LineCollection,\n PathCollection,\n PolyCollection,\n EventCollection,\n QuadMesh,\n)\nfrom matplotlib.colorizer import Colorizer\nfrom matplotlib.colors import Colormap, Normalize\nfrom matplotlib.container import BarContainer, ErrorbarContainer, StemContainer\nfrom matplotlib.contour import ContourSet, QuadContourSet\nfrom matplotlib.image import AxesImage, PcolorImage\nfrom matplotlib.inset import InsetIndicator\nfrom matplotlib.legend import Legend\nfrom matplotlib.legend_handler import HandlerBase\nfrom matplotlib.lines import Line2D, AxLine\nfrom matplotlib.mlab import GaussianKDE\nfrom matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge\nfrom matplotlib.quiver import Quiver, QuiverKey, Barbs\nfrom matplotlib.text import Annotation, Text\nfrom matplotlib.transforms import Transform\nfrom matplotlib.typing import CoordsType\nimport matplotlib.tri as mtri\nimport matplotlib.table as mtable\nimport matplotlib.stackplot as mstack\nimport matplotlib.streamplot as mstream\n\nimport datetime\nimport PIL.Image\nfrom collections.abc import Callable, Iterable, Sequence\nfrom typing import Any, Literal, overload\nimport numpy as np\nfrom numpy.typing import ArrayLike\nfrom matplotlib.typing import ColorType, MarkerType, LineStyleType\n\nclass Axes(_AxesBase):\n def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ...\n def set_title(\n self,\n label: str,\n fontdict: dict[str, Any] | None = ...,\n loc: Literal["left", "center", "right"] | None = ...,\n pad: float | None = ...,\n *,\n y: float | None = ...,\n **kwargs\n ) -> Text: ...\n def get_legend_handles_labels(\n self, legend_handler_map: dict[type, HandlerBase] | None = ...\n ) -> tuple[list[Artist], list[Any]]: ...\n legend_: Legend | None\n\n @overload\n def legend(self) -> Legend: ...\n @overload\n def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ...\n @overload\n def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ...\n @overload\n def legend(self, labels: Iterable[str], **kwargs) -> Legend: ...\n @overload\n def legend(self, **kwargs) -> Legend: ...\n\n def inset_axes(\n self,\n bounds: tuple[float, float, float, float],\n *,\n transform: Transform | None = ...,\n zorder: float = ...,\n **kwargs\n ) -> Axes: ...\n def indicate_inset(\n self,\n bounds: tuple[float, float, float, float] | None = ...,\n inset_ax: Axes | None = ...,\n *,\n transform: Transform | None = ...,\n facecolor: ColorType = ...,\n edgecolor: ColorType = ...,\n alpha: float = ...,\n zorder: float | None = ...,\n **kwargs\n ) -> InsetIndicator: ...\n def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> InsetIndicator: ...\n def secondary_xaxis(\n self,\n location: Literal["top", "bottom"] | float,\n functions: tuple[\n Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]\n ]\n | Transform\n | None = ...,\n *,\n transform: Transform | None = ...,\n **kwargs\n ) -> SecondaryAxis: ...\n def secondary_yaxis(\n self,\n location: Literal["left", "right"] | float,\n functions: tuple[\n Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]\n ]\n | Transform\n | None = ...,\n *,\n transform: Transform | None = ...,\n **kwargs\n ) -> SecondaryAxis: ...\n def text(\n self,\n x: float,\n y: float,\n s: str,\n fontdict: dict[str, Any] | None = ...,\n **kwargs\n ) -> Text: ...\n def annotate(\n self,\n text: str,\n xy: tuple[float, float],\n xytext: tuple[float, float] | None = ...,\n xycoords: CoordsType = ...,\n textcoords: CoordsType | None = ...,\n arrowprops: dict[str, Any] | None = ...,\n annotation_clip: bool | None = ...,\n **kwargs\n ) -> Annotation: ...\n def axhline(\n self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs\n ) -> Line2D: ...\n def axvline(\n self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs\n ) -> Line2D: ...\n\n # TODO: Could separate the xy2 and slope signatures\n def axline(\n self,\n xy1: tuple[float, float],\n xy2: tuple[float, float] | None = ...,\n *,\n slope: float | None = ...,\n **kwargs\n ) -> AxLine: ...\n def axhspan(\n self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs\n ) -> Rectangle: ...\n def axvspan(\n self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs\n ) -> Rectangle: ...\n def hlines(\n self,\n y: float | ArrayLike,\n xmin: float | ArrayLike,\n xmax: float | ArrayLike,\n colors: ColorType | Sequence[ColorType] | None = ...,\n linestyles: LineStyleType = ...,\n *,\n label: str = ...,\n data=...,\n **kwargs\n ) -> LineCollection: ...\n def vlines(\n self,\n x: float | ArrayLike,\n ymin: float | ArrayLike,\n ymax: float | ArrayLike,\n colors: ColorType | Sequence[ColorType] | None = ...,\n linestyles: LineStyleType = ...,\n *,\n label: str = ...,\n data=...,\n **kwargs\n ) -> LineCollection: ...\n def eventplot(\n self,\n positions: ArrayLike | Sequence[ArrayLike],\n *,\n orientation: Literal["horizontal", "vertical"] = ...,\n lineoffsets: float | Sequence[float] = ...,\n linelengths: float | Sequence[float] = ...,\n linewidths: float | Sequence[float] | None = ...,\n colors: ColorType | Sequence[ColorType] | None = ...,\n alpha: float | Sequence[float] | None = ...,\n linestyles: LineStyleType | Sequence[LineStyleType] = ...,\n data=...,\n **kwargs\n ) -> EventCollection: ...\n def plot(\n self,\n *args: float | ArrayLike | str,\n scalex: bool = ...,\n scaley: bool = ...,\n data=...,\n **kwargs\n ) -> list[Line2D]: ...\n def plot_date(\n self,\n x: ArrayLike,\n y: ArrayLike,\n fmt: str = ...,\n tz: str | datetime.tzinfo | None = ...,\n xdate: bool = ...,\n ydate: bool = ...,\n *,\n data=...,\n **kwargs\n ) -> list[Line2D]: ...\n def loglog(self, *args, **kwargs) -> list[Line2D]: ...\n def semilogx(self, *args, **kwargs) -> list[Line2D]: ...\n def semilogy(self, *args, **kwargs) -> list[Line2D]: ...\n def acorr(\n self, x: ArrayLike, *, data=..., **kwargs\n ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...\n def xcorr(\n self,\n x: ArrayLike,\n y: ArrayLike,\n *,\n normed: bool = ...,\n detrend: Callable[[ArrayLike], ArrayLike] = ...,\n usevlines: bool = ...,\n maxlags: int = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...\n def step(\n self,\n x: ArrayLike,\n y: ArrayLike,\n *args,\n where: Literal["pre", "post", "mid"] = ...,\n data=...,\n **kwargs\n ) -> list[Line2D]: ...\n def bar(\n self,\n x: float | ArrayLike,\n height: float | ArrayLike,\n width: float | ArrayLike = ...,\n bottom: float | ArrayLike | None = ...,\n *,\n align: Literal["center", "edge"] = ...,\n data=...,\n **kwargs\n ) -> BarContainer: ...\n def barh(\n self,\n y: float | ArrayLike,\n width: float | ArrayLike,\n height: float | ArrayLike = ...,\n left: float | ArrayLike | None = ...,\n *,\n align: Literal["center", "edge"] = ...,\n data=...,\n **kwargs\n ) -> BarContainer: ...\n def bar_label(\n self,\n container: BarContainer,\n labels: ArrayLike | None = ...,\n *,\n fmt: str | Callable[[float], str] = ...,\n label_type: Literal["center", "edge"] = ...,\n padding: float = ...,\n **kwargs\n ) -> list[Annotation]: ...\n def broken_barh(\n self,\n xranges: Sequence[tuple[float, float]],\n yrange: tuple[float, float],\n *,\n data=...,\n **kwargs\n ) -> PolyCollection: ...\n def stem(\n self,\n *args: ArrayLike | str,\n linefmt: str | None = ...,\n markerfmt: str | None = ...,\n basefmt: str | None = ...,\n bottom: float = ...,\n label: str | None = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n data=...,\n ) -> StemContainer: ...\n\n # TODO: data kwarg preprocessor?\n def pie(\n self,\n x: ArrayLike,\n *,\n explode: ArrayLike | None = ...,\n labels: Sequence[str] | None = ...,\n colors: ColorType | Sequence[ColorType] | None = ...,\n autopct: str | Callable[[float], str] | None = ...,\n pctdistance: float = ...,\n shadow: bool = ...,\n labeldistance: float | None = ...,\n startangle: float = ...,\n radius: float = ...,\n counterclock: bool = ...,\n wedgeprops: dict[str, Any] | None = ...,\n textprops: dict[str, Any] | None = ...,\n center: tuple[float, float] = ...,\n frame: bool = ...,\n rotatelabels: bool = ...,\n normalize: bool = ...,\n hatch: str | Sequence[str] | None = ...,\n data=...,\n ) -> tuple[list[Wedge], list[Text]] | tuple[\n list[Wedge], list[Text], list[Text]\n ]: ...\n def errorbar(\n self,\n x: float | ArrayLike,\n y: float | ArrayLike,\n yerr: float | ArrayLike | None = ...,\n xerr: float | ArrayLike | None = ...,\n fmt: str = ...,\n *,\n ecolor: ColorType | None = ...,\n elinewidth: float | None = ...,\n capsize: float | None = ...,\n barsabove: bool = ...,\n lolims: bool | ArrayLike = ...,\n uplims: bool | ArrayLike = ...,\n xlolims: bool | ArrayLike = ...,\n xuplims: bool | ArrayLike = ...,\n errorevery: int | tuple[int, int] = ...,\n capthick: float | None = ...,\n data=...,\n **kwargs\n ) -> ErrorbarContainer: ...\n def boxplot(\n self,\n x: ArrayLike | Sequence[ArrayLike],\n *,\n notch: bool | None = ...,\n sym: str | None = ...,\n vert: bool | None = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n whis: float | tuple[float, float] | None = ...,\n positions: ArrayLike | None = ...,\n widths: float | ArrayLike | None = ...,\n patch_artist: bool | None = ...,\n bootstrap: int | None = ...,\n usermedians: ArrayLike | None = ...,\n conf_intervals: ArrayLike | None = ...,\n meanline: bool | None = ...,\n showmeans: bool | None = ...,\n showcaps: bool | None = ...,\n showbox: bool | None = ...,\n showfliers: bool | None = ...,\n boxprops: dict[str, Any] | None = ...,\n tick_labels: Sequence[str] | None = ...,\n flierprops: dict[str, Any] | None = ...,\n medianprops: dict[str, Any] | None = ...,\n meanprops: dict[str, Any] | None = ...,\n capprops: dict[str, Any] | None = ...,\n whiskerprops: dict[str, Any] | None = ...,\n manage_ticks: bool = ...,\n autorange: bool = ...,\n zorder: float | None = ...,\n capwidths: float | ArrayLike | None = ...,\n label: Sequence[str] | None = ...,\n data=...,\n ) -> dict[str, Any]: ...\n def bxp(\n self,\n bxpstats: Sequence[dict[str, Any]],\n positions: ArrayLike | None = ...,\n *,\n widths: float | ArrayLike | None = ...,\n vert: bool | None = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n patch_artist: bool = ...,\n shownotches: bool = ...,\n showmeans: bool = ...,\n showcaps: bool = ...,\n showbox: bool = ...,\n showfliers: bool = ...,\n boxprops: dict[str, Any] | None = ...,\n whiskerprops: dict[str, Any] | None = ...,\n flierprops: dict[str, Any] | None = ...,\n medianprops: dict[str, Any] | None = ...,\n capprops: dict[str, Any] | None = ...,\n meanprops: dict[str, Any] | None = ...,\n meanline: bool = ...,\n manage_ticks: bool = ...,\n zorder: float | None = ...,\n capwidths: float | ArrayLike | None = ...,\n label: Sequence[str] | None = ...,\n ) -> dict[str, Any]: ...\n def scatter(\n self,\n x: float | ArrayLike,\n y: float | ArrayLike,\n s: float | ArrayLike | None = ...,\n c: ArrayLike | Sequence[ColorType] | ColorType | None = ...,\n *,\n marker: MarkerType | None = ...,\n cmap: str | Colormap | None = ...,\n norm: str | Normalize | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n alpha: float | None = ...,\n linewidths: float | Sequence[float] | None = ...,\n edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ...,\n colorizer: Colorizer | None = ...,\n plotnonfinite: bool = ...,\n data=...,\n **kwargs\n ) -> PathCollection: ...\n def hexbin(\n self,\n x: ArrayLike,\n y: ArrayLike,\n C: ArrayLike | None = ...,\n *,\n gridsize: int | tuple[int, int] = ...,\n bins: Literal["log"] | int | Sequence[float] | None = ...,\n xscale: Literal["linear", "log"] = ...,\n yscale: Literal["linear", "log"] = ...,\n extent: tuple[float, float, float, float] | None = ...,\n cmap: str | Colormap | None = ...,\n norm: str | Normalize | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n alpha: float | None = ...,\n linewidths: float | None = ...,\n edgecolors: Literal["face", "none"] | ColorType = ...,\n reduce_C_function: Callable[[np.ndarray | list[float]], float] = ...,\n mincnt: int | None = ...,\n marginals: bool = ...,\n colorizer: Colorizer | None = ...,\n data=...,\n **kwargs\n ) -> PolyCollection: ...\n def arrow(\n self, x: float, y: float, dx: float, dy: float, **kwargs\n ) -> FancyArrow: ...\n def quiverkey(\n self, Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs\n ) -> QuiverKey: ...\n def quiver(self, *args, data=..., **kwargs) -> Quiver: ...\n def barbs(self, *args, data=..., **kwargs) -> Barbs: ...\n def fill(self, *args, data=..., **kwargs) -> list[Polygon]: ...\n def fill_between(\n self,\n x: ArrayLike,\n y1: ArrayLike | float,\n y2: ArrayLike | float = ...,\n where: Sequence[bool] | None = ...,\n interpolate: bool = ...,\n step: Literal["pre", "post", "mid"] | None = ...,\n *,\n data=...,\n **kwargs\n ) -> FillBetweenPolyCollection: ...\n def fill_betweenx(\n self,\n y: ArrayLike,\n x1: ArrayLike | float,\n x2: ArrayLike | float = ...,\n where: Sequence[bool] | None = ...,\n step: Literal["pre", "post", "mid"] | None = ...,\n interpolate: bool = ...,\n *,\n data=...,\n **kwargs\n ) -> FillBetweenPolyCollection: ...\n def imshow(\n self,\n X: ArrayLike | PIL.Image.Image,\n cmap: str | Colormap | None = ...,\n norm: str | Normalize | None = ...,\n *,\n aspect: Literal["equal", "auto"] | float | None = ...,\n interpolation: str | None = ...,\n alpha: float | ArrayLike | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n colorizer: Colorizer | None = ...,\n origin: Literal["upper", "lower"] | None = ...,\n extent: tuple[float, float, float, float] | None = ...,\n interpolation_stage: Literal["data", "rgba", "auto"] | None = ...,\n filternorm: bool = ...,\n filterrad: float = ...,\n resample: bool | None = ...,\n url: str | None = ...,\n data=...,\n **kwargs\n ) -> AxesImage: ...\n def pcolor(\n self,\n *args: ArrayLike,\n shading: Literal["flat", "nearest", "auto"] | None = ...,\n alpha: float | None = ...,\n norm: str | Normalize | None = ...,\n cmap: str | Colormap | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n colorizer: Colorizer | None = ...,\n data=...,\n **kwargs\n ) -> Collection: ...\n def pcolormesh(\n self,\n *args: ArrayLike,\n alpha: float | None = ...,\n norm: str | Normalize | None = ...,\n cmap: str | Colormap | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n colorizer: Colorizer | None = ...,\n shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ...,\n antialiased: bool = ...,\n data=...,\n **kwargs\n ) -> QuadMesh: ...\n def pcolorfast(\n self,\n *args: ArrayLike | tuple[float, float],\n alpha: float | None = ...,\n norm: str | Normalize | None = ...,\n cmap: str | Colormap | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n colorizer: Colorizer | None = ...,\n data=...,\n **kwargs\n ) -> AxesImage | PcolorImage | QuadMesh: ...\n def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ...\n def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ...\n def clabel(\n self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs\n ) -> list[Text]: ...\n def hist(\n self,\n x: ArrayLike | Sequence[ArrayLike],\n bins: int | Sequence[float] | str | None = ...,\n *,\n range: tuple[float, float] | None = ...,\n density: bool = ...,\n weights: ArrayLike | None = ...,\n cumulative: bool | float = ...,\n bottom: ArrayLike | float | None = ...,\n histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ...,\n align: Literal["left", "mid", "right"] = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n rwidth: float | None = ...,\n log: bool = ...,\n color: ColorType | Sequence[ColorType] | None = ...,\n label: str | Sequence[str] | None = ...,\n stacked: bool = ...,\n data=...,\n **kwargs\n ) -> tuple[\n np.ndarray | list[np.ndarray],\n np.ndarray,\n BarContainer | Polygon | list[BarContainer | Polygon],\n ]: ...\n def stairs(\n self,\n values: ArrayLike,\n edges: ArrayLike | None = ...,\n *,\n orientation: Literal["vertical", "horizontal"] = ...,\n baseline: float | ArrayLike | None = ...,\n fill: bool = ...,\n data=...,\n **kwargs\n ) -> StepPatch: ...\n def hist2d(\n self,\n x: ArrayLike,\n y: ArrayLike,\n bins: None\n | int\n | tuple[int, int]\n | ArrayLike\n | tuple[ArrayLike, ArrayLike] = ...,\n *,\n range: ArrayLike | None = ...,\n density: bool = ...,\n weights: ArrayLike | None = ...,\n cmin: float | None = ...,\n cmax: float | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ...\n def ecdf(\n self,\n x: ArrayLike,\n weights: ArrayLike | None = ...,\n *,\n complementary: bool=...,\n orientation: Literal["vertical", "horizontal"]=...,\n compress: bool=...,\n data=...,\n **kwargs\n ) -> Line2D: ...\n def psd(\n self,\n x: ArrayLike,\n *,\n NFFT: int | None = ...,\n Fs: float | None = ...,\n Fc: int | None = ...,\n detrend: Literal["none", "mean", "linear"]\n | Callable[[ArrayLike], ArrayLike]\n | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n noverlap: int | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n scale_by_freq: bool | None = ...,\n return_line: bool | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...\n def csd(\n self,\n x: ArrayLike,\n y: ArrayLike,\n *,\n NFFT: int | None = ...,\n Fs: float | None = ...,\n Fc: int | None = ...,\n detrend: Literal["none", "mean", "linear"]\n | Callable[[ArrayLike], ArrayLike]\n | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n noverlap: int | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n scale_by_freq: bool | None = ...,\n return_line: bool | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...\n def magnitude_spectrum(\n self,\n x: ArrayLike,\n *,\n Fs: float | None = ...,\n Fc: int | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n scale: Literal["default", "linear", "dB"] | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...\n def angle_spectrum(\n self,\n x: ArrayLike,\n *,\n Fs: float | None = ...,\n Fc: int | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...\n def phase_spectrum(\n self,\n x: ArrayLike,\n *,\n Fs: float | None = ...,\n Fc: int | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...\n def cohere(\n self,\n x: ArrayLike,\n y: ArrayLike,\n *,\n NFFT: int = ...,\n Fs: float = ...,\n Fc: int = ...,\n detrend: Literal["none", "mean", "linear"]\n | Callable[[ArrayLike], ArrayLike] = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ...,\n noverlap: int = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] = ...,\n scale_by_freq: bool | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray]: ...\n def specgram(\n self,\n x: ArrayLike,\n *,\n NFFT: int | None = ...,\n Fs: float | None = ...,\n Fc: int | None = ...,\n detrend: Literal["none", "mean", "linear"]\n | Callable[[ArrayLike], ArrayLike]\n | None = ...,\n window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,\n noverlap: int | None = ...,\n cmap: str | Colormap | None = ...,\n xextent: tuple[float, float] | None = ...,\n pad_to: int | None = ...,\n sides: Literal["default", "onesided", "twosided"] | None = ...,\n scale_by_freq: bool | None = ...,\n mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ...,\n scale: Literal["default", "linear", "dB"] | None = ...,\n vmin: float | None = ...,\n vmax: float | None = ...,\n data=...,\n **kwargs\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ...\n def spy(\n self,\n Z: ArrayLike,\n *,\n precision: float | Literal["present"] = ...,\n marker: str | None = ...,\n markersize: float | None = ...,\n aspect: Literal["equal", "auto"] | float | None = ...,\n origin: Literal["upper", "lower"] = ...,\n **kwargs\n ) -> AxesImage: ...\n def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ...\n def violinplot(\n self,\n dataset: ArrayLike | Sequence[ArrayLike],\n positions: ArrayLike | None = ...,\n *,\n vert: bool | None = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n widths: float | ArrayLike = ...,\n showmeans: bool = ...,\n showextrema: bool = ...,\n showmedians: bool = ...,\n quantiles: Sequence[float | Sequence[float]] | None = ...,\n points: int = ...,\n bw_method: Literal["scott", "silverman"]\n | float\n | Callable[[GaussianKDE], float]\n | None = ...,\n side: Literal["both", "low", "high"] = ...,\n data=...,\n ) -> dict[str, Collection]: ...\n def violin(\n self,\n vpstats: Sequence[dict[str, Any]],\n positions: ArrayLike | None = ...,\n *,\n vert: bool | None = ...,\n orientation: Literal["vertical", "horizontal"] = ...,\n widths: float | ArrayLike = ...,\n showmeans: bool = ...,\n showextrema: bool = ...,\n showmedians: bool = ...,\n side: Literal["both", "low", "high"] = ...,\n ) -> dict[str, Collection]: ...\n\n table = mtable.table\n stackplot = mstack.stackplot\n streamplot = mstream.streamplot\n tricontour = mtri.tricontour\n tricontourf = mtri.tricontourf\n tripcolor = mtri.tripcolor\n triplot = mtri.triplot\n
.venv\Lib\site-packages\matplotlib\axes\_axes.pyi
_axes.pyi
Other
26,116
0.95
0.092308
0.111399
awesome-app
794
2024-10-28T19:29:42.370449
Apache-2.0
false
9e5e4e47614ba01e2b4c0bffbc4e4443
import matplotlib.artist as martist\n\nimport datetime\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom matplotlib import cbook\nfrom matplotlib.artist import Artist\nfrom matplotlib.axes import Axes\nfrom matplotlib.axis import XAxis, YAxis, Tick\nfrom matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent\nfrom matplotlib.cbook import CallbackRegistry\nfrom matplotlib.container import Container\nfrom matplotlib.collections import Collection\nfrom matplotlib.colorizer import ColorizingArtist\nfrom matplotlib.legend import Legend\nfrom matplotlib.lines import Line2D\nfrom matplotlib.gridspec import SubplotSpec, GridSpec\nfrom matplotlib.figure import Figure, SubFigure\nfrom matplotlib.image import AxesImage\nfrom matplotlib.patches import Patch\nfrom matplotlib.scale import ScaleBase\nfrom matplotlib.spines import Spines\nfrom matplotlib.table import Table\nfrom matplotlib.text import Text\nfrom matplotlib.transforms import Transform, Bbox\n\nfrom cycler import Cycler\n\nimport numpy as np\nfrom numpy.typing import ArrayLike\nfrom typing import Any, Literal, TypeVar, overload\nfrom matplotlib.typing import ColorType\n\n_T = TypeVar("_T", bound=Artist)\n\nclass _axis_method_wrapper:\n attr_name: str\n method_name: str\n __doc__: str\n def __init__(\n self, attr_name: str, method_name: str, *, doc_sub: dict[str, str] | None = ...\n ) -> None: ...\n def __set_name__(self, owner: Any, name: str) -> None: ...\n\nclass _AxesBase(martist.Artist):\n name: str\n patch: Patch\n spines: Spines\n fmt_xdata: Callable[[float], str] | None\n fmt_ydata: Callable[[float], str] | None\n xaxis: XAxis\n yaxis: YAxis\n bbox: Bbox\n dataLim: Bbox\n transAxes: Transform\n transScale: Transform\n transLimits: Transform\n transData: Transform\n ignore_existing_data_limits: bool\n axison: bool\n containers: list[Container]\n callbacks: CallbackRegistry\n child_axes: list[_AxesBase]\n legend_: Legend | None\n title: Text\n _projection_init: Any\n\n def __init__(\n self,\n fig: Figure,\n *args: tuple[float, float, float, float] | Bbox | int,\n facecolor: ColorType | None = ...,\n frameon: bool = ...,\n sharex: _AxesBase | None = ...,\n sharey: _AxesBase | None = ...,\n label: Any = ...,\n xscale: str | ScaleBase | None = ...,\n yscale: str | ScaleBase | None = ...,\n box_aspect: float | None = ...,\n forward_navigation_events: bool | Literal["auto"] = ...,\n **kwargs\n ) -> None: ...\n def get_subplotspec(self) -> SubplotSpec | None: ...\n def set_subplotspec(self, subplotspec: SubplotSpec) -> None: ...\n def get_gridspec(self) -> GridSpec | None: ...\n def set_figure(self, fig: Figure | SubFigure) -> None: ...\n @property\n def viewLim(self) -> Bbox: ...\n def get_xaxis_transform(\n self, which: Literal["grid", "tick1", "tick2"] = ...\n ) -> Transform: ...\n def get_xaxis_text1_transform(\n self, pad_points: float\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_xaxis_text2_transform(\n self, pad_points\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_transform(\n self, which: Literal["grid", "tick1", "tick2"] = ...\n ) -> Transform: ...\n def get_yaxis_text1_transform(\n self, pad_points\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_yaxis_text2_transform(\n self, pad_points\n ) -> tuple[\n Transform,\n Literal["center", "top", "bottom", "baseline", "center_baseline"],\n Literal["center", "left", "right"],\n ]: ...\n def get_position(self, original: bool = ...) -> Bbox: ...\n def set_position(\n self,\n pos: Bbox | tuple[float, float, float, float],\n which: Literal["both", "active", "original"] = ...,\n ) -> None: ...\n def reset_position(self) -> None: ...\n def set_axes_locator(\n self, locator: Callable[[_AxesBase, RendererBase], Bbox]\n ) -> None: ...\n def get_axes_locator(self) -> Callable[[_AxesBase, RendererBase], Bbox]: ...\n def sharex(self, other: _AxesBase) -> None: ...\n def sharey(self, other: _AxesBase) -> None: ...\n def clear(self) -> None: ...\n def cla(self) -> None: ...\n\n class ArtistList(Sequence[_T]):\n def __init__(\n self,\n axes: _AxesBase,\n prop_name: str,\n valid_types: type | Iterable[type] | None = ...,\n invalid_types: type | Iterable[type] | None = ...,\n ) -> None: ...\n def __len__(self) -> int: ...\n def __iter__(self) -> Iterator[_T]: ...\n @overload\n def __getitem__(self, key: int) -> _T: ...\n @overload\n def __getitem__(self, key: slice) -> list[_T]: ...\n\n @overload\n def __add__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...\n @overload\n def __add__(self, other: list[Any]) -> list[Any]: ...\n @overload\n def __add__(self, other: tuple[Any]) -> tuple[Any]: ...\n\n @overload\n def __radd__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...\n @overload\n def __radd__(self, other: list[Any]) -> list[Any]: ...\n @overload\n def __radd__(self, other: tuple[Any]) -> tuple[Any]: ...\n\n @property\n def artists(self) -> _AxesBase.ArtistList[Artist]: ...\n @property\n def collections(self) -> _AxesBase.ArtistList[Collection]: ...\n @property\n def images(self) -> _AxesBase.ArtistList[AxesImage]: ...\n @property\n def lines(self) -> _AxesBase.ArtistList[Line2D]: ...\n @property\n def patches(self) -> _AxesBase.ArtistList[Patch]: ...\n @property\n def tables(self) -> _AxesBase.ArtistList[Table]: ...\n @property\n def texts(self) -> _AxesBase.ArtistList[Text]: ...\n def get_facecolor(self) -> ColorType: ...\n def set_facecolor(self, color: ColorType | None) -> None: ...\n @overload\n def set_prop_cycle(self, cycler: Cycler | None) -> None: ...\n @overload\n def set_prop_cycle(self, label: str, values: Iterable[Any]) -> None: ...\n @overload\n def set_prop_cycle(self, **kwargs: Iterable[Any]) -> None: ...\n def get_aspect(self) -> float | Literal["auto"]: ...\n def set_aspect(\n self,\n aspect: float | Literal["auto", "equal"],\n adjustable: Literal["box", "datalim"] | None = ...,\n anchor: str | tuple[float, float] | None = ...,\n share: bool = ...,\n ) -> None: ...\n def get_adjustable(self) -> Literal["box", "datalim"]: ...\n def set_adjustable(\n self, adjustable: Literal["box", "datalim"], share: bool = ...\n ) -> None: ...\n def get_box_aspect(self) -> float | None: ...\n def set_box_aspect(self, aspect: float | None = ...) -> None: ...\n def get_anchor(self) -> str | tuple[float, float]: ...\n def set_anchor(\n self, anchor: str | tuple[float, float], share: bool = ...\n ) -> None: ...\n def get_data_ratio(self) -> float: ...\n def apply_aspect(self, position: Bbox | None = ...) -> None: ...\n @overload\n def axis(\n self,\n arg: tuple[float, float, float, float] | bool | str | None = ...,\n /,\n *,\n emit: bool = ...\n ) -> tuple[float, float, float, float]: ...\n @overload\n def axis(\n self,\n *,\n emit: bool = ...,\n xmin: float | None = ...,\n xmax: float | None = ...,\n ymin: float | None = ...,\n ymax: float | None = ...\n ) -> tuple[float, float, float, float]: ...\n def get_legend(self) -> Legend: ...\n def get_images(self) -> list[AxesImage]: ...\n def get_lines(self) -> list[Line2D]: ...\n def get_xaxis(self) -> XAxis: ...\n def get_yaxis(self) -> YAxis: ...\n def has_data(self) -> bool: ...\n def add_artist(self, a: Artist) -> Artist: ...\n def add_child_axes(self, ax: _AxesBase) -> _AxesBase: ...\n def add_collection(\n self, collection: Collection, autolim: bool = ...\n ) -> Collection: ...\n def add_image(self, image: AxesImage) -> AxesImage: ...\n def add_line(self, line: Line2D) -> Line2D: ...\n def add_patch(self, p: Patch) -> Patch: ...\n def add_table(self, tab: Table) -> Table: ...\n def add_container(self, container: Container) -> Container: ...\n def relim(self, visible_only: bool = ...) -> None: ...\n def update_datalim(\n self, xys: ArrayLike, updatex: bool = ..., updatey: bool = ...\n ) -> None: ...\n def in_axes(self, mouseevent: MouseEvent) -> bool: ...\n def get_autoscale_on(self) -> bool: ...\n def set_autoscale_on(self, b: bool) -> None: ...\n @property\n def use_sticky_edges(self) -> bool: ...\n @use_sticky_edges.setter\n def use_sticky_edges(self, b: bool) -> None: ...\n def get_xmargin(self) -> float: ...\n def get_ymargin(self) -> float: ...\n def set_xmargin(self, m: float) -> None: ...\n def set_ymargin(self, m: float) -> None: ...\n\n # Probably could be made better with overloads\n def margins(\n self,\n *margins: float,\n x: float | None = ...,\n y: float | None = ...,\n tight: bool | None = ...\n ) -> tuple[float, float] | None: ...\n def set_rasterization_zorder(self, z: float | None) -> None: ...\n def get_rasterization_zorder(self) -> float | None: ...\n def autoscale(\n self,\n enable: bool = ...,\n axis: Literal["both", "x", "y"] = ...,\n tight: bool | None = ...,\n ) -> None: ...\n def autoscale_view(\n self, tight: bool | None = ..., scalex: bool = ..., scaley: bool = ...\n ) -> None: ...\n def draw_artist(self, a: Artist) -> None: ...\n def redraw_in_frame(self) -> None: ...\n def get_frame_on(self) -> bool: ...\n def set_frame_on(self, b: bool) -> None: ...\n def get_axisbelow(self) -> bool | Literal["line"]: ...\n def set_axisbelow(self, b: bool | Literal["line"]) -> None: ...\n def grid(\n self,\n visible: bool | None = ...,\n which: Literal["major", "minor", "both"] = ...,\n axis: Literal["both", "x", "y"] = ...,\n **kwargs\n ) -> None: ...\n def ticklabel_format(\n self,\n *,\n axis: Literal["both", "x", "y"] = ...,\n style: Literal["", "sci", "scientific", "plain"] | None = ...,\n scilimits: tuple[int, int] | None = ...,\n useOffset: bool | float | None = ...,\n useLocale: bool | None = ...,\n useMathText: bool | None = ...\n ) -> None: ...\n def locator_params(\n self, axis: Literal["both", "x", "y"] = ..., tight: bool | None = ..., **kwargs\n ) -> None: ...\n def tick_params(self, axis: Literal["both", "x", "y"] = ..., **kwargs) -> None: ...\n def set_axis_off(self) -> None: ...\n def set_axis_on(self) -> None: ...\n def get_xlabel(self) -> str: ...\n def set_xlabel(\n self,\n xlabel: str,\n fontdict: dict[str, Any] | None = ...,\n labelpad: float | None = ...,\n *,\n loc: Literal["left", "center", "right"] | None = ...,\n **kwargs\n ) -> Text: ...\n def invert_xaxis(self) -> None: ...\n def get_xbound(self) -> tuple[float, float]: ...\n def set_xbound(\n self, lower: float | None = ..., upper: float | None = ...\n ) -> None: ...\n def get_xlim(self) -> tuple[float, float]: ...\n def set_xlim(\n self,\n left: float | tuple[float, float] | None = ...,\n right: float | None = ...,\n *,\n emit: bool = ...,\n auto: bool | None = ...,\n xmin: float | None = ...,\n xmax: float | None = ...\n ) -> tuple[float, float]: ...\n def get_ylabel(self) -> str: ...\n def set_ylabel(\n self,\n ylabel: str,\n fontdict: dict[str, Any] | None = ...,\n labelpad: float | None = ...,\n *,\n loc: Literal["bottom", "center", "top"] | None = ...,\n **kwargs\n ) -> Text: ...\n def invert_yaxis(self) -> None: ...\n def get_ybound(self) -> tuple[float, float]: ...\n def set_ybound(\n self, lower: float | None = ..., upper: float | None = ...\n ) -> None: ...\n def get_ylim(self) -> tuple[float, float]: ...\n def set_ylim(\n self,\n bottom: float | tuple[float, float] | None = ...,\n top: float | None = ...,\n *,\n emit: bool = ...,\n auto: bool | None = ...,\n ymin: float | None = ...,\n ymax: float | None = ...\n ) -> tuple[float, float]: ...\n def format_xdata(self, x: float) -> str: ...\n def format_ydata(self, y: float) -> str: ...\n def format_coord(self, x: float, y: float) -> str: ...\n def minorticks_on(self) -> None: ...\n def minorticks_off(self) -> None: ...\n def can_zoom(self) -> bool: ...\n def can_pan(self) -> bool: ...\n def get_navigate(self) -> bool: ...\n def set_navigate(self, b: bool) -> None: ...\n def get_forward_navigation_events(self) -> bool | Literal["auto"]: ...\n def set_forward_navigation_events(self, forward: bool | Literal["auto"]) -> None: ...\n def get_navigate_mode(self) -> Literal["PAN", "ZOOM"] | None: ...\n def set_navigate_mode(self, b: Literal["PAN", "ZOOM"] | None) -> None: ...\n def start_pan(self, x: float, y: float, button: MouseButton) -> None: ...\n def end_pan(self) -> None: ...\n def drag_pan(\n self, button: MouseButton, key: str | None, x: float, y: float\n ) -> None: ...\n def get_children(self) -> list[Artist]: ...\n def contains_point(self, point: tuple[int, int]) -> bool: ...\n def get_default_bbox_extra_artists(self) -> list[Artist]: ...\n def get_tightbbox(\n self,\n renderer: RendererBase | None = ...,\n *,\n call_axes_locator: bool = ...,\n bbox_extra_artists: Sequence[Artist] | None = ...,\n for_layout_only: bool = ...\n ) -> Bbox | None: ...\n def twinx(self) -> Axes: ...\n def twiny(self) -> Axes: ...\n def get_shared_x_axes(self) -> cbook.GrouperView: ...\n def get_shared_y_axes(self) -> cbook.GrouperView: ...\n def label_outer(self, remove_inner_ticks: bool = ...) -> None: ...\n\n # The methods underneath this line are added via the `_axis_method_wrapper` class\n # Initially they are set to an object, but that object uses `__set_name__` to override\n # itself with a method modified from the Axis methods for the x or y Axis.\n # As such, they are typed according to the resultant method rather than as that object.\n\n def get_xgridlines(self) -> list[Line2D]: ...\n def get_xticklines(self, minor: bool = ...) -> list[Line2D]: ...\n def get_ygridlines(self) -> list[Line2D]: ...\n def get_yticklines(self, minor: bool = ...) -> list[Line2D]: ...\n def _sci(self, im: ColorizingArtist) -> None: ...\n def get_autoscalex_on(self) -> bool: ...\n def get_autoscaley_on(self) -> bool: ...\n def set_autoscalex_on(self, b: bool) -> None: ...\n def set_autoscaley_on(self, b: bool) -> None: ...\n def xaxis_inverted(self) -> bool: ...\n def get_xscale(self) -> str: ...\n def set_xscale(self, value: str | ScaleBase, **kwargs) -> None: ...\n def get_xticks(self, *, minor: bool = ...) -> np.ndarray: ...\n def set_xticks(\n self,\n ticks: ArrayLike,\n labels: Iterable[str] | None = ...,\n *,\n minor: bool = ...,\n **kwargs\n ) -> list[Tick]: ...\n def get_xmajorticklabels(self) -> list[Text]: ...\n def get_xminorticklabels(self) -> list[Text]: ...\n def get_xticklabels(\n self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...\n ) -> list[Text]: ...\n def set_xticklabels(\n self,\n labels: Iterable[str | Text],\n *,\n minor: bool = ...,\n fontdict: dict[str, Any] | None = ...,\n **kwargs\n ) -> list[Text]: ...\n def yaxis_inverted(self) -> bool: ...\n def get_yscale(self) -> str: ...\n def set_yscale(self, value: str | ScaleBase, **kwargs) -> None: ...\n def get_yticks(self, *, minor: bool = ...) -> np.ndarray: ...\n def set_yticks(\n self,\n ticks: ArrayLike,\n labels: Iterable[str] | None = ...,\n *,\n minor: bool = ...,\n **kwargs\n ) -> list[Tick]: ...\n def get_ymajorticklabels(self) -> list[Text]: ...\n def get_yminorticklabels(self) -> list[Text]: ...\n def get_yticklabels(\n self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...\n ) -> list[Text]: ...\n def set_yticklabels(\n self,\n labels: Iterable[str | Text],\n *,\n minor: bool = ...,\n fontdict: dict[str, Any] | None = ...,\n **kwargs\n ) -> list[Text]: ...\n def xaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...\n def yaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...\n
.venv\Lib\site-packages\matplotlib\axes\_base.pyi
_base.pyi
Other
17,051
0.95
0.376906
0.060674
vue-tools
50
2023-12-10T16:51:13.802701
Apache-2.0
false
0080cdf30b7aa303be47f4d14865dc98
import numbers\n\nimport numpy as np\n\nfrom matplotlib import _api, _docstring, transforms\nimport matplotlib.ticker as mticker\nfrom matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator\nfrom matplotlib.axis import Axis\nfrom matplotlib.transforms import Transform\n\n\nclass SecondaryAxis(_AxesBase):\n """\n General class to hold a Secondary_X/Yaxis.\n """\n\n def __init__(self, parent, orientation, location, functions, transform=None,\n **kwargs):\n """\n See `.secondary_xaxis` and `.secondary_yaxis` for the doc string.\n While there is no need for this to be private, it should really be\n called by those higher level functions.\n """\n _api.check_in_list(["x", "y"], orientation=orientation)\n self._functions = functions\n self._parent = parent\n self._orientation = orientation\n self._ticks_set = False\n\n fig = self._parent.get_figure(root=False)\n if self._orientation == 'x':\n super().__init__(fig, [0, 1., 1, 0.0001], **kwargs)\n self._axis = self.xaxis\n self._locstrings = ['top', 'bottom']\n self._otherstrings = ['left', 'right']\n else: # 'y'\n super().__init__(fig, [0, 1., 0.0001, 1], **kwargs)\n self._axis = self.yaxis\n self._locstrings = ['right', 'left']\n self._otherstrings = ['top', 'bottom']\n self._parentscale = None\n # this gets positioned w/o constrained_layout so exclude:\n\n self.set_location(location, transform)\n self.set_functions(functions)\n\n # styling:\n otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis\n otheraxis.set_major_locator(mticker.NullLocator())\n otheraxis.set_ticks_position('none')\n\n self.spines[self._otherstrings].set_visible(False)\n self.spines[self._locstrings].set_visible(True)\n\n if self._pos < 0.5:\n # flip the location strings...\n self._locstrings = self._locstrings[::-1]\n self.set_alignment(self._locstrings[0])\n\n def set_alignment(self, align):\n """\n Set if axes spine and labels are drawn at top or bottom (or left/right)\n of the Axes.\n\n Parameters\n ----------\n align : {'top', 'bottom', 'left', 'right'}\n Either 'top' or 'bottom' for orientation='x' or\n 'left' or 'right' for orientation='y' axis.\n """\n _api.check_in_list(self._locstrings, align=align)\n if align == self._locstrings[1]: # Need to change the orientation.\n self._locstrings = self._locstrings[::-1]\n self.spines[self._locstrings[0]].set_visible(True)\n self.spines[self._locstrings[1]].set_visible(False)\n self._axis.set_ticks_position(align)\n self._axis.set_label_position(align)\n\n def set_location(self, location, transform=None):\n """\n Set the vertical or horizontal location of the axes in\n parent-normalized coordinates.\n\n Parameters\n ----------\n location : {'top', 'bottom', 'left', 'right'} or float\n The position to put the secondary axis. Strings can be 'top' or\n 'bottom' for orientation='x' and 'right' or 'left' for\n orientation='y'. A float indicates the relative position on the\n parent Axes to put the new Axes, 0.0 being the bottom (or left)\n and 1.0 being the top (or right).\n\n transform : `.Transform`, optional\n Transform for the location to use. Defaults to\n the parent's ``transAxes``, so locations are normally relative to\n the parent axes.\n\n .. versionadded:: 3.9\n """\n\n _api.check_isinstance((transforms.Transform, None), transform=transform)\n\n # This puts the rectangle into figure-relative coordinates.\n if isinstance(location, str):\n _api.check_in_list(self._locstrings, location=location)\n self._pos = 1. if location in ('top', 'right') else 0.\n elif isinstance(location, numbers.Real):\n self._pos = location\n else:\n raise ValueError(\n f"location must be {self._locstrings[0]!r}, "\n f"{self._locstrings[1]!r}, or a float, not {location!r}")\n\n self._loc = location\n\n if self._orientation == 'x':\n # An x-secondary axes is like an inset axes from x = 0 to x = 1 and\n # from y = pos to y = pos + eps, in the parent's transAxes coords.\n bounds = [0, self._pos, 1., 1e-10]\n\n # If a transformation is provided, use its y component rather than\n # the parent's transAxes. This can be used to place axes in the data\n # coords, for instance.\n if transform is not None:\n transform = transforms.blended_transform_factory(\n self._parent.transAxes, transform)\n else: # 'y'\n bounds = [self._pos, 0, 1e-10, 1]\n if transform is not None:\n transform = transforms.blended_transform_factory(\n transform, self._parent.transAxes) # Use provided x axis\n\n # If no transform is provided, use the parent's transAxes\n if transform is None:\n transform = self._parent.transAxes\n\n # this locator lets the axes move in the parent axes coordinates.\n # so it never needs to know where the parent is explicitly in\n # figure coordinates.\n # it gets called in ax.apply_aspect() (of all places)\n self.set_axes_locator(_TransformedBoundsLocator(bounds, transform))\n\n def apply_aspect(self, position=None):\n # docstring inherited.\n self._set_lims()\n super().apply_aspect(position)\n\n @_docstring.copy(Axis.set_ticks)\n def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):\n ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs)\n self.stale = True\n self._ticks_set = True\n return ret\n\n def set_functions(self, functions):\n """\n Set how the secondary axis converts limits from the parent Axes.\n\n Parameters\n ----------\n functions : 2-tuple of func, or `Transform` with an inverse.\n Transform between the parent axis values and the secondary axis\n values.\n\n If supplied as a 2-tuple of functions, the first function is\n the forward transform function and the second is the inverse\n transform.\n\n If a transform is supplied, then the transform must have an\n inverse.\n """\n\n if (isinstance(functions, tuple) and len(functions) == 2 and\n callable(functions[0]) and callable(functions[1])):\n # make an arbitrary convert from a two-tuple of functions\n # forward and inverse.\n self._functions = functions\n elif isinstance(functions, Transform):\n self._functions = (\n functions.transform,\n lambda x: functions.inverted().transform(x)\n )\n elif functions is None:\n self._functions = (lambda x: x, lambda x: x)\n else:\n raise ValueError('functions argument of secondary Axes '\n 'must be a two-tuple of callable functions '\n 'with the first function being the transform '\n 'and the second being the inverse')\n self._set_scale()\n\n def draw(self, renderer):\n """\n Draw the secondary Axes.\n\n Consults the parent Axes for its limits and converts them\n using the converter specified by\n `~.axes._secondary_axes.set_functions` (or *functions*\n parameter when Axes initialized.)\n """\n self._set_lims()\n # this sets the scale in case the parent has set its scale.\n self._set_scale()\n super().draw(renderer)\n\n def _set_scale(self):\n """\n Check if parent has set its scale\n """\n\n if self._orientation == 'x':\n pscale = self._parent.xaxis.get_scale()\n set_scale = self.set_xscale\n else: # 'y'\n pscale = self._parent.yaxis.get_scale()\n set_scale = self.set_yscale\n if pscale == self._parentscale:\n return\n\n if self._ticks_set:\n ticks = self._axis.get_ticklocs()\n\n # need to invert the roles here for the ticks to line up.\n set_scale('functionlog' if pscale == 'log' else 'function',\n functions=self._functions[::-1])\n\n # OK, set_scale sets the locators, but if we've called\n # axsecond.set_ticks, we want to keep those.\n if self._ticks_set:\n self._axis.set_major_locator(mticker.FixedLocator(ticks))\n\n # If the parent scale doesn't change, we can skip this next time.\n self._parentscale = pscale\n\n def _set_lims(self):\n """\n Set the limits based on parent limits and the convert method\n between the parent and this secondary Axes.\n """\n if self._orientation == 'x':\n lims = self._parent.get_xlim()\n set_lim = self.set_xlim\n else: # 'y'\n lims = self._parent.get_ylim()\n set_lim = self.set_ylim\n order = lims[0] < lims[1]\n lims = self._functions[0](np.array(lims))\n neworder = lims[0] < lims[1]\n if neworder != order:\n # Flip because the transform will take care of the flipping.\n lims = lims[::-1]\n set_lim(lims)\n\n def set_aspect(self, *args, **kwargs):\n """\n Secondary Axes cannot set the aspect ratio, so calling this just\n sets a warning.\n """\n _api.warn_external("Secondary Axes can't set the aspect ratio")\n\n def set_color(self, color):\n """\n Change the color of the secondary Axes and all decorators.\n\n Parameters\n ----------\n color : :mpltype:`color`\n """\n axis = self._axis_map[self._orientation]\n axis.set_tick_params(colors=color)\n for spine in self.spines.values():\n if spine.axis is axis:\n spine.set_color(color)\n axis.label.set_color(color)\n\n\n_secax_docstring = '''\nWarnings\n--------\nThis method is experimental as of 3.1, and the API may change.\n\nParameters\n----------\nlocation : {'top', 'bottom', 'left', 'right'} or float\n The position to put the secondary axis. Strings can be 'top' or\n 'bottom' for orientation='x' and 'right' or 'left' for\n orientation='y'. A float indicates the relative position on the\n parent Axes to put the new Axes, 0.0 being the bottom (or left)\n and 1.0 being the top (or right).\n\nfunctions : 2-tuple of func, or Transform with an inverse\n\n If a 2-tuple of functions, the user specifies the transform\n function and its inverse. i.e.\n ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an\n reciprocal transform with a factor of 2. Both functions must accept\n numpy arrays as input.\n\n The user can also directly supply a subclass of\n `.transforms.Transform` so long as it has an inverse.\n\n See :doc:`/gallery/subplots_axes_and_figures/secondary_axis`\n for examples of making these conversions.\n\ntransform : `.Transform`, optional\n If specified, *location* will be\n placed relative to this transform (in the direction of the axis)\n rather than the parent's axis. i.e. a secondary x-axis will\n use the provided y transform and the x transform of the parent.\n\n .. versionadded:: 3.9\n\nReturns\n-------\nax : axes._secondary_axes.SecondaryAxis\n\nOther Parameters\n----------------\n**kwargs : `~matplotlib.axes.Axes` properties.\n Other miscellaneous Axes parameters.\n'''\n_docstring.interpd.register(_secax_docstring=_secax_docstring)\n
.venv\Lib\site-packages\matplotlib\axes\_secondary_axes.py
_secondary_axes.py
Python
11,887
0.95
0.167702
0.092937
vue-tools
2
2024-09-26T10:37:59.690670
MIT
false
9d4be70d984b3e672b7604f43258db8e
from matplotlib.axes._base import _AxesBase\nfrom matplotlib.axis import Tick\n\nfrom matplotlib.transforms import Transform\n\nfrom collections.abc import Callable, Iterable\nfrom typing import Literal\nfrom numpy.typing import ArrayLike\nfrom matplotlib.typing import ColorType\n\nclass SecondaryAxis(_AxesBase):\n def __init__(\n self,\n parent: _AxesBase,\n orientation: Literal["x", "y"],\n location: Literal["top", "bottom", "right", "left"] | float,\n functions: tuple[\n Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]\n ]\n | Transform,\n transform: Transform | None = ...,\n **kwargs\n ) -> None: ...\n def set_alignment(\n self, align: Literal["top", "bottom", "right", "left"]\n ) -> None: ...\n def set_location(\n self,\n location: Literal["top", "bottom", "right", "left"] | float,\n transform: Transform | None = ...\n ) -> None: ...\n def set_ticks(\n self,\n ticks: ArrayLike,\n labels: Iterable[str] | None = ...,\n *,\n minor: bool = ...,\n **kwargs\n ) -> list[Tick]: ...\n def set_functions(\n self,\n functions: tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] | Transform,\n ) -> None: ...\n def set_aspect(self, *args, **kwargs) -> None: ...\n def set_color(self, color: ColorType) -> None: ...\n
.venv\Lib\site-packages\matplotlib\axes\_secondary_axes.pyi
_secondary_axes.pyi
Other
1,414
0.85
0.177778
0.071429
vue-tools
793
2023-09-19T22:34:32.451435
BSD-3-Clause
false
22edd8fa78b700ffa864181f027dc727
from . import _base\nfrom ._axes import Axes\n\n# Backcompat.\nSubplot = Axes\n\n\nclass _SubplotBaseMeta(type):\n def __instancecheck__(self, obj):\n return (isinstance(obj, _base._AxesBase)\n and obj.get_subplotspec() is not None)\n\n\nclass SubplotBase(metaclass=_SubplotBaseMeta):\n pass\n\n\ndef subplot_class_factory(cls): return cls\n
.venv\Lib\site-packages\matplotlib\axes\__init__.py
__init__.py
Python
351
0.95
0.222222
0.090909
python-kit
910
2024-02-20T17:48:21.132472
MIT
false
88a8aa2f4c118802e95504639682b05c
from typing import TypeVar\n\nfrom ._axes import Axes as Axes\n\n\n_T = TypeVar("_T")\n\n# Backcompat.\nSubplot = Axes\n\nclass _SubplotBaseMeta(type):\n def __instancecheck__(self, obj) -> bool: ...\n\nclass SubplotBase(metaclass=_SubplotBaseMeta): ...\n\ndef subplot_class_factory(cls: type[_T]) -> type[_T]: ...\n
.venv\Lib\site-packages\matplotlib\axes\__init__.pyi
__init__.pyi
Other
303
0.95
0.25
0.111111
python-kit
854
2025-06-15T09:01:36.697678
MIT
false
914cd19d332af9323c2d71760d2b0711
\n\n
.venv\Lib\site-packages\matplotlib\axes\__pycache__\_secondary_axes.cpython-313.pyc
_secondary_axes.cpython-313.pyc
Other
13,993
0.95
0.087805
0.010989
react-lib
353
2024-07-06T18:39:57.375264
Apache-2.0
false
1a4e262ec7b3556509e1b444c25eddae
\n\n
.venv\Lib\site-packages\matplotlib\axes\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,178
0.7
0
0
vue-tools
783
2025-05-04T08:36:22.938678
MIT
false
f3e144bb8efd857f8130b0a7f9d9f2db
"""\nAn `Anti-Grain Geometry`_ (AGG) backend.\n\nFeatures that are implemented:\n\n* capstyles and join styles\n* dashes\n* linewidth\n* lines, rectangles, ellipses\n* clipping to a rectangle\n* output to RGBA and Pillow-supported image formats\n* alpha blending\n* DPI scaling properly - everything scales properly (dashes, linewidths, etc)\n* draw polygon\n* freetype2 w/ ft2font\n\nStill TODO:\n\n* integrate screen dpi w/ ppi and text\n\n.. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com\n"""\n\nfrom contextlib import nullcontext\nfrom math import radians, cos, sin\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)\nfrom matplotlib.font_manager import fontManager as _fontManager, get_font\nfrom matplotlib.ft2font import LoadFlags\nfrom matplotlib.mathtext import MathTextParser\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Bbox, BboxBase\nfrom matplotlib.backends._backend_agg import RendererAgg as _RendererAgg\n\n\ndef get_hinting_flag():\n mapping = {\n 'default': LoadFlags.DEFAULT,\n 'no_autohint': LoadFlags.NO_AUTOHINT,\n 'force_autohint': LoadFlags.FORCE_AUTOHINT,\n 'no_hinting': LoadFlags.NO_HINTING,\n True: LoadFlags.FORCE_AUTOHINT,\n False: LoadFlags.NO_HINTING,\n 'either': LoadFlags.DEFAULT,\n 'native': LoadFlags.NO_AUTOHINT,\n 'auto': LoadFlags.FORCE_AUTOHINT,\n 'none': LoadFlags.NO_HINTING,\n }\n return mapping[mpl.rcParams['text.hinting']]\n\n\nclass RendererAgg(RendererBase):\n """\n The renderer handles all the drawing primitives using a graphics\n context instance that controls the colors/styles\n """\n\n def __init__(self, width, height, dpi):\n super().__init__()\n\n self.dpi = dpi\n self.width = width\n self.height = height\n self._renderer = _RendererAgg(int(width), int(height), dpi)\n self._filter_renderers = []\n\n self._update_methods()\n self.mathtext_parser = MathTextParser('agg')\n\n self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)\n\n def __getstate__(self):\n # We only want to preserve the init keywords of the Renderer.\n # Anything else can be re-created.\n return {'width': self.width, 'height': self.height, 'dpi': self.dpi}\n\n def __setstate__(self, state):\n self.__init__(state['width'], state['height'], state['dpi'])\n\n def _update_methods(self):\n self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles\n self.draw_image = self._renderer.draw_image\n self.draw_markers = self._renderer.draw_markers\n self.draw_path_collection = self._renderer.draw_path_collection\n self.draw_quad_mesh = self._renderer.draw_quad_mesh\n self.copy_from_bbox = self._renderer.copy_from_bbox\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing\n npts = path.vertices.shape[0]\n\n if (npts > nmax > 100 and path.should_simplify and\n rgbFace is None and gc.get_hatch() is None):\n nch = np.ceil(npts / nmax)\n chsize = int(np.ceil(npts / nch))\n i0 = np.arange(0, npts, chsize)\n i1 = np.zeros_like(i0)\n i1[:-1] = i0[1:] - 1\n i1[-1] = npts\n for ii0, ii1 in zip(i0, i1):\n v = path.vertices[ii0:ii1, :]\n c = path.codes\n if c is not None:\n c = c[ii0:ii1]\n c[0] = Path.MOVETO # move to end of last chunk\n p = Path(v, c)\n p.simplify_threshold = path.simplify_threshold\n try:\n self._renderer.draw_path(gc, p, transform, rgbFace)\n except OverflowError:\n msg = (\n "Exceeded cell block limit in Agg.\n\n"\n "Please reduce the value of "\n f"rcParams['agg.path.chunksize'] (currently {nmax}) "\n "or increase the path simplification threshold"\n "(rcParams['path.simplify_threshold'] = "\n f"{mpl.rcParams['path.simplify_threshold']:.2f} by "\n "default and path.simplify_threshold = "\n f"{path.simplify_threshold:.2f} on the input)."\n )\n raise OverflowError(msg) from None\n else:\n try:\n self._renderer.draw_path(gc, path, transform, rgbFace)\n except OverflowError:\n cant_chunk = ''\n if rgbFace is not None:\n cant_chunk += "- cannot split filled path\n"\n if gc.get_hatch() is not None:\n cant_chunk += "- cannot split hatched path\n"\n if not path.should_simplify:\n cant_chunk += "- path.should_simplify is False\n"\n if len(cant_chunk):\n msg = (\n "Exceeded cell block limit in Agg, however for the "\n "following reasons:\n\n"\n f"{cant_chunk}\n"\n "we cannot automatically split up this path to draw."\n "\n\nPlease manually simplify your path."\n )\n\n else:\n inc_threshold = (\n "or increase the path simplification threshold"\n "(rcParams['path.simplify_threshold'] = "\n f"{mpl.rcParams['path.simplify_threshold']} "\n "by default and path.simplify_threshold "\n f"= {path.simplify_threshold} "\n "on the input)."\n )\n if nmax > 100:\n msg = (\n "Exceeded cell block limit in Agg. Please reduce "\n "the value of rcParams['agg.path.chunksize'] "\n f"(currently {nmax}) {inc_threshold}"\n )\n else:\n msg = (\n "Exceeded cell block limit in Agg. Please set "\n "the value of rcParams['agg.path.chunksize'], "\n f"(currently {nmax}) to be greater than 100 "\n + inc_threshold\n )\n\n raise OverflowError(msg) from None\n\n def draw_mathtext(self, gc, x, y, s, prop, angle):\n """Draw mathtext using :mod:`matplotlib.mathtext`."""\n ox, oy, width, height, descent, font_image = \\n self.mathtext_parser.parse(s, self.dpi, prop,\n antialiased=gc.get_antialiased())\n\n xd = descent * sin(radians(angle))\n yd = descent * cos(radians(angle))\n x = round(x + ox + xd)\n y = round(y - oy + yd)\n self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n if ismath:\n return self.draw_mathtext(gc, x, y, s, prop, angle)\n font = self._prepare_font(prop)\n # We pass '0' for angle here, since it will be rotated (in raster\n # space) in the following call to draw_text_image).\n font.set_text(s, 0, flags=get_hinting_flag())\n font.draw_glyphs_to_bitmap(\n antialiased=gc.get_antialiased())\n d = font.get_descent() / 64.0\n # The descent needs to be adjusted for the angle.\n xo, yo = font.get_bitmap_offset()\n xo /= 64.0\n yo /= 64.0\n xd = d * sin(radians(angle))\n yd = d * cos(radians(angle))\n x = round(x + xo + xd)\n y = round(y + yo + yd)\n self._renderer.draw_text_image(font, x, y + 1, angle, gc)\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n\n _api.check_in_list(["TeX", True, False], ismath=ismath)\n if ismath == "TeX":\n return super().get_text_width_height_descent(s, prop, ismath)\n\n if ismath:\n ox, oy, width, height, descent, font_image = \\n self.mathtext_parser.parse(s, self.dpi, prop)\n return width, height, descent\n\n font = self._prepare_font(prop)\n font.set_text(s, 0.0, flags=get_hinting_flag())\n w, h = font.get_width_height() # width and height of unrotated string\n d = font.get_descent()\n w /= 64.0 # convert from subpixels\n h /= 64.0\n d /= 64.0\n return w, h, d\n\n def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):\n # docstring inherited\n # todo, handle props, angle, origins\n size = prop.get_size_in_points()\n\n texmanager = self.get_texmanager()\n\n Z = texmanager.get_grey(s, size, self.dpi)\n Z = np.array(Z * 255.0, np.uint8)\n\n w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX")\n xd = d * sin(radians(angle))\n yd = d * cos(radians(angle))\n x = round(x + xd)\n y = round(y + yd)\n self._renderer.draw_text_image(Z, x, y, angle, gc)\n\n def get_canvas_width_height(self):\n # docstring inherited\n return self.width, self.height\n\n def _prepare_font(self, font_prop):\n """\n Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size.\n """\n font = get_font(_fontManager._find_fonts_by_props(font_prop))\n font.clear()\n size = font_prop.get_size_in_points()\n font.set_size(size, self.dpi)\n return font\n\n def points_to_pixels(self, points):\n # docstring inherited\n return points * self.dpi / 72\n\n def buffer_rgba(self):\n return memoryview(self._renderer)\n\n def tostring_argb(self):\n return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()\n\n def clear(self):\n self._renderer.clear()\n\n def option_image_nocomposite(self):\n # docstring inherited\n\n # It is generally faster to composite each image directly to\n # the Figure, and there's no file size benefit to compositing\n # with the Agg backend\n return True\n\n def option_scale_image(self):\n # docstring inherited\n return False\n\n def restore_region(self, region, bbox=None, xy=None):\n """\n Restore the saved region. If bbox (instance of BboxBase, or\n its extents) is given, only the region specified by the bbox\n will be restored. *xy* (a pair of floats) optionally\n specifies the new position (the LLC of the original region,\n not the LLC of the bbox) where the region will be restored.\n\n >>> region = renderer.copy_from_bbox()\n >>> x1, y1, x2, y2 = region.get_extents()\n >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),\n ... xy=(x1-dx, y1))\n\n """\n if bbox is not None or xy is not None:\n if bbox is None:\n x1, y1, x2, y2 = region.get_extents()\n elif isinstance(bbox, BboxBase):\n x1, y1, x2, y2 = bbox.extents\n else:\n x1, y1, x2, y2 = bbox\n\n if xy is None:\n ox, oy = x1, y1\n else:\n ox, oy = xy\n\n # The incoming data is float, but the _renderer type-checking wants\n # to see integers.\n self._renderer.restore_region(region, int(x1), int(y1),\n int(x2), int(y2), int(ox), int(oy))\n\n else:\n self._renderer.restore_region(region)\n\n def start_filter(self):\n """\n Start filtering. It simply creates a new canvas (the old one is saved).\n """\n self._filter_renderers.append(self._renderer)\n self._renderer = _RendererAgg(int(self.width), int(self.height),\n self.dpi)\n self._update_methods()\n\n def stop_filter(self, post_processing):\n """\n Save the current canvas as an image and apply post processing.\n\n The *post_processing* function::\n\n def post_processing(image, dpi):\n # ny, nx, depth = image.shape\n # image (numpy array) has RGBA channels and has a depth of 4.\n ...\n # create a new_image (numpy array of 4 channels, size can be\n # different). The resulting image may have offsets from\n # lower-left corner of the original image\n return new_image, offset_x, offset_y\n\n The saved renderer is restored and the returned image from\n post_processing is plotted (using draw_image) on it.\n """\n orig_img = np.asarray(self.buffer_rgba())\n slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3])\n cropped_img = orig_img[slice_y, slice_x]\n\n self._renderer = self._filter_renderers.pop()\n self._update_methods()\n\n if cropped_img.size:\n img, ox, oy = post_processing(cropped_img / 255, self.dpi)\n gc = self.new_gc()\n if img.dtype.kind == 'f':\n img = np.asarray(img * 255., np.uint8)\n self._renderer.draw_image(\n gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy,\n img[::-1])\n\n\nclass FigureCanvasAgg(FigureCanvasBase):\n # docstring inherited\n\n _lastKey = None # Overwritten per-instance on the first draw.\n\n def copy_from_bbox(self, bbox):\n renderer = self.get_renderer()\n return renderer.copy_from_bbox(bbox)\n\n def restore_region(self, region, bbox=None, xy=None):\n renderer = self.get_renderer()\n return renderer.restore_region(region, bbox, xy)\n\n def draw(self):\n # docstring inherited\n self.renderer = self.get_renderer()\n self.renderer.clear()\n # Acquire a lock on the shared font cache.\n with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar\n else nullcontext()):\n self.figure.draw(self.renderer)\n # A GUI class may be need to update a window using this draw, so\n # don't forget to call the superclass.\n super().draw()\n\n def get_renderer(self):\n w, h = self.figure.bbox.size\n key = w, h, self.figure.dpi\n reuse_renderer = (self._lastKey == key)\n if not reuse_renderer:\n self.renderer = RendererAgg(w, h, self.figure.dpi)\n self._lastKey = key\n return self.renderer\n\n def tostring_argb(self):\n """\n Get the image as ARGB `bytes`.\n\n `draw` must be called at least once before this function will work and\n to update the renderer for any subsequent changes to the Figure.\n """\n return self.renderer.tostring_argb()\n\n def buffer_rgba(self):\n """\n Get the image as a `memoryview` to the renderer's buffer.\n\n `draw` must be called at least once before this function will work and\n to update the renderer for any subsequent changes to the Figure.\n """\n return self.renderer.buffer_rgba()\n\n def print_raw(self, filename_or_obj, *, metadata=None):\n if metadata is not None:\n raise ValueError("metadata not supported for raw/rgba")\n FigureCanvasAgg.draw(self)\n renderer = self.get_renderer()\n with cbook.open_file_cm(filename_or_obj, "wb") as fh:\n fh.write(renderer.buffer_rgba())\n\n print_rgba = print_raw\n\n def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):\n """\n Draw the canvas, then save it using `.image.imsave` (to which\n *pil_kwargs* and *metadata* are forwarded).\n """\n FigureCanvasAgg.draw(self)\n mpl.image.imsave(\n filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",\n dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)\n\n def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):\n """\n Write the figure to a PNG file.\n\n Parameters\n ----------\n filename_or_obj : str or path-like or file-like\n The file to write to.\n\n metadata : dict, optional\n Metadata in the PNG file as key-value pairs of bytes or latin-1\n encodable strings.\n According to the PNG specification, keys must be shorter than 79\n chars.\n\n The `PNG specification`_ defines some common keywords that may be\n used as appropriate:\n\n - Title: Short (one line) title or caption for image.\n - Author: Name of image's creator.\n - Description: Description of image (possibly long).\n - Copyright: Copyright notice.\n - Creation Time: Time of original image creation\n (usually RFC 1123 format).\n - Software: Software used to create the image.\n - Disclaimer: Legal disclaimer.\n - Warning: Warning of nature of content.\n - Source: Device used to create the image.\n - Comment: Miscellaneous comment;\n conversion from other image format.\n\n Other keywords may be invented for other purposes.\n\n If 'Software' is not given, an autogenerated value for Matplotlib\n will be used. This can be removed by setting it to *None*.\n\n For more details see the `PNG specification`_.\n\n .. _PNG specification: \\n https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords\n\n pil_kwargs : dict, optional\n Keyword arguments passed to `PIL.Image.Image.save`.\n\n If the 'pnginfo' key is present, it completely overrides\n *metadata*, including the default 'Software' key.\n """\n self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)\n\n def print_to_buffer(self):\n FigureCanvasAgg.draw(self)\n renderer = self.get_renderer()\n return (bytes(renderer.buffer_rgba()),\n (int(renderer.width), int(renderer.height)))\n\n # Note that these methods should typically be called via savefig() and\n # print_figure(), and the latter ensures that `self.figure.dpi` already\n # matches the dpi kwarg (if any).\n\n def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):\n # savefig() has already applied savefig.facecolor; we now set it to\n # white to make imsave() blend semi-transparent figures against an\n # assumed white background.\n with mpl.rc_context({"savefig.facecolor": "white"}):\n self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)\n\n print_jpeg = print_jpg\n\n def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):\n self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)\n\n print_tiff = print_tif\n\n def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):\n self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)\n\n print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(\n """\n Write the figure to a {} file.\n\n Parameters\n ----------\n filename_or_obj : str or path-like or file-like\n The file to write to.\n pil_kwargs : dict, optional\n Additional keyword arguments that are passed to\n `PIL.Image.Image.save` when saving the figure.\n """.format, ["JPEG", "TIFF", "WebP"])\n\n\n@_Backend.export\nclass _BackendAgg(_Backend):\n backend_version = 'v2.2'\n FigureCanvas = FigureCanvasAgg\n FigureManager = FigureManagerBase\n
.venv\Lib\site-packages\matplotlib\backends\backend_agg.py
backend_agg.py
Python
19,888
0.95
0.142045
0.110092
awesome-app
335
2025-01-04T03:30:52.173938
BSD-3-Clause
false
ce670a6c48df885a91df1e0bb0b17d37
"""\nA Cairo backend for Matplotlib\n==============================\n:Author: Steve Chaplin and others\n\nThis backend depends on cairocffi or pycairo.\n"""\n\nimport functools\nimport gzip\nimport math\n\nimport numpy as np\n\ntry:\n import cairo\n if cairo.version_info < (1, 14, 0): # Introduced set_device_scale.\n raise ImportError(f"Cairo backend requires cairo>=1.14.0, "\n f"but only {cairo.version_info} is available")\nexcept ImportError:\n try:\n import cairocffi as cairo\n except ImportError as err:\n raise ImportError(\n "cairo backend requires that pycairo>=1.14.0 or cairocffi "\n "is installed") from err\n\nfrom .. import _api, cbook, font_manager\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,\n RendererBase)\nfrom matplotlib.font_manager import ttfFontProperty\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Affine2D\n\n\ndef _set_rgba(ctx, color, alpha, forced_alpha):\n if len(color) == 3 or forced_alpha:\n ctx.set_source_rgba(*color[:3], alpha)\n else:\n ctx.set_source_rgba(*color)\n\n\ndef _append_path(ctx, path, transform, clip=None):\n for points, code in path.iter_segments(\n transform, remove_nans=True, clip=clip):\n if code == Path.MOVETO:\n ctx.move_to(*points)\n elif code == Path.CLOSEPOLY:\n ctx.close_path()\n elif code == Path.LINETO:\n ctx.line_to(*points)\n elif code == Path.CURVE3:\n cur = np.asarray(ctx.get_current_point())\n a = points[:2]\n b = points[-2:]\n ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)\n elif code == Path.CURVE4:\n ctx.curve_to(*points)\n\n\ndef _cairo_font_args_from_font_prop(prop):\n """\n Convert a `.FontProperties` or a `.FontEntry` to arguments that can be\n passed to `.Context.select_font_face`.\n """\n def attr(field):\n try:\n return getattr(prop, f"get_{field}")()\n except AttributeError:\n return getattr(prop, field)\n\n name = attr("name")\n slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}")\n weight = attr("weight")\n weight = (cairo.FONT_WEIGHT_NORMAL\n if font_manager.weight_dict.get(weight, weight) < 550\n else cairo.FONT_WEIGHT_BOLD)\n return name, slant, weight\n\n\nclass RendererCairo(RendererBase):\n def __init__(self, dpi):\n self.dpi = dpi\n self.gc = GraphicsContextCairo(renderer=self)\n self.width = None\n self.height = None\n self.text_ctx = cairo.Context(\n cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))\n super().__init__()\n\n def set_context(self, ctx):\n surface = ctx.get_target()\n if hasattr(surface, "get_width") and hasattr(surface, "get_height"):\n size = surface.get_width(), surface.get_height()\n elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface.\n ext = surface.get_extents()\n size = ext.width, ext.height\n else: # vector surfaces.\n ctx.save()\n ctx.reset_clip()\n rect, *rest = ctx.copy_clip_rectangle_list()\n if rest:\n raise TypeError("Cannot infer surface size")\n _, _, *size = rect\n ctx.restore()\n self.gc.ctx = ctx\n self.width, self.height = size\n\n @staticmethod\n def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides):\n if fill_c is not None:\n ctx.save()\n _set_rgba(ctx, fill_c, alpha, alpha_overrides)\n ctx.fill_preserve()\n ctx.restore()\n ctx.stroke()\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n ctx = gc.ctx\n # Clip the path to the actual rendering extents if it isn't filled.\n clip = (ctx.clip_extents()\n if rgbFace is None and gc.get_hatch() is None\n else None)\n transform = (transform\n + Affine2D().scale(1, -1).translate(0, self.height))\n ctx.new_path()\n _append_path(ctx, path, transform, clip)\n if rgbFace is not None:\n ctx.save()\n _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())\n ctx.fill_preserve()\n ctx.restore()\n hatch_path = gc.get_hatch_path()\n if hatch_path:\n dpi = int(self.dpi)\n hatch_surface = ctx.get_target().create_similar(\n cairo.Content.COLOR_ALPHA, dpi, dpi)\n hatch_ctx = cairo.Context(hatch_surface)\n _append_path(hatch_ctx, hatch_path,\n Affine2D().scale(dpi, -dpi).translate(0, dpi),\n None)\n hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth()))\n hatch_ctx.set_source_rgba(*gc.get_hatch_color())\n hatch_ctx.fill_preserve()\n hatch_ctx.stroke()\n hatch_pattern = cairo.SurfacePattern(hatch_surface)\n hatch_pattern.set_extend(cairo.Extend.REPEAT)\n ctx.save()\n ctx.set_source(hatch_pattern)\n ctx.fill_preserve()\n ctx.restore()\n ctx.stroke()\n\n def draw_markers(self, gc, marker_path, marker_trans, path, transform,\n rgbFace=None):\n # docstring inherited\n\n ctx = gc.ctx\n ctx.new_path()\n # Create the path for the marker; it needs to be flipped here already!\n _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1))\n marker_path = ctx.copy_path_flat()\n\n # Figure out whether the path has a fill\n x1, y1, x2, y2 = ctx.fill_extents()\n if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0:\n filled = False\n # No fill, just unset this (so we don't try to fill it later on)\n rgbFace = None\n else:\n filled = True\n\n transform = (transform\n + Affine2D().scale(1, -1).translate(0, self.height))\n\n ctx.new_path()\n for i, (vertices, codes) in enumerate(\n path.iter_segments(transform, simplify=False)):\n if len(vertices):\n x, y = vertices[-2:]\n ctx.save()\n\n # Translate and apply path\n ctx.translate(x, y)\n ctx.append_path(marker_path)\n\n ctx.restore()\n\n # Slower code path if there is a fill; we need to draw\n # the fill and stroke for each marker at the same time.\n # Also flush out the drawing every once in a while to\n # prevent the paths from getting way too long.\n if filled or i % 1000 == 0:\n self._fill_and_stroke(\n ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())\n\n # Fast path, if there is no fill, draw everything in one step\n if not filled:\n self._fill_and_stroke(\n ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())\n\n def draw_image(self, gc, x, y, im):\n im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])\n surface = cairo.ImageSurface.create_for_data(\n im.ravel().data, cairo.FORMAT_ARGB32,\n im.shape[1], im.shape[0], im.shape[1] * 4)\n ctx = gc.ctx\n y = self.height - y - im.shape[0]\n\n ctx.save()\n ctx.set_source_surface(surface, float(x), float(y))\n ctx.paint()\n ctx.restore()\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n\n # Note: (x, y) are device/display coords, not user-coords, unlike other\n # draw_* methods\n if ismath:\n self._draw_mathtext(gc, x, y, s, prop, angle)\n\n else:\n ctx = gc.ctx\n ctx.new_path()\n ctx.move_to(x, y)\n\n ctx.save()\n ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))\n ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))\n opts = cairo.FontOptions()\n opts.set_antialias(gc.get_antialiased())\n ctx.set_font_options(opts)\n if angle:\n ctx.rotate(np.deg2rad(-angle))\n ctx.show_text(s)\n ctx.restore()\n\n def _draw_mathtext(self, gc, x, y, s, prop, angle):\n ctx = gc.ctx\n width, height, descent, glyphs, rects = \\n self._text2path.mathtext_parser.parse(s, self.dpi, prop)\n\n ctx.save()\n ctx.translate(x, y)\n if angle:\n ctx.rotate(np.deg2rad(-angle))\n\n for font, fontsize, idx, ox, oy in glyphs:\n ctx.new_path()\n ctx.move_to(ox, -oy)\n ctx.select_font_face(\n *_cairo_font_args_from_font_prop(ttfFontProperty(font)))\n ctx.set_font_size(self.points_to_pixels(fontsize))\n ctx.show_text(chr(idx))\n\n for ox, oy, w, h in rects:\n ctx.new_path()\n ctx.rectangle(ox, -oy, w, -h)\n ctx.set_source_rgb(0, 0, 0)\n ctx.fill_preserve()\n\n ctx.restore()\n\n def get_canvas_width_height(self):\n # docstring inherited\n return self.width, self.height\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n\n if ismath == 'TeX':\n return super().get_text_width_height_descent(s, prop, ismath)\n\n if ismath:\n width, height, descent, *_ = \\n self._text2path.mathtext_parser.parse(s, self.dpi, prop)\n return width, height, descent\n\n ctx = self.text_ctx\n # problem - scale remembers last setting and font can become\n # enormous causing program to crash\n # save/restore prevents the problem\n ctx.save()\n ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))\n ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))\n\n y_bearing, w, h = ctx.text_extents(s)[1:4]\n ctx.restore()\n\n return w, h, h + y_bearing\n\n def new_gc(self):\n # docstring inherited\n self.gc.ctx.save()\n # FIXME: The following doesn't properly implement a stack-like behavior\n # and relies instead on the (non-guaranteed) fact that artists never\n # rely on nesting gc states, so directly resetting the attributes (IOW\n # a single-level stack) is enough.\n self.gc._alpha = 1\n self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA\n self.gc._hatch = None\n return self.gc\n\n def points_to_pixels(self, points):\n # docstring inherited\n return points / 72 * self.dpi\n\n\nclass GraphicsContextCairo(GraphicsContextBase):\n _joind = {\n 'bevel': cairo.LINE_JOIN_BEVEL,\n 'miter': cairo.LINE_JOIN_MITER,\n 'round': cairo.LINE_JOIN_ROUND,\n }\n\n _capd = {\n 'butt': cairo.LINE_CAP_BUTT,\n 'projecting': cairo.LINE_CAP_SQUARE,\n 'round': cairo.LINE_CAP_ROUND,\n }\n\n def __init__(self, renderer):\n super().__init__()\n self.renderer = renderer\n\n def restore(self):\n self.ctx.restore()\n\n def set_alpha(self, alpha):\n super().set_alpha(alpha)\n _set_rgba(\n self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha())\n\n def set_antialiased(self, b):\n self.ctx.set_antialias(\n cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE)\n\n def get_antialiased(self):\n return self.ctx.get_antialias()\n\n def set_capstyle(self, cs):\n self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))\n self._capstyle = cs\n\n def set_clip_rectangle(self, rectangle):\n if not rectangle:\n return\n x, y, w, h = np.round(rectangle.bounds)\n ctx = self.ctx\n ctx.new_path()\n ctx.rectangle(x, self.renderer.height - h - y, w, h)\n ctx.clip()\n\n def set_clip_path(self, path):\n if not path:\n return\n tpath, affine = path.get_transformed_path_and_affine()\n ctx = self.ctx\n ctx.new_path()\n affine = (affine\n + Affine2D().scale(1, -1).translate(0, self.renderer.height))\n _append_path(ctx, tpath, affine)\n ctx.clip()\n\n def set_dashes(self, offset, dashes):\n self._dashes = offset, dashes\n if dashes is None:\n self.ctx.set_dash([], 0) # switch dashes off\n else:\n self.ctx.set_dash(\n list(self.renderer.points_to_pixels(np.asarray(dashes))),\n offset)\n\n def set_foreground(self, fg, isRGBA=None):\n super().set_foreground(fg, isRGBA)\n if len(self._rgb) == 3:\n self.ctx.set_source_rgb(*self._rgb)\n else:\n self.ctx.set_source_rgba(*self._rgb)\n\n def get_rgb(self):\n return self.ctx.get_source().get_rgba()[:3]\n\n def set_joinstyle(self, js):\n self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))\n self._joinstyle = js\n\n def set_linewidth(self, w):\n self._linewidth = float(w)\n self.ctx.set_line_width(self.renderer.points_to_pixels(w))\n\n\nclass _CairoRegion:\n def __init__(self, slices, data):\n self._slices = slices\n self._data = data\n\n\nclass FigureCanvasCairo(FigureCanvasBase):\n @property\n def _renderer(self):\n # In theory, _renderer should be set in __init__, but GUI canvas\n # subclasses (FigureCanvasFooCairo) don't always interact well with\n # multiple inheritance (FigureCanvasFoo inits but doesn't super-init\n # FigureCanvasCairo), so initialize it in the getter instead.\n if not hasattr(self, "_cached_renderer"):\n self._cached_renderer = RendererCairo(self.figure.dpi)\n return self._cached_renderer\n\n def get_renderer(self):\n return self._renderer\n\n def copy_from_bbox(self, bbox):\n surface = self._renderer.gc.ctx.get_target()\n if not isinstance(surface, cairo.ImageSurface):\n raise RuntimeError(\n "copy_from_bbox only works when rendering to an ImageSurface")\n sw = surface.get_width()\n sh = surface.get_height()\n x0 = math.ceil(bbox.x0)\n x1 = math.floor(bbox.x1)\n y0 = math.ceil(sh - bbox.y1)\n y1 = math.floor(sh - bbox.y0)\n if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1\n and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1):\n raise ValueError("Invalid bbox")\n sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0))\n data = (np.frombuffer(surface.get_data(), np.uint32)\n .reshape((sh, sw))[sls].copy())\n return _CairoRegion(sls, data)\n\n def restore_region(self, region):\n surface = self._renderer.gc.ctx.get_target()\n if not isinstance(surface, cairo.ImageSurface):\n raise RuntimeError(\n "restore_region only works when rendering to an ImageSurface")\n surface.flush()\n sw = surface.get_width()\n sh = surface.get_height()\n sly, slx = region._slices\n (np.frombuffer(surface.get_data(), np.uint32)\n .reshape((sh, sw))[sly, slx]) = region._data\n surface.mark_dirty_rectangle(\n slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start)\n\n def print_png(self, fobj):\n self._get_printed_image_surface().write_to_png(fobj)\n\n def print_rgba(self, fobj):\n width, height = self.get_width_height()\n buf = self._get_printed_image_surface().get_data()\n fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888(\n np.asarray(buf).reshape((width, height, 4))))\n\n print_raw = print_rgba\n\n def _get_printed_image_surface(self):\n self._renderer.dpi = self.figure.dpi\n width, height = self.get_width_height()\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n self._renderer.set_context(cairo.Context(surface))\n self.figure.draw(self._renderer)\n return surface\n\n def _save(self, fmt, fobj, *, orientation='portrait'):\n # save PDF/PS/SVG\n\n dpi = 72\n self.figure.dpi = dpi\n w_in, h_in = self.figure.get_size_inches()\n width_in_points, height_in_points = w_in * dpi, h_in * dpi\n\n if orientation == 'landscape':\n width_in_points, height_in_points = (\n height_in_points, width_in_points)\n\n if fmt == 'ps':\n if not hasattr(cairo, 'PSSurface'):\n raise RuntimeError('cairo has not been compiled with PS '\n 'support enabled')\n surface = cairo.PSSurface(fobj, width_in_points, height_in_points)\n elif fmt == 'pdf':\n if not hasattr(cairo, 'PDFSurface'):\n raise RuntimeError('cairo has not been compiled with PDF '\n 'support enabled')\n surface = cairo.PDFSurface(fobj, width_in_points, height_in_points)\n elif fmt in ('svg', 'svgz'):\n if not hasattr(cairo, 'SVGSurface'):\n raise RuntimeError('cairo has not been compiled with SVG '\n 'support enabled')\n if fmt == 'svgz':\n if isinstance(fobj, str):\n fobj = gzip.GzipFile(fobj, 'wb')\n else:\n fobj = gzip.GzipFile(None, 'wb', fileobj=fobj)\n surface = cairo.SVGSurface(fobj, width_in_points, height_in_points)\n else:\n raise ValueError(f"Unknown format: {fmt!r}")\n\n self._renderer.dpi = self.figure.dpi\n self._renderer.set_context(cairo.Context(surface))\n ctx = self._renderer.gc.ctx\n\n if orientation == 'landscape':\n ctx.rotate(np.pi / 2)\n ctx.translate(0, -height_in_points)\n # Perhaps add an '%%Orientation: Landscape' comment?\n\n self.figure.draw(self._renderer)\n\n ctx.show_page()\n surface.finish()\n if fmt == 'svgz':\n fobj.close()\n\n print_pdf = functools.partialmethod(_save, "pdf")\n print_ps = functools.partialmethod(_save, "ps")\n print_svg = functools.partialmethod(_save, "svg")\n print_svgz = functools.partialmethod(_save, "svgz")\n\n\n@_Backend.export\nclass _BackendCairo(_Backend):\n backend_version = cairo.version\n FigureCanvas = FigureCanvasCairo\n FigureManager = FigureManagerBase\n
.venv\Lib\site-packages\matplotlib\backends\backend_cairo.py
backend_cairo.py
Python
18,618
0.95
0.183365
0.074157
react-lib
676
2025-01-26T22:17:39.821651
BSD-3-Clause
false
1eea43f9d88b6b7e611f62a3843848fc
import functools\nimport logging\nimport os\nfrom pathlib import Path\n\nimport matplotlib as mpl\nfrom matplotlib import _api, backend_tools, cbook\nfrom matplotlib.backend_bases import (\n ToolContainerBase, MouseButton,\n CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)\n\ntry:\n import gi\nexcept ImportError as err:\n raise ImportError("The GTK3 backends require PyGObject") from err\n\ntry:\n # :raises ValueError: If module/version is already loaded, already\n # required, or unavailable.\n gi.require_version("Gtk", "3.0")\nexcept ValueError as e:\n # in this case we want to re-raise as ImportError so the\n # auto-backend selection logic correctly skips.\n raise ImportError(e) from e\n\nfrom gi.repository import Gio, GLib, GObject, Gtk, Gdk\nfrom . import _backend_gtk\nfrom ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611\n _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,\n TimerGTK as TimerGTK3,\n)\n\n\n_log = logging.getLogger(__name__)\n\n\n@functools.cache\ndef _mpl_to_gtk_cursor(mpl_cursor):\n return Gdk.Cursor.new_from_name(\n Gdk.Display.get_default(),\n _backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor))\n\n\nclass FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea):\n required_interactive_framework = "gtk3"\n manager_class = _api.classproperty(lambda cls: FigureManagerGTK3)\n # Setting this as a static constant prevents\n # this resulting expression from leaking\n event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK\n | Gdk.EventMask.BUTTON_RELEASE_MASK\n | Gdk.EventMask.EXPOSURE_MASK\n | Gdk.EventMask.KEY_PRESS_MASK\n | Gdk.EventMask.KEY_RELEASE_MASK\n | Gdk.EventMask.ENTER_NOTIFY_MASK\n | Gdk.EventMask.LEAVE_NOTIFY_MASK\n | Gdk.EventMask.POINTER_MOTION_MASK\n | Gdk.EventMask.SCROLL_MASK)\n\n def __init__(self, figure=None):\n super().__init__(figure=figure)\n\n self._idle_draw_id = 0\n self._rubberband_rect = None\n\n self.connect('scroll_event', self.scroll_event)\n self.connect('button_press_event', self.button_press_event)\n self.connect('button_release_event', self.button_release_event)\n self.connect('configure_event', self.configure_event)\n self.connect('screen-changed', self._update_device_pixel_ratio)\n self.connect('notify::scale-factor', self._update_device_pixel_ratio)\n self.connect('draw', self.on_draw_event)\n self.connect('draw', self._post_draw)\n self.connect('key_press_event', self.key_press_event)\n self.connect('key_release_event', self.key_release_event)\n self.connect('motion_notify_event', self.motion_notify_event)\n self.connect('enter_notify_event', self.enter_notify_event)\n self.connect('leave_notify_event', self.leave_notify_event)\n self.connect('size_allocate', self.size_allocate)\n\n self.set_events(self.__class__.event_mask)\n\n self.set_can_focus(True)\n\n css = Gtk.CssProvider()\n css.load_from_data(b".matplotlib-canvas { background-color: white; }")\n style_ctx = self.get_style_context()\n style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n style_ctx.add_class("matplotlib-canvas")\n\n def destroy(self):\n CloseEvent("close_event", self)._process()\n\n def set_cursor(self, cursor):\n # docstring inherited\n window = self.get_property("window")\n if window is not None:\n window.set_cursor(_mpl_to_gtk_cursor(cursor))\n context = GLib.MainContext.default()\n context.iteration(True)\n\n def _mpl_coords(self, event=None):\n """\n Convert the position of a GTK event, or of the current cursor position\n if *event* is None, to Matplotlib coordinates.\n\n GTK use logical pixels, but the figure is scaled to physical pixels for\n rendering. Transform to physical pixels so that all of the down-stream\n transforms work as expected.\n\n Also, the origin is different and needs to be corrected.\n """\n if event is None:\n window = self.get_window()\n t, x, y, state = window.get_device_position(\n window.get_display().get_device_manager().get_client_pointer())\n else:\n x, y = event.x, event.y\n x = x * self.device_pixel_ratio\n # flip y so y=0 is bottom of canvas\n y = self.figure.bbox.height - y * self.device_pixel_ratio\n return x, y\n\n def scroll_event(self, widget, event):\n step = 1 if event.direction == Gdk.ScrollDirection.UP else -1\n MouseEvent("scroll_event", self,\n *self._mpl_coords(event), step=step,\n modifiers=self._mpl_modifiers(event.state),\n guiEvent=event)._process()\n return False # finish event propagation?\n\n def button_press_event(self, widget, event):\n MouseEvent("button_press_event", self,\n *self._mpl_coords(event), event.button,\n modifiers=self._mpl_modifiers(event.state),\n guiEvent=event)._process()\n return False # finish event propagation?\n\n def button_release_event(self, widget, event):\n MouseEvent("button_release_event", self,\n *self._mpl_coords(event), event.button,\n modifiers=self._mpl_modifiers(event.state),\n guiEvent=event)._process()\n return False # finish event propagation?\n\n def key_press_event(self, widget, event):\n KeyEvent("key_press_event", self,\n self._get_key(event), *self._mpl_coords(),\n guiEvent=event)._process()\n return True # stop event propagation\n\n def key_release_event(self, widget, event):\n KeyEvent("key_release_event", self,\n self._get_key(event), *self._mpl_coords(),\n guiEvent=event)._process()\n return True # stop event propagation\n\n def motion_notify_event(self, widget, event):\n MouseEvent("motion_notify_event", self, *self._mpl_coords(event),\n buttons=self._mpl_buttons(event.state),\n modifiers=self._mpl_modifiers(event.state),\n guiEvent=event)._process()\n return False # finish event propagation?\n\n def enter_notify_event(self, widget, event):\n gtk_mods = Gdk.Keymap.get_for_display(\n self.get_display()).get_modifier_state()\n LocationEvent("figure_enter_event", self, *self._mpl_coords(event),\n modifiers=self._mpl_modifiers(gtk_mods),\n guiEvent=event)._process()\n\n def leave_notify_event(self, widget, event):\n gtk_mods = Gdk.Keymap.get_for_display(\n self.get_display()).get_modifier_state()\n LocationEvent("figure_leave_event", self, *self._mpl_coords(event),\n modifiers=self._mpl_modifiers(gtk_mods),\n guiEvent=event)._process()\n\n def size_allocate(self, widget, allocation):\n dpival = self.figure.dpi\n winch = allocation.width * self.device_pixel_ratio / dpival\n hinch = allocation.height * self.device_pixel_ratio / dpival\n self.figure.set_size_inches(winch, hinch, forward=False)\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n\n @staticmethod\n def _mpl_buttons(event_state):\n modifiers = [\n (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),\n (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),\n (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),\n (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),\n (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),\n ]\n # State *before* press/release.\n return [name for name, mask in modifiers if event_state & mask]\n\n @staticmethod\n def _mpl_modifiers(event_state, *, exclude=None):\n modifiers = [\n ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),\n ("alt", Gdk.ModifierType.MOD1_MASK, "alt"),\n ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),\n ("super", Gdk.ModifierType.MOD4_MASK, "super"),\n ]\n return [name for name, mask, key in modifiers\n if exclude != key and event_state & mask]\n\n def _get_key(self, event):\n unikey = chr(Gdk.keyval_to_unicode(event.keyval))\n key = cbook._unikey_or_keysym_to_mplkey(\n unikey, Gdk.keyval_name(event.keyval))\n mods = self._mpl_modifiers(event.state, exclude=key)\n if "shift" in mods and unikey.isprintable():\n mods.remove("shift")\n return "+".join([*mods, key])\n\n def _update_device_pixel_ratio(self, *args, **kwargs):\n # We need to be careful in cases with mixed resolution displays if\n # device_pixel_ratio changes.\n if self._set_device_pixel_ratio(self.get_scale_factor()):\n # The easiest way to resize the canvas is to emit a resize event\n # since we implement all the logic for resizing the canvas for that\n # event.\n self.queue_resize()\n self.queue_draw()\n\n def configure_event(self, widget, event):\n if widget.get_property("window") is None:\n return\n w = event.width * self.device_pixel_ratio\n h = event.height * self.device_pixel_ratio\n if w < 3 or h < 3:\n return # empty fig\n # resize the figure (in inches)\n dpi = self.figure.dpi\n self.figure.set_size_inches(w / dpi, h / dpi, forward=False)\n return False # finish event propagation?\n\n def _draw_rubberband(self, rect):\n self._rubberband_rect = rect\n # TODO: Only update the rubberband area.\n self.queue_draw()\n\n def _post_draw(self, widget, ctx):\n if self._rubberband_rect is None:\n return\n\n x0, y0, w, h = (dim / self.device_pixel_ratio\n for dim in self._rubberband_rect)\n x1 = x0 + w\n y1 = y0 + h\n\n # Draw the lines from x0, y0 towards x1, y1 so that the\n # dashes don't "jump" when moving the zoom box.\n ctx.move_to(x0, y0)\n ctx.line_to(x0, y1)\n ctx.move_to(x0, y0)\n ctx.line_to(x1, y0)\n ctx.move_to(x0, y1)\n ctx.line_to(x1, y1)\n ctx.move_to(x1, y0)\n ctx.line_to(x1, y1)\n\n ctx.set_antialias(1)\n ctx.set_line_width(1)\n ctx.set_dash((3, 3), 0)\n ctx.set_source_rgb(0, 0, 0)\n ctx.stroke_preserve()\n\n ctx.set_dash((3, 3), 3)\n ctx.set_source_rgb(1, 1, 1)\n ctx.stroke()\n\n def on_draw_event(self, widget, ctx):\n # to be overwritten by GTK3Agg or GTK3Cairo\n pass\n\n def draw(self):\n # docstring inherited\n if self.is_drawable():\n self.queue_draw()\n\n def draw_idle(self):\n # docstring inherited\n if self._idle_draw_id != 0:\n return\n def idle_draw(*args):\n try:\n self.draw()\n finally:\n self._idle_draw_id = 0\n return False\n self._idle_draw_id = GLib.idle_add(idle_draw)\n\n def flush_events(self):\n # docstring inherited\n context = GLib.MainContext.default()\n while context.pending():\n context.iteration(True)\n\n\nclass NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar):\n def __init__(self, canvas):\n GObject.GObject.__init__(self)\n\n self.set_style(Gtk.ToolbarStyle.ICONS)\n\n self._gtk_ids = {}\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n self.insert(Gtk.SeparatorToolItem(), -1)\n continue\n image = Gtk.Image.new_from_gicon(\n Gio.Icon.new_for_string(\n str(cbook._get_data_path('images',\n f'{image_file}-symbolic.svg'))),\n Gtk.IconSize.LARGE_TOOLBAR)\n self._gtk_ids[text] = button = (\n Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else\n Gtk.ToolButton())\n button.set_label(text)\n button.set_icon_widget(image)\n # Save the handler id, so that we can block it as needed.\n button._signal_handler = button.connect(\n 'clicked', getattr(self, callback))\n button.set_tooltip_text(tooltip_text)\n self.insert(button, -1)\n\n # This filler item ensures the toolbar is always at least two text\n # lines high. Otherwise the canvas gets redrawn as the mouse hovers\n # over images because those use two-line messages which resize the\n # toolbar.\n toolitem = Gtk.ToolItem()\n self.insert(toolitem, -1)\n label = Gtk.Label()\n label.set_markup(\n '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')\n toolitem.set_expand(True) # Push real message to the right.\n toolitem.add(label)\n\n toolitem = Gtk.ToolItem()\n self.insert(toolitem, -1)\n self.message = Gtk.Label()\n self.message.set_justify(Gtk.Justification.RIGHT)\n toolitem.add(self.message)\n\n self.show_all()\n\n _NavigationToolbar2GTK.__init__(self, canvas)\n\n def save_figure(self, *args):\n dialog = Gtk.FileChooserDialog(\n title="Save the figure",\n transient_for=self.canvas.get_toplevel(),\n action=Gtk.FileChooserAction.SAVE,\n buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,\n Gtk.STOCK_SAVE, Gtk.ResponseType.OK),\n )\n for name, fmts \\n in self.canvas.get_supported_filetypes_grouped().items():\n ff = Gtk.FileFilter()\n ff.set_name(name)\n for fmt in fmts:\n ff.add_pattern(f'*.{fmt}')\n dialog.add_filter(ff)\n if self.canvas.get_default_filetype() in fmts:\n dialog.set_filter(ff)\n\n @functools.partial(dialog.connect, "notify::filter")\n def on_notify_filter(*args):\n name = dialog.get_filter().get_name()\n fmt = self.canvas.get_supported_filetypes_grouped()[name][0]\n dialog.set_current_name(\n str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}')))\n\n dialog.set_current_folder(mpl.rcParams["savefig.directory"])\n dialog.set_current_name(self.canvas.get_default_filename())\n dialog.set_do_overwrite_confirmation(True)\n\n response = dialog.run()\n fname = dialog.get_filename()\n ff = dialog.get_filter() # Doesn't autoadjust to filename :/\n fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0]\n dialog.destroy()\n if response != Gtk.ResponseType.OK:\n return None\n # Save dir for next time, unless empty str (which means use cwd).\n if mpl.rcParams['savefig.directory']:\n mpl.rcParams['savefig.directory'] = os.path.dirname(fname)\n try:\n self.canvas.figure.savefig(fname, format=fmt)\n return fname\n except Exception as e:\n dialog = Gtk.MessageDialog(\n transient_for=self.canvas.get_toplevel(), text=str(e),\n message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)\n dialog.run()\n dialog.destroy()\n\n\nclass ToolbarGTK3(ToolContainerBase, Gtk.Box):\n _icon_extension = '-symbolic.svg'\n\n def __init__(self, toolmanager):\n ToolContainerBase.__init__(self, toolmanager)\n Gtk.Box.__init__(self)\n self.set_property('orientation', Gtk.Orientation.HORIZONTAL)\n self._message = Gtk.Label()\n self._message.set_justify(Gtk.Justification.RIGHT)\n self.pack_end(self._message, False, False, 0)\n self.show_all()\n self._groups = {}\n self._toolitems = {}\n\n def add_toolitem(self, name, group, position, image_file, description,\n toggle):\n if toggle:\n button = Gtk.ToggleToolButton()\n else:\n button = Gtk.ToolButton()\n button.set_label(name)\n\n if image_file is not None:\n image = Gtk.Image.new_from_gicon(\n Gio.Icon.new_for_string(image_file),\n Gtk.IconSize.LARGE_TOOLBAR)\n button.set_icon_widget(image)\n\n if position is None:\n position = -1\n\n self._add_button(button, group, position)\n signal = button.connect('clicked', self._call_tool, name)\n button.set_tooltip_text(description)\n button.show_all()\n self._toolitems.setdefault(name, [])\n self._toolitems[name].append((button, signal))\n\n def _add_button(self, button, group, position):\n if group not in self._groups:\n if self._groups:\n self._add_separator()\n toolbar = Gtk.Toolbar()\n toolbar.set_style(Gtk.ToolbarStyle.ICONS)\n self.pack_start(toolbar, False, False, 0)\n toolbar.show_all()\n self._groups[group] = toolbar\n self._groups[group].insert(button, position)\n\n def _call_tool(self, btn, name):\n self.trigger_tool(name)\n\n def toggle_toolitem(self, name, toggled):\n if name not in self._toolitems:\n return\n for toolitem, signal in self._toolitems[name]:\n toolitem.handler_block(signal)\n toolitem.set_active(toggled)\n toolitem.handler_unblock(signal)\n\n def remove_toolitem(self, name):\n for toolitem, _signal in self._toolitems.pop(name, []):\n for group in self._groups:\n if toolitem in self._groups[group]:\n self._groups[group].remove(toolitem)\n\n def _add_separator(self):\n sep = Gtk.Separator()\n sep.set_property("orientation", Gtk.Orientation.VERTICAL)\n self.pack_start(sep, False, True, 0)\n sep.show_all()\n\n def set_message(self, s):\n self._message.set_label(s)\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK3)\nclass SaveFigureGTK3(backend_tools.SaveFigureBase):\n def trigger(self, *args, **kwargs):\n NavigationToolbar2GTK3.save_figure(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK3)\nclass HelpGTK3(backend_tools.ToolHelpBase):\n def _normalize_shortcut(self, key):\n """\n Convert Matplotlib key presses to GTK+ accelerator identifiers.\n\n Related to `FigureCanvasGTK3._get_key`.\n """\n special = {\n 'backspace': 'BackSpace',\n 'pagedown': 'Page_Down',\n 'pageup': 'Page_Up',\n 'scroll_lock': 'Scroll_Lock',\n }\n\n parts = key.split('+')\n mods = ['<' + mod + '>' for mod in parts[:-1]]\n key = parts[-1]\n\n if key in special:\n key = special[key]\n elif len(key) > 1:\n key = key.capitalize()\n elif key.isupper():\n mods += ['<shift>']\n\n return ''.join(mods) + key\n\n def _is_valid_shortcut(self, key):\n """\n Check for a valid shortcut to be displayed.\n\n - GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`).\n - The shortcut window only shows keyboard shortcuts, not mouse buttons.\n """\n return 'cmd+' not in key and not key.startswith('MouseButton.')\n\n def _show_shortcuts_window(self):\n section = Gtk.ShortcutsSection()\n\n for name, tool in sorted(self.toolmanager.tools.items()):\n if not tool.description:\n continue\n\n # Putting everything in a separate group allows GTK to\n # automatically split them into separate columns/pages, which is\n # useful because we have lots of shortcuts, some with many keys\n # that are very wide.\n group = Gtk.ShortcutsGroup()\n section.add(group)\n # A hack to remove the title since we have no group naming.\n group.forall(lambda widget, data: widget.set_visible(False), None)\n\n shortcut = Gtk.ShortcutsShortcut(\n accelerator=' '.join(\n self._normalize_shortcut(key)\n for key in self.toolmanager.get_tool_keymap(name)\n if self._is_valid_shortcut(key)),\n title=tool.name,\n subtitle=tool.description)\n group.add(shortcut)\n\n window = Gtk.ShortcutsWindow(\n title='Help',\n modal=True,\n transient_for=self._figure.canvas.get_toplevel())\n section.show() # Must be done explicitly before add!\n window.add(section)\n\n window.show_all()\n\n def _show_shortcuts_dialog(self):\n dialog = Gtk.MessageDialog(\n self._figure.canvas.get_toplevel(),\n 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(),\n title="Help")\n dialog.run()\n dialog.destroy()\n\n def trigger(self, *args):\n if Gtk.check_version(3, 20, 0) is None:\n self._show_shortcuts_window()\n else:\n self._show_shortcuts_dialog()\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK3)\nclass ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase):\n def trigger(self, *args, **kwargs):\n clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n window = self.canvas.get_window()\n x, y, width, height = window.get_geometry()\n pb = Gdk.pixbuf_get_from_window(window, x, y, width, height)\n clipboard.set_image(pb)\n\n\nToolbar = ToolbarGTK3\nbackend_tools._register_tool_class(\n FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK)\nbackend_tools._register_tool_class(\n FigureCanvasGTK3, _backend_gtk.RubberbandGTK)\n\n\nclass FigureManagerGTK3(_FigureManagerGTK):\n _toolbar2_class = NavigationToolbar2GTK3\n _toolmanager_toolbar_class = ToolbarGTK3\n\n\n@_BackendGTK.export\nclass _BackendGTK3(_BackendGTK):\n FigureCanvas = FigureCanvasGTK3\n FigureManager = FigureManagerGTK3\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk3.py
backend_gtk3.py
Python
22,277
0.95
0.174497
0.072
python-kit
864
2023-10-11T21:57:44.803823
Apache-2.0
false
eeb38b517dab8f6f0cfa43e9c338cea4
import numpy as np\n\nfrom .. import cbook, transforms\nfrom . import backend_agg, backend_gtk3\nfrom .backend_gtk3 import GLib, Gtk, _BackendGTK3\n\nimport cairo # Presence of cairo is already checked by _backend_gtk.\n\n\nclass FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg,\n backend_gtk3.FigureCanvasGTK3):\n def __init__(self, figure):\n super().__init__(figure=figure)\n self._bbox_queue = []\n\n def on_draw_event(self, widget, ctx):\n if self._idle_draw_id:\n GLib.source_remove(self._idle_draw_id)\n self._idle_draw_id = 0\n self.draw()\n\n scale = self.device_pixel_ratio\n allocation = self.get_allocation()\n w = allocation.width * scale\n h = allocation.height * scale\n\n if not len(self._bbox_queue):\n Gtk.render_background(\n self.get_style_context(), ctx,\n allocation.x, allocation.y,\n allocation.width, allocation.height)\n bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]\n else:\n bbox_queue = self._bbox_queue\n\n for bbox in bbox_queue:\n x = int(bbox.x0)\n y = h - int(bbox.y1)\n width = int(bbox.x1) - int(bbox.x0)\n height = int(bbox.y1) - int(bbox.y0)\n\n buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(\n np.asarray(self.copy_from_bbox(bbox)))\n image = cairo.ImageSurface.create_for_data(\n buf.ravel().data, cairo.FORMAT_ARGB32, width, height)\n image.set_device_scale(scale, scale)\n ctx.set_source_surface(image, x / scale, y / scale)\n ctx.paint()\n\n if len(self._bbox_queue):\n self._bbox_queue = []\n\n return False\n\n def blit(self, bbox=None):\n # If bbox is None, blit the entire canvas to gtk. Otherwise\n # blit only the area defined by the bbox.\n if bbox is None:\n bbox = self.figure.bbox\n\n scale = self.device_pixel_ratio\n allocation = self.get_allocation()\n x = int(bbox.x0 / scale)\n y = allocation.height - int(bbox.y1 / scale)\n width = (int(bbox.x1) - int(bbox.x0)) // scale\n height = (int(bbox.y1) - int(bbox.y0)) // scale\n\n self._bbox_queue.append(bbox)\n self.queue_draw_area(x, y, width, height)\n\n\n@_BackendGTK3.export\nclass _BackendGTK3Agg(_BackendGTK3):\n FigureCanvas = FigureCanvasGTK3Agg\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk3agg.py
backend_gtk3agg.py
Python
2,463
0.95
0.135135
0.034483
python-kit
819
2023-08-26T09:32:15.608040
Apache-2.0
false
da4238e599cbec2f680197c016495167
from contextlib import nullcontext\n\nfrom .backend_cairo import FigureCanvasCairo\nfrom .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3\n\n\nclass FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3):\n def on_draw_event(self, widget, ctx):\n if self._idle_draw_id:\n GLib.source_remove(self._idle_draw_id)\n self._idle_draw_id = 0\n self.draw()\n\n with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar\n else nullcontext()):\n allocation = self.get_allocation()\n # Render the background before scaling, as the allocated size here is in\n # logical pixels.\n Gtk.render_background(\n self.get_style_context(), ctx,\n 0, 0, allocation.width, allocation.height)\n scale = self.device_pixel_ratio\n # Scale physical drawing to logical size.\n ctx.scale(1 / scale, 1 / scale)\n self._renderer.set_context(ctx)\n # Set renderer to physical size so it renders in full resolution.\n self._renderer.width = allocation.width * scale\n self._renderer.height = allocation.height * scale\n self._renderer.dpi = self.figure.dpi\n self.figure.draw(self._renderer)\n\n\n@_BackendGTK3.export\nclass _BackendGTK3Cairo(_BackendGTK3):\n FigureCanvas = FigureCanvasGTK3Cairo\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk3cairo.py
backend_gtk3cairo.py
Python
1,392
0.95
0.142857
0.137931
react-lib
181
2023-08-20T18:33:03.958545
Apache-2.0
false
05537f3dbcea7088fd65eaad1f7615f8
import functools\nimport io\nimport os\n\nimport matplotlib as mpl\nfrom matplotlib import _api, backend_tools, cbook\nfrom matplotlib.backend_bases import (\n ToolContainerBase, MouseButton,\n KeyEvent, LocationEvent, MouseEvent, ResizeEvent, CloseEvent)\n\ntry:\n import gi\nexcept ImportError as err:\n raise ImportError("The GTK4 backends require PyGObject") from err\n\ntry:\n # :raises ValueError: If module/version is already loaded, already\n # required, or unavailable.\n gi.require_version("Gtk", "4.0")\nexcept ValueError as e:\n # in this case we want to re-raise as ImportError so the\n # auto-backend selection logic correctly skips.\n raise ImportError(e) from e\n\nfrom gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf\nfrom . import _backend_gtk\nfrom ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611\n _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,\n TimerGTK as TimerGTK4,\n)\n\n_GOBJECT_GE_3_47 = gi.version_info >= (3, 47, 0)\n\n\nclass FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea):\n required_interactive_framework = "gtk4"\n supports_blit = False\n manager_class = _api.classproperty(lambda cls: FigureManagerGTK4)\n\n def __init__(self, figure=None):\n super().__init__(figure=figure)\n\n self.set_hexpand(True)\n self.set_vexpand(True)\n\n self._idle_draw_id = 0\n self._rubberband_rect = None\n\n self.set_draw_func(self._draw_func)\n self.connect('resize', self.resize_event)\n self.connect('notify::scale-factor', self._update_device_pixel_ratio)\n\n click = Gtk.GestureClick()\n click.set_button(0) # All buttons.\n click.connect('pressed', self.button_press_event)\n click.connect('released', self.button_release_event)\n self.add_controller(click)\n\n key = Gtk.EventControllerKey()\n key.connect('key-pressed', self.key_press_event)\n key.connect('key-released', self.key_release_event)\n self.add_controller(key)\n\n motion = Gtk.EventControllerMotion()\n motion.connect('motion', self.motion_notify_event)\n motion.connect('enter', self.enter_notify_event)\n motion.connect('leave', self.leave_notify_event)\n self.add_controller(motion)\n\n scroll = Gtk.EventControllerScroll.new(\n Gtk.EventControllerScrollFlags.VERTICAL)\n scroll.connect('scroll', self.scroll_event)\n self.add_controller(scroll)\n\n self.set_focusable(True)\n\n css = Gtk.CssProvider()\n style = '.matplotlib-canvas { background-color: white; }'\n if Gtk.check_version(4, 9, 3) is None:\n css.load_from_data(style, -1)\n else:\n css.load_from_data(style.encode('utf-8'))\n style_ctx = self.get_style_context()\n style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n style_ctx.add_class("matplotlib-canvas")\n\n def destroy(self):\n CloseEvent("close_event", self)._process()\n\n def set_cursor(self, cursor):\n # docstring inherited\n self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor))\n\n def _mpl_coords(self, xy=None):\n """\n Convert the *xy* position of a GTK event, or of the current cursor\n position if *xy* is None, to Matplotlib coordinates.\n\n GTK use logical pixels, but the figure is scaled to physical pixels for\n rendering. Transform to physical pixels so that all of the down-stream\n transforms work as expected.\n\n Also, the origin is different and needs to be corrected.\n """\n if xy is None:\n surface = self.get_native().get_surface()\n is_over, x, y, mask = surface.get_device_position(\n self.get_display().get_default_seat().get_pointer())\n else:\n x, y = xy\n x = x * self.device_pixel_ratio\n # flip y so y=0 is bottom of canvas\n y = self.figure.bbox.height - y * self.device_pixel_ratio\n return x, y\n\n def scroll_event(self, controller, dx, dy):\n MouseEvent(\n "scroll_event", self, *self._mpl_coords(), step=dy,\n modifiers=self._mpl_modifiers(controller),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n return True\n\n def button_press_event(self, controller, n_press, x, y):\n MouseEvent(\n "button_press_event", self, *self._mpl_coords((x, y)),\n controller.get_current_button(),\n modifiers=self._mpl_modifiers(controller),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n self.grab_focus()\n\n def button_release_event(self, controller, n_press, x, y):\n MouseEvent(\n "button_release_event", self, *self._mpl_coords((x, y)),\n controller.get_current_button(),\n modifiers=self._mpl_modifiers(controller),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n\n def key_press_event(self, controller, keyval, keycode, state):\n KeyEvent(\n "key_press_event", self, self._get_key(keyval, keycode, state),\n *self._mpl_coords(),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n return True\n\n def key_release_event(self, controller, keyval, keycode, state):\n KeyEvent(\n "key_release_event", self, self._get_key(keyval, keycode, state),\n *self._mpl_coords(),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n return True\n\n def motion_notify_event(self, controller, x, y):\n MouseEvent(\n "motion_notify_event", self, *self._mpl_coords((x, y)),\n buttons=self._mpl_buttons(controller),\n modifiers=self._mpl_modifiers(controller),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n\n def enter_notify_event(self, controller, x, y):\n LocationEvent(\n "figure_enter_event", self, *self._mpl_coords((x, y)),\n modifiers=self._mpl_modifiers(),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n\n def leave_notify_event(self, controller):\n LocationEvent(\n "figure_leave_event", self, *self._mpl_coords(),\n modifiers=self._mpl_modifiers(),\n guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,\n )._process()\n\n def resize_event(self, area, width, height):\n self._update_device_pixel_ratio()\n dpi = self.figure.dpi\n winch = width * self.device_pixel_ratio / dpi\n hinch = height * self.device_pixel_ratio / dpi\n self.figure.set_size_inches(winch, hinch, forward=False)\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n\n def _mpl_buttons(self, controller):\n # NOTE: This spews "Broken accounting of active state" warnings on\n # right click on macOS.\n surface = self.get_native().get_surface()\n is_over, x, y, event_state = surface.get_device_position(\n self.get_display().get_default_seat().get_pointer())\n # NOTE: alternatively we could use\n # event_state = controller.get_current_event_state()\n # but for button_press/button_release this would report the state\n # *prior* to the event rather than after it; the above reports the\n # state *after* it.\n mod_table = [\n (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),\n (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),\n (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),\n (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),\n (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),\n ]\n return {name for name, mask in mod_table if event_state & mask}\n\n def _mpl_modifiers(self, controller=None):\n if controller is None:\n surface = self.get_native().get_surface()\n is_over, x, y, event_state = surface.get_device_position(\n self.get_display().get_default_seat().get_pointer())\n else:\n event_state = controller.get_current_event_state()\n mod_table = [\n ("ctrl", Gdk.ModifierType.CONTROL_MASK),\n ("alt", Gdk.ModifierType.ALT_MASK),\n ("shift", Gdk.ModifierType.SHIFT_MASK),\n ("super", Gdk.ModifierType.SUPER_MASK),\n ]\n return [name for name, mask in mod_table if event_state & mask]\n\n def _get_key(self, keyval, keycode, state):\n unikey = chr(Gdk.keyval_to_unicode(keyval))\n key = cbook._unikey_or_keysym_to_mplkey(\n unikey,\n Gdk.keyval_name(keyval))\n modifiers = [\n ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),\n ("alt", Gdk.ModifierType.ALT_MASK, "alt"),\n ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),\n ("super", Gdk.ModifierType.SUPER_MASK, "super"),\n ]\n mods = [\n mod for mod, mask, mod_key in modifiers\n if (mod_key != key and state & mask\n and not (mod == "shift" and unikey.isprintable()))]\n return "+".join([*mods, key])\n\n def _update_device_pixel_ratio(self, *args, **kwargs):\n # We need to be careful in cases with mixed resolution displays if\n # device_pixel_ratio changes.\n if self._set_device_pixel_ratio(self.get_scale_factor()):\n self.draw()\n\n def _draw_rubberband(self, rect):\n self._rubberband_rect = rect\n # TODO: Only update the rubberband area.\n self.queue_draw()\n\n def _draw_func(self, drawing_area, ctx, width, height):\n self.on_draw_event(self, ctx)\n self._post_draw(self, ctx)\n\n def _post_draw(self, widget, ctx):\n if self._rubberband_rect is None:\n return\n\n lw = 1\n dash = 3\n x0, y0, w, h = (dim / self.device_pixel_ratio\n for dim in self._rubberband_rect)\n x1 = x0 + w\n y1 = y0 + h\n\n # Draw the lines from x0, y0 towards x1, y1 so that the\n # dashes don't "jump" when moving the zoom box.\n ctx.move_to(x0, y0)\n ctx.line_to(x0, y1)\n ctx.move_to(x0, y0)\n ctx.line_to(x1, y0)\n ctx.move_to(x0, y1)\n ctx.line_to(x1, y1)\n ctx.move_to(x1, y0)\n ctx.line_to(x1, y1)\n\n ctx.set_antialias(1)\n ctx.set_line_width(lw)\n ctx.set_dash((dash, dash), 0)\n ctx.set_source_rgb(0, 0, 0)\n ctx.stroke_preserve()\n\n ctx.set_dash((dash, dash), dash)\n ctx.set_source_rgb(1, 1, 1)\n ctx.stroke()\n\n def on_draw_event(self, widget, ctx):\n # to be overwritten by GTK4Agg or GTK4Cairo\n pass\n\n def draw(self):\n # docstring inherited\n if self.is_drawable():\n self.queue_draw()\n\n def draw_idle(self):\n # docstring inherited\n if self._idle_draw_id != 0:\n return\n def idle_draw(*args):\n try:\n self.draw()\n finally:\n self._idle_draw_id = 0\n return False\n self._idle_draw_id = GLib.idle_add(idle_draw)\n\n def flush_events(self):\n # docstring inherited\n context = GLib.MainContext.default()\n while context.pending():\n context.iteration(True)\n\n\nclass NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box):\n def __init__(self, canvas):\n Gtk.Box.__init__(self)\n\n self.add_css_class('toolbar')\n\n self._gtk_ids = {}\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n self.append(Gtk.Separator())\n continue\n image = Gtk.Image.new_from_gicon(\n Gio.Icon.new_for_string(\n str(cbook._get_data_path('images',\n f'{image_file}-symbolic.svg'))))\n self._gtk_ids[text] = button = (\n Gtk.ToggleButton() if callback in ['zoom', 'pan'] else\n Gtk.Button())\n button.set_child(image)\n button.add_css_class('flat')\n button.add_css_class('image-button')\n # Save the handler id, so that we can block it as needed.\n button._signal_handler = button.connect(\n 'clicked', getattr(self, callback))\n button.set_tooltip_text(tooltip_text)\n self.append(button)\n\n # This filler item ensures the toolbar is always at least two text\n # lines high. Otherwise the canvas gets redrawn as the mouse hovers\n # over images because those use two-line messages which resize the\n # toolbar.\n label = Gtk.Label()\n label.set_markup(\n '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')\n label.set_hexpand(True) # Push real message to the right.\n self.append(label)\n\n self.message = Gtk.Label()\n self.message.set_justify(Gtk.Justification.RIGHT)\n self.append(self.message)\n\n _NavigationToolbar2GTK.__init__(self, canvas)\n\n def save_figure(self, *args):\n dialog = Gtk.FileChooserNative(\n title='Save the figure',\n transient_for=self.canvas.get_root(),\n action=Gtk.FileChooserAction.SAVE,\n modal=True)\n self._save_dialog = dialog # Must keep a reference.\n\n ff = Gtk.FileFilter()\n ff.set_name('All files')\n ff.add_pattern('*')\n dialog.add_filter(ff)\n dialog.set_filter(ff)\n\n formats = []\n default_format = None\n for i, (name, fmts) in enumerate(\n self.canvas.get_supported_filetypes_grouped().items()):\n ff = Gtk.FileFilter()\n ff.set_name(name)\n for fmt in fmts:\n ff.add_pattern(f'*.{fmt}')\n dialog.add_filter(ff)\n formats.append(name)\n if self.canvas.get_default_filetype() in fmts:\n default_format = i\n # Setting the choice doesn't always work, so make sure the default\n # format is first.\n formats = [formats[default_format], *formats[:default_format],\n *formats[default_format+1:]]\n dialog.add_choice('format', 'File format', formats, formats)\n dialog.set_choice('format', formats[0])\n\n dialog.set_current_folder(Gio.File.new_for_path(\n os.path.expanduser(mpl.rcParams['savefig.directory'])))\n dialog.set_current_name(self.canvas.get_default_filename())\n\n @functools.partial(dialog.connect, 'response')\n def on_response(dialog, response):\n file = dialog.get_file()\n fmt = dialog.get_choice('format')\n fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0]\n dialog.destroy()\n self._save_dialog = None\n if response != Gtk.ResponseType.ACCEPT:\n return\n # Save dir for next time, unless empty str (which means use cwd).\n if mpl.rcParams['savefig.directory']:\n parent = file.get_parent()\n mpl.rcParams['savefig.directory'] = parent.get_path()\n try:\n self.canvas.figure.savefig(file.get_path(), format=fmt)\n except Exception as e:\n msg = Gtk.MessageDialog(\n transient_for=self.canvas.get_root(),\n message_type=Gtk.MessageType.ERROR,\n buttons=Gtk.ButtonsType.OK, modal=True,\n text=str(e))\n msg.show()\n\n dialog.show()\n return self.UNKNOWN_SAVED_STATUS\n\n\nclass ToolbarGTK4(ToolContainerBase, Gtk.Box):\n _icon_extension = '-symbolic.svg'\n\n def __init__(self, toolmanager):\n ToolContainerBase.__init__(self, toolmanager)\n Gtk.Box.__init__(self)\n self.set_property('orientation', Gtk.Orientation.HORIZONTAL)\n\n # Tool items are created later, but must appear before the message.\n self._tool_box = Gtk.Box()\n self.append(self._tool_box)\n self._groups = {}\n self._toolitems = {}\n\n # This filler item ensures the toolbar is always at least two text\n # lines high. Otherwise the canvas gets redrawn as the mouse hovers\n # over images because those use two-line messages which resize the\n # toolbar.\n label = Gtk.Label()\n label.set_markup(\n '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')\n label.set_hexpand(True) # Push real message to the right.\n self.append(label)\n\n self._message = Gtk.Label()\n self._message.set_justify(Gtk.Justification.RIGHT)\n self.append(self._message)\n\n def add_toolitem(self, name, group, position, image_file, description,\n toggle):\n if toggle:\n button = Gtk.ToggleButton()\n else:\n button = Gtk.Button()\n button.set_label(name)\n button.add_css_class('flat')\n\n if image_file is not None:\n image = Gtk.Image.new_from_gicon(\n Gio.Icon.new_for_string(image_file))\n button.set_child(image)\n button.add_css_class('image-button')\n\n if position is None:\n position = -1\n\n self._add_button(button, group, position)\n signal = button.connect('clicked', self._call_tool, name)\n button.set_tooltip_text(description)\n self._toolitems.setdefault(name, [])\n self._toolitems[name].append((button, signal))\n\n def _find_child_at_position(self, group, position):\n children = [None]\n child = self._groups[group].get_first_child()\n while child is not None:\n children.append(child)\n child = child.get_next_sibling()\n return children[position]\n\n def _add_button(self, button, group, position):\n if group not in self._groups:\n if self._groups:\n self._add_separator()\n group_box = Gtk.Box()\n self._tool_box.append(group_box)\n self._groups[group] = group_box\n self._groups[group].insert_child_after(\n button, self._find_child_at_position(group, position))\n\n def _call_tool(self, btn, name):\n self.trigger_tool(name)\n\n def toggle_toolitem(self, name, toggled):\n if name not in self._toolitems:\n return\n for toolitem, signal in self._toolitems[name]:\n toolitem.handler_block(signal)\n toolitem.set_active(toggled)\n toolitem.handler_unblock(signal)\n\n def remove_toolitem(self, name):\n for toolitem, _signal in self._toolitems.pop(name, []):\n for group in self._groups:\n if toolitem in self._groups[group]:\n self._groups[group].remove(toolitem)\n\n def _add_separator(self):\n sep = Gtk.Separator()\n sep.set_property("orientation", Gtk.Orientation.VERTICAL)\n self._tool_box.append(sep)\n\n def set_message(self, s):\n self._message.set_label(s)\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK4)\nclass SaveFigureGTK4(backend_tools.SaveFigureBase):\n def trigger(self, *args, **kwargs):\n NavigationToolbar2GTK4.save_figure(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK4)\nclass HelpGTK4(backend_tools.ToolHelpBase):\n def _normalize_shortcut(self, key):\n """\n Convert Matplotlib key presses to GTK+ accelerator identifiers.\n\n Related to `FigureCanvasGTK4._get_key`.\n """\n special = {\n 'backspace': 'BackSpace',\n 'pagedown': 'Page_Down',\n 'pageup': 'Page_Up',\n 'scroll_lock': 'Scroll_Lock',\n }\n\n parts = key.split('+')\n mods = ['<' + mod + '>' for mod in parts[:-1]]\n key = parts[-1]\n\n if key in special:\n key = special[key]\n elif len(key) > 1:\n key = key.capitalize()\n elif key.isupper():\n mods += ['<shift>']\n\n return ''.join(mods) + key\n\n def _is_valid_shortcut(self, key):\n """\n Check for a valid shortcut to be displayed.\n\n - GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`).\n - The shortcut window only shows keyboard shortcuts, not mouse buttons.\n """\n return 'cmd+' not in key and not key.startswith('MouseButton.')\n\n def trigger(self, *args):\n section = Gtk.ShortcutsSection()\n\n for name, tool in sorted(self.toolmanager.tools.items()):\n if not tool.description:\n continue\n\n # Putting everything in a separate group allows GTK to\n # automatically split them into separate columns/pages, which is\n # useful because we have lots of shortcuts, some with many keys\n # that are very wide.\n group = Gtk.ShortcutsGroup()\n section.append(group)\n # A hack to remove the title since we have no group naming.\n child = group.get_first_child()\n while child is not None:\n child.set_visible(False)\n child = child.get_next_sibling()\n\n shortcut = Gtk.ShortcutsShortcut(\n accelerator=' '.join(\n self._normalize_shortcut(key)\n for key in self.toolmanager.get_tool_keymap(name)\n if self._is_valid_shortcut(key)),\n title=tool.name,\n subtitle=tool.description)\n group.append(shortcut)\n\n window = Gtk.ShortcutsWindow(\n title='Help',\n modal=True,\n transient_for=self._figure.canvas.get_root())\n window.set_child(section)\n\n window.show()\n\n\n@backend_tools._register_tool_class(FigureCanvasGTK4)\nclass ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase):\n def trigger(self, *args, **kwargs):\n with io.BytesIO() as f:\n self.canvas.print_rgba(f)\n w, h = self.canvas.get_width_height()\n pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),\n GdkPixbuf.Colorspace.RGB, True,\n 8, w, h, w*4)\n clipboard = self.canvas.get_clipboard()\n clipboard.set(pb)\n\n\nbackend_tools._register_tool_class(\n FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK)\nbackend_tools._register_tool_class(\n FigureCanvasGTK4, _backend_gtk.RubberbandGTK)\nToolbar = ToolbarGTK4\n\n\nclass FigureManagerGTK4(_FigureManagerGTK):\n _toolbar2_class = NavigationToolbar2GTK4\n _toolmanager_toolbar_class = ToolbarGTK4\n\n\n@_BackendGTK.export\nclass _BackendGTK4(_BackendGTK):\n FigureCanvas = FigureCanvasGTK4\n FigureManager = FigureManagerGTK4\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk4.py
backend_gtk4.py
Python
23,026
0.95
0.173844
0.081594
python-kit
823
2023-09-13T04:02:26.386512
GPL-3.0
false
ee6d6e422aec3f5eda55176ceb1b000c
import numpy as np\n\nfrom .. import cbook\nfrom . import backend_agg, backend_gtk4\nfrom .backend_gtk4 import GLib, Gtk, _BackendGTK4\n\nimport cairo # Presence of cairo is already checked by _backend_gtk.\n\n\nclass FigureCanvasGTK4Agg(backend_agg.FigureCanvasAgg,\n backend_gtk4.FigureCanvasGTK4):\n\n def on_draw_event(self, widget, ctx):\n if self._idle_draw_id:\n GLib.source_remove(self._idle_draw_id)\n self._idle_draw_id = 0\n self.draw()\n\n scale = self.device_pixel_ratio\n allocation = self.get_allocation()\n\n Gtk.render_background(\n self.get_style_context(), ctx,\n allocation.x, allocation.y,\n allocation.width, allocation.height)\n\n buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(\n np.asarray(self.get_renderer().buffer_rgba()))\n height, width, _ = buf.shape\n image = cairo.ImageSurface.create_for_data(\n buf.ravel().data, cairo.FORMAT_ARGB32, width, height)\n image.set_device_scale(scale, scale)\n ctx.set_source_surface(image, 0, 0)\n ctx.paint()\n\n return False\n\n\n@_BackendGTK4.export\nclass _BackendGTK4Agg(_BackendGTK4):\n FigureCanvas = FigureCanvasGTK4Agg\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk4agg.py
backend_gtk4agg.py
Python
1,262
0.95
0.097561
0
awesome-app
594
2024-06-20T12:09:42.751390
BSD-3-Clause
false
a571c270eac39d4579e15f2efb998882
from contextlib import nullcontext\n\nfrom .backend_cairo import FigureCanvasCairo\nfrom .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4\n\n\nclass FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4):\n def _set_device_pixel_ratio(self, ratio):\n # Cairo in GTK4 always uses logical pixels, so we don't need to do anything for\n # changes to the device pixel ratio.\n return False\n\n def on_draw_event(self, widget, ctx):\n if self._idle_draw_id:\n GLib.source_remove(self._idle_draw_id)\n self._idle_draw_id = 0\n self.draw()\n\n with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar\n else nullcontext()):\n self._renderer.set_context(ctx)\n allocation = self.get_allocation()\n Gtk.render_background(\n self.get_style_context(), ctx,\n allocation.x, allocation.y,\n allocation.width, allocation.height)\n self.figure.draw(self._renderer)\n\n\n@_BackendGTK4.export\nclass _BackendGTK4Cairo(_BackendGTK4):\n FigureCanvas = FigureCanvasGTK4Cairo\n
.venv\Lib\site-packages\matplotlib\backends\backend_gtk4cairo.py
backend_gtk4cairo.py
Python
1,125
0.95
0.21875
0.08
awesome-app
35
2024-04-15T20:40:26.338733
MIT
false
73b761e41e344363bdbb437c2683c787
import os\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook\nfrom matplotlib._pylab_helpers import Gcf\nfrom . import _macosx\nfrom .backend_agg import FigureCanvasAgg\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,\n ResizeEvent, TimerBase, _allow_interrupt)\n\n\nclass TimerMac(_macosx.Timer, TimerBase):\n """Subclass of `.TimerBase` using CFRunLoop timer events."""\n # completely implemented at the C-level (in _macosx.Timer)\n\n\ndef _allow_interrupt_macos():\n """A context manager that allows terminating a plot by sending a SIGINT."""\n return _allow_interrupt(\n lambda rsock: _macosx.wake_on_fd_write(rsock.fileno()), _macosx.stop)\n\n\nclass FigureCanvasMac(FigureCanvasAgg, _macosx.FigureCanvas, FigureCanvasBase):\n # docstring inherited\n\n # Ideally this class would be `class FCMacAgg(FCAgg, FCMac)`\n # (FC=FigureCanvas) where FCMac would be an ObjC-implemented mac-specific\n # class also inheriting from FCBase (this is the approach with other GUI\n # toolkits). However, writing an extension type inheriting from a Python\n # base class is slightly tricky (the extension type must be a heap type),\n # and we can just as well lift the FCBase base up one level, keeping it *at\n # the end* to have the right method resolution order.\n\n # Events such as button presses, mouse movements, and key presses are\n # handled in C and events (MouseEvent, etc.) are triggered from there.\n\n required_interactive_framework = "macosx"\n _timer_cls = TimerMac\n manager_class = _api.classproperty(lambda cls: FigureManagerMac)\n\n def __init__(self, figure):\n super().__init__(figure=figure)\n self._draw_pending = False\n self._is_drawing = False\n # Keep track of the timers that are alive\n self._timers = set()\n\n def draw(self):\n """Render the figure and update the macosx canvas."""\n # The renderer draw is done here; delaying causes problems with code\n # that uses the result of the draw() to update plot elements.\n if self._is_drawing:\n return\n with cbook._setattr_cm(self, _is_drawing=True):\n super().draw()\n self.update()\n\n def draw_idle(self):\n # docstring inherited\n if not (getattr(self, '_draw_pending', False) or\n getattr(self, '_is_drawing', False)):\n self._draw_pending = True\n # Add a singleshot timer to the eventloop that will call back\n # into the Python method _draw_idle to take care of the draw\n self._single_shot_timer(self._draw_idle)\n\n def _single_shot_timer(self, callback):\n """Add a single shot timer with the given callback"""\n def callback_func(callback, timer):\n callback()\n self._timers.remove(timer)\n timer = self.new_timer(interval=0)\n timer.single_shot = True\n timer.add_callback(callback_func, callback, timer)\n self._timers.add(timer)\n timer.start()\n\n def _draw_idle(self):\n """\n Draw method for singleshot timer\n\n This draw method can be added to a singleshot timer, which can\n accumulate draws while the eventloop is spinning. This method will\n then only draw the first time and short-circuit the others.\n """\n with self._idle_draw_cntx():\n if not self._draw_pending:\n # Short-circuit because our draw request has already been\n # taken care of\n return\n self._draw_pending = False\n self.draw()\n\n def blit(self, bbox=None):\n # docstring inherited\n super().blit(bbox)\n self.update()\n\n def resize(self, width, height):\n # Size from macOS is logical pixels, dpi is physical.\n scale = self.figure.dpi / self.device_pixel_ratio\n width /= scale\n height /= scale\n self.figure.set_size_inches(width, height, forward=False)\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n\n def start_event_loop(self, timeout=0):\n # docstring inherited\n # Set up a SIGINT handler to allow terminating a plot via CTRL-C.\n with _allow_interrupt_macos():\n self._start_event_loop(timeout=timeout) # Forward to ObjC implementation.\n\n\nclass NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2):\n\n def __init__(self, canvas):\n data_path = cbook._get_data_path('images')\n _, tooltips, image_names, _ = zip(*NavigationToolbar2.toolitems)\n _macosx.NavigationToolbar2.__init__(\n self, canvas,\n tuple(str(data_path / image_name) + ".pdf"\n for image_name in image_names if image_name is not None),\n tuple(tooltip for tooltip in tooltips if tooltip is not None))\n NavigationToolbar2.__init__(self, canvas)\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))\n\n def remove_rubberband(self):\n self.canvas.remove_rubberband()\n\n def save_figure(self, *args):\n directory = os.path.expanduser(mpl.rcParams['savefig.directory'])\n filename = _macosx.choose_save_file('Save the figure',\n directory,\n self.canvas.get_default_filename())\n if filename is None: # Cancel\n return\n # Save dir for next time, unless empty str (which means use cwd).\n if mpl.rcParams['savefig.directory']:\n mpl.rcParams['savefig.directory'] = os.path.dirname(filename)\n self.canvas.figure.savefig(filename)\n return filename\n\n\nclass FigureManagerMac(_macosx.FigureManager, FigureManagerBase):\n _toolbar2_class = NavigationToolbar2Mac\n\n def __init__(self, canvas, num):\n self._shown = False\n _macosx.FigureManager.__init__(self, canvas)\n icon_path = str(cbook._get_data_path('images/matplotlib.pdf'))\n _macosx.FigureManager.set_icon(icon_path)\n FigureManagerBase.__init__(self, canvas, num)\n self._set_window_mode(mpl.rcParams["macosx.window_mode"])\n if self.toolbar is not None:\n self.toolbar.update()\n if mpl.is_interactive():\n self.show()\n self.canvas.draw_idle()\n\n def _close_button_pressed(self):\n Gcf.destroy(self)\n self.canvas.flush_events()\n\n def destroy(self):\n # We need to clear any pending timers that never fired, otherwise\n # we get a memory leak from the timer callbacks holding a reference\n while self.canvas._timers:\n timer = self.canvas._timers.pop()\n timer.stop()\n super().destroy()\n\n @classmethod\n def start_main_loop(cls):\n # Set up a SIGINT handler to allow terminating a plot via CTRL-C.\n with _allow_interrupt_macos():\n _macosx.show()\n\n def show(self):\n if self.canvas.figure.stale:\n self.canvas.draw_idle()\n if not self._shown:\n self._show()\n self._shown = True\n if mpl.rcParams["figure.raise_window"]:\n self._raise()\n\n\n@_Backend.export\nclass _BackendMac(_Backend):\n FigureCanvas = FigureCanvasMac\n FigureManager = FigureManagerMac\n mainloop = FigureManagerMac.start_main_loop\n
.venv\Lib\site-packages\matplotlib\backends\backend_macosx.py
backend_macosx.py
Python
7,397
0.95
0.234694
0.166667
vue-tools
33
2025-03-27T19:23:55.080518
GPL-3.0
false
ed7a7c98cf682dce59bda1ed424d5c2c
import numpy as np\n\nfrom matplotlib import cbook\nfrom .backend_agg import RendererAgg\nfrom matplotlib._tight_bbox import process_figure_for_rasterizing\n\n\nclass MixedModeRenderer:\n """\n A helper class to implement a renderer that switches between\n vector and raster drawing. An example may be a PDF writer, where\n most things are drawn with PDF vector commands, but some very\n complex objects, such as quad meshes, are rasterised and then\n output as images.\n """\n def __init__(self, figure, width, height, dpi, vector_renderer,\n raster_renderer_class=None,\n bbox_inches_restore=None):\n """\n Parameters\n ----------\n figure : `~matplotlib.figure.Figure`\n The figure instance.\n width : float\n The width of the canvas in logical units\n height : float\n The height of the canvas in logical units\n dpi : float\n The dpi of the canvas\n vector_renderer : `~matplotlib.backend_bases.RendererBase`\n An instance of a subclass of\n `~matplotlib.backend_bases.RendererBase` that will be used for the\n vector drawing.\n raster_renderer_class : `~matplotlib.backend_bases.RendererBase`\n The renderer class to use for the raster drawing. If not provided,\n this will use the Agg backend (which is currently the only viable\n option anyway.)\n\n """\n if raster_renderer_class is None:\n raster_renderer_class = RendererAgg\n\n self._raster_renderer_class = raster_renderer_class\n self._width = width\n self._height = height\n self.dpi = dpi\n\n self._vector_renderer = vector_renderer\n\n self._raster_renderer = None\n\n # A reference to the figure is needed as we need to change\n # the figure dpi before and after the rasterization. Although\n # this looks ugly, I couldn't find a better solution. -JJL\n self.figure = figure\n self._figdpi = figure.dpi\n\n self._bbox_inches_restore = bbox_inches_restore\n\n self._renderer = vector_renderer\n\n def __getattr__(self, attr):\n # Proxy everything that hasn't been overridden to the base\n # renderer. Things that *are* overridden can call methods\n # on self._renderer directly, but must not cache/store\n # methods (because things like RendererAgg change their\n # methods on the fly in order to optimise proxying down\n # to the underlying C implementation).\n return getattr(self._renderer, attr)\n\n def start_rasterizing(self):\n """\n Enter "raster" mode. All subsequent drawing commands (until\n `stop_rasterizing` is called) will be drawn with the raster backend.\n """\n # change the dpi of the figure temporarily.\n self.figure.dpi = self.dpi\n if self._bbox_inches_restore: # when tight bbox is used\n r = process_figure_for_rasterizing(self.figure,\n self._bbox_inches_restore)\n self._bbox_inches_restore = r\n\n self._raster_renderer = self._raster_renderer_class(\n self._width*self.dpi, self._height*self.dpi, self.dpi)\n self._renderer = self._raster_renderer\n\n def stop_rasterizing(self):\n """\n Exit "raster" mode. All of the drawing that was done since\n the last `start_rasterizing` call will be copied to the\n vector backend by calling draw_image.\n """\n\n self._renderer = self._vector_renderer\n\n height = self._height * self.dpi\n img = np.asarray(self._raster_renderer.buffer_rgba())\n slice_y, slice_x = cbook._get_nonzero_slices(img[..., 3])\n cropped_img = img[slice_y, slice_x]\n if cropped_img.size:\n gc = self._renderer.new_gc()\n # TODO: If the mixedmode resolution differs from the figure's\n # dpi, the image must be scaled (dpi->_figdpi). Not all\n # backends support this.\n self._renderer.draw_image(\n gc,\n slice_x.start * self._figdpi / self.dpi,\n (height - slice_y.stop) * self._figdpi / self.dpi,\n cropped_img[::-1])\n self._raster_renderer = None\n\n # restore the figure dpi.\n self.figure.dpi = self._figdpi\n\n if self._bbox_inches_restore: # when tight bbox is used\n r = process_figure_for_rasterizing(self.figure,\n self._bbox_inches_restore,\n self._figdpi)\n self._bbox_inches_restore = r\n
.venv\Lib\site-packages\matplotlib\backends\backend_mixed.py
backend_mixed.py
Python
4,696
0.95
0.109244
0.138614
awesome-app
81
2023-12-17T00:23:51.202648
Apache-2.0
false
07a218a5dedc2ebcb6d8170970b1ad05
"""Interactive figures in the IPython notebook."""\n# Note: There is a notebook in\n# lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify\n# that changes made maintain expected behaviour.\n\nfrom base64 import b64encode\nimport io\nimport json\nimport pathlib\nimport uuid\n\nfrom ipykernel.comm import Comm\nfrom IPython.display import display, Javascript, HTML\n\nfrom matplotlib import is_interactive\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2\nfrom .backend_webagg_core import (\n FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg)\nfrom .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611\n TimerTornado, TimerAsyncio)\n\n\ndef connection_info():\n """\n Return a string showing the figure and connection status for the backend.\n\n This is intended as a diagnostic tool, and not for general use.\n """\n result = [\n '{fig} - {socket}'.format(\n fig=(manager.canvas.figure.get_label()\n or f"Figure {manager.num}"),\n socket=manager.web_sockets)\n for manager in Gcf.get_all_fig_managers()\n ]\n if not is_interactive():\n result.append(f'Figures pending show: {len(Gcf.figs)}')\n return '\n'.join(result)\n\n\n_FONT_AWESOME_CLASSES = { # font-awesome 4 names\n 'home': 'fa fa-home',\n 'back': 'fa fa-arrow-left',\n 'forward': 'fa fa-arrow-right',\n 'zoom_to_rect': 'fa fa-square-o',\n 'move': 'fa fa-arrows',\n 'download': 'fa fa-floppy-o',\n None: None\n}\n\n\nclass NavigationIPy(NavigationToolbar2WebAgg):\n\n # Use the standard toolbar items + download button\n toolitems = [(text, tooltip_text,\n _FONT_AWESOME_CLASSES[image_file], name_of_method)\n for text, tooltip_text, image_file, name_of_method\n in (NavigationToolbar2.toolitems +\n (('Download', 'Download plot', 'download', 'download'),))\n if image_file in _FONT_AWESOME_CLASSES]\n\n\nclass FigureManagerNbAgg(FigureManagerWebAgg):\n _toolbar2_class = ToolbarCls = NavigationIPy\n\n def __init__(self, canvas, num):\n self._shown = False\n super().__init__(canvas, num)\n\n @classmethod\n def create_with_canvas(cls, canvas_class, figure, num):\n canvas = canvas_class(figure)\n manager = cls(canvas, num)\n if is_interactive():\n manager.show()\n canvas.draw_idle()\n\n def destroy(event):\n canvas.mpl_disconnect(cid)\n Gcf.destroy(manager)\n\n cid = canvas.mpl_connect('close_event', destroy)\n return manager\n\n def display_js(self):\n # XXX How to do this just once? It has to deal with multiple\n # browser instances using the same kernel (require.js - but the\n # file isn't static?).\n display(Javascript(FigureManagerNbAgg.get_javascript()))\n\n def show(self):\n if not self._shown:\n self.display_js()\n self._create_comm()\n else:\n self.canvas.draw_idle()\n self._shown = True\n # plt.figure adds an event which makes the figure in focus the active\n # one. Disable this behaviour, as it results in figures being put as\n # the active figure after they have been shown, even in non-interactive\n # mode.\n if hasattr(self, '_cidgcf'):\n self.canvas.mpl_disconnect(self._cidgcf)\n if not is_interactive():\n from matplotlib._pylab_helpers import Gcf\n Gcf.figs.pop(self.num, None)\n\n def reshow(self):\n """\n A special method to re-show the figure in the notebook.\n\n """\n self._shown = False\n self.show()\n\n @property\n def connected(self):\n return bool(self.web_sockets)\n\n @classmethod\n def get_javascript(cls, stream=None):\n if stream is None:\n output = io.StringIO()\n else:\n output = stream\n super().get_javascript(stream=output)\n output.write((pathlib.Path(__file__).parent\n / "web_backend/js/nbagg_mpl.js")\n .read_text(encoding="utf-8"))\n if stream is None:\n return output.getvalue()\n\n def _create_comm(self):\n comm = CommSocket(self)\n self.add_web_socket(comm)\n return comm\n\n def destroy(self):\n self._send_event('close')\n # need to copy comms as callbacks will modify this list\n for comm in list(self.web_sockets):\n comm.on_close()\n self.clearup_closed()\n\n def clearup_closed(self):\n """Clear up any closed Comms."""\n self.web_sockets = {socket for socket in self.web_sockets\n if socket.is_open()}\n\n if len(self.web_sockets) == 0:\n CloseEvent("close_event", self.canvas)._process()\n\n def remove_comm(self, comm_id):\n self.web_sockets = {socket for socket in self.web_sockets\n if socket.comm.comm_id != comm_id}\n\n\nclass FigureCanvasNbAgg(FigureCanvasWebAggCore):\n manager_class = FigureManagerNbAgg\n\n\nclass CommSocket:\n """\n Manages the Comm connection between IPython and the browser (client).\n\n Comms are 2 way, with the CommSocket being able to publish a message\n via the send_json method, and handle a message with on_message. On the\n JS side figure.send_message and figure.ws.onmessage do the sending and\n receiving respectively.\n\n """\n def __init__(self, manager):\n self.supports_binary = None\n self.manager = manager\n self.uuid = str(uuid.uuid4())\n # Publish an output area with a unique ID. The javascript can then\n # hook into this area.\n display(HTML("<div id=%r></div>" % self.uuid))\n try:\n self.comm = Comm('matplotlib', data={'id': self.uuid})\n except AttributeError as err:\n raise RuntimeError('Unable to create an IPython notebook Comm '\n 'instance. Are you in the IPython '\n 'notebook?') from err\n self.comm.on_msg(self.on_message)\n\n manager = self.manager\n self._ext_close = False\n\n def _on_close(close_message):\n self._ext_close = True\n manager.remove_comm(close_message['content']['comm_id'])\n manager.clearup_closed()\n\n self.comm.on_close(_on_close)\n\n def is_open(self):\n return not (self._ext_close or self.comm._closed)\n\n def on_close(self):\n # When the socket is closed, deregister the websocket with\n # the FigureManager.\n if self.is_open():\n try:\n self.comm.close()\n except KeyError:\n # apparently already cleaned it up?\n pass\n\n def send_json(self, content):\n self.comm.send({'data': json.dumps(content)})\n\n def send_binary(self, blob):\n if self.supports_binary:\n self.comm.send({'blob': 'image/png'}, buffers=[blob])\n else:\n # The comm is ASCII, so we send the image in base64 encoded data\n # URL form.\n data = b64encode(blob).decode('ascii')\n data_uri = f"data:image/png;base64,{data}"\n self.comm.send({'data': data_uri})\n\n def on_message(self, message):\n # The 'supports_binary' message is relevant to the\n # websocket itself. The other messages get passed along\n # to matplotlib as-is.\n\n # Every message has a "type" and a "figure_id".\n message = json.loads(message['content']['data'])\n if message['type'] == 'closing':\n self.on_close()\n self.manager.clearup_closed()\n elif message['type'] == 'supports_binary':\n self.supports_binary = message['value']\n else:\n self.manager.handle_json(message)\n\n\n@_Backend.export\nclass _BackendNbAgg(_Backend):\n FigureCanvas = FigureCanvasNbAgg\n FigureManager = FigureManagerNbAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_nbagg.py
backend_nbagg.py
Python
8,000
0.95
0.197531
0.116162
node-utils
20
2023-07-26T02:05:03.481319
MIT
false
45aba459691b5b7e2a5691c938b4099b
import codecs\nimport datetime\nimport functools\nfrom io import BytesIO\nimport logging\nimport math\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nfrom tempfile import TemporaryDirectory\nimport weakref\n\nfrom PIL import Image\n\nimport matplotlib as mpl\nfrom matplotlib import cbook, font_manager as fm\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, RendererBase\n)\nfrom matplotlib.backends.backend_mixed import MixedModeRenderer\nfrom matplotlib.backends.backend_pdf import (\n _create_pdf_info_dict, _datetime_to_pdf)\nfrom matplotlib.path import Path\nfrom matplotlib.figure import Figure\nfrom matplotlib.font_manager import FontProperties\nfrom matplotlib._pylab_helpers import Gcf\n\n_log = logging.getLogger(__name__)\n\n\n_DOCUMENTCLASS = r"\documentclass{article}"\n\n\n# Note: When formatting floating point values, it is important to use the\n# %f/{:f} format rather than %s/{} to avoid triggering scientific notation,\n# which is not recognized by TeX.\n\ndef _get_preamble():\n """Prepare a LaTeX preamble based on the rcParams configuration."""\n font_size_pt = FontProperties(\n size=mpl.rcParams["font.size"]\n ).get_size_in_points()\n return "\n".join([\n # Remove Matplotlib's custom command \mathdefault. (Not using\n # \mathnormal instead since this looks odd with Computer Modern.)\n r"\def\mathdefault#1{#1}",\n # Use displaystyle for all math.\n r"\everymath=\expandafter{\the\everymath\displaystyle}",\n # Set up font sizes to match font.size setting.\n # If present, use the KOMA package scrextend to adjust the standard\n # LaTeX font commands (\tiny, ..., \normalsize, ..., \Huge) accordingly.\n # Otherwise, only set \normalsize, manually.\n r"\IfFileExists{scrextend.sty}{",\n r" \usepackage[fontsize=%fpt]{scrextend}" % font_size_pt,\n r"}{",\n r" \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}"\n % (font_size_pt, 1.2 * font_size_pt),\n r" \normalsize",\n r"}",\n # Allow pgf.preamble to override the above definitions.\n mpl.rcParams["pgf.preamble"],\n *([\n r"\ifdefined\pdftexversion\else % non-pdftex case.",\n r" \usepackage{fontspec}",\n ] + [\n r" \%s{%s}[Path=\detokenize{%s/}]"\n % (command, path.name, path.parent.as_posix())\n for command, path in zip(\n ["setmainfont", "setsansfont", "setmonofont"],\n [pathlib.Path(fm.findfont(family))\n for family in ["serif", "sans\\-serif", "monospace"]]\n )\n ] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),\n # Documented as "must come last".\n mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"),\n ])\n\n\n# It's better to use only one unit for all coordinates, since the\n# arithmetic in latex seems to produce inaccurate conversions.\nlatex_pt_to_in = 1. / 72.27\nlatex_in_to_pt = 1. / latex_pt_to_in\nmpl_pt_to_in = 1. / 72.\nmpl_in_to_pt = 1. / mpl_pt_to_in\n\n\ndef _tex_escape(text):\n r"""\n Do some necessary and/or useful substitutions for texts to be included in\n LaTeX documents.\n """\n return text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")\n\n\ndef _writeln(fh, line):\n # Ending lines with a % prevents TeX from inserting spurious spaces\n # (https://tex.stackexchange.com/questions/7453).\n fh.write(line)\n fh.write("%\n")\n\n\ndef _escape_and_apply_props(s, prop):\n """\n Generate a TeX string that renders string *s* with font properties *prop*,\n also applying any required escapes to *s*.\n """\n commands = []\n\n families = {"serif": r"\rmfamily", "sans": r"\sffamily",\n "sans-serif": r"\sffamily", "monospace": r"\ttfamily"}\n family = prop.get_family()[0]\n if family in families:\n commands.append(families[family])\n elif not mpl.rcParams["pgf.rcfonts"]:\n commands.append(r"\fontfamily{\familydefault}")\n elif any(font.name == family for font in fm.fontManager.ttflist):\n commands.append(\n r"\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fi" % family)\n else:\n _log.warning("Ignoring unknown font: %s", family)\n\n size = prop.get_size_in_points()\n commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))\n\n styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}\n commands.append(styles[prop.get_style()])\n\n boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",\n "extra bold", "black"]\n if prop.get_weight() in boldstyles:\n commands.append(r"\bfseries")\n\n commands.append(r"\selectfont")\n return (\n "{"\n + "".join(commands)\n + r"\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}"\n # It should normally be enough to set the catcode of % to 12 ("normal\n # character"); this works on TeXLive 2021 but not on 2018, so we just\n # make it active too.\n + r"\catcode`\%=\active\def%{\%}"\n + _tex_escape(s)\n + "}"\n )\n\n\ndef _metadata_to_str(key, value):\n """Convert metadata key/value to a form that hyperref accepts."""\n if isinstance(value, datetime.datetime):\n value = _datetime_to_pdf(value)\n elif key == 'Trapped':\n value = value.name.decode('ascii')\n else:\n value = str(value)\n return f'{key}={{{value}}}'\n\n\ndef make_pdf_to_png_converter():\n """Return a function that converts a pdf file to a png file."""\n try:\n mpl._get_executable_info("pdftocairo")\n except mpl.ExecutableNotFoundError:\n pass\n else:\n return lambda pdffile, pngfile, dpi: subprocess.check_output(\n ["pdftocairo", "-singlefile", "-transp", "-png", "-r", "%d" % dpi,\n pdffile, os.path.splitext(pngfile)[0]],\n stderr=subprocess.STDOUT)\n try:\n gs_info = mpl._get_executable_info("gs")\n except mpl.ExecutableNotFoundError:\n pass\n else:\n return lambda pdffile, pngfile, dpi: subprocess.check_output(\n [gs_info.executable,\n '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',\n '-dUseCIEColor', '-dTextAlphaBits=4',\n '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',\n '-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile,\n '-r%d' % dpi, pdffile],\n stderr=subprocess.STDOUT)\n raise RuntimeError("No suitable pdf to png renderer found.")\n\n\nclass LatexError(Exception):\n def __init__(self, message, latex_output=""):\n super().__init__(message)\n self.latex_output = latex_output\n\n def __str__(self):\n s, = self.args\n if self.latex_output:\n s += "\n" + self.latex_output\n return s\n\n\nclass LatexManager:\n """\n The LatexManager opens an instance of the LaTeX application for\n determining the metrics of text elements. The LaTeX environment can be\n modified by setting fonts and/or a custom preamble in `.rcParams`.\n """\n\n @staticmethod\n def _build_latex_header():\n latex_header = [\n _DOCUMENTCLASS,\n # Include TeX program name as a comment for cache invalidation.\n # TeX does not allow this to be the first line.\n rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",\n # Test whether \includegraphics supports interpolate option.\n r"\usepackage{graphicx}",\n _get_preamble(),\n r"\begin{document}",\n r"\typeout{pgf_backend_query_start}",\n ]\n return "\n".join(latex_header)\n\n @classmethod\n def _get_cached_or_new(cls):\n """\n Return the previous LatexManager if the header and tex system did not\n change, or a new instance otherwise.\n """\n return cls._get_cached_or_new_impl(cls._build_latex_header())\n\n @classmethod\n @functools.lru_cache(1)\n def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.\n return cls()\n\n def _stdin_writeln(self, s):\n if self.latex is None:\n self._setup_latex_process()\n self.latex.stdin.write(s)\n self.latex.stdin.write("\n")\n self.latex.stdin.flush()\n\n def _expect(self, s):\n s = list(s)\n chars = []\n while True:\n c = self.latex.stdout.read(1)\n chars.append(c)\n if chars[-len(s):] == s:\n break\n if not c:\n self.latex.kill()\n self.latex = None\n raise LatexError("LaTeX process halted", "".join(chars))\n return "".join(chars)\n\n def _expect_prompt(self):\n return self._expect("\n*")\n\n def __init__(self):\n # create a tmp directory for running latex, register it for deletion\n self._tmpdir = TemporaryDirectory()\n self.tmpdir = self._tmpdir.name\n self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup)\n\n # test the LaTeX setup to ensure a clean startup of the subprocess\n self._setup_latex_process(expect_reply=False)\n stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n")\n if self.latex.returncode != 0:\n raise LatexError(\n f"LaTeX errored (probably missing font or error in preamble) "\n f"while processing the following input:\n"\n f"{self._build_latex_header()}",\n stdout)\n self.latex = None # Will be set up on first use.\n # Per-instance cache.\n self._get_box_metrics = functools.lru_cache(self._get_box_metrics)\n\n def _setup_latex_process(self, *, expect_reply=True):\n # Open LaTeX process for real work; register it for deletion. On\n # Windows, we must ensure that the subprocess has quit before being\n # able to delete the tmpdir in which it runs; in order to do so, we\n # must first `kill()` it, and then `communicate()` with or `wait()` on\n # it.\n try:\n self.latex = subprocess.Popen(\n [mpl.rcParams["pgf.texsystem"], "-halt-on-error"],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n encoding="utf-8", cwd=self.tmpdir)\n except FileNotFoundError as err:\n raise RuntimeError(\n f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change "\n f"rcParams['pgf.texsystem'] to an available TeX implementation"\n ) from err\n except OSError as err:\n raise RuntimeError(\n f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err\n\n def finalize_latex(latex):\n latex.kill()\n try:\n latex.communicate()\n except RuntimeError:\n latex.wait()\n\n self._finalize_latex = weakref.finalize(\n self, finalize_latex, self.latex)\n # write header with 'pgf_backend_query_start' token\n self._stdin_writeln(self._build_latex_header())\n if expect_reply: # read until 'pgf_backend_query_start' token appears\n self._expect("*pgf_backend_query_start")\n self._expect_prompt()\n\n def get_width_height_descent(self, text, prop):\n """\n Get the width, total height, and descent (in TeX points) for a text\n typeset by the current LaTeX environment.\n """\n return self._get_box_metrics(_escape_and_apply_props(text, prop))\n\n def _get_box_metrics(self, tex):\n """\n Get the width, total height and descent (in TeX points) for a TeX\n command's output in the current LaTeX environment.\n """\n # This method gets wrapped in __init__ for per-instance caching.\n self._stdin_writeln( # Send textbox to TeX & request metrics typeout.\n # \sbox doesn't handle catcode assignments inside its argument,\n # so repeat the assignment of the catcode of "^" and "%" outside.\n r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}"\n r"\typeout{\the\wd0,\the\ht0,\the\dp0}}"\n % tex)\n try:\n answer = self._expect_prompt()\n except LatexError as err:\n # Here and below, use '{}' instead of {!r} to avoid doubling all\n # backslashes.\n raise ValueError("Error measuring {}\nLaTeX Output:\n{}"\n .format(tex, err.latex_output)) from err\n try:\n # Parse metrics from the answer string. Last line is prompt, and\n # next-to-last-line is blank line from \typeout.\n width, height, offset = answer.splitlines()[-3].split(",")\n except Exception as err:\n raise ValueError("Error measuring {}\nLaTeX Output:\n{}"\n .format(tex, answer)) from err\n w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])\n # The height returned from LaTeX goes from base to top;\n # the height Matplotlib expects goes from bottom to top.\n return w, h + o, o\n\n\n@functools.lru_cache(1)\ndef _get_image_inclusion_command():\n man = LatexManager._get_cached_or_new()\n man._stdin_writeln(\n r"\includegraphics[interpolate=true]{%s}"\n # Don't mess with backslashes on Windows.\n % cbook._get_data_path("images/matplotlib.png").as_posix())\n try:\n man._expect_prompt()\n return r"\includegraphics"\n except LatexError:\n # Discard the broken manager.\n LatexManager._get_cached_or_new_impl.cache_clear()\n return r"\pgfimage"\n\n\nclass RendererPgf(RendererBase):\n\n def __init__(self, figure, fh):\n """\n Create a new PGF renderer that translates any drawing instruction\n into text commands to be interpreted in a latex pgfpicture environment.\n\n Attributes\n ----------\n figure : `~matplotlib.figure.Figure`\n Matplotlib figure to initialize height, width and dpi from.\n fh : file-like\n File handle for the output of the drawing commands.\n """\n\n super().__init__()\n self.dpi = figure.dpi\n self.fh = fh\n self.figure = figure\n self.image_counter = 0\n\n def draw_markers(self, gc, marker_path, marker_trans, path, trans,\n rgbFace=None):\n # docstring inherited\n\n _writeln(self.fh, r"\begin{pgfscope}")\n\n # convert from display units to in\n f = 1. / self.dpi\n\n # set style and clip\n self._print_pgf_clip(gc)\n self._print_pgf_path_styles(gc, rgbFace)\n\n # build marker definition\n bl, tr = marker_path.get_extents(marker_trans).get_points()\n coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f\n _writeln(self.fh,\n r"\pgfsys@defobject{currentmarker}"\n r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)\n self._print_pgf_path(None, marker_path, marker_trans)\n self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,\n fill=rgbFace is not None)\n _writeln(self.fh, r"}")\n\n maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.\n clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)\n\n # draw marker for each vertex\n for point, code in path.iter_segments(trans, simplify=False,\n clip=clip):\n x, y = point[0] * f, point[1] * f\n _writeln(self.fh, r"\begin{pgfscope}")\n _writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))\n _writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")\n _writeln(self.fh, r"\end{pgfscope}")\n\n _writeln(self.fh, r"\end{pgfscope}")\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n _writeln(self.fh, r"\begin{pgfscope}")\n # draw the path\n self._print_pgf_clip(gc)\n self._print_pgf_path_styles(gc, rgbFace)\n self._print_pgf_path(gc, path, transform, rgbFace)\n self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,\n fill=rgbFace is not None)\n _writeln(self.fh, r"\end{pgfscope}")\n\n # if present, draw pattern on top\n if gc.get_hatch():\n _writeln(self.fh, r"\begin{pgfscope}")\n self._print_pgf_path_styles(gc, rgbFace)\n\n # combine clip and path for clipping\n self._print_pgf_clip(gc)\n self._print_pgf_path(gc, path, transform, rgbFace)\n _writeln(self.fh, r"\pgfusepath{clip}")\n\n # build pattern definition\n _writeln(self.fh,\n r"\pgfsys@defobject{currentpattern}"\n r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")\n _writeln(self.fh, r"\begin{pgfscope}")\n _writeln(self.fh,\n r"\pgfpathrectangle"\n r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")\n _writeln(self.fh, r"\pgfusepath{clip}")\n scale = mpl.transforms.Affine2D().scale(self.dpi)\n self._print_pgf_path(None, gc.get_hatch_path(), scale)\n self._pgf_path_draw(stroke=True)\n _writeln(self.fh, r"\end{pgfscope}")\n _writeln(self.fh, r"}")\n # repeat pattern, filling the bounding rect of the path\n f = 1. / self.dpi\n (xmin, ymin), (xmax, ymax) = \\n path.get_extents(transform).get_points()\n xmin, xmax = f * xmin, f * xmax\n ymin, ymax = f * ymin, f * ymax\n repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)\n _writeln(self.fh,\n r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))\n for iy in range(repy):\n for ix in range(repx):\n _writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")\n _writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")\n _writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)\n _writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")\n\n _writeln(self.fh, r"\end{pgfscope}")\n\n def _print_pgf_clip(self, gc):\n f = 1. / self.dpi\n # check for clip box\n bbox = gc.get_clip_rectangle()\n if bbox:\n p1, p2 = bbox.get_points()\n w, h = p2 - p1\n coords = p1[0] * f, p1[1] * f, w * f, h * f\n _writeln(self.fh,\n r"\pgfpathrectangle"\n r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"\n % coords)\n _writeln(self.fh, r"\pgfusepath{clip}")\n\n # check for clip path\n clippath, clippath_trans = gc.get_clip_path()\n if clippath is not None:\n self._print_pgf_path(gc, clippath, clippath_trans)\n _writeln(self.fh, r"\pgfusepath{clip}")\n\n def _print_pgf_path_styles(self, gc, rgbFace):\n # cap style\n capstyles = {"butt": r"\pgfsetbuttcap",\n "round": r"\pgfsetroundcap",\n "projecting": r"\pgfsetrectcap"}\n _writeln(self.fh, capstyles[gc.get_capstyle()])\n\n # join style\n joinstyles = {"miter": r"\pgfsetmiterjoin",\n "round": r"\pgfsetroundjoin",\n "bevel": r"\pgfsetbeveljoin"}\n _writeln(self.fh, joinstyles[gc.get_joinstyle()])\n\n # filling\n has_fill = rgbFace is not None\n\n if gc.get_forced_alpha():\n fillopacity = strokeopacity = gc.get_alpha()\n else:\n strokeopacity = gc.get_rgb()[3]\n fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0\n\n if has_fill:\n _writeln(self.fh,\n r"\definecolor{currentfill}{rgb}{%f,%f,%f}"\n % tuple(rgbFace[:3]))\n _writeln(self.fh, r"\pgfsetfillcolor{currentfill}")\n if has_fill and fillopacity != 1.0:\n _writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)\n\n # linewidth and color\n lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt\n stroke_rgba = gc.get_rgb()\n _writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)\n _writeln(self.fh,\n r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"\n % stroke_rgba[:3])\n _writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")\n if strokeopacity != 1.0:\n _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)\n\n # line style\n dash_offset, dash_list = gc.get_dashes()\n if dash_list is None:\n _writeln(self.fh, r"\pgfsetdash{}{0pt}")\n else:\n _writeln(self.fh,\n r"\pgfsetdash{%s}{%fpt}"\n % ("".join(r"{%fpt}" % dash for dash in dash_list),\n dash_offset))\n\n def _print_pgf_path(self, gc, path, transform, rgbFace=None):\n f = 1. / self.dpi\n # check for clip box / ignore clip for filled paths\n bbox = gc.get_clip_rectangle() if gc else None\n maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.\n if bbox and (rgbFace is None):\n p1, p2 = bbox.get_points()\n clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord),\n min(p2[0], maxcoord), min(p2[1], maxcoord))\n else:\n clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)\n # build path\n for points, code in path.iter_segments(transform, clip=clip):\n if code == Path.MOVETO:\n x, y = tuple(points)\n _writeln(self.fh,\n r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %\n (f * x, f * y))\n elif code == Path.CLOSEPOLY:\n _writeln(self.fh, r"\pgfpathclose")\n elif code == Path.LINETO:\n x, y = tuple(points)\n _writeln(self.fh,\n r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %\n (f * x, f * y))\n elif code == Path.CURVE3:\n cx, cy, px, py = tuple(points)\n coords = cx * f, cy * f, px * f, py * f\n _writeln(self.fh,\n r"\pgfpathquadraticcurveto"\n r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"\n % coords)\n elif code == Path.CURVE4:\n c1x, c1y, c2x, c2y, px, py = tuple(points)\n coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f\n _writeln(self.fh,\n r"\pgfpathcurveto"\n r"{\pgfqpoint{%fin}{%fin}}"\n r"{\pgfqpoint{%fin}{%fin}}"\n r"{\pgfqpoint{%fin}{%fin}}"\n % coords)\n\n # apply pgf decorators\n sketch_params = gc.get_sketch_params() if gc else None\n if sketch_params is not None:\n # Only "length" directly maps to "segment length" in PGF's API.\n # PGF uses "amplitude" to pass the combined deviation in both x-\n # and y-direction, while matplotlib only varies the length of the\n # wiggle along the line ("randomness" and "length" parameters)\n # and has a separate "scale" argument for the amplitude.\n # -> Use "randomness" as PRNG seed to allow the user to force the\n # same shape on multiple sketched lines\n scale, length, randomness = sketch_params\n if scale is not None:\n # make matplotlib and PGF rendering visually similar\n length *= 0.5\n scale *= 2\n # PGF guarantees that repeated loading is a no-op\n _writeln(self.fh, r"\usepgfmodule{decorations}")\n _writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}")\n _writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, "\n f"segment length = {(length * f):f}in, "\n f"amplitude = {(scale * f):f}in}}")\n _writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}")\n _writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}")\n\n def _pgf_path_draw(self, stroke=True, fill=False):\n actions = []\n if stroke:\n actions.append("stroke")\n if fill:\n actions.append("fill")\n _writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))\n\n def option_scale_image(self):\n # docstring inherited\n return True\n\n def option_image_nocomposite(self):\n # docstring inherited\n return not mpl.rcParams['image.composite_image']\n\n def draw_image(self, gc, x, y, im, transform=None):\n # docstring inherited\n\n h, w = im.shape[:2]\n if w == 0 or h == 0:\n return\n\n if not os.path.exists(getattr(self.fh, "name", "")):\n raise ValueError(\n "streamed pgf-code does not support raster graphics, consider "\n "using the pgf-to-pdf option")\n\n # save the images to png files\n path = pathlib.Path(self.fh.name)\n fname_img = "%s-img%d.png" % (path.stem, self.image_counter)\n Image.fromarray(im[::-1]).save(path.parent / fname_img)\n self.image_counter += 1\n\n # reference the image in the pgf picture\n _writeln(self.fh, r"\begin{pgfscope}")\n self._print_pgf_clip(gc)\n f = 1. / self.dpi # from display coords to inch\n if transform is None:\n _writeln(self.fh,\n r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))\n w, h = w * f, h * f\n else:\n tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()\n _writeln(self.fh,\n r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %\n (tr1 * f, tr2 * f, tr3 * f, tr4 * f,\n (tr5 + x) * f, (tr6 + y) * f))\n w = h = 1 # scale is already included in the transform\n interp = str(transform is None).lower() # interpolation in PDF reader\n _writeln(self.fh,\n r"\pgftext[left,bottom]"\n r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %\n (_get_image_inclusion_command(),\n interp, w, h, fname_img))\n _writeln(self.fh, r"\end{pgfscope}")\n\n def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):\n # docstring inherited\n self.draw_text(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext)\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n\n # prepare string for tex\n s = _escape_and_apply_props(s, prop)\n\n _writeln(self.fh, r"\begin{pgfscope}")\n self._print_pgf_clip(gc)\n\n alpha = gc.get_alpha()\n if alpha != 1.0:\n _writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)\n _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)\n rgb = tuple(gc.get_rgb())[:3]\n _writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)\n _writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")\n _writeln(self.fh, r"\pgfsetfillcolor{textcolor}")\n s = r"\color{textcolor}" + s\n\n dpi = self.figure.dpi\n text_args = []\n if mtext and (\n (angle == 0 or\n mtext.get_rotation_mode() == "anchor") and\n mtext.get_verticalalignment() != "center_baseline"):\n # if text anchoring can be supported, get the original coordinates\n # and add alignment information\n pos = mtext.get_unitless_position()\n x, y = mtext.get_transform().transform(pos)\n halign = {"left": "left", "right": "right", "center": ""}\n valign = {"top": "top", "bottom": "bottom",\n "baseline": "base", "center": ""}\n text_args.extend([\n f"x={x/dpi:f}in",\n f"y={y/dpi:f}in",\n halign[mtext.get_horizontalalignment()],\n valign[mtext.get_verticalalignment()],\n ])\n else:\n # if not, use the text layout provided by Matplotlib.\n text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")\n\n if angle != 0:\n text_args.append("rotate=%f" % angle)\n\n _writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))\n _writeln(self.fh, r"\end{pgfscope}")\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n # get text metrics in units of latex pt, convert to display units\n w, h, d = (LatexManager._get_cached_or_new()\n .get_width_height_descent(s, prop))\n # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in\n # but having a little bit more space around the text looks better,\n # plus the bounding box reported by LaTeX is VERY narrow\n f = mpl_pt_to_in * self.dpi\n return w * f, h * f, d * f\n\n def flipy(self):\n # docstring inherited\n return False\n\n def get_canvas_width_height(self):\n # docstring inherited\n return (self.figure.get_figwidth() * self.dpi,\n self.figure.get_figheight() * self.dpi)\n\n def points_to_pixels(self, points):\n # docstring inherited\n return points * mpl_pt_to_in * self.dpi\n\n\nclass FigureCanvasPgf(FigureCanvasBase):\n filetypes = {"pgf": "LaTeX PGF picture",\n "pdf": "LaTeX compiled PGF picture",\n "png": "Portable Network Graphics", }\n\n def get_default_filetype(self):\n return 'pdf'\n\n def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None):\n\n header_text = """%% Creator: Matplotlib, PGF backend\n%%\n%% To include the figure in your LaTeX document, write\n%% \\input{<filename>.pgf}\n%%\n%% Make sure the required packages are loaded in your preamble\n%% \\usepackage{pgf}\n%%\n%% Also ensure that all the required font packages are loaded; for instance,\n%% the lmodern package is sometimes necessary when using math font.\n%% \\usepackage{lmodern}\n%%\n%% Figures using additional raster images can only be included by \\input if\n%% they are in the same directory as the main LaTeX file. For loading figures\n%% from other directories you can use the `import` package\n%% \\usepackage{import}\n%%\n%% and then include the figures with\n%% \\import{<path to file>}{<filename>.pgf}\n%%\n"""\n\n # append the preamble used by the backend as a comment for debugging\n header_info_preamble = ["%% Matplotlib used the following preamble"]\n for line in _get_preamble().splitlines():\n header_info_preamble.append("%% " + line)\n header_info_preamble.append("%%")\n header_info_preamble = "\n".join(header_info_preamble)\n\n # get figure size in inch\n w, h = self.figure.get_figwidth(), self.figure.get_figheight()\n dpi = self.figure.dpi\n\n # create pgfpicture environment and write the pgf code\n fh.write(header_text)\n fh.write(header_info_preamble)\n fh.write("\n")\n _writeln(fh, r"\begingroup")\n _writeln(fh, r"\makeatletter")\n _writeln(fh, r"\begin{pgfpicture}")\n _writeln(fh,\n r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"\n % (w, h))\n _writeln(fh, r"\pgfusepath{use as bounding box, clip}")\n renderer = MixedModeRenderer(self.figure, w, h, dpi,\n RendererPgf(self.figure, fh),\n bbox_inches_restore=bbox_inches_restore)\n self.figure.draw(renderer)\n\n # end the pgfpicture environment\n _writeln(fh, r"\end{pgfpicture}")\n _writeln(fh, r"\makeatother")\n _writeln(fh, r"\endgroup")\n\n def print_pgf(self, fname_or_fh, **kwargs):\n """\n Output pgf macros for drawing the figure so it can be included and\n rendered in latex documents.\n """\n with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:\n if not cbook.file_requires_unicode(file):\n file = codecs.getwriter("utf-8")(file)\n self._print_pgf_to_fh(file, **kwargs)\n\n def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):\n """Use LaTeX to compile a pgf generated figure to pdf."""\n w, h = self.figure.get_size_inches()\n\n info_dict = _create_pdf_info_dict('pgf', metadata or {})\n pdfinfo = ','.join(\n _metadata_to_str(k, v) for k, v in info_dict.items())\n\n # print figure to pgf and compile it with latex\n with TemporaryDirectory() as tmpdir:\n tmppath = pathlib.Path(tmpdir)\n self.print_pgf(tmppath / "figure.pgf", **kwargs)\n (tmppath / "figure.tex").write_text(\n "\n".join([\n _DOCUMENTCLASS,\n r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,\n r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"\n % (w, h),\n r"\usepackage{pgf}",\n _get_preamble(),\n r"\begin{document}",\n r"\centering",\n r"\input{figure.pgf}",\n r"\end{document}",\n ]), encoding="utf-8")\n texcommand = mpl.rcParams["pgf.texsystem"]\n cbook._check_and_log_subprocess(\n [texcommand, "-interaction=nonstopmode", "-halt-on-error",\n "figure.tex"], _log, cwd=tmpdir)\n with ((tmppath / "figure.pdf").open("rb") as orig,\n cbook.open_file_cm(fname_or_fh, "wb") as dest):\n shutil.copyfileobj(orig, dest) # copy file contents to target\n\n def print_png(self, fname_or_fh, **kwargs):\n """Use LaTeX to compile a pgf figure to pdf and convert it to png."""\n converter = make_pdf_to_png_converter()\n with TemporaryDirectory() as tmpdir:\n tmppath = pathlib.Path(tmpdir)\n pdf_path = tmppath / "figure.pdf"\n png_path = tmppath / "figure.png"\n self.print_pdf(pdf_path, **kwargs)\n converter(pdf_path, png_path, dpi=self.figure.dpi)\n with (png_path.open("rb") as orig,\n cbook.open_file_cm(fname_or_fh, "wb") as dest):\n shutil.copyfileobj(orig, dest) # copy file contents to target\n\n def get_renderer(self):\n return RendererPgf(self.figure, None)\n\n def draw(self):\n self.figure.draw_without_rendering()\n return super().draw()\n\n\nFigureManagerPgf = FigureManagerBase\n\n\n@_Backend.export\nclass _BackendPgf(_Backend):\n FigureCanvas = FigureCanvasPgf\n\n\nclass PdfPages:\n """\n A multi-page PDF file using the pgf backend\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> # Initialize:\n >>> with PdfPages('foo.pdf') as pdf:\n ... # As many times as you like, create a figure fig and save it:\n ... fig = plt.figure()\n ... pdf.savefig(fig)\n ... # When no figure is specified the current figure is saved\n ... pdf.savefig()\n """\n\n def __init__(self, filename, *, metadata=None):\n """\n Create a new PdfPages object.\n\n Parameters\n ----------\n filename : str or path-like\n Plots using `PdfPages.savefig` will be written to a file at this\n location. Any older file with the same name is overwritten.\n\n metadata : dict, optional\n Information dictionary object (see PDF reference section 10.2.1\n 'Document Information Dictionary'), e.g.:\n ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.\n\n The standard keys are 'Title', 'Author', 'Subject', 'Keywords',\n 'Creator', 'Producer', 'CreationDate', 'ModDate', and\n 'Trapped'. Values have been predefined for 'Creator', 'Producer'\n and 'CreationDate'. They can be removed by setting them to `None`.\n\n Note that some versions of LaTeX engines may ignore the 'Producer'\n key and set it to themselves.\n """\n self._output_name = filename\n self._n_figures = 0\n self._metadata = (metadata or {}).copy()\n self._info_dict = _create_pdf_info_dict('pgf', self._metadata)\n self._file = BytesIO()\n\n def _write_header(self, width_inches, height_inches):\n pdfinfo = ','.join(\n _metadata_to_str(k, v) for k, v in self._info_dict.items())\n latex_header = "\n".join([\n _DOCUMENTCLASS,\n r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,\n r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"\n % (width_inches, height_inches),\n r"\usepackage{pgf}",\n _get_preamble(),\n r"\setlength{\parindent}{0pt}",\n r"\begin{document}%",\n ])\n self._file.write(latex_header.encode('utf-8'))\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n def close(self):\n """\n Finalize this object, running LaTeX in a temporary directory\n and moving the final pdf file to *filename*.\n """\n self._file.write(rb'\end{document}\n')\n if self._n_figures > 0:\n self._run_latex()\n self._file.close()\n\n def _run_latex(self):\n texcommand = mpl.rcParams["pgf.texsystem"]\n with TemporaryDirectory() as tmpdir:\n tex_source = pathlib.Path(tmpdir, "pdf_pages.tex")\n tex_source.write_bytes(self._file.getvalue())\n cbook._check_and_log_subprocess(\n [texcommand, "-interaction=nonstopmode", "-halt-on-error",\n tex_source],\n _log, cwd=tmpdir)\n shutil.move(tex_source.with_suffix(".pdf"), self._output_name)\n\n def savefig(self, figure=None, **kwargs):\n """\n Save a `.Figure` to this file as a new page.\n\n Any other keyword arguments are passed to `~.Figure.savefig`.\n\n Parameters\n ----------\n figure : `.Figure` or int, default: the active figure\n The figure, or index of the figure, that is saved to the file.\n """\n if not isinstance(figure, Figure):\n if figure is None:\n manager = Gcf.get_active()\n else:\n manager = Gcf.get_fig_manager(figure)\n if manager is None:\n raise ValueError(f"No figure {figure}")\n figure = manager.canvas.figure\n\n width, height = figure.get_size_inches()\n if self._n_figures == 0:\n self._write_header(width, height)\n else:\n # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and\n # luatex<0.85; they were renamed to \pagewidth and \pageheight\n # on luatex>=0.85.\n self._file.write(\n rb'\newpage'\n rb'\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%fin'\n rb'\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin'\n b'%%\n' % (width, height)\n )\n figure.savefig(self._file, format="pgf", backend="pgf", **kwargs)\n self._n_figures += 1\n\n def get_pagecount(self):\n """Return the current number of pages in the multipage pdf file."""\n return self._n_figures\n
.venv\Lib\site-packages\matplotlib\backends\backend_pgf.py
backend_pgf.py
Python
39,567
0.95
0.150495
0.113895
node-utils
854
2025-05-31T20:18:43.234789
Apache-2.0
false
f0708ae18df34086397678ba513cf4d6
"""\nA PostScript backend, which can produce both PostScript .ps and .eps.\n"""\n\nimport bisect\nimport codecs\nimport datetime\nfrom enum import Enum\nimport functools\nfrom io import StringIO\nimport itertools\nimport logging\nimport math\nimport os\nimport pathlib\nimport shutil\nimport struct\nfrom tempfile import TemporaryDirectory\nimport textwrap\nimport time\n\nimport fontTools\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib import _api, cbook, _path, _text_helpers\nfrom matplotlib._afm import AFM\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)\nfrom matplotlib.cbook import is_writable_file_like, file_requires_unicode\nfrom matplotlib.font_manager import get_font\nfrom matplotlib.ft2font import LoadFlags\nfrom matplotlib._mathtext_data import uni2type1\nfrom matplotlib.path import Path\nfrom matplotlib.texmanager import TexManager\nfrom matplotlib.transforms import Affine2D\nfrom matplotlib.backends.backend_mixed import MixedModeRenderer\nfrom . import _backend_pdf_ps\n\n\n_log = logging.getLogger(__name__)\ndebugPS = False\n\n\npapersize = {'letter': (8.5, 11),\n 'legal': (8.5, 14),\n 'ledger': (11, 17),\n 'a0': (33.11, 46.81),\n 'a1': (23.39, 33.11),\n 'a2': (16.54, 23.39),\n 'a3': (11.69, 16.54),\n 'a4': (8.27, 11.69),\n 'a5': (5.83, 8.27),\n 'a6': (4.13, 5.83),\n 'a7': (2.91, 4.13),\n 'a8': (2.05, 2.91),\n 'a9': (1.46, 2.05),\n 'a10': (1.02, 1.46),\n 'b0': (40.55, 57.32),\n 'b1': (28.66, 40.55),\n 'b2': (20.27, 28.66),\n 'b3': (14.33, 20.27),\n 'b4': (10.11, 14.33),\n 'b5': (7.16, 10.11),\n 'b6': (5.04, 7.16),\n 'b7': (3.58, 5.04),\n 'b8': (2.51, 3.58),\n 'b9': (1.76, 2.51),\n 'b10': (1.26, 1.76)}\n\n\ndef _nums_to_str(*args, sep=" "):\n return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)\n\n\ndef _move_path_to_path_or_stream(src, dst):\n """\n Move the contents of file at *src* to path-or-filelike *dst*.\n\n If *dst* is a path, the metadata of *src* are *not* copied.\n """\n if is_writable_file_like(dst):\n fh = (open(src, encoding='latin-1')\n if file_requires_unicode(dst)\n else open(src, 'rb'))\n with fh:\n shutil.copyfileobj(fh, dst)\n else:\n shutil.move(src, dst, copy_function=shutil.copyfile)\n\n\ndef _font_to_ps_type3(font_path, chars):\n """\n Subset *chars* from the font at *font_path* into a Type 3 font.\n\n Parameters\n ----------\n font_path : path-like\n Path to the font to be subsetted.\n chars : str\n The characters to include in the subsetted font.\n\n Returns\n -------\n str\n The string representation of a Type 3 font, which can be included\n verbatim into a PostScript file.\n """\n font = get_font(font_path, hinting_factor=1)\n glyph_ids = [font.get_char_index(c) for c in chars]\n\n preamble = """\\n%!PS-Adobe-3.0 Resource-Font\n%%Creator: Converted from TrueType to Type 3 by Matplotlib.\n10 dict begin\n/FontName /{font_name} def\n/PaintType 0 def\n/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def\n/FontBBox [{bbox}] def\n/FontType 3 def\n/Encoding [{encoding}] def\n/CharStrings {num_glyphs} dict dup begin\n/.notdef 0 def\n""".format(font_name=font.postscript_name,\n inv_units_per_em=1 / font.units_per_EM,\n bbox=" ".join(map(str, font.bbox)),\n encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"\n for glyph_id in glyph_ids),\n num_glyphs=len(glyph_ids) + 1)\n postamble = """\nend readonly def\n\n/BuildGlyph {\n exch begin\n CharStrings exch\n 2 copy known not {pop /.notdef} if\n true 3 1 roll get exec\n end\n} _d\n\n/BuildChar {\n 1 index /Encoding get exch get\n 1 index /BuildGlyph get exec\n} _d\n\nFontName currentdict end definefont pop\n"""\n\n entries = []\n for glyph_id in glyph_ids:\n g = font.load_glyph(glyph_id, LoadFlags.NO_SCALE)\n v, c = font.get_path()\n entries.append(\n "/%(name)s{%(bbox)s sc\n" % {\n "name": font.get_glyph_name(glyph_id),\n "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),\n }\n + _path.convert_to_string(\n # Convert back to TrueType's internal units (1/64's).\n # (Other dimensions are already in these units.)\n Path(v * 64, c), None, None, False, None, 0,\n # No code for quad Beziers triggers auto-conversion to cubics.\n # Drop intermediate closepolys (relying on the outline\n # decomposer always explicitly moving to the closing point\n # first).\n [b"m", b"l", b"", b"c", b""], True).decode("ascii")\n + "ce} _d"\n )\n\n return preamble + "\n".join(entries) + postamble\n\n\ndef _font_to_ps_type42(font_path, chars, fh):\n """\n Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.\n\n Parameters\n ----------\n font_path : path-like\n Path to the font to be subsetted.\n chars : str\n The characters to include in the subsetted font.\n fh : file-like\n Where to write the font.\n """\n subset_str = ''.join(chr(c) for c in chars)\n _log.debug("SUBSET %s characters: %s", font_path, subset_str)\n try:\n kw = {}\n # fix this once we support loading more fonts from a collection\n # https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541\n if font_path.endswith('.ttc'):\n kw['fontNumber'] = 0\n with (fontTools.ttLib.TTFont(font_path, **kw) as font,\n _backend_pdf_ps.get_glyphs_subset(font_path, subset_str) as subset):\n fontdata = _backend_pdf_ps.font_as_file(subset).getvalue()\n _log.debug(\n "SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,\n len(fontdata)\n )\n fh.write(_serialize_type42(font, subset, fontdata))\n except RuntimeError:\n _log.warning(\n "The PostScript backend does not currently support the selected font (%s).",\n font_path)\n raise\n\n\ndef _serialize_type42(font, subset, fontdata):\n """\n Output a PostScript Type-42 format representation of font\n\n Parameters\n ----------\n font : fontTools.ttLib.ttFont.TTFont\n The original font object\n subset : fontTools.ttLib.ttFont.TTFont\n The subset font object\n fontdata : bytes\n The raw font data in TTF format\n\n Returns\n -------\n str\n The Type-42 formatted font\n """\n version, breakpoints = _version_and_breakpoints(font.get('loca'), fontdata)\n post = font['post']\n name = font['name']\n chars = _generate_charstrings(subset)\n sfnts = _generate_sfnts(fontdata, subset, breakpoints)\n return textwrap.dedent(f"""\n %%!PS-TrueTypeFont-{version[0]}.{version[1]}-{font['head'].fontRevision:.7f}\n 10 dict begin\n /FontType 42 def\n /FontMatrix [1 0 0 1 0 0] def\n /FontName /{name.getDebugName(6)} def\n /FontInfo 7 dict dup begin\n /FullName ({name.getDebugName(4)}) def\n /FamilyName ({name.getDebugName(1)}) def\n /Version ({name.getDebugName(5)}) def\n /ItalicAngle {post.italicAngle} def\n /isFixedPitch {'true' if post.isFixedPitch else 'false'} def\n /UnderlinePosition {post.underlinePosition} def\n /UnderlineThickness {post.underlineThickness} def\n end readonly def\n /Encoding StandardEncoding def\n /FontBBox [{_nums_to_str(*_bounds(font))}] def\n /PaintType 0 def\n /CIDMap 0 def\n {chars}\n {sfnts}\n FontName currentdict end definefont pop\n """)\n\n\ndef _version_and_breakpoints(loca, fontdata):\n """\n Read the version number of the font and determine sfnts breakpoints.\n\n When a TrueType font file is written as a Type 42 font, it has to be\n broken into substrings of at most 65535 bytes. These substrings must\n begin at font table boundaries or glyph boundaries in the glyf table.\n This function determines all possible breakpoints and it is the caller's\n responsibility to do the splitting.\n\n Helper function for _font_to_ps_type42.\n\n Parameters\n ----------\n loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None\n The loca table of the font if available\n fontdata : bytes\n The raw data of the font\n\n Returns\n -------\n version : tuple[int, int]\n A 2-tuple of the major version number and minor version number.\n breakpoints : list[int]\n The breakpoints is a sorted list of offsets into fontdata; if loca is not\n available, just the table boundaries.\n """\n v1, v2, numTables = struct.unpack('>3h', fontdata[:6])\n version = (v1, v2)\n\n tables = {}\n for i in range(numTables):\n tag, _, offset, _ = struct.unpack('>4sIII', fontdata[12 + i*16:12 + (i+1)*16])\n tables[tag.decode('ascii')] = offset\n if loca is not None:\n glyf_breakpoints = {tables['glyf'] + offset for offset in loca.locations[:-1]}\n else:\n glyf_breakpoints = set()\n breakpoints = sorted({*tables.values(), *glyf_breakpoints, len(fontdata)})\n\n return version, breakpoints\n\n\ndef _bounds(font):\n """\n Compute the font bounding box, as if all glyphs were written\n at the same start position.\n\n Helper function for _font_to_ps_type42.\n\n Parameters\n ----------\n font : fontTools.ttLib.ttFont.TTFont\n The font\n\n Returns\n -------\n tuple\n (xMin, yMin, xMax, yMax) of the combined bounding box\n of all the glyphs in the font\n """\n gs = font.getGlyphSet(False)\n pen = fontTools.pens.boundsPen.BoundsPen(gs)\n for name in gs.keys():\n gs[name].draw(pen)\n return pen.bounds or (0, 0, 0, 0)\n\n\ndef _generate_charstrings(font):\n """\n Transform font glyphs into CharStrings\n\n Helper function for _font_to_ps_type42.\n\n Parameters\n ----------\n font : fontTools.ttLib.ttFont.TTFont\n The font\n\n Returns\n -------\n str\n A definition of the CharStrings dictionary in PostScript\n """\n go = font.getGlyphOrder()\n s = f'/CharStrings {len(go)} dict dup begin\n'\n for i, name in enumerate(go):\n s += f'/{name} {i} def\n'\n s += 'end readonly def'\n return s\n\n\ndef _generate_sfnts(fontdata, font, breakpoints):\n """\n Transform font data into PostScript sfnts format.\n\n Helper function for _font_to_ps_type42.\n\n Parameters\n ----------\n fontdata : bytes\n The raw data of the font\n font : fontTools.ttLib.ttFont.TTFont\n The fontTools font object\n breakpoints : list\n Sorted offsets of possible breakpoints\n\n Returns\n -------\n str\n The sfnts array for the font definition, consisting\n of hex-encoded strings in PostScript format\n """\n s = '/sfnts['\n pos = 0\n while pos < len(fontdata):\n i = bisect.bisect_left(breakpoints, pos + 65534)\n newpos = breakpoints[i-1]\n if newpos <= pos:\n # have to accept a larger string\n newpos = breakpoints[-1]\n s += f'<{fontdata[pos:newpos].hex()}00>' # Always NUL terminate.\n pos = newpos\n s += ']def'\n return '\n'.join(s[i:i+100] for i in range(0, len(s), 100))\n\n\ndef _log_if_debug_on(meth):\n """\n Wrap `RendererPS` method *meth* to emit a PS comment with the method name,\n if the global flag `debugPS` is set.\n """\n @functools.wraps(meth)\n def wrapper(self, *args, **kwargs):\n if debugPS:\n self._pswriter.write(f"% {meth.__name__}\n")\n return meth(self, *args, **kwargs)\n\n return wrapper\n\n\nclass RendererPS(_backend_pdf_ps.RendererPDFPSBase):\n """\n The renderer handles all the drawing primitives using a graphics\n context instance that controls the colors/styles.\n """\n\n _afm_font_dir = cbook._get_data_path("fonts/afm")\n _use_afm_rc_name = "ps.useafm"\n\n def __init__(self, width, height, pswriter, imagedpi=72):\n # Although postscript itself is dpi independent, we need to inform the\n # image code about a requested dpi to generate high resolution images\n # and them scale them before embedding them.\n super().__init__(width, height)\n self._pswriter = pswriter\n if mpl.rcParams['text.usetex']:\n self.textcnt = 0\n self.psfrag = []\n self.imagedpi = imagedpi\n\n # current renderer state (None=uninitialised)\n self.color = None\n self.linewidth = None\n self.linejoin = None\n self.linecap = None\n self.linedash = None\n self.fontname = None\n self.fontsize = None\n self._hatches = {}\n self.image_magnification = imagedpi / 72\n self._clip_paths = {}\n self._path_collection_id = 0\n\n self._character_tracker = _backend_pdf_ps.CharacterTracker()\n self._logwarn_once = functools.cache(_log.warning)\n\n def _is_transparent(self, rgb_or_rgba):\n if rgb_or_rgba is None:\n return True # Consistent with rgbFace semantics.\n elif len(rgb_or_rgba) == 4:\n if rgb_or_rgba[3] == 0:\n return True\n if rgb_or_rgba[3] != 1:\n self._logwarn_once(\n "The PostScript backend does not support transparency; "\n "partially transparent artists will be rendered opaque.")\n return False\n else: # len() == 3.\n return False\n\n def set_color(self, r, g, b, store=True):\n if (r, g, b) != self.color:\n self._pswriter.write(f"{_nums_to_str(r)} setgray\n"\n if r == g == b else\n f"{_nums_to_str(r, g, b)} setrgbcolor\n")\n if store:\n self.color = (r, g, b)\n\n def set_linewidth(self, linewidth, store=True):\n linewidth = float(linewidth)\n if linewidth != self.linewidth:\n self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")\n if store:\n self.linewidth = linewidth\n\n @staticmethod\n def _linejoin_cmd(linejoin):\n # Support for directly passing integer values is for backcompat.\n linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[\n linejoin]\n return f"{linejoin:d} setlinejoin\n"\n\n def set_linejoin(self, linejoin, store=True):\n if linejoin != self.linejoin:\n self._pswriter.write(self._linejoin_cmd(linejoin))\n if store:\n self.linejoin = linejoin\n\n @staticmethod\n def _linecap_cmd(linecap):\n # Support for directly passing integer values is for backcompat.\n linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[\n linecap]\n return f"{linecap:d} setlinecap\n"\n\n def set_linecap(self, linecap, store=True):\n if linecap != self.linecap:\n self._pswriter.write(self._linecap_cmd(linecap))\n if store:\n self.linecap = linecap\n\n def set_linedash(self, offset, seq, store=True):\n if self.linedash is not None:\n oldo, oldseq = self.linedash\n if np.array_equal(seq, oldseq) and oldo == offset:\n return\n\n self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"\n if seq is not None and len(seq) else\n "[] 0 setdash\n")\n if store:\n self.linedash = (offset, seq)\n\n def set_font(self, fontname, fontsize, store=True):\n if (fontname, fontsize) != (self.fontname, self.fontsize):\n self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")\n if store:\n self.fontname = fontname\n self.fontsize = fontsize\n\n def create_hatch(self, hatch, linewidth):\n sidelen = 72\n if hatch in self._hatches:\n return self._hatches[hatch]\n name = 'H%d' % len(self._hatches)\n pageheight = self.height * 72\n self._pswriter.write(f"""\\n << /PatternType 1\n /PaintType 2\n /TilingType 2\n /BBox[0 0 {sidelen:d} {sidelen:d}]\n /XStep {sidelen:d}\n /YStep {sidelen:d}\n\n /PaintProc {{\n pop\n {linewidth:g} setlinewidth\n{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}\n gsave\n fill\n grestore\n stroke\n }} bind\n >>\n matrix\n 0 {pageheight:g} translate\n makepattern\n /{name} exch def\n""")\n self._hatches[hatch] = name\n return name\n\n def get_image_magnification(self):\n """\n Get the factor by which to magnify images passed to draw_image.\n Allows a backend to have images at a different resolution to other\n artists.\n """\n return self.image_magnification\n\n def _convert_path(self, path, transform, clip=False, simplify=None):\n if clip:\n clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)\n else:\n clip = None\n return _path.convert_to_string(\n path, transform, clip, simplify, None,\n 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")\n\n def _get_clip_cmd(self, gc):\n clip = []\n rect = gc.get_clip_rectangle()\n if rect is not None:\n clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")\n path, trf = gc.get_clip_path()\n if path is not None:\n key = (path, id(trf))\n custom_clip_cmd = self._clip_paths.get(key)\n if custom_clip_cmd is None:\n custom_clip_cmd = "c%d" % len(self._clip_paths)\n self._pswriter.write(f"""\\n/{custom_clip_cmd} {{\n{self._convert_path(path, trf, simplify=False)}\nclip\nnewpath\n}} bind def\n""")\n self._clip_paths[key] = custom_clip_cmd\n clip.append(f"{custom_clip_cmd}\n")\n return "".join(clip)\n\n @_log_if_debug_on\n def draw_image(self, gc, x, y, im, transform=None):\n # docstring inherited\n\n h, w = im.shape[:2]\n imagecmd = "false 3 colorimage"\n data = im[::-1, :, :3] # Vertically flipped rgb values.\n hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.\n\n if transform is None:\n matrix = "1 0 0 1 0 0"\n xscale = w / self.image_magnification\n yscale = h / self.image_magnification\n else:\n matrix = " ".join(map(str, transform.frozen().to_values()))\n xscale = 1.0\n yscale = 1.0\n\n self._pswriter.write(f"""\\ngsave\n{self._get_clip_cmd(gc)}\n{x:g} {y:g} translate\n[{matrix}] concat\n{xscale:g} {yscale:g} scale\n/DataString {w:d} string def\n{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]\n{{\ncurrentfile DataString readhexstring pop\n}} bind {imagecmd}\n{hexdata}\ngrestore\n""")\n\n @_log_if_debug_on\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n clip = rgbFace is None and gc.get_hatch_path() is None\n simplify = path.should_simplify and clip\n ps = self._convert_path(path, transform, clip=clip, simplify=simplify)\n self._draw_ps(ps, gc, rgbFace)\n\n @_log_if_debug_on\n def draw_markers(\n self, gc, marker_path, marker_trans, path, trans, rgbFace=None):\n # docstring inherited\n\n ps_color = (\n None\n if self._is_transparent(rgbFace)\n else f'{_nums_to_str(rgbFace[0])} setgray'\n if rgbFace[0] == rgbFace[1] == rgbFace[2]\n else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')\n\n # construct the generic marker command:\n\n # don't want the translate to be global\n ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']\n\n lw = gc.get_linewidth()\n alpha = (gc.get_alpha()\n if gc.get_forced_alpha() or len(gc.get_rgb()) == 3\n else gc.get_rgb()[3])\n stroke = lw > 0 and alpha > 0\n if stroke:\n ps_cmd.append('%.1f setlinewidth' % lw)\n ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))\n ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))\n\n ps_cmd.append(self._convert_path(marker_path, marker_trans,\n simplify=False))\n\n if rgbFace:\n if stroke:\n ps_cmd.append('gsave')\n if ps_color:\n ps_cmd.extend([ps_color, 'fill'])\n if stroke:\n ps_cmd.append('grestore')\n\n if stroke:\n ps_cmd.append('stroke')\n ps_cmd.extend(['grestore', '} bind def'])\n\n for vertices, code in path.iter_segments(\n trans,\n clip=(0, 0, self.width*72, self.height*72),\n simplify=False):\n if len(vertices):\n x, y = vertices[-2:]\n ps_cmd.append(f"{x:g} {y:g} o")\n\n ps = '\n'.join(ps_cmd)\n self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)\n\n @_log_if_debug_on\n def draw_path_collection(self, gc, master_transform, paths, all_transforms,\n offsets, offset_trans, facecolors, edgecolors,\n linewidths, linestyles, antialiaseds, urls,\n offset_position):\n # Is the optimization worth it? Rough calculation:\n # cost of emitting a path in-line is\n # (len_path + 2) * uses_per_path\n # cost of definition+use is\n # (len_path + 3) + 3 * uses_per_path\n len_path = len(paths[0].vertices) if len(paths) > 0 else 0\n uses_per_path = self._iter_collection_uses_per_path(\n paths, all_transforms, offsets, facecolors, edgecolors)\n should_do_optimization = \\n len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path\n if not should_do_optimization:\n return RendererBase.draw_path_collection(\n self, gc, master_transform, paths, all_transforms,\n offsets, offset_trans, facecolors, edgecolors,\n linewidths, linestyles, antialiaseds, urls,\n offset_position)\n\n path_codes = []\n for i, (path, transform) in enumerate(self._iter_collection_raw_paths(\n master_transform, paths, all_transforms)):\n name = 'p%d_%d' % (self._path_collection_id, i)\n path_bytes = self._convert_path(path, transform, simplify=False)\n self._pswriter.write(f"""\\n/{name} {{\nnewpath\ntranslate\n{path_bytes}\n}} bind def\n""")\n path_codes.append(name)\n\n for xo, yo, path_id, gc0, rgbFace in self._iter_collection(\n gc, path_codes, offsets, offset_trans,\n facecolors, edgecolors, linewidths, linestyles,\n antialiaseds, urls, offset_position):\n ps = f"{xo:g} {yo:g} {path_id}"\n self._draw_ps(ps, gc0, rgbFace)\n\n self._path_collection_id += 1\n\n @_log_if_debug_on\n def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):\n # docstring inherited\n if self._is_transparent(gc.get_rgb()):\n return # Special handling for fully transparent.\n\n if not hasattr(self, "psfrag"):\n self._logwarn_once(\n "The PS backend determines usetex status solely based on "\n "rcParams['text.usetex'] and does not support having "\n "usetex=True only for some elements; this element will thus "\n "be rendered as if usetex=False.")\n self.draw_text(gc, x, y, s, prop, angle, False, mtext)\n return\n\n w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")\n fontsize = prop.get_size_in_points()\n thetext = 'psmarker%d' % self.textcnt\n color = _nums_to_str(*gc.get_rgb()[:3], sep=',')\n fontcmd = {'sans-serif': r'{\sffamily %s}',\n 'monospace': r'{\ttfamily %s}'}.get(\n mpl.rcParams['font.family'][0], r'{\rmfamily %s}')\n s = fontcmd % s\n tex = r'\color[rgb]{%s} %s' % (color, s)\n\n # Stick to bottom-left alignment, so subtract descent from the text-normal\n # direction since text is normally positioned by its baseline.\n rangle = np.radians(angle + 90)\n pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))\n self.psfrag.append(\n r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (\n thetext, angle, fontsize, fontsize*1.25, tex))\n\n self._pswriter.write(f"""\\ngsave\n{pos} moveto\n({thetext})\nshow\ngrestore\n""")\n self.textcnt += 1\n\n @_log_if_debug_on\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n\n if self._is_transparent(gc.get_rgb()):\n return # Special handling for fully transparent.\n\n if ismath == 'TeX':\n return self.draw_tex(gc, x, y, s, prop, angle)\n\n if ismath:\n return self.draw_mathtext(gc, x, y, s, prop, angle)\n\n stream = [] # list of (ps_name, x, char_name)\n\n if mpl.rcParams['ps.useafm']:\n font = self._get_font_afm(prop)\n ps_name = (font.postscript_name.encode("ascii", "replace")\n .decode("ascii"))\n scale = 0.001 * prop.get_size_in_points()\n thisx = 0\n last_name = None # kerns returns 0 for None.\n for c in s:\n name = uni2type1.get(ord(c), f"uni{ord(c):04X}")\n try:\n width = font.get_width_from_char_name(name)\n except KeyError:\n name = 'question'\n width = font.get_width_char('?')\n kern = font.get_kern_dist_from_name(last_name, name)\n last_name = name\n thisx += kern * scale\n stream.append((ps_name, thisx, name))\n thisx += width * scale\n\n else:\n font = self._get_font_ttf(prop)\n self._character_tracker.track(font, s)\n for item in _text_helpers.layout(s, font):\n ps_name = (item.ft_object.postscript_name\n .encode("ascii", "replace").decode("ascii"))\n glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)\n stream.append((ps_name, item.x, glyph_name))\n self.set_color(*gc.get_rgb())\n\n for ps_name, group in itertools. \\n groupby(stream, lambda entry: entry[0]):\n self.set_font(ps_name, prop.get_size_in_points(), False)\n thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"\n for _, x, name in group)\n self._pswriter.write(f"""\\ngsave\n{self._get_clip_cmd(gc)}\n{x:g} {y:g} translate\n{angle:g} rotate\n{thetext}\ngrestore\n""")\n\n @_log_if_debug_on\n def draw_mathtext(self, gc, x, y, s, prop, angle):\n """Draw the math text using matplotlib.mathtext."""\n width, height, descent, glyphs, rects = \\n self._text2path.mathtext_parser.parse(s, 72, prop)\n self.set_color(*gc.get_rgb())\n self._pswriter.write(\n f"gsave\n"\n f"{x:g} {y:g} translate\n"\n f"{angle:g} rotate\n")\n lastfont = None\n for font, fontsize, num, ox, oy in glyphs:\n self._character_tracker.track_glyph(font, num)\n if (font.postscript_name, fontsize) != lastfont:\n lastfont = font.postscript_name, fontsize\n self._pswriter.write(\n f"/{font.postscript_name} {fontsize} selectfont\n")\n glyph_name = (\n font.get_name_char(chr(num)) if isinstance(font, AFM) else\n font.get_glyph_name(font.get_char_index(num)))\n self._pswriter.write(\n f"{ox:g} {oy:g} moveto\n"\n f"/{glyph_name} glyphshow\n")\n for ox, oy, w, h in rects:\n self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")\n self._pswriter.write("grestore\n")\n\n @_log_if_debug_on\n def draw_gouraud_triangles(self, gc, points, colors, trans):\n assert len(points) == len(colors)\n if len(points) == 0:\n return\n assert points.ndim == 3\n assert points.shape[1] == 3\n assert points.shape[2] == 2\n assert colors.ndim == 3\n assert colors.shape[1] == 3\n assert colors.shape[2] == 4\n\n shape = points.shape\n flat_points = points.reshape((shape[0] * shape[1], 2))\n flat_points = trans.transform(flat_points)\n flat_colors = colors.reshape((shape[0] * shape[1], 4))\n points_min = np.min(flat_points, axis=0) - (1 << 12)\n points_max = np.max(flat_points, axis=0) + (1 << 12)\n factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))\n\n xmin, ymin = points_min\n xmax, ymax = points_max\n\n data = np.empty(\n shape[0] * shape[1],\n dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])\n data['flags'] = 0\n data['points'] = (flat_points - points_min) * factor\n data['colors'] = flat_colors[:, :3] * 255.0\n hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.\n\n self._pswriter.write(f"""\\ngsave\n<< /ShadingType 4\n /ColorSpace [/DeviceRGB]\n /BitsPerCoordinate 32\n /BitsPerComponent 8\n /BitsPerFlag 8\n /AntiAlias true\n /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]\n /DataSource <\n{hexdata}\n>\n>>\nshfill\ngrestore\n""")\n\n def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):\n """\n Emit the PostScript snippet *ps* with all the attributes from *gc*\n applied. *ps* must consist of PostScript commands to construct a path.\n\n The *fill* and/or *stroke* kwargs can be set to False if the *ps*\n string already includes filling and/or stroking, in which case\n `_draw_ps` is just supplying properties and clipping.\n """\n write = self._pswriter.write\n mightstroke = (gc.get_linewidth() > 0\n and not self._is_transparent(gc.get_rgb()))\n if not mightstroke:\n stroke = False\n if self._is_transparent(rgbFace):\n fill = False\n hatch = gc.get_hatch()\n\n if mightstroke:\n self.set_linewidth(gc.get_linewidth())\n self.set_linejoin(gc.get_joinstyle())\n self.set_linecap(gc.get_capstyle())\n self.set_linedash(*gc.get_dashes())\n if mightstroke or hatch:\n self.set_color(*gc.get_rgb()[:3])\n write('gsave\n')\n\n write(self._get_clip_cmd(gc))\n\n write(ps.strip())\n write("\n")\n\n if fill:\n if stroke or hatch:\n write("gsave\n")\n self.set_color(*rgbFace[:3], store=False)\n write("fill\n")\n if stroke or hatch:\n write("grestore\n")\n\n if hatch:\n hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth())\n write("gsave\n")\n write(_nums_to_str(*gc.get_hatch_color()[:3]))\n write(f" {hatch_name} setpattern fill grestore\n")\n\n if stroke:\n write("stroke\n")\n\n write("grestore\n")\n\n\nclass _Orientation(Enum):\n portrait, landscape = range(2)\n\n def swap_if_landscape(self, shape):\n return shape[::-1] if self.name == "landscape" else shape\n\n\nclass FigureCanvasPS(FigureCanvasBase):\n fixed_dpi = 72\n filetypes = {'ps': 'Postscript',\n 'eps': 'Encapsulated Postscript'}\n\n def get_default_filetype(self):\n return 'ps'\n\n def _print_ps(\n self, fmt, outfile, *,\n metadata=None, papertype=None, orientation='portrait',\n bbox_inches_restore=None, **kwargs):\n\n dpi = self.figure.dpi\n self.figure.dpi = 72 # Override the dpi kwarg\n\n dsc_comments = {}\n if isinstance(outfile, (str, os.PathLike)):\n filename = pathlib.Path(outfile).name\n dsc_comments["Title"] = \\n filename.encode("ascii", "replace").decode("ascii")\n dsc_comments["Creator"] = (metadata or {}).get(\n "Creator",\n f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")\n # See https://reproducible-builds.org/specs/source-date-epoch/\n source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")\n dsc_comments["CreationDate"] = (\n datetime.datetime.fromtimestamp(\n int(source_date_epoch),\n datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")\n if source_date_epoch\n else time.ctime())\n dsc_comments = "\n".join(\n f"%%{k}: {v}" for k, v in dsc_comments.items())\n\n if papertype is None:\n papertype = mpl.rcParams['ps.papersize']\n papertype = papertype.lower()\n _api.check_in_list(['figure', *papersize], papertype=papertype)\n\n orientation = _api.check_getitem(\n _Orientation, orientation=orientation.lower())\n\n printer = (self._print_figure_tex\n if mpl.rcParams['text.usetex'] else\n self._print_figure)\n printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,\n orientation=orientation, papertype=papertype,\n bbox_inches_restore=bbox_inches_restore, **kwargs)\n\n def _print_figure(\n self, fmt, outfile, *,\n dpi, dsc_comments, orientation, papertype,\n bbox_inches_restore=None):\n """\n Render the figure to a filesystem path or a file-like object.\n\n Parameters are as for `.print_figure`, except that *dsc_comments* is a\n string containing Document Structuring Convention comments,\n generated from the *metadata* parameter to `.print_figure`.\n """\n is_eps = fmt == 'eps'\n if not (isinstance(outfile, (str, os.PathLike))\n or is_writable_file_like(outfile)):\n raise ValueError("outfile must be a path or a file-like object")\n\n # find the appropriate papertype\n width, height = self.figure.get_size_inches()\n if is_eps or papertype == 'figure':\n paper_width, paper_height = width, height\n else:\n paper_width, paper_height = orientation.swap_if_landscape(\n papersize[papertype])\n\n # center the figure on the paper\n xo = 72 * 0.5 * (paper_width - width)\n yo = 72 * 0.5 * (paper_height - height)\n\n llx = xo\n lly = yo\n urx = llx + self.figure.bbox.width\n ury = lly + self.figure.bbox.height\n rotation = 0\n if orientation is _Orientation.landscape:\n llx, lly, urx, ury = lly, llx, ury, urx\n xo, yo = 72 * paper_height - yo, xo\n rotation = 90\n bbox = (llx, lly, urx, ury)\n\n self._pswriter = StringIO()\n\n # mixed mode rendering\n ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)\n renderer = MixedModeRenderer(\n self.figure, width, height, dpi, ps_renderer,\n bbox_inches_restore=bbox_inches_restore)\n\n self.figure.draw(renderer)\n\n def print_figure_impl(fh):\n # write the PostScript headers\n if is_eps:\n print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)\n else:\n print("%!PS-Adobe-3.0", file=fh)\n if papertype != 'figure':\n print(f"%%DocumentPaperSizes: {papertype}", file=fh)\n print("%%Pages: 1", file=fh)\n print(f"%%LanguageLevel: 3\n"\n f"{dsc_comments}\n"\n f"%%Orientation: {orientation.name}\n"\n f"{_get_bbox_header(bbox)}\n"\n f"%%EndComments\n",\n end="", file=fh)\n\n Ndict = len(_psDefs)\n print("%%BeginProlog", file=fh)\n if not mpl.rcParams['ps.useafm']:\n Ndict += len(ps_renderer._character_tracker.used)\n print("/mpldict %d dict def" % Ndict, file=fh)\n print("mpldict begin", file=fh)\n print("\n".join(_psDefs), file=fh)\n if not mpl.rcParams['ps.useafm']:\n for font_path, chars \\n in ps_renderer._character_tracker.used.items():\n if not chars:\n continue\n fonttype = mpl.rcParams['ps.fonttype']\n # Can't use more than 255 chars from a single Type 3 font.\n if len(chars) > 255:\n fonttype = 42\n fh.flush()\n if fonttype == 3:\n fh.write(_font_to_ps_type3(font_path, chars))\n else: # Type 42 only.\n _font_to_ps_type42(font_path, chars, fh)\n print("end", file=fh)\n print("%%EndProlog", file=fh)\n\n if not is_eps:\n print("%%Page: 1 1", file=fh)\n print("mpldict begin", file=fh)\n\n print("%s translate" % _nums_to_str(xo, yo), file=fh)\n if rotation:\n print("%d rotate" % rotation, file=fh)\n print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)\n\n # write the figure\n print(self._pswriter.getvalue(), file=fh)\n\n # write the trailer\n print("end", file=fh)\n print("showpage", file=fh)\n if not is_eps:\n print("%%EOF", file=fh)\n fh.flush()\n\n if mpl.rcParams['ps.usedistiller']:\n # We are going to use an external program to process the output.\n # Write to a temporary file.\n with TemporaryDirectory() as tmpdir:\n tmpfile = os.path.join(tmpdir, "tmp.ps")\n with open(tmpfile, 'w', encoding='latin-1') as fh:\n print_figure_impl(fh)\n if mpl.rcParams['ps.usedistiller'] == 'ghostscript':\n _try_distill(gs_distill,\n tmpfile, is_eps, ptype=papertype, bbox=bbox)\n elif mpl.rcParams['ps.usedistiller'] == 'xpdf':\n _try_distill(xpdf_distill,\n tmpfile, is_eps, ptype=papertype, bbox=bbox)\n _move_path_to_path_or_stream(tmpfile, outfile)\n\n else: # Write directly to outfile.\n with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:\n if not file_requires_unicode(file):\n file = codecs.getwriter("latin-1")(file)\n print_figure_impl(file)\n\n def _print_figure_tex(\n self, fmt, outfile, *,\n dpi, dsc_comments, orientation, papertype,\n bbox_inches_restore=None):\n """\n If :rc:`text.usetex` is True, a temporary pair of tex/eps files\n are created to allow tex to manage the text layout via the PSFrags\n package. These files are processed to yield the final ps or eps file.\n\n The rest of the behavior is as for `._print_figure`.\n """\n is_eps = fmt == 'eps'\n\n width, height = self.figure.get_size_inches()\n xo = 0\n yo = 0\n\n llx = xo\n lly = yo\n urx = llx + self.figure.bbox.width\n ury = lly + self.figure.bbox.height\n bbox = (llx, lly, urx, ury)\n\n self._pswriter = StringIO()\n\n # mixed mode rendering\n ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)\n renderer = MixedModeRenderer(self.figure,\n width, height, dpi, ps_renderer,\n bbox_inches_restore=bbox_inches_restore)\n\n self.figure.draw(renderer)\n\n # write to a temp file, we'll move it to outfile when done\n with TemporaryDirectory() as tmpdir:\n tmppath = pathlib.Path(tmpdir, "tmp.ps")\n tmppath.write_text(\n f"""\\n%!PS-Adobe-3.0 EPSF-3.0\n%%LanguageLevel: 3\n{dsc_comments}\n{_get_bbox_header(bbox)}\n%%EndComments\n%%BeginProlog\n/mpldict {len(_psDefs)} dict def\nmpldict begin\n{"".join(_psDefs)}\nend\n%%EndProlog\nmpldict begin\n{_nums_to_str(xo, yo)} translate\n0 0 {_nums_to_str(width*72, height*72)} rectclip\n{self._pswriter.getvalue()}\nend\nshowpage\n""",\n encoding="latin-1")\n\n if orientation is _Orientation.landscape: # now, ready to rotate\n width, height = height, width\n bbox = (lly, llx, ury, urx)\n\n # set the paper size to the figure size if is_eps. The\n # resulting ps file has the given size with correct bounding\n # box so that there is no need to call 'pstoeps'\n if is_eps or papertype == 'figure':\n paper_width, paper_height = orientation.swap_if_landscape(\n self.figure.get_size_inches())\n else:\n paper_width, paper_height = papersize[papertype]\n\n psfrag_rotated = _convert_psfrags(\n tmppath, ps_renderer.psfrag, paper_width, paper_height,\n orientation.name)\n\n if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'\n or mpl.rcParams['text.usetex']):\n _try_distill(gs_distill,\n tmppath, is_eps, ptype=papertype, bbox=bbox,\n rotated=psfrag_rotated)\n elif mpl.rcParams['ps.usedistiller'] == 'xpdf':\n _try_distill(xpdf_distill,\n tmppath, is_eps, ptype=papertype, bbox=bbox,\n rotated=psfrag_rotated)\n\n _move_path_to_path_or_stream(tmppath, outfile)\n\n print_ps = functools.partialmethod(_print_ps, "ps")\n print_eps = functools.partialmethod(_print_ps, "eps")\n\n def draw(self):\n self.figure.draw_without_rendering()\n return super().draw()\n\n\ndef _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):\n """\n When we want to use the LaTeX backend with postscript, we write PSFrag tags\n to a temporary postscript file, each one marking a position for LaTeX to\n render some text. convert_psfrags generates a LaTeX document containing the\n commands to convert those tags to text. LaTeX/dvips produces the postscript\n file that includes the actual text.\n """\n with mpl.rc_context({\n "text.latex.preamble":\n mpl.rcParams["text.latex.preamble"] +\n mpl.texmanager._usepackage_if_not_loaded("color") +\n mpl.texmanager._usepackage_if_not_loaded("graphicx") +\n mpl.texmanager._usepackage_if_not_loaded("psfrag") +\n r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"\n % {"width": paper_width, "height": paper_height}\n }):\n dvifile = TexManager().make_dvi(\n "\n"\n r"\begin{figure}""\n"\n r" \centering\leavevmode""\n"\n r" %(psfrags)s""\n"\n r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"\n r"\end{figure}"\n % {\n "psfrags": "\n".join(psfrags),\n "angle": 90 if orientation == 'landscape' else 0,\n "epsfile": tmppath.resolve().as_posix(),\n },\n fontsize=10) # tex's default fontsize.\n\n with TemporaryDirectory() as tmpdir:\n psfile = os.path.join(tmpdir, "tmp.ps")\n cbook._check_and_log_subprocess(\n ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)\n shutil.move(psfile, tmppath)\n\n # check if the dvips created a ps in landscape paper. Somehow,\n # above latex+dvips results in a ps file in a landscape mode for a\n # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the\n # bounding box of the final output got messed up. We check see if\n # the generated ps file is in landscape and return this\n # information. The return value is used in pstoeps step to recover\n # the correct bounding box. 2010-06-05 JJL\n with open(tmppath) as fh:\n psfrag_rotated = "Landscape" in fh.read(1000)\n return psfrag_rotated\n\n\ndef _try_distill(func, tmppath, *args, **kwargs):\n try:\n func(str(tmppath), *args, **kwargs)\n except mpl.ExecutableNotFoundError as exc:\n _log.warning("%s. Distillation step skipped.", exc)\n\n\ndef gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):\n """\n Use ghostscript's pswrite or epswrite device to distill a file.\n This yields smaller files without illegal encapsulated postscript\n operators. The output is low-level, converting text to outlines.\n """\n\n if eps:\n paper_option = ["-dEPSCrop"]\n elif ptype == "figure":\n # The bbox will have its lower-left corner at (0, 0), so upper-right\n # corner corresponds with paper size.\n paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",\n f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]\n else:\n paper_option = [f"-sPAPERSIZE={ptype}"]\n\n psfile = tmpfile + '.ps'\n dpi = mpl.rcParams['ps.distiller.res']\n\n cbook._check_and_log_subprocess(\n [mpl._get_executable_info("gs").executable,\n "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",\n *paper_option, f"-sOutputFile={psfile}", tmpfile],\n _log)\n\n os.remove(tmpfile)\n shutil.move(psfile, tmpfile)\n\n # While it is best if above steps preserve the original bounding\n # box, there seem to be cases when it is not. For those cases,\n # the original bbox can be restored during the pstoeps step.\n\n if eps:\n # For some versions of gs, above steps result in a ps file where the\n # original bbox is no more correct. Do not adjust bbox for now.\n pstoeps(tmpfile, bbox, rotated=rotated)\n\n\ndef xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):\n """\n Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.\n This yields smaller files without illegal encapsulated postscript\n operators. This distiller is preferred, generating high-level postscript\n output that treats text as text.\n """\n mpl._get_executable_info("gs") # Effectively checks for ps2pdf.\n mpl._get_executable_info("pdftops")\n\n if eps:\n paper_option = ["-dEPSCrop"]\n elif ptype == "figure":\n # The bbox will have its lower-left corner at (0, 0), so upper-right\n # corner corresponds with paper size.\n paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",\n f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]\n else:\n paper_option = [f"-sPAPERSIZE#{ptype}"]\n\n with TemporaryDirectory() as tmpdir:\n tmppdf = pathlib.Path(tmpdir, "tmp.pdf")\n tmpps = pathlib.Path(tmpdir, "tmp.ps")\n # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows\n # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).\n cbook._check_and_log_subprocess(\n ["ps2pdf",\n "-dAutoFilterColorImages#false",\n "-dAutoFilterGrayImages#false",\n "-sAutoRotatePages#None",\n "-sGrayImageFilter#FlateEncode",\n "-sColorImageFilter#FlateEncode",\n *paper_option,\n tmpfile, tmppdf], _log)\n cbook._check_and_log_subprocess(\n ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)\n shutil.move(tmpps, tmpfile)\n if eps:\n pstoeps(tmpfile)\n\n\n@_api.deprecated("3.9")\ndef get_bbox_header(lbrt, rotated=False):\n """\n Return a postscript header string for the given bbox lbrt=(l, b, r, t).\n Optionally, return rotate command.\n """\n return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "")\n\n\ndef _get_bbox_header(lbrt):\n """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t)."""\n l, b, r, t = lbrt\n return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n"\n f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}")\n\n\ndef _get_rotate_command(lbrt):\n """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t)."""\n l, b, r, t = lbrt\n return f"{l+r:.2f} {0:.2f} translate\n90 rotate"\n\n\ndef pstoeps(tmpfile, bbox=None, rotated=False):\n """\n Convert the postscript to encapsulated postscript. The bbox of\n the eps file will be replaced with the given *bbox* argument. If\n None, original bbox will be used.\n """\n\n epsfile = tmpfile + '.eps'\n with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:\n write = epsh.write\n # Modify the header:\n for line in tmph:\n if line.startswith(b'%!PS'):\n write(b"%!PS-Adobe-3.0 EPSF-3.0\n")\n if bbox:\n write(_get_bbox_header(bbox).encode('ascii') + b'\n')\n elif line.startswith(b'%%EndComments'):\n write(line)\n write(b'%%BeginProlog\n'\n b'save\n'\n b'countdictstack\n'\n b'mark\n'\n b'newpath\n'\n b'/showpage {} def\n'\n b'/setpagedevice {pop} def\n'\n b'%%EndProlog\n'\n b'%%Page 1 1\n')\n if rotated: # The output eps file need to be rotated.\n write(_get_rotate_command(bbox).encode('ascii') + b'\n')\n break\n elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',\n b'%%DocumentMedia', b'%%Pages')):\n pass\n else:\n write(line)\n # Now rewrite the rest of the file, and modify the trailer.\n # This is done in a second loop such that the header of the embedded\n # eps file is not modified.\n for line in tmph:\n if line.startswith(b'%%EOF'):\n write(b'cleartomark\n'\n b'countdictstack\n'\n b'exch sub { end } repeat\n'\n b'restore\n'\n b'showpage\n'\n b'%%EOF\n')\n elif line.startswith(b'%%PageBoundingBox'):\n pass\n else:\n write(line)\n\n os.remove(tmpfile)\n shutil.move(epsfile, tmpfile)\n\n\nFigureManagerPS = FigureManagerBase\n\n\n# The following Python dictionary psDefs contains the entries for the\n# PostScript dictionary mpldict. This dictionary implements most of\n# the matplotlib primitives and some abbreviations.\n#\n# References:\n# https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf\n# http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial\n# http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/\n#\n\n# The usage comments use the notation of the operator summary\n# in the PostScript Language reference manual.\n_psDefs = [\n # name proc *_d* -\n # Note that this cannot be bound to /d, because when embedding a Type3 font\n # we may want to define a "d" glyph using "/d{...} d" which would locally\n # overwrite the definition.\n "/_d { bind def } bind def",\n # x y *m* -\n "/m { moveto } _d",\n # x y *l* -\n "/l { lineto } _d",\n # x y *r* -\n "/r { rlineto } _d",\n # x1 y1 x2 y2 x y *c* -\n "/c { curveto } _d",\n # *cl* -\n "/cl { closepath } _d",\n # *ce* -\n "/ce { closepath eofill } _d",\n # wx wy llx lly urx ury *setcachedevice* -\n "/sc { setcachedevice } _d",\n]\n\n\n@_Backend.export\nclass _BackendPS(_Backend):\n backend_version = 'Level II'\n FigureCanvas = FigureCanvasPS\n
.venv\Lib\site-packages\matplotlib\backends\backend_ps.py
backend_ps.py
Python
51,991
0.75
0.170831
0.070313
node-utils
529
2024-08-19T08:18:51.078135
MIT
false
72d49034cdfa60893263caea419dc3ee
import functools\nimport os\nimport sys\nimport traceback\n\nimport matplotlib as mpl\nfrom matplotlib import _api, backend_tools, cbook\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,\n TimerBase, cursors, ToolContainerBase, MouseButton,\n CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent,\n _allow_interrupt)\nimport matplotlib.backends.qt_editor.figureoptions as figureoptions\nfrom . import qt_compat\nfrom .qt_compat import (\n QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted)\n\n\n# SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name\n# instead they have manually specified names.\nSPECIAL_KEYS = {\n _to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [\n ("Key_Escape", "escape"),\n ("Key_Tab", "tab"),\n ("Key_Backspace", "backspace"),\n ("Key_Return", "enter"),\n ("Key_Enter", "enter"),\n ("Key_Insert", "insert"),\n ("Key_Delete", "delete"),\n ("Key_Pause", "pause"),\n ("Key_SysReq", "sysreq"),\n ("Key_Clear", "clear"),\n ("Key_Home", "home"),\n ("Key_End", "end"),\n ("Key_Left", "left"),\n ("Key_Up", "up"),\n ("Key_Right", "right"),\n ("Key_Down", "down"),\n ("Key_PageUp", "pageup"),\n ("Key_PageDown", "pagedown"),\n ("Key_Shift", "shift"),\n # In macOS, the control and super (aka cmd/apple) keys are switched.\n ("Key_Control", "control" if sys.platform != "darwin" else "cmd"),\n ("Key_Meta", "meta" if sys.platform != "darwin" else "control"),\n ("Key_Alt", "alt"),\n ("Key_CapsLock", "caps_lock"),\n ("Key_F1", "f1"),\n ("Key_F2", "f2"),\n ("Key_F3", "f3"),\n ("Key_F4", "f4"),\n ("Key_F5", "f5"),\n ("Key_F6", "f6"),\n ("Key_F7", "f7"),\n ("Key_F8", "f8"),\n ("Key_F9", "f9"),\n ("Key_F10", "f10"),\n ("Key_F10", "f11"),\n ("Key_F12", "f12"),\n ("Key_Super_L", "super"),\n ("Key_Super_R", "super"),\n ]\n}\n# Define which modifier keys are collected on keyboard events.\n# Elements are (Qt::KeyboardModifiers, Qt::Key) tuples.\n# Order determines the modifier order (ctrl+alt+...) reported by Matplotlib.\n_MODIFIER_KEYS = [\n (_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)),\n _to_int(getattr(QtCore.Qt.Key, key)))\n for mod, key in [\n ("ControlModifier", "Key_Control"),\n ("AltModifier", "Key_Alt"),\n ("ShiftModifier", "Key_Shift"),\n ("MetaModifier", "Key_Meta"),\n ]\n]\ncursord = {\n k: getattr(QtCore.Qt.CursorShape, v) for k, v in [\n (cursors.MOVE, "SizeAllCursor"),\n (cursors.HAND, "PointingHandCursor"),\n (cursors.POINTER, "ArrowCursor"),\n (cursors.SELECT_REGION, "CrossCursor"),\n (cursors.WAIT, "WaitCursor"),\n (cursors.RESIZE_HORIZONTAL, "SizeHorCursor"),\n (cursors.RESIZE_VERTICAL, "SizeVerCursor"),\n ]\n}\n\n\n# lru_cache keeps a reference to the QApplication instance, keeping it from\n# being GC'd.\n@functools.lru_cache(1)\ndef _create_qApp():\n app = QtWidgets.QApplication.instance()\n\n # Create a new QApplication and configure it if none exists yet, as only\n # one QApplication can exist at a time.\n if app is None:\n # display_is_valid returns False only if on Linux and neither X11\n # nor Wayland display can be opened.\n if not mpl._c_internal_utils.display_is_valid():\n raise RuntimeError('Invalid DISPLAY variable')\n\n # Check to make sure a QApplication from a different major version\n # of Qt is not instantiated in the process\n if QT_API in {'PyQt6', 'PySide6'}:\n other_bindings = ('PyQt5', 'PySide2')\n qt_version = 6\n elif QT_API in {'PyQt5', 'PySide2'}:\n other_bindings = ('PyQt6', 'PySide6')\n qt_version = 5\n else:\n raise RuntimeError("Should never be here")\n\n for binding in other_bindings:\n mod = sys.modules.get(f'{binding}.QtWidgets')\n if mod is not None and mod.QApplication.instance() is not None:\n other_core = sys.modules.get(f'{binding}.QtCore')\n _api.warn_external(\n f'Matplotlib is using {QT_API} which wraps '\n f'{QtCore.qVersion()} however an instantiated '\n f'QApplication from {binding} which wraps '\n f'{other_core.qVersion()} exists. Mixing Qt major '\n 'versions may not work as expected.'\n )\n break\n if qt_version == 5:\n try:\n QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)\n except AttributeError: # Only for Qt>=5.6, <6.\n pass\n try:\n QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(\n QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)\n except AttributeError: # Only for Qt>=5.14.\n pass\n app = QtWidgets.QApplication(["matplotlib"])\n if sys.platform == "darwin":\n image = str(cbook._get_data_path('images/matplotlib.svg'))\n icon = QtGui.QIcon(image)\n app.setWindowIcon(icon)\n app.setQuitOnLastWindowClosed(True)\n cbook._setup_new_guiapp()\n if qt_version == 5:\n app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)\n\n return app\n\n\ndef _allow_interrupt_qt(qapp_or_eventloop):\n """A context manager that allows terminating a plot by sending a SIGINT."""\n\n # Use QSocketNotifier to read the socketpair while the Qt event loop runs.\n\n def prepare_notifier(rsock):\n sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read)\n\n @sn.activated.connect\n def _may_clear_sock():\n # Running a Python function on socket activation gives the interpreter a\n # chance to handle the signal in Python land. We also need to drain the\n # socket with recv() to re-arm it, because it will be written to as part of\n # the wakeup. (We need this in case set_wakeup_fd catches a signal other\n # than SIGINT and we shall continue waiting.)\n try:\n rsock.recv(1)\n except BlockingIOError:\n # This may occasionally fire too soon or more than once on Windows, so\n # be forgiving about reading an empty socket.\n pass\n\n return sn # Actually keep the notifier alive.\n\n def handle_sigint():\n if hasattr(qapp_or_eventloop, 'closeAllWindows'):\n qapp_or_eventloop.closeAllWindows()\n qapp_or_eventloop.quit()\n\n return _allow_interrupt(prepare_notifier, handle_sigint)\n\n\nclass TimerQT(TimerBase):\n """Subclass of `.TimerBase` using QTimer events."""\n\n def __init__(self, *args, **kwargs):\n # Create a new timer and connect the timeout() signal to the\n # _on_timer method.\n self._timer = QtCore.QTimer()\n self._timer.timeout.connect(self._on_timer)\n super().__init__(*args, **kwargs)\n\n def __del__(self):\n # The check for deletedness is needed to avoid an error at animation\n # shutdown with PySide2.\n if not _isdeleted(self._timer):\n self._timer_stop()\n\n def _timer_set_single_shot(self):\n self._timer.setSingleShot(self._single)\n\n def _timer_set_interval(self):\n self._timer.setInterval(self._interval)\n\n def _timer_start(self):\n self._timer.start()\n\n def _timer_stop(self):\n self._timer.stop()\n\n\nclass FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget):\n required_interactive_framework = "qt"\n _timer_cls = TimerQT\n manager_class = _api.classproperty(lambda cls: FigureManagerQT)\n\n buttond = {\n getattr(QtCore.Qt.MouseButton, k): v for k, v in [\n ("LeftButton", MouseButton.LEFT),\n ("RightButton", MouseButton.RIGHT),\n ("MiddleButton", MouseButton.MIDDLE),\n ("XButton1", MouseButton.BACK),\n ("XButton2", MouseButton.FORWARD),\n ]\n }\n\n def __init__(self, figure=None):\n _create_qApp()\n super().__init__(figure=figure)\n\n self._draw_pending = False\n self._is_drawing = False\n self._draw_rect_callback = lambda painter: None\n self._in_resize_event = False\n\n self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent)\n self.setMouseTracking(True)\n self.resize(*self.get_width_height())\n\n palette = QtGui.QPalette(QtGui.QColor("white"))\n self.setPalette(palette)\n\n @QtCore.Slot()\n def _update_pixel_ratio(self):\n if self._set_device_pixel_ratio(\n self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0\n # The easiest way to resize the canvas is to emit a resizeEvent\n # since we implement all the logic for resizing the canvas for\n # that event.\n event = QtGui.QResizeEvent(self.size(), self.size())\n self.resizeEvent(event)\n\n @QtCore.Slot(QtGui.QScreen)\n def _update_screen(self, screen):\n # Handler for changes to a window's attached screen.\n self._update_pixel_ratio()\n if screen is not None:\n screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio)\n screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio)\n\n def showEvent(self, event):\n # Set up correct pixel ratio, and connect to any signal changes for it,\n # once the window is shown (and thus has these attributes).\n window = self.window().windowHandle()\n window.screenChanged.connect(self._update_screen)\n self._update_screen(window.screen())\n\n def set_cursor(self, cursor):\n # docstring inherited\n self.setCursor(_api.check_getitem(cursord, cursor=cursor))\n\n def mouseEventCoords(self, pos=None):\n """\n Calculate mouse coordinates in physical pixels.\n\n Qt uses logical pixels, but the figure is scaled to physical\n pixels for rendering. Transform to physical pixels so that\n all of the down-stream transforms work as expected.\n\n Also, the origin is different and needs to be corrected.\n """\n if pos is None:\n pos = self.mapFromGlobal(QtGui.QCursor.pos())\n elif hasattr(pos, "position"): # qt6 QtGui.QEvent\n pos = pos.position()\n elif hasattr(pos, "pos"): # qt5 QtCore.QEvent\n pos = pos.pos()\n # (otherwise, it's already a QPoint)\n x = pos.x()\n # flip y so y=0 is bottom of canvas\n y = self.figure.bbox.height / self.device_pixel_ratio - pos.y()\n return x * self.device_pixel_ratio, y * self.device_pixel_ratio\n\n def enterEvent(self, event):\n # Force querying of the modifiers, as the cached modifier state can\n # have been invalidated while the window was out of focus.\n mods = QtWidgets.QApplication.instance().queryKeyboardModifiers()\n if self.figure is None:\n return\n LocationEvent("figure_enter_event", self,\n *self.mouseEventCoords(event),\n modifiers=self._mpl_modifiers(mods),\n guiEvent=event)._process()\n\n def leaveEvent(self, event):\n QtWidgets.QApplication.restoreOverrideCursor()\n if self.figure is None:\n return\n LocationEvent("figure_leave_event", self,\n *self.mouseEventCoords(),\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def mousePressEvent(self, event):\n button = self.buttond.get(event.button())\n if button is not None and self.figure is not None:\n MouseEvent("button_press_event", self,\n *self.mouseEventCoords(event), button,\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def mouseDoubleClickEvent(self, event):\n button = self.buttond.get(event.button())\n if button is not None and self.figure is not None:\n MouseEvent("button_press_event", self,\n *self.mouseEventCoords(event), button, dblclick=True,\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def mouseMoveEvent(self, event):\n if self.figure is None:\n return\n MouseEvent("motion_notify_event", self,\n *self.mouseEventCoords(event),\n buttons=self._mpl_buttons(event.buttons()),\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def mouseReleaseEvent(self, event):\n button = self.buttond.get(event.button())\n if button is not None and self.figure is not None:\n MouseEvent("button_release_event", self,\n *self.mouseEventCoords(event), button,\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def wheelEvent(self, event):\n # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not\n # provided (`isNull()`) and is unreliable on X11 ("xcb").\n if (event.pixelDelta().isNull()\n or QtWidgets.QApplication.instance().platformName() == "xcb"):\n steps = event.angleDelta().y() / 120\n else:\n steps = event.pixelDelta().y()\n if steps and self.figure is not None:\n MouseEvent("scroll_event", self,\n *self.mouseEventCoords(event), step=steps,\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def keyPressEvent(self, event):\n key = self._get_key(event)\n if key is not None and self.figure is not None:\n KeyEvent("key_press_event", self,\n key, *self.mouseEventCoords(),\n guiEvent=event)._process()\n\n def keyReleaseEvent(self, event):\n key = self._get_key(event)\n if key is not None and self.figure is not None:\n KeyEvent("key_release_event", self,\n key, *self.mouseEventCoords(),\n guiEvent=event)._process()\n\n def resizeEvent(self, event):\n if self._in_resize_event: # Prevent PyQt6 recursion\n return\n if self.figure is None:\n return\n self._in_resize_event = True\n try:\n w = event.size().width() * self.device_pixel_ratio\n h = event.size().height() * self.device_pixel_ratio\n dpival = self.figure.dpi\n winch = w / dpival\n hinch = h / dpival\n self.figure.set_size_inches(winch, hinch, forward=False)\n # pass back into Qt to let it finish\n QtWidgets.QWidget.resizeEvent(self, event)\n # emit our resize events\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n finally:\n self._in_resize_event = False\n\n def sizeHint(self):\n w, h = self.get_width_height()\n return QtCore.QSize(w, h)\n\n def minimumSizeHint(self):\n return QtCore.QSize(10, 10)\n\n @staticmethod\n def _mpl_buttons(buttons):\n buttons = _to_int(buttons)\n # State *after* press/release.\n return {button for mask, button in FigureCanvasQT.buttond.items()\n if _to_int(mask) & buttons}\n\n @staticmethod\n def _mpl_modifiers(modifiers=None, *, exclude=None):\n if modifiers is None:\n modifiers = QtWidgets.QApplication.instance().keyboardModifiers()\n modifiers = _to_int(modifiers)\n # get names of the pressed modifier keys\n # 'control' is named 'control' when a standalone key, but 'ctrl' when a\n # modifier\n # bit twiddling to pick out modifier keys from modifiers bitmask,\n # if exclude is a MODIFIER, it should not be duplicated in mods\n return [SPECIAL_KEYS[key].replace('control', 'ctrl')\n for mask, key in _MODIFIER_KEYS\n if exclude != key and modifiers & mask]\n\n def _get_key(self, event):\n event_key = event.key()\n mods = self._mpl_modifiers(exclude=event_key)\n try:\n # for certain keys (enter, left, backspace, etc) use a word for the\n # key, rather than Unicode\n key = SPECIAL_KEYS[event_key]\n except KeyError:\n # Unicode defines code points up to 0x10ffff (sys.maxunicode)\n # QT will use Key_Codes larger than that for keyboard keys that are\n # not Unicode characters (like multimedia keys)\n # skip these\n # if you really want them, you should add them to SPECIAL_KEYS\n if event_key > sys.maxunicode:\n return None\n\n key = chr(event_key)\n # qt delivers capitalized letters. fix capitalization\n # note that capslock is ignored\n if 'shift' in mods:\n mods.remove('shift')\n else:\n key = key.lower()\n\n return '+'.join(mods + [key])\n\n def flush_events(self):\n # docstring inherited\n QtWidgets.QApplication.instance().processEvents()\n\n def start_event_loop(self, timeout=0):\n # docstring inherited\n if hasattr(self, "_event_loop") and self._event_loop.isRunning():\n raise RuntimeError("Event loop already running")\n self._event_loop = event_loop = QtCore.QEventLoop()\n if timeout > 0:\n _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit)\n\n with _allow_interrupt_qt(event_loop):\n qt_compat._exec(event_loop)\n\n def stop_event_loop(self, event=None):\n # docstring inherited\n if hasattr(self, "_event_loop"):\n self._event_loop.quit()\n\n def draw(self):\n """Render the figure, and queue a request for a Qt draw."""\n # The renderer draw is done here; delaying causes problems with code\n # that uses the result of the draw() to update plot elements.\n if self._is_drawing:\n return\n with cbook._setattr_cm(self, _is_drawing=True):\n super().draw()\n self.update()\n\n def draw_idle(self):\n """Queue redraw of the Agg buffer and request Qt paintEvent."""\n # The Agg draw needs to be handled by the same thread Matplotlib\n # modifies the scene graph from. Post Agg draw request to the\n # current event loop in order to ensure thread affinity and to\n # accumulate multiple draw requests from event handling.\n # TODO: queued signal connection might be safer than singleShot\n if not (getattr(self, '_draw_pending', False) or\n getattr(self, '_is_drawing', False)):\n self._draw_pending = True\n QtCore.QTimer.singleShot(0, self._draw_idle)\n\n def blit(self, bbox=None):\n # docstring inherited\n if bbox is None and self.figure:\n bbox = self.figure.bbox # Blit the entire canvas if bbox is None.\n # repaint uses logical pixels, not physical pixels like the renderer.\n l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds)\n t = b + h\n self.repaint(l, self.rect().height() - t, w, h)\n\n def _draw_idle(self):\n with self._idle_draw_cntx():\n if not self._draw_pending:\n return\n self._draw_pending = False\n if self.height() <= 0 or self.width() <= 0:\n return\n try:\n self.draw()\n except Exception:\n # Uncaught exceptions are fatal for PyQt5, so catch them.\n traceback.print_exc()\n\n def drawRectangle(self, rect):\n # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs\n # to be called at the end of paintEvent.\n if rect is not None:\n x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect)\n x1 = x0 + w\n y1 = y0 + h\n def _draw_rect_callback(painter):\n pen = QtGui.QPen(\n QtGui.QColor("black"),\n 1 / self.device_pixel_ratio\n )\n\n pen.setDashPattern([3, 3])\n for color, offset in [\n (QtGui.QColor("black"), 0),\n (QtGui.QColor("white"), 3),\n ]:\n pen.setDashOffset(offset)\n pen.setColor(color)\n painter.setPen(pen)\n # Draw the lines from x0, y0 towards x1, y1 so that the\n # dashes don't "jump" when moving the zoom box.\n painter.drawLine(x0, y0, x0, y1)\n painter.drawLine(x0, y0, x1, y0)\n painter.drawLine(x0, y1, x1, y1)\n painter.drawLine(x1, y0, x1, y1)\n else:\n def _draw_rect_callback(painter):\n return\n self._draw_rect_callback = _draw_rect_callback\n self.update()\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n closing = QtCore.Signal()\n\n def closeEvent(self, event):\n self.closing.emit()\n super().closeEvent(event)\n\n\nclass FigureManagerQT(FigureManagerBase):\n """\n Attributes\n ----------\n canvas : `FigureCanvas`\n The FigureCanvas instance\n num : int or str\n The Figure number\n toolbar : qt.QToolBar\n The qt.QToolBar\n window : qt.QMainWindow\n The qt.QMainWindow\n """\n\n def __init__(self, canvas, num):\n self.window = MainWindow()\n super().__init__(canvas, num)\n self.window.closing.connect(self._widgetclosed)\n\n if sys.platform != "darwin":\n image = str(cbook._get_data_path('images/matplotlib.svg'))\n icon = QtGui.QIcon(image)\n self.window.setWindowIcon(icon)\n\n self.window._destroying = False\n\n if self.toolbar:\n self.window.addToolBar(self.toolbar)\n tbs_height = self.toolbar.sizeHint().height()\n else:\n tbs_height = 0\n\n # resize the main window so it will display the canvas with the\n # requested size:\n cs = canvas.sizeHint()\n cs_height = cs.height()\n height = cs_height + tbs_height\n self.window.resize(cs.width(), height)\n\n self.window.setCentralWidget(self.canvas)\n\n if mpl.is_interactive():\n self.window.show()\n self.canvas.draw_idle()\n\n # Give the keyboard focus to the figure instead of the manager:\n # StrongFocus accepts both tab and click to focus and will enable the\n # canvas to process event without clicking.\n # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum\n self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)\n self.canvas.setFocus()\n\n self.window.raise_()\n\n def full_screen_toggle(self):\n if self.window.isFullScreen():\n self.window.showNormal()\n else:\n self.window.showFullScreen()\n\n def _widgetclosed(self):\n CloseEvent("close_event", self.canvas)._process()\n if self.window._destroying:\n return\n self.window._destroying = True\n try:\n Gcf.destroy(self)\n except AttributeError:\n pass\n # It seems that when the python session is killed,\n # Gcf can get destroyed before the Gcf.destroy\n # line is run, leading to a useless AttributeError.\n\n def resize(self, width, height):\n # The Qt methods return sizes in 'virtual' pixels so we do need to\n # rescale from physical to logical pixels.\n width = int(width / self.canvas.device_pixel_ratio)\n height = int(height / self.canvas.device_pixel_ratio)\n extra_width = self.window.width() - self.canvas.width()\n extra_height = self.window.height() - self.canvas.height()\n self.canvas.resize(width, height)\n self.window.resize(width + extra_width, height + extra_height)\n\n @classmethod\n def start_main_loop(cls):\n qapp = QtWidgets.QApplication.instance()\n if qapp:\n with _allow_interrupt_qt(qapp):\n qt_compat._exec(qapp)\n\n def show(self):\n self.window._destroying = False\n self.window.show()\n if mpl.rcParams['figure.raise_window']:\n self.window.activateWindow()\n self.window.raise_()\n\n def destroy(self, *args):\n # check for qApp first, as PySide deletes it in its atexit handler\n if QtWidgets.QApplication.instance() is None:\n return\n if self.window._destroying:\n return\n self.window._destroying = True\n if self.toolbar:\n self.toolbar.destroy()\n self.window.close()\n\n def get_window_title(self):\n return self.window.windowTitle()\n\n def set_window_title(self, title):\n self.window.setWindowTitle(title)\n\n\nclass NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar):\n toolitems = [*NavigationToolbar2.toolitems]\n toolitems.insert(\n # Add 'customize' action after 'subplots'\n [name for name, *_ in toolitems].index("Subplots") + 1,\n ("Customize", "Edit axis, curve and image parameters",\n "qt4_editor_options", "edit_parameters"))\n\n def __init__(self, canvas, parent=None, coordinates=True):\n """coordinates: should we show the coordinates on the right?"""\n QtWidgets.QToolBar.__init__(self, parent)\n self.setAllowedAreas(QtCore.Qt.ToolBarArea(\n _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |\n _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))\n self.coordinates = coordinates\n self._actions = {} # mapping of toolitem method names to QActions.\n self._subplot_dialog = None\n\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n self.addSeparator()\n else:\n slot = getattr(self, callback)\n # https://bugreports.qt.io/browse/PYSIDE-2512\n slot = functools.wraps(slot)(functools.partial(slot))\n slot = QtCore.Slot()(slot)\n\n a = self.addAction(self._icon(image_file + '.png'),\n text, slot)\n self._actions[callback] = a\n if callback in ['zoom', 'pan']:\n a.setCheckable(True)\n if tooltip_text is not None:\n a.setToolTip(tooltip_text)\n\n # Add the (x, y) location widget at the right side of the toolbar\n # The stretch factor is 1 which means any resizing of the toolbar\n # will resize this label instead of the buttons.\n if self.coordinates:\n self.locLabel = QtWidgets.QLabel("", self)\n self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag(\n _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |\n _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))\n\n self.locLabel.setSizePolicy(QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Policy.Expanding,\n QtWidgets.QSizePolicy.Policy.Ignored,\n ))\n labelAction = self.addWidget(self.locLabel)\n labelAction.setVisible(True)\n\n NavigationToolbar2.__init__(self, canvas)\n\n def _icon(self, name):\n """\n Construct a `.QIcon` from an image file *name*, including the extension\n and relative to Matplotlib's "images" data directory.\n """\n # use a high-resolution icon with suffix '_large' if available\n # note: user-provided icons may not have '_large' versions\n path_regular = cbook._get_data_path('images', name)\n path_large = path_regular.with_name(\n path_regular.name.replace('.png', '_large.png'))\n filename = str(path_large if path_large.exists() else path_regular)\n\n pm = QtGui.QPixmap(filename)\n pm.setDevicePixelRatio(\n self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0\n if self.palette().color(self.backgroundRole()).value() < 128:\n icon_color = self.palette().color(self.foregroundRole())\n mask = pm.createMaskFromColor(\n QtGui.QColor('black'),\n QtCore.Qt.MaskMode.MaskOutColor)\n pm.fill(icon_color)\n pm.setMask(mask)\n return QtGui.QIcon(pm)\n\n def edit_parameters(self):\n axes = self.canvas.figure.get_axes()\n if not axes:\n QtWidgets.QMessageBox.warning(\n self.canvas.parent(), "Error", "There are no Axes to edit.")\n return\n elif len(axes) == 1:\n ax, = axes\n else:\n titles = [\n ax.get_label() or\n ax.get_title() or\n ax.get_title("left") or\n ax.get_title("right") or\n " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or\n f"<anonymous {type(ax).__name__}>"\n for ax in axes]\n duplicate_titles = [\n title for title in titles if titles.count(title) > 1]\n for i, ax in enumerate(axes):\n if titles[i] in duplicate_titles:\n titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles.\n item, ok = QtWidgets.QInputDialog.getItem(\n self.canvas.parent(),\n 'Customize', 'Select Axes:', titles, 0, False)\n if not ok:\n return\n ax = axes[titles.index(item)]\n figureoptions.figure_edit(ax, self)\n\n def _update_buttons_checked(self):\n # sync button checkstates to match active mode\n if 'pan' in self._actions:\n self._actions['pan'].setChecked(self.mode.name == 'PAN')\n if 'zoom' in self._actions:\n self._actions['zoom'].setChecked(self.mode.name == 'ZOOM')\n\n def pan(self, *args):\n super().pan(*args)\n self._update_buttons_checked()\n\n def zoom(self, *args):\n super().zoom(*args)\n self._update_buttons_checked()\n\n def set_message(self, s):\n if self.coordinates:\n self.locLabel.setText(s)\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n height = self.canvas.figure.bbox.height\n y1 = height - y1\n y0 = height - y0\n rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]\n self.canvas.drawRectangle(rect)\n\n def remove_rubberband(self):\n self.canvas.drawRectangle(None)\n\n def configure_subplots(self):\n if self._subplot_dialog is None:\n self._subplot_dialog = SubplotToolQt(\n self.canvas.figure, self.canvas.parent())\n self.canvas.mpl_connect(\n "close_event", lambda e: self._subplot_dialog.reject())\n self._subplot_dialog.update_from_current_subplotpars()\n self._subplot_dialog.setModal(True)\n self._subplot_dialog.show()\n return self._subplot_dialog\n\n def save_figure(self, *args):\n filetypes = self.canvas.get_supported_filetypes_grouped()\n sorted_filetypes = sorted(filetypes.items())\n default_filetype = self.canvas.get_default_filetype()\n\n startpath = os.path.expanduser(mpl.rcParams['savefig.directory'])\n start = os.path.join(startpath, self.canvas.get_default_filename())\n filters = []\n selectedFilter = None\n for name, exts in sorted_filetypes:\n exts_list = " ".join(['*.%s' % ext for ext in exts])\n filter = f'{name} ({exts_list})'\n if default_filetype in exts:\n selectedFilter = filter\n filters.append(filter)\n filters = ';;'.join(filters)\n\n fname, filter = QtWidgets.QFileDialog.getSaveFileName(\n self.canvas.parent(), "Choose a filename to save to", start,\n filters, selectedFilter)\n if fname:\n # Save dir for next time, unless empty str (i.e., use cwd).\n if startpath != "":\n mpl.rcParams['savefig.directory'] = os.path.dirname(fname)\n try:\n self.canvas.figure.savefig(fname)\n except Exception as e:\n QtWidgets.QMessageBox.critical(\n self, "Error saving file", str(e),\n QtWidgets.QMessageBox.StandardButton.Ok,\n QtWidgets.QMessageBox.StandardButton.NoButton)\n return fname\n\n def set_history_buttons(self):\n can_backward = self._nav_stack._pos > 0\n can_forward = self._nav_stack._pos < len(self._nav_stack) - 1\n if 'back' in self._actions:\n self._actions['back'].setEnabled(can_backward)\n if 'forward' in self._actions:\n self._actions['forward'].setEnabled(can_forward)\n\n\nclass SubplotToolQt(QtWidgets.QDialog):\n def __init__(self, targetfig, parent):\n super().__init__(parent)\n self.setWindowIcon(QtGui.QIcon(\n str(cbook._get_data_path("images/matplotlib.png"))))\n self.setObjectName("SubplotTool")\n self._spinboxes = {}\n main_layout = QtWidgets.QHBoxLayout()\n self.setLayout(main_layout)\n for group, spinboxes, buttons in [\n ("Borders",\n ["top", "bottom", "left", "right"],\n [("Export values", self._export_values)]),\n ("Spacings",\n ["hspace", "wspace"],\n [("Tight layout", self._tight_layout),\n ("Reset", self._reset),\n ("Close", self.close)])]:\n layout = QtWidgets.QVBoxLayout()\n main_layout.addLayout(layout)\n box = QtWidgets.QGroupBox(group)\n layout.addWidget(box)\n inner = QtWidgets.QFormLayout(box)\n for name in spinboxes:\n self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox()\n spinbox.setRange(0, 1)\n spinbox.setDecimals(3)\n spinbox.setSingleStep(0.005)\n spinbox.setKeyboardTracking(False)\n spinbox.valueChanged.connect(self._on_value_changed)\n inner.addRow(name, spinbox)\n layout.addStretch(1)\n for name, method in buttons:\n button = QtWidgets.QPushButton(name)\n # Don't trigger on <enter>, which is used to input values.\n button.setAutoDefault(False)\n button.clicked.connect(method)\n layout.addWidget(button)\n if name == "Close":\n button.setFocus()\n self._figure = targetfig\n self._defaults = {}\n self._export_values_dialog = None\n self.update_from_current_subplotpars()\n\n def update_from_current_subplotpars(self):\n self._defaults = {spinbox: getattr(self._figure.subplotpars, name)\n for name, spinbox in self._spinboxes.items()}\n self._reset() # Set spinbox current values without triggering signals.\n\n def _export_values(self):\n # Explicitly round to 3 decimals (which is also the spinbox precision)\n # to avoid numbers of the form 0.100...001.\n self._export_values_dialog = QtWidgets.QDialog()\n layout = QtWidgets.QVBoxLayout()\n self._export_values_dialog.setLayout(layout)\n text = QtWidgets.QPlainTextEdit()\n text.setReadOnly(True)\n layout.addWidget(text)\n text.setPlainText(\n ",\n".join(f"{attr}={spinbox.value():.3}"\n for attr, spinbox in self._spinboxes.items()))\n # Adjust the height of the text widget to fit the whole text, plus\n # some padding.\n size = text.maximumSize()\n size.setHeight(\n QtGui.QFontMetrics(text.document().defaultFont())\n .size(0, text.toPlainText()).height() + 20)\n text.setMaximumSize(size)\n self._export_values_dialog.show()\n\n def _on_value_changed(self):\n spinboxes = self._spinboxes\n # Set all mins and maxes, so that this can also be used in _reset().\n for lower, higher in [("bottom", "top"), ("left", "right")]:\n spinboxes[higher].setMinimum(spinboxes[lower].value() + .001)\n spinboxes[lower].setMaximum(spinboxes[higher].value() - .001)\n self._figure.subplots_adjust(\n **{attr: spinbox.value() for attr, spinbox in spinboxes.items()})\n self._figure.canvas.draw_idle()\n\n def _tight_layout(self):\n self._figure.tight_layout()\n for attr, spinbox in self._spinboxes.items():\n spinbox.blockSignals(True)\n spinbox.setValue(getattr(self._figure.subplotpars, attr))\n spinbox.blockSignals(False)\n self._figure.canvas.draw_idle()\n\n def _reset(self):\n for spinbox, value in self._defaults.items():\n spinbox.setRange(0, 1)\n spinbox.blockSignals(True)\n spinbox.setValue(value)\n spinbox.blockSignals(False)\n self._on_value_changed()\n\n\nclass ToolbarQt(ToolContainerBase, QtWidgets.QToolBar):\n def __init__(self, toolmanager, parent=None):\n ToolContainerBase.__init__(self, toolmanager)\n QtWidgets.QToolBar.__init__(self, parent)\n self.setAllowedAreas(QtCore.Qt.ToolBarArea(\n _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |\n _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))\n message_label = QtWidgets.QLabel("")\n message_label.setAlignment(QtCore.Qt.AlignmentFlag(\n _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |\n _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))\n message_label.setSizePolicy(QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Policy.Expanding,\n QtWidgets.QSizePolicy.Policy.Ignored,\n ))\n self._message_action = self.addWidget(message_label)\n self._toolitems = {}\n self._groups = {}\n\n def add_toolitem(\n self, name, group, position, image_file, description, toggle):\n\n button = QtWidgets.QToolButton(self)\n if image_file:\n button.setIcon(NavigationToolbar2QT._icon(self, image_file))\n button.setText(name)\n if description:\n button.setToolTip(description)\n\n def handler():\n self.trigger_tool(name)\n if toggle:\n button.setCheckable(True)\n button.toggled.connect(handler)\n else:\n button.clicked.connect(handler)\n\n self._toolitems.setdefault(name, [])\n self._add_to_group(group, name, button, position)\n self._toolitems[name].append((button, handler))\n\n def _add_to_group(self, group, name, button, position):\n gr = self._groups.get(group, [])\n if not gr:\n sep = self.insertSeparator(self._message_action)\n gr.append(sep)\n before = gr[position]\n widget = self.insertWidget(before, button)\n gr.insert(position, widget)\n self._groups[group] = gr\n\n def toggle_toolitem(self, name, toggled):\n if name not in self._toolitems:\n return\n for button, handler in self._toolitems[name]:\n button.toggled.disconnect(handler)\n button.setChecked(toggled)\n button.toggled.connect(handler)\n\n def remove_toolitem(self, name):\n for button, handler in self._toolitems.pop(name, []):\n button.setParent(None)\n\n def set_message(self, s):\n self.widgetForAction(self._message_action).setText(s)\n\n\n@backend_tools._register_tool_class(FigureCanvasQT)\nclass ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._subplot_dialog = None\n\n def trigger(self, *args):\n NavigationToolbar2QT.configure_subplots(self)\n\n\n@backend_tools._register_tool_class(FigureCanvasQT)\nclass SaveFigureQt(backend_tools.SaveFigureBase):\n def trigger(self, *args):\n NavigationToolbar2QT.save_figure(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(FigureCanvasQT)\nclass RubberbandQt(backend_tools.RubberbandBase):\n def draw_rubberband(self, x0, y0, x1, y1):\n NavigationToolbar2QT.draw_rubberband(\n self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)\n\n def remove_rubberband(self):\n NavigationToolbar2QT.remove_rubberband(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(FigureCanvasQT)\nclass HelpQt(backend_tools.ToolHelpBase):\n def trigger(self, *args):\n QtWidgets.QMessageBox.information(None, "Help", self._get_help_html())\n\n\n@backend_tools._register_tool_class(FigureCanvasQT)\nclass ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase):\n def trigger(self, *args, **kwargs):\n pixmap = self.canvas.grab()\n QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap)\n\n\nFigureManagerQT._toolbar2_class = NavigationToolbar2QT\nFigureManagerQT._toolmanager_toolbar_class = ToolbarQt\n\n\n@_Backend.export\nclass _BackendQT(_Backend):\n backend_version = __version__\n FigureCanvas = FigureCanvasQT\n FigureManager = FigureManagerQT\n mainloop = FigureManagerQT.start_main_loop\n
.venv\Lib\site-packages\matplotlib\backends\backend_qt.py
backend_qt.py
Python
41,541
0.95
0.217877
0.116004
node-utils
574
2024-11-13T12:17:30.432456
Apache-2.0
false
b58d7717c024cfe44d799b62ee8edce1
from .. import backends\n\nbackends._QT_FORCE_QT5_BINDING = True\n\n\nfrom .backend_qt import ( # noqa\n SPECIAL_KEYS,\n # Public API\n cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT,\n FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt,\n SaveFigureQt, ConfigureSubplotsQt, RubberbandQt,\n HelpQt, ToolCopyToClipboardQT,\n # internal re-exports\n FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2,\n TimerBase, ToolContainerBase, figureoptions, Gcf\n)\nfrom . import backend_qt as _backend_qt # noqa\n\n\n@_BackendQT.export\nclass _BackendQT5(_BackendQT):\n pass\n\n\ndef __getattr__(name):\n if name == 'qApp':\n return _backend_qt.qApp\n raise AttributeError(f"module {__name__!r} has no attribute {name!r}")\n
.venv\Lib\site-packages\matplotlib\backends\backend_qt5.py
backend_qt5.py
Python
787
0.95
0.107143
0.095238
react-lib
162
2024-08-25T12:21:36.990811
BSD-3-Clause
false
2d98c554404bd617a8cee06261d54391
"""\nRender to qt from agg\n"""\nfrom .. import backends\n\nbackends._QT_FORCE_QT5_BINDING = True\nfrom .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611\n _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT,\n FigureCanvasAgg, FigureCanvasQT)\n\n\n@_BackendQTAgg.export\nclass _BackendQT5Agg(_BackendQTAgg):\n pass\n
.venv\Lib\site-packages\matplotlib\backends\backend_qt5agg.py
backend_qt5agg.py
Python
352
0.95
0.071429
0
react-lib
786
2024-08-21T11:25:44.167501
GPL-3.0
false
0b5e4ea96a1d0fc85efd7b5860ffddb7
from .. import backends\n\nbackends._QT_FORCE_QT5_BINDING = True\nfrom .backend_qtcairo import ( # noqa: F401, E402 # pylint: disable=W0611\n _BackendQTCairo, FigureCanvasQTCairo, FigureCanvasCairo, FigureCanvasQT\n)\n\n\n@_BackendQTCairo.export\nclass _BackendQT5Cairo(_BackendQTCairo):\n pass\n
.venv\Lib\site-packages\matplotlib\backends\backend_qt5cairo.py
backend_qt5cairo.py
Python
292
0.95
0.090909
0
vue-tools
981
2023-09-21T18:57:47.389924
MIT
false
9fd9cf6c2cb5485d5c3fa7be736c48eb
"""\nRender to qt from agg.\n"""\n\nimport ctypes\n\nfrom matplotlib.transforms import Bbox\n\nfrom .qt_compat import QT_API, QtCore, QtGui\nfrom .backend_agg import FigureCanvasAgg\nfrom .backend_qt import _BackendQT, FigureCanvasQT\nfrom .backend_qt import ( # noqa: F401 # pylint: disable=W0611\n FigureManagerQT, NavigationToolbar2QT)\n\n\nclass FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT):\n\n def paintEvent(self, event):\n """\n Copy the image from the Agg canvas to the qt.drawable.\n\n In Qt, all drawing should be done inside of here when a widget is\n shown onscreen.\n """\n self._draw_idle() # Only does something if a draw is pending.\n\n # If the canvas does not have a renderer, then give up and wait for\n # FigureCanvasAgg.draw(self) to be called.\n if not hasattr(self, 'renderer'):\n return\n\n painter = QtGui.QPainter(self)\n try:\n # See documentation of QRect: bottom() and right() are off\n # by 1, so use left() + width() and top() + height().\n rect = event.rect()\n # scale rect dimensions using the screen dpi ratio to get\n # correct values for the Figure coordinates (rather than\n # QT5's coords)\n width = rect.width() * self.device_pixel_ratio\n height = rect.height() * self.device_pixel_ratio\n left, top = self.mouseEventCoords(rect.topLeft())\n # shift the "top" by the height of the image to get the\n # correct corner for our coordinate system\n bottom = top - height\n # same with the right side of the image\n right = left + width\n # create a buffer using the image bounding box\n bbox = Bbox([[left, bottom], [right, top]])\n buf = memoryview(self.copy_from_bbox(bbox))\n\n if QT_API == "PyQt6":\n from PyQt6 import sip\n ptr = int(sip.voidptr(buf))\n else:\n ptr = buf\n\n painter.eraseRect(rect) # clear the widget canvas\n qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0],\n QtGui.QImage.Format.Format_RGBA8888)\n qimage.setDevicePixelRatio(self.device_pixel_ratio)\n # set origin using original QT coordinates\n origin = QtCore.QPoint(rect.left(), rect.top())\n painter.drawImage(origin, qimage)\n # Adjust the buf reference count to work around a memory\n # leak bug in QImage under PySide.\n if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):\n ctypes.c_long.from_address(id(buf)).value = 1\n\n self._draw_rect_callback(painter)\n finally:\n painter.end()\n\n def print_figure(self, *args, **kwargs):\n super().print_figure(*args, **kwargs)\n # In some cases, Qt will itself trigger a paint event after closing the file\n # save dialog. When that happens, we need to be sure that the internal canvas is\n # re-drawn. However, if the user is using an automatically-chosen Qt backend but\n # saving with a different backend (such as pgf), we do not want to trigger a\n # full draw in Qt, so just set the flag for next time.\n self._draw_pending = True\n\n\n@_BackendQT.export\nclass _BackendQTAgg(_BackendQT):\n FigureCanvas = FigureCanvasQTAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_qtagg.py
backend_qtagg.py
Python
3,413
0.95
0.162791
0.267606
node-utils
593
2023-10-09T02:16:38.921300
MIT
false
40ca8808d65c7d29f44ca56db54cdd53
import ctypes\n\nfrom .backend_cairo import cairo, FigureCanvasCairo\nfrom .backend_qt import _BackendQT, FigureCanvasQT\nfrom .qt_compat import QT_API, QtCore, QtGui\n\n\nclass FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT):\n def draw(self):\n if hasattr(self._renderer.gc, "ctx"):\n self._renderer.dpi = self.figure.dpi\n self.figure.draw(self._renderer)\n super().draw()\n\n def paintEvent(self, event):\n width = int(self.device_pixel_ratio * self.width())\n height = int(self.device_pixel_ratio * self.height())\n if (width, height) != self._renderer.get_canvas_width_height():\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n self._renderer.set_context(cairo.Context(surface))\n self._renderer.dpi = self.figure.dpi\n self.figure.draw(self._renderer)\n buf = self._renderer.gc.ctx.get_target().get_data()\n if QT_API == "PyQt6":\n from PyQt6 import sip\n ptr = int(sip.voidptr(buf))\n else:\n ptr = buf\n qimage = QtGui.QImage(\n ptr, width, height,\n QtGui.QImage.Format.Format_ARGB32_Premultiplied)\n # Adjust the buf reference count to work around a memory leak bug in\n # QImage under PySide.\n if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):\n ctypes.c_long.from_address(id(buf)).value = 1\n qimage.setDevicePixelRatio(self.device_pixel_ratio)\n painter = QtGui.QPainter(self)\n painter.eraseRect(event.rect())\n painter.drawImage(0, 0, qimage)\n self._draw_rect_callback(painter)\n painter.end()\n\n\n@_BackendQT.export\nclass _BackendQTCairo(_BackendQT):\n FigureCanvas = FigureCanvasQTCairo\n
.venv\Lib\site-packages\matplotlib\backends\backend_qtcairo.py
backend_qtcairo.py
Python
1,770
0.95
0.173913
0.05
awesome-app
275
2023-09-04T02:48:52.033945
GPL-3.0
false
16cdc33395b1a3774d06cbd159571500
import base64\nimport codecs\nimport datetime\nimport gzip\nimport hashlib\nfrom io import BytesIO\nimport itertools\nimport logging\nimport os\nimport re\nimport uuid\n\nimport numpy as np\nfrom PIL import Image\n\nimport matplotlib as mpl\nfrom matplotlib import cbook, font_manager as fm\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)\nfrom matplotlib.backends.backend_mixed import MixedModeRenderer\nfrom matplotlib.colors import rgb2hex\nfrom matplotlib.dates import UTC\nfrom matplotlib.path import Path\nfrom matplotlib import _path\nfrom matplotlib.transforms import Affine2D, Affine2DBase\n\n\n_log = logging.getLogger(__name__)\n\n\n# ----------------------------------------------------------------------\n# SimpleXMLWriter class\n#\n# Based on an original by Fredrik Lundh, but modified here to:\n# 1. Support modern Python idioms\n# 2. Remove encoding support (it's handled by the file writer instead)\n# 3. Support proper indentation\n# 4. Minify things a little bit\n\n# --------------------------------------------------------------------\n# The SimpleXMLWriter module is\n#\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# By obtaining, using, and/or copying this software and/or its\n# associated documentation, you agree that you have read, understood,\n# and will comply with the following terms and conditions:\n#\n# Permission to use, copy, modify, and distribute this software and\n# its associated documentation for any purpose and without fee is\n# hereby granted, provided that the above copyright notice appears in\n# all copies, and that both that copyright notice and this permission\n# notice appear in supporting documentation, and that the name of\n# Secret Labs AB or the author not be used in advertising or publicity\n# pertaining to distribution of the software without specific, written\n# prior permission.\n#\n# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\n# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\n# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\n# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\n# OF THIS SOFTWARE.\n# --------------------------------------------------------------------\n\n\ndef _escape_cdata(s):\n s = s.replace("&", "&amp;")\n s = s.replace("<", "&lt;")\n s = s.replace(">", "&gt;")\n return s\n\n\n_escape_xml_comment = re.compile(r'-(?=-)')\n\n\ndef _escape_comment(s):\n s = _escape_cdata(s)\n return _escape_xml_comment.sub('- ', s)\n\n\ndef _escape_attrib(s):\n s = s.replace("&", "&amp;")\n s = s.replace("'", "&apos;")\n s = s.replace('"', "&quot;")\n s = s.replace("<", "&lt;")\n s = s.replace(">", "&gt;")\n return s\n\n\ndef _quote_escape_attrib(s):\n return ('"' + _escape_cdata(s) + '"' if '"' not in s else\n "'" + _escape_cdata(s) + "'" if "'" not in s else\n '"' + _escape_attrib(s) + '"')\n\n\ndef _short_float_fmt(x):\n """\n Create a short string representation of a float, which is %f\n formatting with trailing zeros and the decimal point removed.\n """\n return f'{x:f}'.rstrip('0').rstrip('.')\n\n\nclass XMLWriter:\n """\n Parameters\n ----------\n file : writable text file-like object\n """\n\n def __init__(self, file):\n self.__write = file.write\n if hasattr(file, "flush"):\n self.flush = file.flush\n self.__open = 0 # true if start tag is open\n self.__tags = []\n self.__data = []\n self.__indentation = " " * 64\n\n def __flush(self, indent=True):\n # flush internal buffers\n if self.__open:\n if indent:\n self.__write(">\n")\n else:\n self.__write(">")\n self.__open = 0\n if self.__data:\n data = ''.join(self.__data)\n self.__write(_escape_cdata(data))\n self.__data = []\n\n def start(self, tag, attrib={}, **extra):\n """\n Open a new element. Attributes can be given as keyword\n arguments, or as a string/string dictionary. The method returns\n an opaque identifier that can be passed to the :meth:`close`\n method, to close all open elements up to and including this one.\n\n Parameters\n ----------\n tag\n Element tag.\n attrib\n Attribute dictionary. Alternatively, attributes can be given as\n keyword arguments.\n\n Returns\n -------\n An element identifier.\n """\n self.__flush()\n tag = _escape_cdata(tag)\n self.__data = []\n self.__tags.append(tag)\n self.__write(self.__indentation[:len(self.__tags) - 1])\n self.__write(f"<{tag}")\n for k, v in {**attrib, **extra}.items():\n if v:\n k = _escape_cdata(k)\n v = _quote_escape_attrib(v)\n self.__write(f' {k}={v}')\n self.__open = 1\n return len(self.__tags) - 1\n\n def comment(self, comment):\n """\n Add a comment to the output stream.\n\n Parameters\n ----------\n comment : str\n Comment text.\n """\n self.__flush()\n self.__write(self.__indentation[:len(self.__tags)])\n self.__write(f"<!-- {_escape_comment(comment)} -->\n")\n\n def data(self, text):\n """\n Add character data to the output stream.\n\n Parameters\n ----------\n text : str\n Character data.\n """\n self.__data.append(text)\n\n def end(self, tag=None, indent=True):\n """\n Close the current element (opened by the most recent call to\n :meth:`start`).\n\n Parameters\n ----------\n tag\n Element tag. If given, the tag must match the start tag. If\n omitted, the current element is closed.\n indent : bool, default: True\n """\n if tag:\n assert self.__tags, f"unbalanced end({tag})"\n assert _escape_cdata(tag) == self.__tags[-1], \\n f"expected end({self.__tags[-1]}), got {tag}"\n else:\n assert self.__tags, "unbalanced end()"\n tag = self.__tags.pop()\n if self.__data:\n self.__flush(indent)\n elif self.__open:\n self.__open = 0\n self.__write("/>\n")\n return\n if indent:\n self.__write(self.__indentation[:len(self.__tags)])\n self.__write(f"</{tag}>\n")\n\n def close(self, id):\n """\n Close open elements, up to (and including) the element identified\n by the given identifier.\n\n Parameters\n ----------\n id\n Element identifier, as returned by the :meth:`start` method.\n """\n while len(self.__tags) > id:\n self.end()\n\n def element(self, tag, text=None, attrib={}, **extra):\n """\n Add an entire element. This is the same as calling :meth:`start`,\n :meth:`data`, and :meth:`end` in sequence. The *text* argument can be\n omitted.\n """\n self.start(tag, attrib, **extra)\n if text:\n self.data(text)\n self.end(indent=False)\n\n def flush(self):\n """Flush the output stream."""\n pass # replaced by the constructor\n\n\ndef _generate_transform(transform_list):\n parts = []\n for type, value in transform_list:\n if (type == 'scale' and (value == (1,) or value == (1, 1))\n or type == 'translate' and value == (0, 0)\n or type == 'rotate' and value == (0,)):\n continue\n if type == 'matrix' and isinstance(value, Affine2DBase):\n value = value.to_values()\n parts.append('{}({})'.format(\n type, ' '.join(_short_float_fmt(x) for x in value)))\n return ' '.join(parts)\n\n\ndef _generate_css(attrib):\n return "; ".join(f"{k}: {v}" for k, v in attrib.items())\n\n\n_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'}\n\n\ndef _check_is_str(info, key):\n if not isinstance(info, str):\n raise TypeError(f'Invalid type for {key} metadata. Expected str, not '\n f'{type(info)}.')\n\n\ndef _check_is_iterable_of_str(infos, key):\n if np.iterable(infos):\n for info in infos:\n if not isinstance(info, str):\n raise TypeError(f'Invalid type for {key} metadata. Expected '\n f'iterable of str, not {type(info)}.')\n else:\n raise TypeError(f'Invalid type for {key} metadata. Expected str or '\n f'iterable of str, not {type(infos)}.')\n\n\nclass RendererSVG(RendererBase):\n def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,\n *, metadata=None):\n self.width = width\n self.height = height\n self.writer = XMLWriter(svgwriter)\n self.image_dpi = image_dpi # actual dpi at which we rasterize stuff\n\n if basename is None:\n basename = getattr(svgwriter, "name", "")\n if not isinstance(basename, str):\n basename = ""\n self.basename = basename\n\n self._groupd = {}\n self._image_counter = itertools.count()\n self._clip_path_ids = {}\n self._clipd = {}\n self._markers = {}\n self._path_collection_id = 0\n self._hatchd = {}\n self._has_gouraud = False\n self._n_gradients = 0\n\n super().__init__()\n self._glyph_map = dict()\n str_height = _short_float_fmt(height)\n str_width = _short_float_fmt(width)\n svgwriter.write(svgProlog)\n self._start_id = self.writer.start(\n 'svg',\n width=f'{str_width}pt',\n height=f'{str_height}pt',\n viewBox=f'0 0 {str_width} {str_height}',\n xmlns="http://www.w3.org/2000/svg",\n version="1.1",\n id=mpl.rcParams['svg.id'],\n attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})\n self._write_metadata(metadata)\n self._write_default_style()\n\n def _get_clippath_id(self, clippath):\n """\n Returns a stable and unique identifier for the *clippath* argument\n object within the current rendering context.\n\n This allows plots that include custom clip paths to produce identical\n SVG output on each render, provided that the :rc:`svg.hashsalt` config\n setting and the ``SOURCE_DATE_EPOCH`` build-time environment variable\n are set to fixed values.\n """\n if clippath not in self._clip_path_ids:\n self._clip_path_ids[clippath] = len(self._clip_path_ids)\n return self._clip_path_ids[clippath]\n\n def finalize(self):\n self._write_clips()\n self._write_hatches()\n self.writer.close(self._start_id)\n self.writer.flush()\n\n def _write_metadata(self, metadata):\n # Add metadata following the Dublin Core Metadata Initiative, and the\n # Creative Commons Rights Expression Language. This is mainly for\n # compatibility with Inkscape.\n if metadata is None:\n metadata = {}\n metadata = {\n 'Format': 'image/svg+xml',\n 'Type': 'http://purl.org/dc/dcmitype/StillImage',\n 'Creator':\n f'Matplotlib v{mpl.__version__}, https://matplotlib.org/',\n **metadata\n }\n writer = self.writer\n\n if 'Title' in metadata:\n title = metadata['Title']\n _check_is_str(title, 'Title')\n writer.element('title', text=title)\n\n # Special handling.\n date = metadata.get('Date', None)\n if date is not None:\n if isinstance(date, str):\n dates = [date]\n elif isinstance(date, (datetime.datetime, datetime.date)):\n dates = [date.isoformat()]\n elif np.iterable(date):\n dates = []\n for d in date:\n if isinstance(d, str):\n dates.append(d)\n elif isinstance(d, (datetime.datetime, datetime.date)):\n dates.append(d.isoformat())\n else:\n raise TypeError(\n f'Invalid type for Date metadata. '\n f'Expected iterable of str, date, or datetime, '\n f'not {type(d)}.')\n else:\n raise TypeError(f'Invalid type for Date metadata. '\n f'Expected str, date, datetime, or iterable '\n f'of the same, not {type(date)}.')\n metadata['Date'] = '/'.join(dates)\n elif 'Date' not in metadata:\n # Do not add `Date` if the user explicitly set `Date` to `None`\n # Get source date from SOURCE_DATE_EPOCH, if set.\n # See https://reproducible-builds.org/specs/source-date-epoch/\n date = os.getenv("SOURCE_DATE_EPOCH")\n if date:\n date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc)\n metadata['Date'] = date.replace(tzinfo=UTC).isoformat()\n else:\n metadata['Date'] = datetime.datetime.today().isoformat()\n\n mid = None\n def ensure_metadata(mid):\n if mid is not None:\n return mid\n mid = writer.start('metadata')\n writer.start('rdf:RDF', attrib={\n 'xmlns:dc': "http://purl.org/dc/elements/1.1/",\n 'xmlns:cc': "http://creativecommons.org/ns#",\n 'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#",\n })\n writer.start('cc:Work')\n return mid\n\n uri = metadata.pop('Type', None)\n if uri is not None:\n mid = ensure_metadata(mid)\n writer.element('dc:type', attrib={'rdf:resource': uri})\n\n # Single value only.\n for key in ['Title', 'Coverage', 'Date', 'Description', 'Format',\n 'Identifier', 'Language', 'Relation', 'Source']:\n info = metadata.pop(key, None)\n if info is not None:\n mid = ensure_metadata(mid)\n _check_is_str(info, key)\n writer.element(f'dc:{key.lower()}', text=info)\n\n # Multiple Agent values.\n for key in ['Creator', 'Contributor', 'Publisher', 'Rights']:\n agents = metadata.pop(key, None)\n if agents is None:\n continue\n\n if isinstance(agents, str):\n agents = [agents]\n\n _check_is_iterable_of_str(agents, key)\n # Now we know that we have an iterable of str\n mid = ensure_metadata(mid)\n writer.start(f'dc:{key.lower()}')\n for agent in agents:\n writer.start('cc:Agent')\n writer.element('dc:title', text=agent)\n writer.end('cc:Agent')\n writer.end(f'dc:{key.lower()}')\n\n # Multiple values.\n keywords = metadata.pop('Keywords', None)\n if keywords is not None:\n if isinstance(keywords, str):\n keywords = [keywords]\n _check_is_iterable_of_str(keywords, 'Keywords')\n # Now we know that we have an iterable of str\n mid = ensure_metadata(mid)\n writer.start('dc:subject')\n writer.start('rdf:Bag')\n for keyword in keywords:\n writer.element('rdf:li', text=keyword)\n writer.end('rdf:Bag')\n writer.end('dc:subject')\n\n if mid is not None:\n writer.close(mid)\n\n if metadata:\n raise ValueError('Unknown metadata key(s) passed to SVG writer: ' +\n ','.join(metadata))\n\n def _write_default_style(self):\n writer = self.writer\n default_style = _generate_css({\n 'stroke-linejoin': 'round',\n 'stroke-linecap': 'butt'})\n writer.start('defs')\n writer.element('style', type='text/css', text='*{%s}' % default_style)\n writer.end('defs')\n\n def _make_id(self, type, content):\n salt = mpl.rcParams['svg.hashsalt']\n if salt is None:\n salt = str(uuid.uuid4())\n m = hashlib.sha256()\n m.update(salt.encode('utf8'))\n m.update(str(content).encode('utf8'))\n return f'{type}{m.hexdigest()[:10]}'\n\n def _make_flip_transform(self, transform):\n return transform + Affine2D().scale(1, -1).translate(0, self.height)\n\n def _get_hatch(self, gc, rgbFace):\n """\n Create a new hatch pattern\n """\n if rgbFace is not None:\n rgbFace = tuple(rgbFace)\n edge = gc.get_hatch_color()\n if edge is not None:\n edge = tuple(edge)\n lw = gc.get_hatch_linewidth()\n dictkey = (gc.get_hatch(), rgbFace, edge, lw)\n oid = self._hatchd.get(dictkey)\n if oid is None:\n oid = self._make_id('h', dictkey)\n self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge, lw), oid)\n else:\n _, oid = oid\n return oid\n\n def _write_hatches(self):\n if not len(self._hatchd):\n return\n HATCH_SIZE = 72\n writer = self.writer\n writer.start('defs')\n for (path, face, stroke, lw), oid in self._hatchd.values():\n writer.start(\n 'pattern',\n id=oid,\n patternUnits="userSpaceOnUse",\n x="0", y="0", width=str(HATCH_SIZE),\n height=str(HATCH_SIZE))\n path_data = self._convert_path(\n path,\n Affine2D()\n .scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE),\n simplify=False)\n if face is None:\n fill = 'none'\n else:\n fill = rgb2hex(face)\n writer.element(\n 'rect',\n x="0", y="0", width=str(HATCH_SIZE+1),\n height=str(HATCH_SIZE+1),\n fill=fill)\n hatch_style = {\n 'fill': rgb2hex(stroke),\n 'stroke': rgb2hex(stroke),\n 'stroke-width': str(lw),\n 'stroke-linecap': 'butt',\n 'stroke-linejoin': 'miter'\n }\n if stroke[3] < 1:\n hatch_style['stroke-opacity'] = str(stroke[3])\n writer.element(\n 'path',\n d=path_data,\n style=_generate_css(hatch_style)\n )\n writer.end('pattern')\n writer.end('defs')\n\n def _get_style_dict(self, gc, rgbFace):\n """Generate a style string from the GraphicsContext and rgbFace."""\n attrib = {}\n\n forced_alpha = gc.get_forced_alpha()\n\n if gc.get_hatch() is not None:\n attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})"\n if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0\n and not forced_alpha):\n attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])\n else:\n if rgbFace is None:\n attrib['fill'] = 'none'\n else:\n if tuple(rgbFace[:3]) != (0, 0, 0):\n attrib['fill'] = rgb2hex(rgbFace)\n if (len(rgbFace) == 4 and rgbFace[3] != 1.0\n and not forced_alpha):\n attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])\n\n if forced_alpha and gc.get_alpha() != 1.0:\n attrib['opacity'] = _short_float_fmt(gc.get_alpha())\n\n offset, seq = gc.get_dashes()\n if seq is not None:\n attrib['stroke-dasharray'] = ','.join(\n _short_float_fmt(val) for val in seq)\n attrib['stroke-dashoffset'] = _short_float_fmt(float(offset))\n\n linewidth = gc.get_linewidth()\n if linewidth:\n rgb = gc.get_rgb()\n attrib['stroke'] = rgb2hex(rgb)\n if not forced_alpha and rgb[3] != 1.0:\n attrib['stroke-opacity'] = _short_float_fmt(rgb[3])\n if linewidth != 1.0:\n attrib['stroke-width'] = _short_float_fmt(linewidth)\n if gc.get_joinstyle() != 'round':\n attrib['stroke-linejoin'] = gc.get_joinstyle()\n if gc.get_capstyle() != 'butt':\n attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()]\n\n return attrib\n\n def _get_style(self, gc, rgbFace):\n return _generate_css(self._get_style_dict(gc, rgbFace))\n\n def _get_clip_attrs(self, gc):\n cliprect = gc.get_clip_rectangle()\n clippath, clippath_trans = gc.get_clip_path()\n if clippath is not None:\n clippath_trans = self._make_flip_transform(clippath_trans)\n dictkey = (self._get_clippath_id(clippath), str(clippath_trans))\n elif cliprect is not None:\n x, y, w, h = cliprect.bounds\n y = self.height-(y+h)\n dictkey = (x, y, w, h)\n else:\n return {}\n clip = self._clipd.get(dictkey)\n if clip is None:\n oid = self._make_id('p', dictkey)\n if clippath is not None:\n self._clipd[dictkey] = ((clippath, clippath_trans), oid)\n else:\n self._clipd[dictkey] = (dictkey, oid)\n else:\n _, oid = clip\n return {'clip-path': f'url(#{oid})'}\n\n def _write_clips(self):\n if not len(self._clipd):\n return\n writer = self.writer\n writer.start('defs')\n for clip, oid in self._clipd.values():\n writer.start('clipPath', id=oid)\n if len(clip) == 2:\n clippath, clippath_trans = clip\n path_data = self._convert_path(\n clippath, clippath_trans, simplify=False)\n writer.element('path', d=path_data)\n else:\n x, y, w, h = clip\n writer.element(\n 'rect',\n x=_short_float_fmt(x),\n y=_short_float_fmt(y),\n width=_short_float_fmt(w),\n height=_short_float_fmt(h))\n writer.end('clipPath')\n writer.end('defs')\n\n def open_group(self, s, gid=None):\n # docstring inherited\n if gid:\n self.writer.start('g', id=gid)\n else:\n self._groupd[s] = self._groupd.get(s, 0) + 1\n self.writer.start('g', id=f"{s}_{self._groupd[s]:d}")\n\n def close_group(self, s):\n # docstring inherited\n self.writer.end('g')\n\n def option_image_nocomposite(self):\n # docstring inherited\n return not mpl.rcParams['image.composite_image']\n\n def _convert_path(self, path, transform=None, clip=None, simplify=None,\n sketch=None):\n if clip:\n clip = (0.0, 0.0, self.width, self.height)\n else:\n clip = None\n return _path.convert_to_string(\n path, transform, clip, simplify, sketch, 6,\n [b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii')\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n trans_and_flip = self._make_flip_transform(transform)\n clip = (rgbFace is None and gc.get_hatch_path() is None)\n simplify = path.should_simplify and clip\n path_data = self._convert_path(\n path, trans_and_flip, clip=clip, simplify=simplify,\n sketch=gc.get_sketch_params())\n\n if gc.get_url() is not None:\n self.writer.start('a', {'xlink:href': gc.get_url()})\n self.writer.element('path', d=path_data, **self._get_clip_attrs(gc),\n style=self._get_style(gc, rgbFace))\n if gc.get_url() is not None:\n self.writer.end('a')\n\n def draw_markers(\n self, gc, marker_path, marker_trans, path, trans, rgbFace=None):\n # docstring inherited\n\n if not len(path.vertices):\n return\n\n writer = self.writer\n path_data = self._convert_path(\n marker_path,\n marker_trans + Affine2D().scale(1.0, -1.0),\n simplify=False)\n style = self._get_style_dict(gc, rgbFace)\n dictkey = (path_data, _generate_css(style))\n oid = self._markers.get(dictkey)\n style = _generate_css({k: v for k, v in style.items()\n if k.startswith('stroke')})\n\n if oid is None:\n oid = self._make_id('m', dictkey)\n writer.start('defs')\n writer.element('path', id=oid, d=path_data, style=style)\n writer.end('defs')\n self._markers[dictkey] = oid\n\n writer.start('g', **self._get_clip_attrs(gc))\n if gc.get_url() is not None:\n self.writer.start('a', {'xlink:href': gc.get_url()})\n trans_and_flip = self._make_flip_transform(trans)\n attrib = {'xlink:href': f'#{oid}'}\n clip = (0, 0, self.width*72, self.height*72)\n for vertices, code in path.iter_segments(\n trans_and_flip, clip=clip, simplify=False):\n if len(vertices):\n x, y = vertices[-2:]\n attrib['x'] = _short_float_fmt(x)\n attrib['y'] = _short_float_fmt(y)\n attrib['style'] = self._get_style(gc, rgbFace)\n writer.element('use', attrib=attrib)\n if gc.get_url() is not None:\n self.writer.end('a')\n writer.end('g')\n\n def draw_path_collection(self, gc, master_transform, paths, all_transforms,\n offsets, offset_trans, facecolors, edgecolors,\n linewidths, linestyles, antialiaseds, urls,\n offset_position):\n # Is the optimization worth it? Rough calculation:\n # cost of emitting a path in-line is\n # (len_path + 5) * uses_per_path\n # cost of definition+use is\n # (len_path + 3) + 9 * uses_per_path\n len_path = len(paths[0].vertices) if len(paths) > 0 else 0\n uses_per_path = self._iter_collection_uses_per_path(\n paths, all_transforms, offsets, facecolors, edgecolors)\n should_do_optimization = \\n len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path\n if not should_do_optimization:\n return super().draw_path_collection(\n gc, master_transform, paths, all_transforms,\n offsets, offset_trans, facecolors, edgecolors,\n linewidths, linestyles, antialiaseds, urls,\n offset_position)\n\n writer = self.writer\n path_codes = []\n writer.start('defs')\n for i, (path, transform) in enumerate(self._iter_collection_raw_paths(\n master_transform, paths, all_transforms)):\n transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)\n d = self._convert_path(path, transform, simplify=False)\n oid = 'C{:x}_{:x}_{}'.format(\n self._path_collection_id, i, self._make_id('', d))\n writer.element('path', id=oid, d=d)\n path_codes.append(oid)\n writer.end('defs')\n\n for xo, yo, path_id, gc0, rgbFace in self._iter_collection(\n gc, path_codes, offsets, offset_trans,\n facecolors, edgecolors, linewidths, linestyles,\n antialiaseds, urls, offset_position):\n url = gc0.get_url()\n if url is not None:\n writer.start('a', attrib={'xlink:href': url})\n clip_attrs = self._get_clip_attrs(gc0)\n if clip_attrs:\n writer.start('g', **clip_attrs)\n attrib = {\n 'xlink:href': f'#{path_id}',\n 'x': _short_float_fmt(xo),\n 'y': _short_float_fmt(self.height - yo),\n 'style': self._get_style(gc0, rgbFace)\n }\n writer.element('use', attrib=attrib)\n if clip_attrs:\n writer.end('g')\n if url is not None:\n writer.end('a')\n\n self._path_collection_id += 1\n\n def _draw_gouraud_triangle(self, transformed_points, colors):\n # This uses a method described here:\n #\n # http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html\n #\n # that uses three overlapping linear gradients to simulate a\n # Gouraud triangle. Each gradient goes from fully opaque in\n # one corner to fully transparent along the opposite edge.\n # The line between the stop points is perpendicular to the\n # opposite edge. Underlying these three gradients is a solid\n # triangle whose color is the average of all three points.\n\n avg_color = np.average(colors, axis=0)\n if avg_color[-1] == 0:\n # Skip fully-transparent triangles\n return\n\n writer = self.writer\n writer.start('defs')\n for i in range(3):\n x1, y1 = transformed_points[i]\n x2, y2 = transformed_points[(i + 1) % 3]\n x3, y3 = transformed_points[(i + 2) % 3]\n rgba_color = colors[i]\n\n if x2 == x3:\n xb = x2\n yb = y1\n elif y2 == y3:\n xb = x1\n yb = y2\n else:\n m1 = (y2 - y3) / (x2 - x3)\n b1 = y2 - (m1 * x2)\n m2 = -(1.0 / m1)\n b2 = y1 - (m2 * x1)\n xb = (-b1 + b2) / (m1 - m2)\n yb = m2 * xb + b2\n\n writer.start(\n 'linearGradient',\n id=f"GR{self._n_gradients:x}_{i:d}",\n gradientUnits="userSpaceOnUse",\n x1=_short_float_fmt(x1), y1=_short_float_fmt(y1),\n x2=_short_float_fmt(xb), y2=_short_float_fmt(yb))\n writer.element(\n 'stop',\n offset='1',\n style=_generate_css({\n 'stop-color': rgb2hex(avg_color),\n 'stop-opacity': _short_float_fmt(rgba_color[-1])}))\n writer.element(\n 'stop',\n offset='0',\n style=_generate_css({'stop-color': rgb2hex(rgba_color),\n 'stop-opacity': "0"}))\n\n writer.end('linearGradient')\n\n writer.end('defs')\n\n # triangle formation using "path"\n dpath = (f"M {_short_float_fmt(x1)},{_short_float_fmt(y1)}"\n f" L {_short_float_fmt(x2)},{_short_float_fmt(y2)}"\n f" {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z")\n\n writer.element(\n 'path',\n attrib={'d': dpath,\n 'fill': rgb2hex(avg_color),\n 'fill-opacity': '1',\n 'shape-rendering': "crispEdges"})\n\n writer.start(\n 'g',\n attrib={'stroke': "none",\n 'stroke-width': "0",\n 'shape-rendering': "crispEdges",\n 'filter': "url(#colorMat)"})\n\n writer.element(\n 'path',\n attrib={'d': dpath,\n 'fill': f'url(#GR{self._n_gradients:x}_0)',\n 'shape-rendering': "crispEdges"})\n\n writer.element(\n 'path',\n attrib={'d': dpath,\n 'fill': f'url(#GR{self._n_gradients:x}_1)',\n 'filter': 'url(#colorAdd)',\n 'shape-rendering': "crispEdges"})\n\n writer.element(\n 'path',\n attrib={'d': dpath,\n 'fill': f'url(#GR{self._n_gradients:x}_2)',\n 'filter': 'url(#colorAdd)',\n 'shape-rendering': "crispEdges"})\n\n writer.end('g')\n\n self._n_gradients += 1\n\n def draw_gouraud_triangles(self, gc, triangles_array, colors_array,\n transform):\n writer = self.writer\n writer.start('g', **self._get_clip_attrs(gc))\n transform = transform.frozen()\n trans_and_flip = self._make_flip_transform(transform)\n\n if not self._has_gouraud:\n self._has_gouraud = True\n writer.start(\n 'filter',\n id='colorAdd')\n writer.element(\n 'feComposite',\n attrib={'in': 'SourceGraphic'},\n in2='BackgroundImage',\n operator='arithmetic',\n k2="1", k3="1")\n writer.end('filter')\n # feColorMatrix filter to correct opacity\n writer.start(\n 'filter',\n id='colorMat')\n writer.element(\n 'feColorMatrix',\n attrib={'type': 'matrix'},\n values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ')\n writer.end('filter')\n\n for points, colors in zip(triangles_array, colors_array):\n self._draw_gouraud_triangle(trans_and_flip.transform(points), colors)\n writer.end('g')\n\n def option_scale_image(self):\n # docstring inherited\n return True\n\n def get_image_magnification(self):\n return self.image_dpi / 72.0\n\n def draw_image(self, gc, x, y, im, transform=None):\n # docstring inherited\n\n h, w = im.shape[:2]\n\n if w == 0 or h == 0:\n return\n\n clip_attrs = self._get_clip_attrs(gc)\n if clip_attrs:\n # Can't apply clip-path directly to the image because the image has\n # a transformation, which would also be applied to the clip-path.\n self.writer.start('g', **clip_attrs)\n\n url = gc.get_url()\n if url is not None:\n self.writer.start('a', attrib={'xlink:href': url})\n\n attrib = {}\n oid = gc.get_gid()\n if mpl.rcParams['svg.image_inline']:\n buf = BytesIO()\n Image.fromarray(im).save(buf, format="png")\n oid = oid or self._make_id('image', buf.getvalue())\n attrib['xlink:href'] = (\n "data:image/png;base64,\n" +\n base64.b64encode(buf.getvalue()).decode('ascii'))\n else:\n if self.basename is None:\n raise ValueError("Cannot save image data to filesystem when "\n "writing SVG to an in-memory buffer")\n filename = f'{self.basename}.image{next(self._image_counter)}.png'\n _log.info('Writing image file for inclusion: %s', filename)\n Image.fromarray(im).save(filename)\n oid = oid or 'Im_' + self._make_id('image', filename)\n attrib['xlink:href'] = filename\n attrib['id'] = oid\n\n if transform is None:\n w = 72.0 * w / self.image_dpi\n h = 72.0 * h / self.image_dpi\n\n self.writer.element(\n 'image',\n transform=_generate_transform([\n ('scale', (1, -1)), ('translate', (0, -h))]),\n x=_short_float_fmt(x),\n y=_short_float_fmt(-(self.height - y - h)),\n width=_short_float_fmt(w), height=_short_float_fmt(h),\n attrib=attrib)\n else:\n alpha = gc.get_alpha()\n if alpha != 1.0:\n attrib['opacity'] = _short_float_fmt(alpha)\n\n flipped = (\n Affine2D().scale(1.0 / w, 1.0 / h) +\n transform +\n Affine2D()\n .translate(x, y)\n .scale(1.0, -1.0)\n .translate(0.0, self.height))\n\n attrib['transform'] = _generate_transform(\n [('matrix', flipped.frozen())])\n attrib['style'] = (\n 'image-rendering:crisp-edges;'\n 'image-rendering:pixelated')\n self.writer.element(\n 'image',\n width=_short_float_fmt(w), height=_short_float_fmt(h),\n attrib=attrib)\n\n if url is not None:\n self.writer.end('a')\n if clip_attrs:\n self.writer.end('g')\n\n def _update_glyph_map_defs(self, glyph_map_new):\n """\n Emit definitions for not-yet-defined glyphs, and record them as having\n been defined.\n """\n writer = self.writer\n if glyph_map_new:\n writer.start('defs')\n for char_id, (vertices, codes) in glyph_map_new.items():\n char_id = self._adjust_char_id(char_id)\n # x64 to go back to FreeType's internal (integral) units.\n path_data = self._convert_path(\n Path(vertices * 64, codes), simplify=False)\n writer.element(\n 'path', id=char_id, d=path_data,\n transform=_generate_transform([('scale', (1 / 64,))]))\n writer.end('defs')\n self._glyph_map.update(glyph_map_new)\n\n def _adjust_char_id(self, char_id):\n return char_id.replace("%20", "_")\n\n def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None):\n # docstring inherited\n writer = self.writer\n\n writer.comment(s)\n\n glyph_map = self._glyph_map\n\n text2path = self._text2path\n color = rgb2hex(gc.get_rgb())\n fontsize = prop.get_size_in_points()\n\n style = {}\n if color != '#000000':\n style['fill'] = color\n alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]\n if alpha != 1:\n style['opacity'] = _short_float_fmt(alpha)\n font_scale = fontsize / text2path.FONT_SCALE\n attrib = {\n 'style': _generate_css(style),\n 'transform': _generate_transform([\n ('translate', (x, y)),\n ('rotate', (-angle,)),\n ('scale', (font_scale, -font_scale))]),\n }\n writer.start('g', attrib=attrib)\n\n if not ismath:\n font = text2path._get_font(prop)\n _glyphs = text2path.get_glyphs_with_font(\n font, s, glyph_map=glyph_map, return_new_glyphs_only=True)\n glyph_info, glyph_map_new, rects = _glyphs\n self._update_glyph_map_defs(glyph_map_new)\n\n for glyph_id, xposition, yposition, scale in glyph_info:\n writer.element(\n 'use',\n transform=_generate_transform([\n ('translate', (xposition, yposition)),\n ('scale', (scale,)),\n ]),\n attrib={'xlink:href': f'#{glyph_id}'})\n\n else:\n if ismath == "TeX":\n _glyphs = text2path.get_glyphs_tex(\n prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)\n else:\n _glyphs = text2path.get_glyphs_mathtext(\n prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)\n glyph_info, glyph_map_new, rects = _glyphs\n self._update_glyph_map_defs(glyph_map_new)\n\n for char_id, xposition, yposition, scale in glyph_info:\n char_id = self._adjust_char_id(char_id)\n writer.element(\n 'use',\n transform=_generate_transform([\n ('translate', (xposition, yposition)),\n ('scale', (scale,)),\n ]),\n attrib={'xlink:href': f'#{char_id}'})\n\n for verts, codes in rects:\n path = Path(verts, codes)\n path_data = self._convert_path(path, simplify=False)\n writer.element('path', d=path_data)\n\n writer.end('g')\n\n def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None):\n # NOTE: If you change the font styling CSS, then be sure the check for\n # svg.fonttype = none in `lib/matplotlib/testing/compare.py::convert` remains in\n # sync. Also be sure to re-generate any SVG using this mode, or else such tests\n # will fail to use the right converter for the expected images, and they will\n # fail strangely.\n writer = self.writer\n\n color = rgb2hex(gc.get_rgb())\n font_style = {}\n color_style = {}\n if color != '#000000':\n color_style['fill'] = color\n\n alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]\n if alpha != 1:\n color_style['opacity'] = _short_float_fmt(alpha)\n\n if not ismath:\n attrib = {}\n\n # Separate font style in their separate attributes\n if prop.get_style() != 'normal':\n font_style['font-style'] = prop.get_style()\n if prop.get_variant() != 'normal':\n font_style['font-variant'] = prop.get_variant()\n weight = fm.weight_dict[prop.get_weight()]\n if weight != 400:\n font_style['font-weight'] = f'{weight}'\n\n def _normalize_sans(name):\n return 'sans-serif' if name in ['sans', 'sans serif'] else name\n\n def _expand_family_entry(fn):\n fn = _normalize_sans(fn)\n # prepend generic font families with all configured font names\n if fn in fm.font_family_aliases:\n # get all of the font names and fix spelling of sans-serif\n # (we accept 3 ways CSS only supports 1)\n for name in fm.FontManager._expand_aliases(fn):\n yield _normalize_sans(name)\n # whether a generic name or a family name, it must appear at\n # least once\n yield fn\n\n def _get_all_quoted_names(prop):\n # only quote specific names, not generic names\n return [name if name in fm.font_family_aliases else repr(name)\n for entry in prop.get_family()\n for name in _expand_family_entry(entry)]\n\n font_style['font-size'] = f'{_short_float_fmt(prop.get_size())}px'\n # ensure expansion, quoting, and dedupe of font names\n font_style['font-family'] = ", ".join(\n dict.fromkeys(_get_all_quoted_names(prop))\n )\n\n if prop.get_stretch() != 'normal':\n font_style['font-stretch'] = prop.get_stretch()\n attrib['style'] = _generate_css({**font_style, **color_style})\n\n if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"):\n # If text anchoring can be supported, get the original\n # coordinates and add alignment information.\n\n # Get anchor coordinates.\n transform = mtext.get_transform()\n ax, ay = transform.transform(mtext.get_unitless_position())\n ay = self.height - ay\n\n # Don't do vertical anchor alignment. Most applications do not\n # support 'alignment-baseline' yet. Apply the vertical layout\n # to the anchor point manually for now.\n angle_rad = np.deg2rad(angle)\n dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)])\n v_offset = np.dot(dir_vert, [(x - ax), (y - ay)])\n ax = ax + v_offset * dir_vert[0]\n ay = ay + v_offset * dir_vert[1]\n\n ha_mpl_to_svg = {'left': 'start', 'right': 'end',\n 'center': 'middle'}\n font_style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()]\n\n attrib['x'] = _short_float_fmt(ax)\n attrib['y'] = _short_float_fmt(ay)\n attrib['style'] = _generate_css({**font_style, **color_style})\n attrib['transform'] = _generate_transform([\n ("rotate", (-angle, ax, ay))])\n\n else:\n attrib['transform'] = _generate_transform([\n ('translate', (x, y)),\n ('rotate', (-angle,))])\n\n writer.element('text', s, attrib=attrib)\n\n else:\n writer.comment(s)\n\n width, height, descent, glyphs, rects = \\n self._text2path.mathtext_parser.parse(s, 72, prop)\n\n # Apply attributes to 'g', not 'text', because we likely have some\n # rectangles as well with the same style and transformation.\n writer.start('g',\n style=_generate_css({**font_style, **color_style}),\n transform=_generate_transform([\n ('translate', (x, y)),\n ('rotate', (-angle,))]),\n )\n\n writer.start('text')\n\n # Sort the characters by font, and output one tspan for each.\n spans = {}\n for font, fontsize, thetext, new_x, new_y in glyphs:\n entry = fm.ttfFontProperty(font)\n font_style = {}\n # Separate font style in its separate attributes\n if entry.style != 'normal':\n font_style['font-style'] = entry.style\n if entry.variant != 'normal':\n font_style['font-variant'] = entry.variant\n if entry.weight != 400:\n font_style['font-weight'] = f'{entry.weight}'\n font_style['font-size'] = f'{_short_float_fmt(fontsize)}px'\n font_style['font-family'] = f'{entry.name!r}' # ensure quoting\n if entry.stretch != 'normal':\n font_style['font-stretch'] = entry.stretch\n style = _generate_css({**font_style, **color_style})\n if thetext == 32:\n thetext = 0xa0 # non-breaking space\n spans.setdefault(style, []).append((new_x, -new_y, thetext))\n\n for style, chars in spans.items():\n chars.sort() # Sort by increasing x position\n for x, y, t in chars: # Output one tspan for each character\n writer.element(\n 'tspan',\n chr(t),\n x=_short_float_fmt(x),\n y=_short_float_fmt(y),\n style=style)\n\n writer.end('text')\n\n for x, y, width, height in rects:\n writer.element(\n 'rect',\n x=_short_float_fmt(x),\n y=_short_float_fmt(-y-1),\n width=_short_float_fmt(width),\n height=_short_float_fmt(height)\n )\n\n writer.end('g')\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n\n clip_attrs = self._get_clip_attrs(gc)\n if clip_attrs:\n # Cannot apply clip-path directly to the text, because\n # it has a transformation\n self.writer.start('g', **clip_attrs)\n\n if gc.get_url() is not None:\n self.writer.start('a', {'xlink:href': gc.get_url()})\n\n if mpl.rcParams['svg.fonttype'] == 'path':\n self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext)\n else:\n self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext)\n\n if gc.get_url() is not None:\n self.writer.end('a')\n\n if clip_attrs:\n self.writer.end('g')\n\n def flipy(self):\n # docstring inherited\n return True\n\n def get_canvas_width_height(self):\n # docstring inherited\n return self.width, self.height\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n return self._text2path.get_text_width_height_descent(s, prop, ismath)\n\n\nclass FigureCanvasSVG(FigureCanvasBase):\n filetypes = {'svg': 'Scalable Vector Graphics',\n 'svgz': 'Scalable Vector Graphics'}\n\n fixed_dpi = 72\n\n def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):\n """\n Parameters\n ----------\n filename : str or path-like or file-like\n Output target; if a string, a file will be opened for writing.\n\n metadata : dict[str, Any], optional\n Metadata in the SVG file defined as key-value pairs of strings,\n datetimes, or lists of strings, e.g., ``{'Creator': 'My software',\n 'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}``.\n\n The standard keys and their value types are:\n\n * *str*: ``'Coverage'``, ``'Description'``, ``'Format'``,\n ``'Identifier'``, ``'Language'``, ``'Relation'``, ``'Source'``,\n ``'Title'``, and ``'Type'``.\n * *str* or *list of str*: ``'Contributor'``, ``'Creator'``,\n ``'Keywords'``, ``'Publisher'``, and ``'Rights'``.\n * *str*, *date*, *datetime*, or *tuple* of same: ``'Date'``. If a\n non-*str*, then it will be formatted as ISO 8601.\n\n Values have been predefined for ``'Creator'``, ``'Date'``,\n ``'Format'``, and ``'Type'``. They can be removed by setting them\n to `None`.\n\n Information is encoded as `Dublin Core Metadata`__.\n\n .. _DC: https://www.dublincore.org/specifications/dublin-core/\n\n __ DC_\n """\n with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh:\n if not cbook.file_requires_unicode(fh):\n fh = codecs.getwriter('utf-8')(fh)\n dpi = self.figure.dpi\n self.figure.dpi = 72\n width, height = self.figure.get_size_inches()\n w, h = width * 72, height * 72\n renderer = MixedModeRenderer(\n self.figure, width, height, dpi,\n RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata),\n bbox_inches_restore=bbox_inches_restore)\n self.figure.draw(renderer)\n renderer.finalize()\n\n def print_svgz(self, filename, **kwargs):\n with (cbook.open_file_cm(filename, "wb") as fh,\n gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter):\n return self.print_svg(gzipwriter, **kwargs)\n\n def get_default_filetype(self):\n return 'svg'\n\n def draw(self):\n self.figure.draw_without_rendering()\n return super().draw()\n\n\nFigureManagerSVG = FigureManagerBase\n\n\nsvgProlog = """\\n<?xml version="1.0" encoding="utf-8" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"\n "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n"""\n\n\n@_Backend.export\nclass _BackendSVG(_Backend):\n backend_version = mpl.__version__\n FigureCanvas = FigureCanvasSVG\n
.venv\Lib\site-packages\matplotlib\backends\backend_svg.py
backend_svg.py
Python
51,000
0.75
0.167391
0.093671
python-kit
308
2023-12-05T20:18:44.870734
GPL-3.0
false
b8d294a96c6163013ebfc9cbb5e593ac
"""\nA fully functional, do-nothing backend intended as a template for backend\nwriters. It is fully functional in that you can select it as a backend e.g.\nwith ::\n\n import matplotlib\n matplotlib.use("template")\n\nand your program will (should!) run without error, though no output is\nproduced. This provides a starting point for backend writers; you can\nselectively implement drawing methods (`~.RendererTemplate.draw_path`,\n`~.RendererTemplate.draw_image`, etc.) and slowly see your figure come to life\ninstead having to have a full-blown implementation before getting any results.\n\nCopy this file to a directory outside the Matplotlib source tree, somewhere\nwhere Python can import it (by adding the directory to your ``sys.path`` or by\npackaging it as a normal Python package); if the backend is importable as\n``import my.backend`` you can then select it using ::\n\n import matplotlib\n matplotlib.use("module://my.backend")\n\nIf your backend implements support for saving figures (i.e. has a ``print_xyz`` method),\nyou can register it as the default handler for a given file type::\n\n from matplotlib.backend_bases import register_backend\n register_backend('xyz', 'my_backend', 'XYZ File Format')\n ...\n plt.savefig("figure.xyz")\n"""\n\nfrom matplotlib import _api\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backend_bases import (\n FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase)\nfrom matplotlib.figure import Figure\n\n\nclass RendererTemplate(RendererBase):\n """\n The renderer handles drawing/rendering operations.\n\n This is a minimal do-nothing class that can be used to get started when\n writing a new backend. Refer to `.backend_bases.RendererBase` for\n documentation of the methods.\n """\n\n def __init__(self, dpi):\n super().__init__()\n self.dpi = dpi\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n pass\n\n # draw_markers is optional, and we get more correct relative\n # timings by leaving it out. backend implementers concerned with\n # performance will probably want to implement it\n# def draw_markers(self, gc, marker_path, marker_trans, path, trans,\n# rgbFace=None):\n# pass\n\n # draw_path_collection is optional, and we get more correct\n # relative timings by leaving it out. backend implementers concerned with\n # performance will probably want to implement it\n# def draw_path_collection(self, gc, master_transform, paths,\n# all_transforms, offsets, offset_trans,\n# facecolors, edgecolors, linewidths, linestyles,\n# antialiaseds):\n# pass\n\n # draw_quad_mesh is optional, and we get more correct\n # relative timings by leaving it out. backend implementers concerned with\n # performance will probably want to implement it\n# def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,\n# coordinates, offsets, offsetTrans, facecolors,\n# antialiased, edgecolors):\n# pass\n\n def draw_image(self, gc, x, y, im):\n pass\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n pass\n\n def flipy(self):\n # docstring inherited\n return True\n\n def get_canvas_width_height(self):\n # docstring inherited\n return 100, 100\n\n def get_text_width_height_descent(self, s, prop, ismath):\n return 1, 1, 1\n\n def new_gc(self):\n # docstring inherited\n return GraphicsContextTemplate()\n\n def points_to_pixels(self, points):\n # if backend doesn't have dpi, e.g., postscript or svg\n return points\n # elif backend assumes a value for pixels_per_inch\n # return points/72.0 * self.dpi.get() * pixels_per_inch/72.0\n # else\n # return points/72.0 * self.dpi.get()\n\n\nclass GraphicsContextTemplate(GraphicsContextBase):\n """\n The graphics context provides the color, line styles, etc. See the cairo\n and postscript backends for examples of mapping the graphics context\n attributes (cap styles, join styles, line widths, colors) to a particular\n backend. In cairo this is done by wrapping a cairo.Context object and\n forwarding the appropriate calls to it using a dictionary mapping styles\n to gdk constants. In Postscript, all the work is done by the renderer,\n mapping line styles to postscript calls.\n\n If it's more appropriate to do the mapping at the renderer level (as in\n the postscript backend), you don't need to override any of the GC methods.\n If it's more appropriate to wrap an instance (as in the cairo backend) and\n do the mapping here, you'll need to override several of the setter\n methods.\n\n The base GraphicsContext stores colors as an RGB tuple on the unit\n interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors\n appropriate for your backend.\n """\n\n\n########################################################################\n#\n# The following functions and classes are for pyplot and implement\n# window/figure managers, etc.\n#\n########################################################################\n\n\nclass FigureManagerTemplate(FigureManagerBase):\n """\n Helper class for pyplot mode, wraps everything up into a neat bundle.\n\n For non-interactive backends, the base class is sufficient. For\n interactive backends, see the documentation of the `.FigureManagerBase`\n class for the list of methods that can/should be overridden.\n """\n\n\nclass FigureCanvasTemplate(FigureCanvasBase):\n """\n The canvas the figure renders into. Calls the draw and print fig\n methods, creates the renderers, etc.\n\n Note: GUI templates will want to connect events for button presses,\n mouse movements and key presses to functions that call the base\n class methods button_press_event, button_release_event,\n motion_notify_event, key_press_event, and key_release_event. See the\n implementations of the interactive backends for examples.\n\n Attributes\n ----------\n figure : `~matplotlib.figure.Figure`\n A high-level Figure instance\n """\n\n # The instantiated manager class. For further customization,\n # ``FigureManager.create_with_canvas`` can also be overridden; see the\n # wx-based backends for an example.\n manager_class = FigureManagerTemplate\n\n def draw(self):\n """\n Draw the figure using the renderer.\n\n It is important that this method actually walk the artist tree\n even if not output is produced because this will trigger\n deferred work (like computing limits auto-limits and tick\n values) that users may want access to before saving to disk.\n """\n renderer = RendererTemplate(self.figure.dpi)\n self.figure.draw(renderer)\n\n # You should provide a print_xxx function for every file format\n # you can write.\n\n # If the file type is not in the base set of filetypes,\n # you should add it to the class-scope filetypes dictionary as follows:\n filetypes = {**FigureCanvasBase.filetypes, 'foo': 'My magic Foo format'}\n\n def print_foo(self, filename, **kwargs):\n """\n Write out format foo.\n\n This method is normally called via `.Figure.savefig` and\n `.FigureCanvasBase.print_figure`, which take care of setting the figure\n facecolor, edgecolor, and dpi to the desired output values, and will\n restore them to the original values. Therefore, `print_foo` does not\n need to handle these settings.\n """\n self.draw()\n\n def get_default_filetype(self):\n return 'foo'\n\n\n########################################################################\n#\n# Now just provide the standard names that backend.__init__ is expecting\n#\n########################################################################\n\nFigureCanvas = FigureCanvasTemplate\nFigureManager = FigureManagerTemplate\n
.venv\Lib\site-packages\matplotlib\backends\backend_template.py
backend_template.py
Python
8,012
0.95
0.211268
0.281437
react-lib
197
2025-01-17T03:31:00.289857
Apache-2.0
false
308f4c4ca04a624059723c0f9c74d120
from . import _backend_tk\nfrom .backend_agg import FigureCanvasAgg\nfrom ._backend_tk import _BackendTk, FigureCanvasTk\nfrom ._backend_tk import ( # noqa: F401 # pylint: disable=W0611\n FigureManagerTk, NavigationToolbar2Tk)\n\n\nclass FigureCanvasTkAgg(FigureCanvasAgg, FigureCanvasTk):\n def draw(self):\n super().draw()\n self.blit()\n\n def blit(self, bbox=None):\n _backend_tk.blit(self._tkphoto, self.renderer.buffer_rgba(),\n (0, 1, 2, 3), bbox=bbox)\n\n\n@_BackendTk.export\nclass _BackendTkAgg(_BackendTk):\n FigureCanvas = FigureCanvasTkAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_tkagg.py
backend_tkagg.py
Python
592
0.95
0.2
0
python-kit
450
2023-12-09T05:03:18.666435
Apache-2.0
false
65a1352e8b7dc3037998c20fa52353f0
import sys\n\nimport numpy as np\n\nfrom . import _backend_tk\nfrom .backend_cairo import cairo, FigureCanvasCairo\nfrom ._backend_tk import _BackendTk, FigureCanvasTk\n\n\nclass FigureCanvasTkCairo(FigureCanvasCairo, FigureCanvasTk):\n def draw(self):\n width = int(self.figure.bbox.width)\n height = int(self.figure.bbox.height)\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n self._renderer.set_context(cairo.Context(surface))\n self._renderer.dpi = self.figure.dpi\n self.figure.draw(self._renderer)\n buf = np.reshape(surface.get_data(), (height, width, 4))\n _backend_tk.blit(\n self._tkphoto, buf,\n (2, 1, 0, 3) if sys.byteorder == "little" else (1, 2, 3, 0))\n\n\n@_BackendTk.export\nclass _BackendTkCairo(_BackendTk):\n FigureCanvas = FigureCanvasTkCairo\n
.venv\Lib\site-packages\matplotlib\backends\backend_tkcairo.py
backend_tkcairo.py
Python
845
0.85
0.153846
0
awesome-app
934
2025-02-08T13:28:35.364232
MIT
false
b94a5607baa809cec5420e0c2daf3633
"""Displays Agg images in the browser, with interactivity."""\n\n# The WebAgg backend is divided into two modules:\n#\n# - `backend_webagg_core.py` contains code necessary to embed a WebAgg\n# plot inside of a web application, and communicate in an abstract\n# way over a web socket.\n#\n# - `backend_webagg.py` contains a concrete implementation of a basic\n# application, implemented with tornado.\n\nfrom contextlib import contextmanager\nimport errno\nfrom io import BytesIO\nimport json\nimport mimetypes\nfrom pathlib import Path\nimport random\nimport sys\nimport signal\nimport threading\n\ntry:\n import tornado\nexcept ImportError as err:\n raise RuntimeError("The WebAgg backend requires Tornado.") from err\n\nimport tornado.web\nimport tornado.ioloop\nimport tornado.websocket\n\nimport matplotlib as mpl\nfrom matplotlib.backend_bases import _Backend\nfrom matplotlib._pylab_helpers import Gcf\nfrom . import backend_webagg_core as core\nfrom .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611\n TimerAsyncio, TimerTornado)\n\n\nwebagg_server_thread = threading.Thread(\n target=lambda: tornado.ioloop.IOLoop.instance().start())\n\n\nclass FigureManagerWebAgg(core.FigureManagerWebAgg):\n _toolbar2_class = core.NavigationToolbar2WebAgg\n\n @classmethod\n def pyplot_show(cls, *, block=None):\n WebAggApplication.initialize()\n\n url = "http://{address}:{port}{prefix}".format(\n address=WebAggApplication.address,\n port=WebAggApplication.port,\n prefix=WebAggApplication.url_prefix)\n\n if mpl.rcParams['webagg.open_in_browser']:\n import webbrowser\n if not webbrowser.open(url):\n print(f"To view figure, visit {url}")\n else:\n print(f"To view figure, visit {url}")\n\n WebAggApplication.start()\n\n\nclass FigureCanvasWebAgg(core.FigureCanvasWebAggCore):\n manager_class = FigureManagerWebAgg\n\n\nclass WebAggApplication(tornado.web.Application):\n initialized = False\n started = False\n\n class FavIcon(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type', 'image/png')\n self.write(Path(mpl.get_data_path(),\n 'images/matplotlib.png').read_bytes())\n\n class SingleFigurePage(tornado.web.RequestHandler):\n def __init__(self, application, request, *, url_prefix='', **kwargs):\n self.url_prefix = url_prefix\n super().__init__(application, request, **kwargs)\n\n def get(self, fignum):\n fignum = int(fignum)\n manager = Gcf.get_fig_manager(fignum)\n\n ws_uri = f'ws://{self.request.host}{self.url_prefix}/'\n self.render(\n "single_figure.html",\n prefix=self.url_prefix,\n ws_uri=ws_uri,\n fig_id=fignum,\n toolitems=core.NavigationToolbar2WebAgg.toolitems,\n canvas=manager.canvas)\n\n class AllFiguresPage(tornado.web.RequestHandler):\n def __init__(self, application, request, *, url_prefix='', **kwargs):\n self.url_prefix = url_prefix\n super().__init__(application, request, **kwargs)\n\n def get(self):\n ws_uri = f'ws://{self.request.host}{self.url_prefix}/'\n self.render(\n "all_figures.html",\n prefix=self.url_prefix,\n ws_uri=ws_uri,\n figures=sorted(Gcf.figs.items()),\n toolitems=core.NavigationToolbar2WebAgg.toolitems)\n\n class MplJs(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type', 'application/javascript')\n\n js_content = core.FigureManagerWebAgg.get_javascript()\n\n self.write(js_content)\n\n class Download(tornado.web.RequestHandler):\n def get(self, fignum, fmt):\n fignum = int(fignum)\n manager = Gcf.get_fig_manager(fignum)\n self.set_header(\n 'Content-Type', mimetypes.types_map.get(fmt, 'binary'))\n buff = BytesIO()\n manager.canvas.figure.savefig(buff, format=fmt)\n self.write(buff.getvalue())\n\n class WebSocket(tornado.websocket.WebSocketHandler):\n supports_binary = True\n\n def open(self, fignum):\n self.fignum = int(fignum)\n self.manager = Gcf.get_fig_manager(self.fignum)\n self.manager.add_web_socket(self)\n if hasattr(self, 'set_nodelay'):\n self.set_nodelay(True)\n\n def on_close(self):\n self.manager.remove_web_socket(self)\n\n def on_message(self, message):\n message = json.loads(message)\n # The 'supports_binary' message is on a client-by-client\n # basis. The others affect the (shared) canvas as a\n # whole.\n if message['type'] == 'supports_binary':\n self.supports_binary = message['value']\n else:\n manager = Gcf.get_fig_manager(self.fignum)\n # It is possible for a figure to be closed,\n # but a stale figure UI is still sending messages\n # from the browser.\n if manager is not None:\n manager.handle_json(message)\n\n def send_json(self, content):\n self.write_message(json.dumps(content))\n\n def send_binary(self, blob):\n if self.supports_binary:\n self.write_message(blob, binary=True)\n else:\n data_uri = "data:image/png;base64,{}".format(\n blob.encode('base64').replace('\n', ''))\n self.write_message(data_uri)\n\n def __init__(self, url_prefix=''):\n if url_prefix:\n assert url_prefix[0] == '/' and url_prefix[-1] != '/', \\n 'url_prefix must start with a "/" and not end with one.'\n\n super().__init__(\n [\n # Static files for the CSS and JS\n (url_prefix + r'/_static/(.*)',\n tornado.web.StaticFileHandler,\n {'path': core.FigureManagerWebAgg.get_static_file_path()}),\n\n # Static images for the toolbar\n (url_prefix + r'/_images/(.*)',\n tornado.web.StaticFileHandler,\n {'path': Path(mpl.get_data_path(), 'images')}),\n\n # A Matplotlib favicon\n (url_prefix + r'/favicon.ico', self.FavIcon),\n\n # The page that contains all of the pieces\n (url_prefix + r'/([0-9]+)', self.SingleFigurePage,\n {'url_prefix': url_prefix}),\n\n # The page that contains all of the figures\n (url_prefix + r'/?', self.AllFiguresPage,\n {'url_prefix': url_prefix}),\n\n (url_prefix + r'/js/mpl.js', self.MplJs),\n\n # Sends images and events to the browser, and receives\n # events from the browser\n (url_prefix + r'/([0-9]+)/ws', self.WebSocket),\n\n # Handles the downloading (i.e., saving) of static images\n (url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)',\n self.Download),\n ],\n template_path=core.FigureManagerWebAgg.get_static_file_path())\n\n @classmethod\n def initialize(cls, url_prefix='', port=None, address=None):\n if cls.initialized:\n return\n\n # Create the class instance\n app = cls(url_prefix=url_prefix)\n\n cls.url_prefix = url_prefix\n\n # This port selection algorithm is borrowed, more or less\n # verbatim, from IPython.\n def random_ports(port, n):\n """\n Generate a list of n random ports near the given port.\n\n The first 5 ports will be sequential, and the remaining n-5 will be\n randomly selected in the range [port-2*n, port+2*n].\n """\n for i in range(min(5, n)):\n yield port + i\n for i in range(n - 5):\n yield port + random.randint(-2 * n, 2 * n)\n\n if address is None:\n cls.address = mpl.rcParams['webagg.address']\n else:\n cls.address = address\n cls.port = mpl.rcParams['webagg.port']\n for port in random_ports(cls.port,\n mpl.rcParams['webagg.port_retries']):\n try:\n app.listen(port, cls.address)\n except OSError as e:\n if e.errno != errno.EADDRINUSE:\n raise\n else:\n cls.port = port\n break\n else:\n raise SystemExit(\n "The webagg server could not be started because an available "\n "port could not be found")\n\n cls.initialized = True\n\n @classmethod\n def start(cls):\n import asyncio\n try:\n asyncio.get_running_loop()\n except RuntimeError:\n pass\n else:\n cls.started = True\n\n if cls.started:\n return\n\n """\n IOLoop.running() was removed as of Tornado 2.4; see for example\n https://groups.google.com/forum/#!topic/python-tornado/QLMzkpQBGOY\n Thus there is no correct way to check if the loop has already been\n launched. We may end up with two concurrently running loops in that\n unlucky case with all the expected consequences.\n """\n ioloop = tornado.ioloop.IOLoop.instance()\n\n def shutdown():\n ioloop.stop()\n print("Server is stopped")\n sys.stdout.flush()\n cls.started = False\n\n @contextmanager\n def catch_sigint():\n old_handler = signal.signal(\n signal.SIGINT,\n lambda sig, frame: ioloop.add_callback_from_signal(shutdown))\n try:\n yield\n finally:\n signal.signal(signal.SIGINT, old_handler)\n\n # Set the flag to True *before* blocking on ioloop.start()\n cls.started = True\n\n print("Press Ctrl+C to stop WebAgg server")\n sys.stdout.flush()\n with catch_sigint():\n ioloop.start()\n\n\ndef ipython_inline_display(figure):\n import tornado.template\n\n WebAggApplication.initialize()\n import asyncio\n try:\n asyncio.get_running_loop()\n except RuntimeError:\n if not webagg_server_thread.is_alive():\n webagg_server_thread.start()\n\n fignum = figure.number\n tpl = Path(core.FigureManagerWebAgg.get_static_file_path(),\n "ipython_inline_figure.html").read_text()\n t = tornado.template.Template(tpl)\n return t.generate(\n prefix=WebAggApplication.url_prefix,\n fig_id=fignum,\n toolitems=core.NavigationToolbar2WebAgg.toolitems,\n canvas=figure.canvas,\n port=WebAggApplication.port).decode('utf-8')\n\n\n@_Backend.export\nclass _BackendWebAgg(_Backend):\n FigureCanvas = FigureCanvasWebAgg\n FigureManager = FigureManagerWebAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_webagg.py
backend_webagg.py
Python
11,022
0.95
0.170732
0.097744
awesome-app
801
2024-08-27T08:36:40.915909
BSD-3-Clause
false
2851b6a909ab859576e5b2bf9a8eeaf6
"""Displays Agg images in the browser, with interactivity."""\n# The WebAgg backend is divided into two modules:\n#\n# - `backend_webagg_core.py` contains code necessary to embed a WebAgg\n# plot inside of a web application, and communicate in an abstract\n# way over a web socket.\n#\n# - `backend_webagg.py` contains a concrete implementation of a basic\n# application, implemented with asyncio.\n\nimport asyncio\nimport datetime\nfrom io import BytesIO, StringIO\nimport json\nimport logging\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nfrom PIL import Image\n\nfrom matplotlib import _api, backend_bases, backend_tools\nfrom matplotlib.backends import backend_agg\nfrom matplotlib.backend_bases import (\n _Backend, MouseButton, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)\n\n_log = logging.getLogger(__name__)\n\n_SPECIAL_KEYS_LUT = {'Alt': 'alt',\n 'AltGraph': 'alt',\n 'CapsLock': 'caps_lock',\n 'Control': 'control',\n 'Meta': 'meta',\n 'NumLock': 'num_lock',\n 'ScrollLock': 'scroll_lock',\n 'Shift': 'shift',\n 'Super': 'super',\n 'Enter': 'enter',\n 'Tab': 'tab',\n 'ArrowDown': 'down',\n 'ArrowLeft': 'left',\n 'ArrowRight': 'right',\n 'ArrowUp': 'up',\n 'End': 'end',\n 'Home': 'home',\n 'PageDown': 'pagedown',\n 'PageUp': 'pageup',\n 'Backspace': 'backspace',\n 'Delete': 'delete',\n 'Insert': 'insert',\n 'Escape': 'escape',\n 'Pause': 'pause',\n 'Select': 'select',\n 'Dead': 'dead',\n 'F1': 'f1',\n 'F2': 'f2',\n 'F3': 'f3',\n 'F4': 'f4',\n 'F5': 'f5',\n 'F6': 'f6',\n 'F7': 'f7',\n 'F8': 'f8',\n 'F9': 'f9',\n 'F10': 'f10',\n 'F11': 'f11',\n 'F12': 'f12'}\n\n\ndef _handle_key(key):\n """Handle key values"""\n value = key[key.index('k') + 1:]\n if 'shift+' in key:\n if len(value) == 1:\n key = key.replace('shift+', '')\n if value in _SPECIAL_KEYS_LUT:\n value = _SPECIAL_KEYS_LUT[value]\n key = key[:key.index('k')] + value\n return key\n\n\nclass TimerTornado(backend_bases.TimerBase):\n def __init__(self, *args, **kwargs):\n self._timer = None\n super().__init__(*args, **kwargs)\n\n def _timer_start(self):\n import tornado\n\n self._timer_stop()\n if self._single:\n ioloop = tornado.ioloop.IOLoop.instance()\n self._timer = ioloop.add_timeout(\n datetime.timedelta(milliseconds=self.interval),\n self._on_timer)\n else:\n self._timer = tornado.ioloop.PeriodicCallback(\n self._on_timer,\n max(self.interval, 1e-6))\n self._timer.start()\n\n def _timer_stop(self):\n import tornado\n\n if self._timer is None:\n return\n elif self._single:\n ioloop = tornado.ioloop.IOLoop.instance()\n ioloop.remove_timeout(self._timer)\n else:\n self._timer.stop()\n self._timer = None\n\n def _timer_set_interval(self):\n # Only stop and restart it if the timer has already been started\n if self._timer is not None:\n self._timer_stop()\n self._timer_start()\n\n\nclass TimerAsyncio(backend_bases.TimerBase):\n def __init__(self, *args, **kwargs):\n self._task = None\n super().__init__(*args, **kwargs)\n\n async def _timer_task(self, interval):\n while True:\n try:\n await asyncio.sleep(interval)\n self._on_timer()\n\n if self._single:\n break\n except asyncio.CancelledError:\n break\n\n def _timer_start(self):\n self._timer_stop()\n\n self._task = asyncio.ensure_future(\n self._timer_task(max(self.interval / 1_000., 1e-6))\n )\n\n def _timer_stop(self):\n if self._task is not None:\n self._task.cancel()\n self._task = None\n\n def _timer_set_interval(self):\n # Only stop and restart it if the timer has already been started\n if self._task is not None:\n self._timer_stop()\n self._timer_start()\n\n\nclass FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg):\n manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg)\n _timer_cls = TimerAsyncio\n # Webagg and friends having the right methods, but still\n # having bugs in practice. Do not advertise that it works until\n # we can debug this.\n supports_blit = False\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Set to True when the renderer contains data that is newer\n # than the PNG buffer.\n self._png_is_old = True\n # Set to True by the `refresh` message so that the next frame\n # sent to the clients will be a full frame.\n self._force_full = True\n # The last buffer, for diff mode.\n self._last_buff = np.empty((0, 0))\n # Store the current image mode so that at any point, clients can\n # request the information. This should be changed by calling\n # self.set_image_mode(mode) so that the notification can be given\n # to the connected clients.\n self._current_image_mode = 'full'\n # Track mouse events to fill in the x, y position of key events.\n self._last_mouse_xy = (None, None)\n\n def show(self):\n # show the figure window\n from matplotlib.pyplot import show\n show()\n\n def draw(self):\n self._png_is_old = True\n try:\n super().draw()\n finally:\n self.manager.refresh_all() # Swap the frames.\n\n def blit(self, bbox=None):\n self._png_is_old = True\n self.manager.refresh_all()\n\n def draw_idle(self):\n self.send_event("draw")\n\n def set_cursor(self, cursor):\n # docstring inherited\n cursor = _api.check_getitem({\n backend_tools.Cursors.HAND: 'pointer',\n backend_tools.Cursors.POINTER: 'default',\n backend_tools.Cursors.SELECT_REGION: 'crosshair',\n backend_tools.Cursors.MOVE: 'move',\n backend_tools.Cursors.WAIT: 'wait',\n backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize',\n backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize',\n }, cursor=cursor)\n self.send_event('cursor', cursor=cursor)\n\n def set_image_mode(self, mode):\n """\n Set the image mode for any subsequent images which will be sent\n to the clients. The modes may currently be either 'full' or 'diff'.\n\n Note: diff images may not contain transparency, therefore upon\n draw this mode may be changed if the resulting image has any\n transparent component.\n """\n _api.check_in_list(['full', 'diff'], mode=mode)\n if self._current_image_mode != mode:\n self._current_image_mode = mode\n self.handle_send_image_mode(None)\n\n def get_diff_image(self):\n if self._png_is_old:\n renderer = self.get_renderer()\n\n pixels = np.asarray(renderer.buffer_rgba())\n # The buffer is created as type uint32 so that entire\n # pixels can be compared in one numpy call, rather than\n # needing to compare each plane separately.\n buff = pixels.view(np.uint32).squeeze(2)\n\n if (self._force_full\n # If the buffer has changed size we need to do a full draw.\n or buff.shape != self._last_buff.shape\n # If any pixels have transparency, we need to force a full\n # draw as we cannot overlay new on top of old.\n or (pixels[:, :, 3] != 255).any()):\n self.set_image_mode('full')\n output = buff\n else:\n self.set_image_mode('diff')\n diff = buff != self._last_buff\n output = np.where(diff, buff, 0)\n\n # Store the current buffer so we can compute the next diff.\n self._last_buff = buff.copy()\n self._force_full = False\n self._png_is_old = False\n\n data = output.view(dtype=np.uint8).reshape((*output.shape, 4))\n with BytesIO() as png:\n Image.fromarray(data).save(png, format="png")\n return png.getvalue()\n\n def handle_event(self, event):\n e_type = event['type']\n handler = getattr(self, f'handle_{e_type}',\n self.handle_unknown_event)\n return handler(event)\n\n def handle_unknown_event(self, event):\n _log.warning('Unhandled message type %s. %s', event["type"], event)\n\n def handle_ack(self, event):\n # Network latency tends to decrease if traffic is flowing\n # in both directions. Therefore, the browser sends back\n # an "ack" message after each image frame is received.\n # This could also be used as a simple sanity check in the\n # future, but for now the performance increase is enough\n # to justify it, even if the server does nothing with it.\n pass\n\n def handle_draw(self, event):\n self.draw()\n\n def _handle_mouse(self, event):\n x = event['x']\n y = event['y']\n y = self.get_renderer().height - y\n self._last_mouse_xy = x, y\n e_type = event['type']\n button = event['button'] + 1 # JS numbers off by 1 compared to mpl.\n buttons = { # JS ordering different compared to mpl.\n button for button, mask in [\n (MouseButton.LEFT, 1),\n (MouseButton.RIGHT, 2),\n (MouseButton.MIDDLE, 4),\n (MouseButton.BACK, 8),\n (MouseButton.FORWARD, 16),\n ] if event['buttons'] & mask # State *after* press/release.\n }\n modifiers = event['modifiers']\n guiEvent = event.get('guiEvent')\n if e_type in ['button_press', 'button_release']:\n MouseEvent(e_type + '_event', self, x, y, button,\n modifiers=modifiers, guiEvent=guiEvent)._process()\n elif e_type == 'dblclick':\n MouseEvent('button_press_event', self, x, y, button, dblclick=True,\n modifiers=modifiers, guiEvent=guiEvent)._process()\n elif e_type == 'scroll':\n MouseEvent('scroll_event', self, x, y, step=event['step'],\n modifiers=modifiers, guiEvent=guiEvent)._process()\n elif e_type == 'motion_notify':\n MouseEvent(e_type + '_event', self, x, y,\n buttons=buttons, modifiers=modifiers, guiEvent=guiEvent,\n )._process()\n elif e_type in ['figure_enter', 'figure_leave']:\n LocationEvent(e_type + '_event', self, x, y,\n modifiers=modifiers, guiEvent=guiEvent)._process()\n\n handle_button_press = handle_button_release = handle_dblclick = \\n handle_figure_enter = handle_figure_leave = handle_motion_notify = \\n handle_scroll = _handle_mouse\n\n def _handle_key(self, event):\n KeyEvent(event['type'] + '_event', self,\n _handle_key(event['key']), *self._last_mouse_xy,\n guiEvent=event.get('guiEvent'))._process()\n handle_key_press = handle_key_release = _handle_key\n\n def handle_toolbar_button(self, event):\n # TODO: Be more suspicious of the input\n getattr(self.toolbar, event['name'])()\n\n def handle_refresh(self, event):\n figure_label = self.figure.get_label()\n if not figure_label:\n figure_label = f"Figure {self.manager.num}"\n self.send_event('figure_label', label=figure_label)\n self._force_full = True\n if self.toolbar:\n # Normal toolbar init would refresh this, but it happens before the\n # browser canvas is set up.\n self.toolbar.set_history_buttons()\n self.draw_idle()\n\n def handle_resize(self, event):\n x = int(event.get('width', 800)) * self.device_pixel_ratio\n y = int(event.get('height', 800)) * self.device_pixel_ratio\n fig = self.figure\n # An attempt at approximating the figure size in pixels.\n fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False)\n # Acknowledge the resize, and force the viewer to update the\n # canvas size to the figure's new size (which is hopefully\n # identical or within a pixel or so).\n self._png_is_old = True\n self.manager.resize(*fig.bbox.size, forward=False)\n ResizeEvent('resize_event', self)._process()\n self.draw_idle()\n\n def handle_send_image_mode(self, event):\n # The client requests notification of what the current image mode is.\n self.send_event('image_mode', mode=self._current_image_mode)\n\n def handle_set_device_pixel_ratio(self, event):\n self._handle_set_device_pixel_ratio(event.get('device_pixel_ratio', 1))\n\n def handle_set_dpi_ratio(self, event):\n # This handler is for backwards-compatibility with older ipympl.\n self._handle_set_device_pixel_ratio(event.get('dpi_ratio', 1))\n\n def _handle_set_device_pixel_ratio(self, device_pixel_ratio):\n if self._set_device_pixel_ratio(device_pixel_ratio):\n self._force_full = True\n self.draw_idle()\n\n def send_event(self, event_type, **kwargs):\n if self.manager:\n self.manager._send_event(event_type, **kwargs)\n\n\n_ALLOWED_TOOL_ITEMS = {\n 'home',\n 'back',\n 'forward',\n 'pan',\n 'zoom',\n 'download',\n None,\n}\n\n\nclass NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2):\n\n # Use the standard toolbar items + download button\n toolitems = [\n (text, tooltip_text, image_file, name_of_method)\n for text, tooltip_text, image_file, name_of_method\n in (*backend_bases.NavigationToolbar2.toolitems,\n ('Download', 'Download plot', 'filesave', 'download'))\n if name_of_method in _ALLOWED_TOOL_ITEMS\n ]\n\n def __init__(self, canvas):\n self.message = ''\n super().__init__(canvas)\n\n def set_message(self, message):\n if message != self.message:\n self.canvas.send_event("message", message=message)\n self.message = message\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n self.canvas.send_event("rubberband", x0=x0, y0=y0, x1=x1, y1=y1)\n\n def remove_rubberband(self):\n self.canvas.send_event("rubberband", x0=-1, y0=-1, x1=-1, y1=-1)\n\n def save_figure(self, *args):\n """Save the current figure."""\n self.canvas.send_event('save')\n return self.UNKNOWN_SAVED_STATUS\n\n def pan(self):\n super().pan()\n self.canvas.send_event('navigate_mode', mode=self.mode.name)\n\n def zoom(self):\n super().zoom()\n self.canvas.send_event('navigate_mode', mode=self.mode.name)\n\n def set_history_buttons(self):\n can_backward = self._nav_stack._pos > 0\n can_forward = self._nav_stack._pos < len(self._nav_stack) - 1\n self.canvas.send_event('history_buttons',\n Back=can_backward, Forward=can_forward)\n\n\nclass FigureManagerWebAgg(backend_bases.FigureManagerBase):\n # This must be None to not break ipympl\n _toolbar2_class = None\n ToolbarCls = NavigationToolbar2WebAgg\n _window_title = "Matplotlib"\n\n def __init__(self, canvas, num):\n self.web_sockets = set()\n super().__init__(canvas, num)\n\n def show(self):\n pass\n\n def resize(self, w, h, forward=True):\n self._send_event(\n 'resize',\n size=(w / self.canvas.device_pixel_ratio,\n h / self.canvas.device_pixel_ratio),\n forward=forward)\n\n def set_window_title(self, title):\n self._send_event('figure_label', label=title)\n self._window_title = title\n\n def get_window_title(self):\n return self._window_title\n\n # The following methods are specific to FigureManagerWebAgg\n\n def add_web_socket(self, web_socket):\n assert hasattr(web_socket, 'send_binary')\n assert hasattr(web_socket, 'send_json')\n self.web_sockets.add(web_socket)\n self.resize(*self.canvas.figure.bbox.size)\n self._send_event('refresh')\n\n def remove_web_socket(self, web_socket):\n self.web_sockets.remove(web_socket)\n\n def handle_json(self, content):\n self.canvas.handle_event(content)\n\n def refresh_all(self):\n if self.web_sockets:\n diff = self.canvas.get_diff_image()\n if diff is not None:\n for s in self.web_sockets:\n s.send_binary(diff)\n\n @classmethod\n def get_javascript(cls, stream=None):\n if stream is None:\n output = StringIO()\n else:\n output = stream\n\n output.write((Path(__file__).parent / "web_backend/js/mpl.js")\n .read_text(encoding="utf-8"))\n\n toolitems = []\n for name, tooltip, image, method in cls.ToolbarCls.toolitems:\n if name is None:\n toolitems.append(['', '', '', ''])\n else:\n toolitems.append([name, tooltip, image, method])\n output.write(f"mpl.toolbar_items = {json.dumps(toolitems)};\n\n")\n\n extensions = []\n for filetype, ext in sorted(FigureCanvasWebAggCore.\n get_supported_filetypes_grouped().\n items()):\n extensions.append(ext[0])\n output.write(f"mpl.extensions = {json.dumps(extensions)};\n\n")\n\n output.write("mpl.default_extension = {};".format(\n json.dumps(FigureCanvasWebAggCore.get_default_filetype())))\n\n if stream is None:\n return output.getvalue()\n\n @classmethod\n def get_static_file_path(cls):\n return os.path.join(os.path.dirname(__file__), 'web_backend')\n\n def _send_event(self, event_type, **kwargs):\n payload = {'type': event_type, **kwargs}\n for s in self.web_sockets:\n s.send_json(payload)\n\n\n@_Backend.export\nclass _BackendWebAggCoreAgg(_Backend):\n FigureCanvas = FigureCanvasWebAggCore\n FigureManager = FigureManagerWebAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_webagg_core.py
backend_webagg_core.py
Python
18,748
0.95
0.191651
0.113636
python-kit
3
2024-07-28T21:55:24.190580
BSD-3-Clause
false
d63ad0864b1cd2d6b944080dbaac4120
"""\nA wxPython backend for matplotlib.\n\nOriginally contributed by Jeremy O'Donoghue (jeremy@o-donoghue.com) and John\nHunter (jdhunter@ace.bsd.uchicago.edu).\n\nCopyright (C) Jeremy O'Donoghue & John Hunter, 2003-4.\n"""\n\nimport functools\nimport logging\nimport math\nimport pathlib\nimport sys\nimport weakref\n\nimport numpy as np\nimport PIL.Image\n\nimport matplotlib as mpl\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase,\n GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase,\n TimerBase, ToolContainerBase, cursors,\n CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)\n\nfrom matplotlib import _api, cbook, backend_tools, _c_internal_utils\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.path import Path\nfrom matplotlib.transforms import Affine2D\n\nimport wx\nimport wx.svg\n\n_log = logging.getLogger(__name__)\n\n# the True dots per inch on the screen; should be display dependent; see\n# http://groups.google.com/d/msg/comp.lang.postscript/-/omHAc9FEuAsJ?hl=en\n# for some info about screen dpi\nPIXELS_PER_INCH = 75\n\n\n# lru_cache holds a reference to the App and prevents it from being gc'ed.\n@functools.lru_cache(1)\ndef _create_wxapp():\n wxapp = wx.App(False)\n wxapp.SetExitOnFrameDelete(True)\n cbook._setup_new_guiapp()\n # Set per-process DPI awareness. This is a NoOp except in MSW\n _c_internal_utils.Win32_SetProcessDpiAwareness_max()\n return wxapp\n\n\nclass TimerWx(TimerBase):\n """Subclass of `.TimerBase` using wx.Timer events."""\n\n def __init__(self, *args, **kwargs):\n self._timer = wx.Timer()\n self._timer.Notify = self._on_timer\n super().__init__(*args, **kwargs)\n\n def _timer_start(self):\n self._timer.Start(self._interval, self._single)\n\n def _timer_stop(self):\n self._timer.Stop()\n\n def _timer_set_interval(self):\n if self._timer.IsRunning():\n self._timer_start() # Restart with new interval.\n\n\n@_api.deprecated(\n "2.0", name="wx", obj_type="backend", removal="the future",\n alternative="wxagg",\n addendum="See the Matplotlib usage FAQ for more info on backends.")\nclass RendererWx(RendererBase):\n """\n The renderer handles all the drawing primitives using a graphics\n context instance that controls the colors/styles. It acts as the\n 'renderer' instance used by many classes in the hierarchy.\n """\n # In wxPython, drawing is performed on a wxDC instance, which will\n # generally be mapped to the client area of the window displaying\n # the plot. Under wxPython, the wxDC instance has a wx.Pen which\n # describes the colour and weight of any lines drawn, and a wxBrush\n # which describes the fill colour of any closed polygon.\n\n # Font styles, families and weight.\n fontweights = {\n 100: wx.FONTWEIGHT_LIGHT,\n 200: wx.FONTWEIGHT_LIGHT,\n 300: wx.FONTWEIGHT_LIGHT,\n 400: wx.FONTWEIGHT_NORMAL,\n 500: wx.FONTWEIGHT_NORMAL,\n 600: wx.FONTWEIGHT_NORMAL,\n 700: wx.FONTWEIGHT_BOLD,\n 800: wx.FONTWEIGHT_BOLD,\n 900: wx.FONTWEIGHT_BOLD,\n 'ultralight': wx.FONTWEIGHT_LIGHT,\n 'light': wx.FONTWEIGHT_LIGHT,\n 'normal': wx.FONTWEIGHT_NORMAL,\n 'medium': wx.FONTWEIGHT_NORMAL,\n 'semibold': wx.FONTWEIGHT_NORMAL,\n 'bold': wx.FONTWEIGHT_BOLD,\n 'heavy': wx.FONTWEIGHT_BOLD,\n 'ultrabold': wx.FONTWEIGHT_BOLD,\n 'black': wx.FONTWEIGHT_BOLD,\n }\n fontangles = {\n 'italic': wx.FONTSTYLE_ITALIC,\n 'normal': wx.FONTSTYLE_NORMAL,\n 'oblique': wx.FONTSTYLE_SLANT,\n }\n\n # wxPython allows for portable font styles, choosing them appropriately for\n # the target platform. Map some standard font names to the portable styles.\n # QUESTION: Is it wise to agree to standard fontnames across all backends?\n fontnames = {\n 'Sans': wx.FONTFAMILY_SWISS,\n 'Roman': wx.FONTFAMILY_ROMAN,\n 'Script': wx.FONTFAMILY_SCRIPT,\n 'Decorative': wx.FONTFAMILY_DECORATIVE,\n 'Modern': wx.FONTFAMILY_MODERN,\n 'Courier': wx.FONTFAMILY_MODERN,\n 'courier': wx.FONTFAMILY_MODERN,\n }\n\n def __init__(self, bitmap, dpi):\n """Initialise a wxWindows renderer instance."""\n super().__init__()\n _log.debug("%s - __init__()", type(self))\n self.width = bitmap.GetWidth()\n self.height = bitmap.GetHeight()\n self.bitmap = bitmap\n self.fontd = {}\n self.dpi = dpi\n self.gc = None\n\n def flipy(self):\n # docstring inherited\n return True\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n\n if ismath:\n s = cbook.strip_math(s)\n\n if self.gc is None:\n gc = self.new_gc()\n else:\n gc = self.gc\n gfx_ctx = gc.gfx_ctx\n font = self.get_wx_font(s, prop)\n gfx_ctx.SetFont(font, wx.BLACK)\n w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)\n\n return w, h, descent\n\n def get_canvas_width_height(self):\n # docstring inherited\n return self.width, self.height\n\n def handle_clip_rectangle(self, gc):\n new_bounds = gc.get_clip_rectangle()\n if new_bounds is not None:\n new_bounds = new_bounds.bounds\n gfx_ctx = gc.gfx_ctx\n if gfx_ctx._lastcliprect != new_bounds:\n gfx_ctx._lastcliprect = new_bounds\n if new_bounds is None:\n gfx_ctx.ResetClip()\n else:\n gfx_ctx.Clip(new_bounds[0],\n self.height - new_bounds[1] - new_bounds[3],\n new_bounds[2], new_bounds[3])\n\n @staticmethod\n def convert_path(gfx_ctx, path, transform):\n wxpath = gfx_ctx.CreatePath()\n for points, code in path.iter_segments(transform):\n if code == Path.MOVETO:\n wxpath.MoveToPoint(*points)\n elif code == Path.LINETO:\n wxpath.AddLineToPoint(*points)\n elif code == Path.CURVE3:\n wxpath.AddQuadCurveToPoint(*points)\n elif code == Path.CURVE4:\n wxpath.AddCurveToPoint(*points)\n elif code == Path.CLOSEPOLY:\n wxpath.CloseSubpath()\n return wxpath\n\n def draw_path(self, gc, path, transform, rgbFace=None):\n # docstring inherited\n gc.select()\n self.handle_clip_rectangle(gc)\n gfx_ctx = gc.gfx_ctx\n transform = transform + \\n Affine2D().scale(1.0, -1.0).translate(0.0, self.height)\n wxpath = self.convert_path(gfx_ctx, path, transform)\n if rgbFace is not None:\n gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace)))\n gfx_ctx.DrawPath(wxpath)\n else:\n gfx_ctx.StrokePath(wxpath)\n gc.unselect()\n\n def draw_image(self, gc, x, y, im):\n bbox = gc.get_clip_rectangle()\n if bbox is not None:\n l, b, w, h = bbox.bounds\n else:\n l = 0\n b = 0\n w = self.width\n h = self.height\n rows, cols = im.shape[:2]\n bitmap = wx.Bitmap.FromBufferRGBA(cols, rows, im.tobytes())\n gc.select()\n gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b),\n int(w), int(-h))\n gc.unselect()\n\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\n # docstring inherited\n\n if ismath:\n s = cbook.strip_math(s)\n _log.debug("%s - draw_text()", type(self))\n gc.select()\n self.handle_clip_rectangle(gc)\n gfx_ctx = gc.gfx_ctx\n\n font = self.get_wx_font(s, prop)\n color = gc.get_wxcolour(gc.get_rgb())\n gfx_ctx.SetFont(font, color)\n\n w, h, d = self.get_text_width_height_descent(s, prop, ismath)\n x = int(x)\n y = int(y - h)\n\n if angle == 0.0:\n gfx_ctx.DrawText(s, x, y)\n else:\n rads = math.radians(angle)\n xo = h * math.sin(rads)\n yo = h * math.cos(rads)\n gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)\n\n gc.unselect()\n\n def new_gc(self):\n # docstring inherited\n _log.debug("%s - new_gc()", type(self))\n self.gc = GraphicsContextWx(self.bitmap, self)\n self.gc.select()\n self.gc.unselect()\n return self.gc\n\n def get_wx_font(self, s, prop):\n """Return a wx font. Cache font instances for efficiency."""\n _log.debug("%s - get_wx_font()", type(self))\n key = hash(prop)\n font = self.fontd.get(key)\n if font is not None:\n return font\n size = self.points_to_pixels(prop.get_size_in_points())\n # Font colour is determined by the active wx.Pen\n # TODO: It may be wise to cache font information\n self.fontd[key] = font = wx.Font( # Cache the font and gc.\n pointSize=round(size),\n family=self.fontnames.get(prop.get_name(), wx.ROMAN),\n style=self.fontangles[prop.get_style()],\n weight=self.fontweights[prop.get_weight()])\n return font\n\n def points_to_pixels(self, points):\n # docstring inherited\n return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0)\n\n\nclass GraphicsContextWx(GraphicsContextBase):\n """\n The graphics context provides the color, line styles, etc.\n\n This class stores a reference to a wxMemoryDC, and a\n wxGraphicsContext that draws to it. Creating a wxGraphicsContext\n seems to be fairly heavy, so these objects are cached based on the\n bitmap object that is passed in.\n\n The base GraphicsContext stores colors as an RGB tuple on the unit\n interval, e.g., (0.5, 0.0, 1.0). wxPython uses an int interval, but\n since wxPython colour management is rather simple, I have not chosen\n to implement a separate colour manager class.\n """\n _capd = {'butt': wx.CAP_BUTT,\n 'projecting': wx.CAP_PROJECTING,\n 'round': wx.CAP_ROUND}\n\n _joind = {'bevel': wx.JOIN_BEVEL,\n 'miter': wx.JOIN_MITER,\n 'round': wx.JOIN_ROUND}\n\n _cache = weakref.WeakKeyDictionary()\n\n def __init__(self, bitmap, renderer):\n super().__init__()\n # assert self.Ok(), "wxMemoryDC not OK to use"\n _log.debug("%s - __init__(): %s", type(self), bitmap)\n\n dc, gfx_ctx = self._cache.get(bitmap, (None, None))\n if dc is None:\n dc = wx.MemoryDC(bitmap)\n gfx_ctx = wx.GraphicsContext.Create(dc)\n gfx_ctx._lastcliprect = None\n self._cache[bitmap] = dc, gfx_ctx\n\n self.bitmap = bitmap\n self.dc = dc\n self.gfx_ctx = gfx_ctx\n self._pen = wx.Pen('BLACK', 1, wx.SOLID)\n gfx_ctx.SetPen(self._pen)\n self.renderer = renderer\n\n def select(self):\n """Select the current bitmap into this wxDC instance."""\n if sys.platform == 'win32':\n self.dc.SelectObject(self.bitmap)\n self.IsSelected = True\n\n def unselect(self):\n """Select a Null bitmap into this wxDC instance."""\n if sys.platform == 'win32':\n self.dc.SelectObject(wx.NullBitmap)\n self.IsSelected = False\n\n def set_foreground(self, fg, isRGBA=None):\n # docstring inherited\n # Implementation note: wxPython has a separate concept of pen and\n # brush - the brush fills any outline trace left by the pen.\n # Here we set both to the same colour - if a figure is not to be\n # filled, the renderer will set the brush to be transparent\n # Same goes for text foreground...\n _log.debug("%s - set_foreground()", type(self))\n self.select()\n super().set_foreground(fg, isRGBA)\n\n self._pen.SetColour(self.get_wxcolour(self.get_rgb()))\n self.gfx_ctx.SetPen(self._pen)\n self.unselect()\n\n def set_linewidth(self, w):\n # docstring inherited\n w = float(w)\n _log.debug("%s - set_linewidth()", type(self))\n self.select()\n if 0 < w < 1:\n w = 1\n super().set_linewidth(w)\n lw = int(self.renderer.points_to_pixels(self._linewidth))\n if lw == 0:\n lw = 1\n self._pen.SetWidth(lw)\n self.gfx_ctx.SetPen(self._pen)\n self.unselect()\n\n def set_capstyle(self, cs):\n # docstring inherited\n _log.debug("%s - set_capstyle()", type(self))\n self.select()\n super().set_capstyle(cs)\n self._pen.SetCap(GraphicsContextWx._capd[self._capstyle])\n self.gfx_ctx.SetPen(self._pen)\n self.unselect()\n\n def set_joinstyle(self, js):\n # docstring inherited\n _log.debug("%s - set_joinstyle()", type(self))\n self.select()\n super().set_joinstyle(js)\n self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])\n self.gfx_ctx.SetPen(self._pen)\n self.unselect()\n\n def get_wxcolour(self, color):\n """Convert an RGB(A) color to a wx.Colour."""\n _log.debug("%s - get_wx_color()", type(self))\n return wx.Colour(*[int(255 * x) for x in color])\n\n\nclass _FigureCanvasWxBase(FigureCanvasBase, wx.Panel):\n """\n The FigureCanvas contains the figure and does event handling.\n\n In the wxPython backend, it is derived from wxPanel, and (usually) lives\n inside a frame instantiated by a FigureManagerWx. The parent window\n probably implements a wx.Sizer to control the displayed control size - but\n we give a hint as to our preferred minimum size.\n """\n\n required_interactive_framework = "wx"\n _timer_cls = TimerWx\n manager_class = _api.classproperty(lambda cls: FigureManagerWx)\n\n keyvald = {\n wx.WXK_CONTROL: 'control',\n wx.WXK_SHIFT: 'shift',\n wx.WXK_ALT: 'alt',\n wx.WXK_CAPITAL: 'caps_lock',\n wx.WXK_LEFT: 'left',\n wx.WXK_UP: 'up',\n wx.WXK_RIGHT: 'right',\n wx.WXK_DOWN: 'down',\n wx.WXK_ESCAPE: 'escape',\n wx.WXK_F1: 'f1',\n wx.WXK_F2: 'f2',\n wx.WXK_F3: 'f3',\n wx.WXK_F4: 'f4',\n wx.WXK_F5: 'f5',\n wx.WXK_F6: 'f6',\n wx.WXK_F7: 'f7',\n wx.WXK_F8: 'f8',\n wx.WXK_F9: 'f9',\n wx.WXK_F10: 'f10',\n wx.WXK_F11: 'f11',\n wx.WXK_F12: 'f12',\n wx.WXK_SCROLL: 'scroll_lock',\n wx.WXK_PAUSE: 'break',\n wx.WXK_BACK: 'backspace',\n wx.WXK_RETURN: 'enter',\n wx.WXK_INSERT: 'insert',\n wx.WXK_DELETE: 'delete',\n wx.WXK_HOME: 'home',\n wx.WXK_END: 'end',\n wx.WXK_PAGEUP: 'pageup',\n wx.WXK_PAGEDOWN: 'pagedown',\n wx.WXK_NUMPAD0: '0',\n wx.WXK_NUMPAD1: '1',\n wx.WXK_NUMPAD2: '2',\n wx.WXK_NUMPAD3: '3',\n wx.WXK_NUMPAD4: '4',\n wx.WXK_NUMPAD5: '5',\n wx.WXK_NUMPAD6: '6',\n wx.WXK_NUMPAD7: '7',\n wx.WXK_NUMPAD8: '8',\n wx.WXK_NUMPAD9: '9',\n wx.WXK_NUMPAD_ADD: '+',\n wx.WXK_NUMPAD_SUBTRACT: '-',\n wx.WXK_NUMPAD_MULTIPLY: '*',\n wx.WXK_NUMPAD_DIVIDE: '/',\n wx.WXK_NUMPAD_DECIMAL: 'dec',\n wx.WXK_NUMPAD_ENTER: 'enter',\n wx.WXK_NUMPAD_UP: 'up',\n wx.WXK_NUMPAD_RIGHT: 'right',\n wx.WXK_NUMPAD_DOWN: 'down',\n wx.WXK_NUMPAD_LEFT: 'left',\n wx.WXK_NUMPAD_PAGEUP: 'pageup',\n wx.WXK_NUMPAD_PAGEDOWN: 'pagedown',\n wx.WXK_NUMPAD_HOME: 'home',\n wx.WXK_NUMPAD_END: 'end',\n wx.WXK_NUMPAD_INSERT: 'insert',\n wx.WXK_NUMPAD_DELETE: 'delete',\n }\n\n def __init__(self, parent, id, figure=None):\n """\n Initialize a FigureWx instance.\n\n - Initialize the FigureCanvasBase and wxPanel parents.\n - Set event handlers for resize, paint, and keyboard and mouse\n interaction.\n """\n\n FigureCanvasBase.__init__(self, figure)\n size = wx.Size(*map(math.ceil, self.figure.bbox.size))\n if wx.Platform != '__WXMSW__':\n size = parent.FromDIP(size)\n # Set preferred window size hint - helps the sizer, if one is connected\n wx.Panel.__init__(self, parent, id, size=size)\n self.bitmap = None\n self._isDrawn = False\n self._rubberband_rect = None\n self._rubberband_pen_black = wx.Pen('BLACK', 1, wx.PENSTYLE_SHORT_DASH)\n self._rubberband_pen_white = wx.Pen('WHITE', 1, wx.PENSTYLE_SOLID)\n\n self.Bind(wx.EVT_SIZE, self._on_size)\n self.Bind(wx.EVT_PAINT, self._on_paint)\n self.Bind(wx.EVT_CHAR_HOOK, self._on_key_down)\n self.Bind(wx.EVT_KEY_UP, self._on_key_up)\n self.Bind(wx.EVT_LEFT_DOWN, self._on_mouse_button)\n self.Bind(wx.EVT_LEFT_DCLICK, self._on_mouse_button)\n self.Bind(wx.EVT_LEFT_UP, self._on_mouse_button)\n self.Bind(wx.EVT_MIDDLE_DOWN, self._on_mouse_button)\n self.Bind(wx.EVT_MIDDLE_DCLICK, self._on_mouse_button)\n self.Bind(wx.EVT_MIDDLE_UP, self._on_mouse_button)\n self.Bind(wx.EVT_RIGHT_DOWN, self._on_mouse_button)\n self.Bind(wx.EVT_RIGHT_DCLICK, self._on_mouse_button)\n self.Bind(wx.EVT_RIGHT_UP, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX1_DOWN, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX1_UP, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX2_DOWN, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX2_UP, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX1_DCLICK, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSE_AUX2_DCLICK, self._on_mouse_button)\n self.Bind(wx.EVT_MOUSEWHEEL, self._on_mouse_wheel)\n self.Bind(wx.EVT_MOTION, self._on_motion)\n self.Bind(wx.EVT_ENTER_WINDOW, self._on_enter)\n self.Bind(wx.EVT_LEAVE_WINDOW, self._on_leave)\n\n self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._on_capture_lost)\n self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._on_capture_lost)\n\n self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker.\n self.SetBackgroundColour(wx.WHITE)\n\n if wx.Platform == '__WXMAC__':\n # Initial scaling. Other platforms handle this automatically\n dpiScale = self.GetDPIScaleFactor()\n self.SetInitialSize(self.GetSize()*(1/dpiScale))\n self._set_device_pixel_ratio(dpiScale)\n\n def Copy_to_Clipboard(self, event=None):\n """Copy bitmap of canvas to system clipboard."""\n bmp_obj = wx.BitmapDataObject()\n bmp_obj.SetBitmap(self.bitmap)\n\n if not wx.TheClipboard.IsOpened():\n open_success = wx.TheClipboard.Open()\n if open_success:\n wx.TheClipboard.SetData(bmp_obj)\n wx.TheClipboard.Flush()\n wx.TheClipboard.Close()\n\n def _update_device_pixel_ratio(self, *args, **kwargs):\n # We need to be careful in cases with mixed resolution displays if\n # device_pixel_ratio changes.\n if self._set_device_pixel_ratio(self.GetDPIScaleFactor()):\n self.draw()\n\n def draw_idle(self):\n # docstring inherited\n _log.debug("%s - draw_idle()", type(self))\n self._isDrawn = False # Force redraw\n # Triggering a paint event is all that is needed to defer drawing\n # until later. The platform will send the event when it thinks it is\n # a good time (usually as soon as there are no other events pending).\n self.Refresh(eraseBackground=False)\n\n def flush_events(self):\n # docstring inherited\n wx.Yield()\n\n def start_event_loop(self, timeout=0):\n # docstring inherited\n if hasattr(self, '_event_loop'):\n raise RuntimeError("Event loop already running")\n timer = wx.Timer(self, id=wx.ID_ANY)\n if timeout > 0:\n timer.Start(int(timeout * 1000), oneShot=True)\n self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=timer.GetId())\n # Event loop handler for start/stop event loop\n self._event_loop = wx.GUIEventLoop()\n self._event_loop.Run()\n timer.Stop()\n\n def stop_event_loop(self, event=None):\n # docstring inherited\n if hasattr(self, '_event_loop'):\n if self._event_loop.IsRunning():\n self._event_loop.Exit()\n del self._event_loop\n\n def _get_imagesave_wildcards(self):\n """Return the wildcard string for the filesave dialog."""\n default_filetype = self.get_default_filetype()\n filetypes = self.get_supported_filetypes_grouped()\n sorted_filetypes = sorted(filetypes.items())\n wildcards = []\n extensions = []\n filter_index = 0\n for i, (name, exts) in enumerate(sorted_filetypes):\n ext_list = ';'.join(['*.%s' % ext for ext in exts])\n extensions.append(exts[0])\n wildcard = f'{name} ({ext_list})|{ext_list}'\n if default_filetype in exts:\n filter_index = i\n wildcards.append(wildcard)\n wildcards = '|'.join(wildcards)\n return wildcards, extensions, filter_index\n\n def gui_repaint(self, drawDC=None):\n """\n Update the displayed image on the GUI canvas, using the supplied\n wx.PaintDC device context.\n """\n _log.debug("%s - gui_repaint()", type(self))\n # The "if self" check avoids a "wrapped C/C++ object has been deleted"\n # RuntimeError if doing things after window is closed.\n if not (self and self.IsShownOnScreen()):\n return\n if not drawDC: # not called from OnPaint use a ClientDC\n drawDC = wx.ClientDC(self)\n # For 'WX' backend on Windows, the bitmap cannot be in use by another\n # DC (see GraphicsContextWx._cache).\n bmp = (self.bitmap.ConvertToImage().ConvertToBitmap()\n if wx.Platform == '__WXMSW__'\n and isinstance(self.figure.canvas.get_renderer(), RendererWx)\n else self.bitmap)\n drawDC.DrawBitmap(bmp, 0, 0)\n if self._rubberband_rect is not None:\n # Some versions of wx+python don't support numpy.float64 here.\n x0, y0, x1, y1 = map(round, self._rubberband_rect)\n rect = [(x0, y0, x1, y0), (x1, y0, x1, y1),\n (x0, y0, x0, y1), (x0, y1, x1, y1)]\n drawDC.DrawLineList(rect, self._rubberband_pen_white)\n drawDC.DrawLineList(rect, self._rubberband_pen_black)\n\n filetypes = {\n **FigureCanvasBase.filetypes,\n 'bmp': 'Windows bitmap',\n 'jpeg': 'JPEG',\n 'jpg': 'JPEG',\n 'pcx': 'PCX',\n 'png': 'Portable Network Graphics',\n 'tif': 'Tagged Image Format File',\n 'tiff': 'Tagged Image Format File',\n 'xpm': 'X pixmap',\n }\n\n def _on_paint(self, event):\n """Called when wxPaintEvt is generated."""\n _log.debug("%s - _on_paint()", type(self))\n drawDC = wx.PaintDC(self)\n if not self._isDrawn:\n self.draw(drawDC=drawDC)\n else:\n self.gui_repaint(drawDC=drawDC)\n drawDC.Destroy()\n\n def _on_size(self, event):\n """\n Called when wxEventSize is generated.\n\n In this application we attempt to resize to fit the window, so it\n is better to take the performance hit and redraw the whole window.\n """\n self._update_device_pixel_ratio()\n _log.debug("%s - _on_size()", type(self))\n sz = self.GetParent().GetSizer()\n if sz:\n si = sz.GetItem(self)\n if sz and si and not si.Proportion and not si.Flag & wx.EXPAND:\n # managed by a sizer, but with a fixed size\n size = self.GetMinSize()\n else:\n # variable size\n size = self.GetClientSize()\n # Do not allow size to become smaller than MinSize\n size.IncTo(self.GetMinSize())\n if getattr(self, "_width", None):\n if size == (self._width, self._height):\n # no change in size\n return\n self._width, self._height = size\n self._isDrawn = False\n\n if self._width <= 1 or self._height <= 1:\n return # Empty figure\n\n # Create a new, correctly sized bitmap\n dpival = self.figure.dpi\n if not wx.Platform == '__WXMSW__':\n scale = self.GetDPIScaleFactor()\n dpival /= scale\n winch = self._width / dpival\n hinch = self._height / dpival\n self.figure.set_size_inches(winch, hinch, forward=False)\n\n # Rendering will happen on the associated paint event\n # so no need to do anything here except to make sure\n # the whole background is repainted.\n self.Refresh(eraseBackground=False)\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n\n @staticmethod\n def _mpl_buttons():\n state = wx.GetMouseState()\n # NOTE: Alternatively, we could use event.LeftIsDown() / etc. but this\n # fails to report multiclick drags on macOS (other OSes have not been\n # verified).\n mod_table = [\n (MouseButton.LEFT, state.LeftIsDown()),\n (MouseButton.RIGHT, state.RightIsDown()),\n (MouseButton.MIDDLE, state.MiddleIsDown()),\n (MouseButton.BACK, state.Aux1IsDown()),\n (MouseButton.FORWARD, state.Aux2IsDown()),\n ]\n # State *after* press/release.\n return {button for button, flag in mod_table if flag}\n\n @staticmethod\n def _mpl_modifiers(event=None, *, exclude=None):\n mod_table = [\n ("ctrl", wx.MOD_CONTROL, wx.WXK_CONTROL),\n ("alt", wx.MOD_ALT, wx.WXK_ALT),\n ("shift", wx.MOD_SHIFT, wx.WXK_SHIFT),\n ]\n if event is not None:\n modifiers = event.GetModifiers()\n return [name for name, mod, key in mod_table\n if modifiers & mod and exclude != key]\n else:\n return [name for name, mod, key in mod_table\n if wx.GetKeyState(key)]\n\n def _get_key(self, event):\n keyval = event.KeyCode\n if keyval in self.keyvald:\n key = self.keyvald[keyval]\n elif keyval < 256:\n key = chr(keyval)\n # wx always returns an uppercase, so make it lowercase if the shift\n # key is not depressed (NOTE: this will not handle Caps Lock)\n if not event.ShiftDown():\n key = key.lower()\n else:\n return None\n mods = self._mpl_modifiers(event, exclude=keyval)\n if "shift" in mods and key.isupper():\n mods.remove("shift")\n return "+".join([*mods, key])\n\n def _mpl_coords(self, pos=None):\n """\n Convert a wx position, defaulting to the current cursor position, to\n Matplotlib coordinates.\n """\n if pos is None:\n pos = wx.GetMouseState()\n x, y = self.ScreenToClient(pos.X, pos.Y)\n else:\n x, y = pos.X, pos.Y\n # flip y so y=0 is bottom of canvas\n if not wx.Platform == '__WXMSW__':\n scale = self.GetDPIScaleFactor()\n return x*scale, self.figure.bbox.height - y*scale\n else:\n return x, self.figure.bbox.height - y\n\n def _on_key_down(self, event):\n """Capture key press."""\n KeyEvent("key_press_event", self,\n self._get_key(event), *self._mpl_coords(),\n guiEvent=event)._process()\n if self:\n event.Skip()\n\n def _on_key_up(self, event):\n """Release key."""\n KeyEvent("key_release_event", self,\n self._get_key(event), *self._mpl_coords(),\n guiEvent=event)._process()\n if self:\n event.Skip()\n\n def set_cursor(self, cursor):\n # docstring inherited\n cursor = wx.Cursor(_api.check_getitem({\n cursors.MOVE: wx.CURSOR_HAND,\n cursors.HAND: wx.CURSOR_HAND,\n cursors.POINTER: wx.CURSOR_ARROW,\n cursors.SELECT_REGION: wx.CURSOR_CROSS,\n cursors.WAIT: wx.CURSOR_WAIT,\n cursors.RESIZE_HORIZONTAL: wx.CURSOR_SIZEWE,\n cursors.RESIZE_VERTICAL: wx.CURSOR_SIZENS,\n }, cursor=cursor))\n self.SetCursor(cursor)\n self.Refresh()\n\n def _set_capture(self, capture=True):\n """Control wx mouse capture."""\n if self.HasCapture():\n self.ReleaseMouse()\n if capture:\n self.CaptureMouse()\n\n def _on_capture_lost(self, event):\n """Capture changed or lost"""\n self._set_capture(False)\n\n def _on_mouse_button(self, event):\n """Start measuring on an axis."""\n event.Skip()\n self._set_capture(event.ButtonDown() or event.ButtonDClick())\n x, y = self._mpl_coords(event)\n button_map = {\n wx.MOUSE_BTN_LEFT: MouseButton.LEFT,\n wx.MOUSE_BTN_MIDDLE: MouseButton.MIDDLE,\n wx.MOUSE_BTN_RIGHT: MouseButton.RIGHT,\n wx.MOUSE_BTN_AUX1: MouseButton.BACK,\n wx.MOUSE_BTN_AUX2: MouseButton.FORWARD,\n }\n button = event.GetButton()\n button = button_map.get(button, button)\n modifiers = self._mpl_modifiers(event)\n if event.ButtonDown():\n MouseEvent("button_press_event", self, x, y, button,\n modifiers=modifiers, guiEvent=event)._process()\n elif event.ButtonDClick():\n MouseEvent("button_press_event", self, x, y, button, dblclick=True,\n modifiers=modifiers, guiEvent=event)._process()\n elif event.ButtonUp():\n MouseEvent("button_release_event", self, x, y, button,\n modifiers=modifiers, guiEvent=event)._process()\n\n def _on_mouse_wheel(self, event):\n """Translate mouse wheel events into matplotlib events"""\n x, y = self._mpl_coords(event)\n # Convert delta/rotation/rate into a floating point step size\n step = event.LinesPerAction * event.WheelRotation / event.WheelDelta\n # Done handling event\n event.Skip()\n # Mac gives two events for every wheel event; skip every second one.\n if wx.Platform == '__WXMAC__':\n if not hasattr(self, '_skipwheelevent'):\n self._skipwheelevent = True\n elif self._skipwheelevent:\n self._skipwheelevent = False\n return # Return without processing event\n else:\n self._skipwheelevent = True\n MouseEvent("scroll_event", self, x, y, step=step,\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def _on_motion(self, event):\n """Start measuring on an axis."""\n event.Skip()\n MouseEvent("motion_notify_event", self,\n *self._mpl_coords(event),\n buttons=self._mpl_buttons(),\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def _on_enter(self, event):\n """Mouse has entered the window."""\n event.Skip()\n LocationEvent("figure_enter_event", self,\n *self._mpl_coords(event),\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n def _on_leave(self, event):\n """Mouse has left the window."""\n event.Skip()\n LocationEvent("figure_leave_event", self,\n *self._mpl_coords(event),\n modifiers=self._mpl_modifiers(),\n guiEvent=event)._process()\n\n\nclass FigureCanvasWx(_FigureCanvasWxBase):\n # Rendering to a Wx canvas using the deprecated Wx renderer.\n\n def draw(self, drawDC=None):\n """\n Render the figure using RendererWx instance renderer, or using a\n previously defined renderer if none is specified.\n """\n _log.debug("%s - draw()", type(self))\n self.renderer = RendererWx(self.bitmap, self.figure.dpi)\n self.figure.draw(self.renderer)\n self._isDrawn = True\n self.gui_repaint(drawDC=drawDC)\n\n def _print_image(self, filetype, filename):\n bitmap = wx.Bitmap(math.ceil(self.figure.bbox.width),\n math.ceil(self.figure.bbox.height))\n self.figure.draw(RendererWx(bitmap, self.figure.dpi))\n saved_obj = (bitmap.ConvertToImage()\n if cbook.is_writable_file_like(filename)\n else bitmap)\n if not saved_obj.SaveFile(filename, filetype):\n raise RuntimeError(f'Could not save figure to {filename}')\n # draw() is required here since bits of state about the last renderer\n # are strewn about the artist draw methods. Do not remove the draw\n # without first verifying that these have been cleaned up. The artist\n # contains() methods will fail otherwise.\n if self._isDrawn:\n self.draw()\n # The "if self" check avoids a "wrapped C/C++ object has been deleted"\n # RuntimeError if doing things after window is closed.\n if self:\n self.Refresh()\n\n print_bmp = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_BMP)\n print_jpeg = print_jpg = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_JPEG)\n print_pcx = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_PCX)\n print_png = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_PNG)\n print_tiff = print_tif = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_TIF)\n print_xpm = functools.partialmethod(\n _print_image, wx.BITMAP_TYPE_XPM)\n\n\nclass FigureFrameWx(wx.Frame):\n def __init__(self, num, fig, *, canvas_class):\n # On non-Windows platform, explicitly set the position - fix\n # positioning bug on some Linux platforms\n if wx.Platform == '__WXMSW__':\n pos = wx.DefaultPosition\n else:\n pos = wx.Point(20, 20)\n super().__init__(parent=None, id=-1, pos=pos)\n # Frame will be sized later by the Fit method\n _log.debug("%s - __init__()", type(self))\n _set_frame_icon(self)\n\n self.canvas = canvas_class(self, -1, fig)\n # Auto-attaches itself to self.canvas.manager\n manager = FigureManagerWx(self.canvas, num, self)\n\n toolbar = self.canvas.manager.toolbar\n if toolbar is not None:\n self.SetToolBar(toolbar)\n\n # On Windows, canvas sizing must occur after toolbar addition;\n # otherwise the toolbar further resizes the canvas.\n w, h = map(math.ceil, fig.bbox.size)\n self.canvas.SetInitialSize(self.FromDIP(wx.Size(w, h)))\n self.canvas.SetMinSize(self.FromDIP(wx.Size(2, 2)))\n self.canvas.SetFocus()\n\n self.Fit()\n\n self.Bind(wx.EVT_CLOSE, self._on_close)\n\n def _on_close(self, event):\n _log.debug("%s - on_close()", type(self))\n CloseEvent("close_event", self.canvas)._process()\n self.canvas.stop_event_loop()\n # set FigureManagerWx.frame to None to prevent repeated attempts to\n # close this frame from FigureManagerWx.destroy()\n self.canvas.manager.frame = None\n # remove figure manager from Gcf.figs\n Gcf.destroy(self.canvas.manager)\n try: # See issue 2941338.\n self.canvas.mpl_disconnect(self.canvas.toolbar._id_drag)\n except AttributeError: # If there's no toolbar.\n pass\n # Carry on with close event propagation, frame & children destruction\n event.Skip()\n\n\nclass FigureManagerWx(FigureManagerBase):\n """\n Container/controller for the FigureCanvas and GUI frame.\n\n It is instantiated by Gcf whenever a new figure is created. Gcf is\n responsible for managing multiple instances of FigureManagerWx.\n\n Attributes\n ----------\n canvas : `FigureCanvas`\n a FigureCanvasWx(wx.Panel) instance\n window : wxFrame\n a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html\n """\n\n def __init__(self, canvas, num, frame):\n _log.debug("%s - __init__()", type(self))\n self.frame = self.window = frame\n super().__init__(canvas, num)\n\n @classmethod\n def create_with_canvas(cls, canvas_class, figure, num):\n # docstring inherited\n wxapp = wx.GetApp() or _create_wxapp()\n frame = FigureFrameWx(num, figure, canvas_class=canvas_class)\n manager = figure.canvas.manager\n if mpl.is_interactive():\n manager.frame.Show()\n figure.canvas.draw_idle()\n return manager\n\n @classmethod\n def start_main_loop(cls):\n if not wx.App.IsMainLoopRunning():\n wxapp = wx.GetApp()\n if wxapp is not None:\n wxapp.MainLoop()\n\n def show(self):\n # docstring inherited\n self.frame.Show()\n self.canvas.draw()\n if mpl.rcParams['figure.raise_window']:\n self.frame.Raise()\n\n def destroy(self, *args):\n # docstring inherited\n _log.debug("%s - destroy()", type(self))\n frame = self.frame\n if frame: # Else, may have been already deleted, e.g. when closing.\n # As this can be called from non-GUI thread from plt.close use\n # wx.CallAfter to ensure thread safety.\n wx.CallAfter(frame.Close)\n\n def full_screen_toggle(self):\n # docstring inherited\n self.frame.ShowFullScreen(not self.frame.IsFullScreen())\n\n def get_window_title(self):\n # docstring inherited\n return self.window.GetTitle()\n\n def set_window_title(self, title):\n # docstring inherited\n self.window.SetTitle(title)\n\n def resize(self, width, height):\n # docstring inherited\n # Directly using SetClientSize doesn't handle the toolbar on Windows.\n self.window.SetSize(self.window.ClientToWindowSize(wx.Size(\n math.ceil(width), math.ceil(height))))\n\n\ndef _load_bitmap(filename):\n """\n Load a wx.Bitmap from a file in the "images" directory of the Matplotlib\n data.\n """\n return wx.Bitmap(str(cbook._get_data_path('images', filename)))\n\n\ndef _set_frame_icon(frame):\n bundle = wx.IconBundle()\n for image in ('matplotlib.png', 'matplotlib_large.png'):\n icon = wx.Icon(_load_bitmap(image))\n if not icon.IsOk():\n return\n bundle.AddIcon(icon)\n frame.SetIcons(bundle)\n\n\nclass NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):\n def __init__(self, canvas, coordinates=True, *, style=wx.TB_BOTTOM):\n wx.ToolBar.__init__(self, canvas.GetParent(), -1, style=style)\n if wx.Platform == '__WXMAC__':\n self.SetToolBitmapSize(self.GetToolBitmapSize()*self.GetDPIScaleFactor())\n\n self.wx_ids = {}\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n self.AddSeparator()\n continue\n self.wx_ids[text] = (\n self.AddTool(\n -1,\n bitmap=self._icon(f"{image_file}.svg"),\n bmpDisabled=wx.NullBitmap,\n label=text, shortHelp=tooltip_text,\n kind=(wx.ITEM_CHECK if text in ["Pan", "Zoom"]\n else wx.ITEM_NORMAL))\n .Id)\n self.Bind(wx.EVT_TOOL, getattr(self, callback),\n id=self.wx_ids[text])\n\n self._coordinates = coordinates\n if self._coordinates:\n self.AddStretchableSpace()\n self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT)\n self.AddControl(self._label_text)\n\n self.Realize()\n\n NavigationToolbar2.__init__(self, canvas)\n\n @staticmethod\n def _icon(name):\n """\n Construct a `wx.Bitmap` suitable for use as icon from an image file\n *name*, including the extension and relative to Matplotlib's "images"\n data directory.\n """\n try:\n dark = wx.SystemSettings.GetAppearance().IsDark()\n except AttributeError: # wxpython < 4.1\n # copied from wx's IsUsingDarkBackground / GetLuminance.\n bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)\n fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n # See wx.Colour.GetLuminance.\n bg_lum = (.299 * bg.red + .587 * bg.green + .114 * bg.blue) / 255\n fg_lum = (.299 * fg.red + .587 * fg.green + .114 * fg.blue) / 255\n dark = fg_lum - bg_lum > .2\n\n path = cbook._get_data_path('images', name)\n if path.suffix == '.svg':\n svg = path.read_bytes()\n if dark:\n svg = svg.replace(b'fill:black;', b'fill:white;')\n toolbarIconSize = wx.ArtProvider().GetDIPSizeHint(wx.ART_TOOLBAR)\n return wx.BitmapBundle.FromSVG(svg, toolbarIconSize)\n else:\n pilimg = PIL.Image.open(path)\n # ensure RGBA as wx BitMap expects RGBA format\n image = np.array(pilimg.convert("RGBA"))\n if dark:\n fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n black_mask = (image[..., :3] == 0).all(axis=-1)\n image[black_mask, :3] = (fg.Red(), fg.Green(), fg.Blue())\n return wx.Bitmap.FromBufferRGBA(\n image.shape[1], image.shape[0], image.tobytes())\n\n def _update_buttons_checked(self):\n if "Pan" in self.wx_ids:\n self.ToggleTool(self.wx_ids["Pan"], self.mode.name == "PAN")\n if "Zoom" in self.wx_ids:\n self.ToggleTool(self.wx_ids["Zoom"], self.mode.name == "ZOOM")\n\n def zoom(self, *args):\n super().zoom(*args)\n self._update_buttons_checked()\n\n def pan(self, *args):\n super().pan(*args)\n self._update_buttons_checked()\n\n def save_figure(self, *args):\n # Fetch the required filename and file type.\n filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()\n default_file = self.canvas.get_default_filename()\n dialog = wx.FileDialog(\n self.canvas.GetParent(), "Save to file",\n mpl.rcParams["savefig.directory"], default_file, filetypes,\n wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)\n dialog.SetFilterIndex(filter_index)\n if dialog.ShowModal() == wx.ID_OK:\n path = pathlib.Path(dialog.GetPath())\n _log.debug('%s - Save file path: %s', type(self), path)\n fmt = exts[dialog.GetFilterIndex()]\n ext = path.suffix[1:]\n if ext in self.canvas.get_supported_filetypes() and fmt != ext:\n # looks like they forgot to set the image type drop\n # down, going with the extension.\n _log.warning('extension %s did not match the selected '\n 'image type %s; going with %s',\n ext, fmt, ext)\n fmt = ext\n # Save dir for next time, unless empty str (which means use cwd).\n if mpl.rcParams["savefig.directory"]:\n mpl.rcParams["savefig.directory"] = str(path.parent)\n try:\n self.canvas.figure.savefig(path, format=fmt)\n return path\n except Exception as e:\n dialog = wx.MessageDialog(\n parent=self.canvas.GetParent(), message=str(e),\n caption='Matplotlib error')\n dialog.ShowModal()\n dialog.Destroy()\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n height = self.canvas.figure.bbox.height\n sf = 1 if wx.Platform == '__WXMSW__' else self.canvas.GetDPIScaleFactor()\n self.canvas._rubberband_rect = (x0/sf, (height - y0)/sf,\n x1/sf, (height - y1)/sf)\n self.canvas.Refresh()\n\n def remove_rubberband(self):\n self.canvas._rubberband_rect = None\n self.canvas.Refresh()\n\n def set_message(self, s):\n if self._coordinates:\n self._label_text.SetLabel(s)\n\n def set_history_buttons(self):\n can_backward = self._nav_stack._pos > 0\n can_forward = self._nav_stack._pos < len(self._nav_stack) - 1\n if 'Back' in self.wx_ids:\n self.EnableTool(self.wx_ids['Back'], can_backward)\n if 'Forward' in self.wx_ids:\n self.EnableTool(self.wx_ids['Forward'], can_forward)\n\n\n# tools for matplotlib.backend_managers.ToolManager:\n\nclass ToolbarWx(ToolContainerBase, wx.ToolBar):\n _icon_extension = '.svg'\n\n def __init__(self, toolmanager, parent=None, style=wx.TB_BOTTOM):\n if parent is None:\n parent = toolmanager.canvas.GetParent()\n ToolContainerBase.__init__(self, toolmanager)\n wx.ToolBar.__init__(self, parent, -1, style=style)\n self._space = self.AddStretchableSpace()\n self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT)\n self.AddControl(self._label_text)\n self._toolitems = {}\n self._groups = {} # Mapping of groups to the separator after them.\n\n def _get_tool_pos(self, tool):\n """\n Find the position (index) of a wx.ToolBarToolBase in a ToolBar.\n\n ``ToolBar.GetToolPos`` is not useful because wx assigns the same Id to\n all Separators and StretchableSpaces.\n """\n pos, = (pos for pos in range(self.ToolsCount)\n if self.GetToolByPos(pos) == tool)\n return pos\n\n def add_toolitem(self, name, group, position, image_file, description,\n toggle):\n # Find or create the separator that follows this group.\n if group not in self._groups:\n self._groups[group] = self.InsertSeparator(\n self._get_tool_pos(self._space))\n sep = self._groups[group]\n # List all separators.\n seps = [t for t in map(self.GetToolByPos, range(self.ToolsCount))\n if t.IsSeparator() and not t.IsStretchableSpace()]\n # Find where to insert the tool.\n if position >= 0:\n # Find the start of the group by looking for the separator\n # preceding this one; then move forward from it.\n start = (0 if sep == seps[0]\n else self._get_tool_pos(seps[seps.index(sep) - 1]) + 1)\n else:\n # Move backwards from this separator.\n start = self._get_tool_pos(sep) + 1\n idx = start + position\n if image_file:\n bmp = NavigationToolbar2Wx._icon(image_file)\n kind = wx.ITEM_NORMAL if not toggle else wx.ITEM_CHECK\n tool = self.InsertTool(idx, -1, name, bmp, wx.NullBitmap, kind,\n description or "")\n else:\n size = (self.GetTextExtent(name)[0] + 10, -1)\n if toggle:\n control = wx.ToggleButton(self, -1, name, size=size)\n else:\n control = wx.Button(self, -1, name, size=size)\n tool = self.InsertControl(idx, control, label=name)\n self.Realize()\n\n def handler(event):\n self.trigger_tool(name)\n\n if image_file:\n self.Bind(wx.EVT_TOOL, handler, tool)\n else:\n control.Bind(wx.EVT_LEFT_DOWN, handler)\n\n self._toolitems.setdefault(name, [])\n self._toolitems[name].append((tool, handler))\n\n def toggle_toolitem(self, name, toggled):\n if name not in self._toolitems:\n return\n for tool, handler in self._toolitems[name]:\n if not tool.IsControl():\n self.ToggleTool(tool.Id, toggled)\n else:\n tool.GetControl().SetValue(toggled)\n self.Refresh()\n\n def remove_toolitem(self, name):\n for tool, handler in self._toolitems.pop(name, []):\n self.DeleteTool(tool.Id)\n\n def set_message(self, s):\n self._label_text.SetLabel(s)\n\n\n@backend_tools._register_tool_class(_FigureCanvasWxBase)\nclass ConfigureSubplotsWx(backend_tools.ConfigureSubplotsBase):\n def trigger(self, *args):\n NavigationToolbar2Wx.configure_subplots(self)\n\n\n@backend_tools._register_tool_class(_FigureCanvasWxBase)\nclass SaveFigureWx(backend_tools.SaveFigureBase):\n def trigger(self, *args):\n NavigationToolbar2Wx.save_figure(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(_FigureCanvasWxBase)\nclass RubberbandWx(backend_tools.RubberbandBase):\n def draw_rubberband(self, x0, y0, x1, y1):\n NavigationToolbar2Wx.draw_rubberband(\n self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)\n\n def remove_rubberband(self):\n NavigationToolbar2Wx.remove_rubberband(\n self._make_classic_style_pseudo_toolbar())\n\n\nclass _HelpDialog(wx.Dialog):\n _instance = None # a reference to an open dialog singleton\n headers = [("Action", "Shortcuts", "Description")]\n widths = [100, 140, 300]\n\n def __init__(self, parent, help_entries):\n super().__init__(parent, title="Help",\n style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n grid_sizer = wx.FlexGridSizer(0, 3, 8, 6)\n # create and add the entries\n bold = self.GetFont().MakeBold()\n for r, row in enumerate(self.headers + help_entries):\n for (col, width) in zip(row, self.widths):\n label = wx.StaticText(self, label=col)\n if r == 0:\n label.SetFont(bold)\n label.Wrap(width)\n grid_sizer.Add(label, 0, 0, 0)\n # finalize layout, create button\n sizer.Add(grid_sizer, 0, wx.ALL, 6)\n ok = wx.Button(self, wx.ID_OK)\n sizer.Add(ok, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 8)\n self.SetSizer(sizer)\n sizer.Fit(self)\n self.Layout()\n self.Bind(wx.EVT_CLOSE, self._on_close)\n ok.Bind(wx.EVT_BUTTON, self._on_close)\n\n def _on_close(self, event):\n _HelpDialog._instance = None # remove global reference\n self.DestroyLater()\n event.Skip()\n\n @classmethod\n def show(cls, parent, help_entries):\n # if no dialog is shown, create one; otherwise just re-raise it\n if cls._instance:\n cls._instance.Raise()\n return\n cls._instance = cls(parent, help_entries)\n cls._instance.Show()\n\n\n@backend_tools._register_tool_class(_FigureCanvasWxBase)\nclass HelpWx(backend_tools.ToolHelpBase):\n def trigger(self, *args):\n _HelpDialog.show(self.figure.canvas.GetTopLevelParent(),\n self._get_help_entries())\n\n\n@backend_tools._register_tool_class(_FigureCanvasWxBase)\nclass ToolCopyToClipboardWx(backend_tools.ToolCopyToClipboardBase):\n def trigger(self, *args, **kwargs):\n if not self.canvas._isDrawn:\n self.canvas.draw()\n if not self.canvas.bitmap.IsOk() or not wx.TheClipboard.Open():\n return\n try:\n wx.TheClipboard.SetData(wx.BitmapDataObject(self.canvas.bitmap))\n finally:\n wx.TheClipboard.Close()\n\n\nFigureManagerWx._toolbar2_class = NavigationToolbar2Wx\nFigureManagerWx._toolmanager_toolbar_class = ToolbarWx\n\n\n@_Backend.export\nclass _BackendWx(_Backend):\n FigureCanvas = FigureCanvasWx\n FigureManager = FigureManagerWx\n mainloop = FigureManagerWx.start_main_loop\n
.venv\Lib\site-packages\matplotlib\backends\backend_wx.py
backend_wx.py
Python
51,296
0.75
0.183201
0.098251
node-utils
32
2025-02-07T12:39:05.681706
MIT
false
4df650d1391ba7f6ac893706b2878b5a
import wx\n\nfrom .backend_agg import FigureCanvasAgg\nfrom .backend_wx import _BackendWx, _FigureCanvasWxBase\nfrom .backend_wx import ( # noqa: F401 # pylint: disable=W0611\n NavigationToolbar2Wx as NavigationToolbar2WxAgg)\n\n\nclass FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase):\n def draw(self, drawDC=None):\n """\n Render the figure using agg.\n """\n FigureCanvasAgg.draw(self)\n self.bitmap = self._create_bitmap()\n self._isDrawn = True\n self.gui_repaint(drawDC=drawDC)\n\n def blit(self, bbox=None):\n # docstring inherited\n bitmap = self._create_bitmap()\n if bbox is None:\n self.bitmap = bitmap\n else:\n srcDC = wx.MemoryDC(bitmap)\n destDC = wx.MemoryDC(self.bitmap)\n x = int(bbox.x0)\n y = int(self.bitmap.GetHeight() - bbox.y1)\n destDC.Blit(x, y, int(bbox.width), int(bbox.height), srcDC, x, y)\n destDC.SelectObject(wx.NullBitmap)\n srcDC.SelectObject(wx.NullBitmap)\n self.gui_repaint()\n\n def _create_bitmap(self):\n """Create a wx.Bitmap from the renderer RGBA buffer"""\n rgba = self.get_renderer().buffer_rgba()\n h, w, _ = rgba.shape\n bitmap = wx.Bitmap.FromBufferRGBA(w, h, rgba)\n bitmap.SetScaleFactor(self.GetDPIScaleFactor())\n return bitmap\n\n\n@_BackendWx.export\nclass _BackendWxAgg(_BackendWx):\n FigureCanvas = FigureCanvasWxAgg\n
.venv\Lib\site-packages\matplotlib\backends\backend_wxagg.py
backend_wxagg.py
Python
1,468
0.95
0.133333
0.026316
vue-tools
902
2023-09-13T03:02:52.359143
MIT
false
65d120c22158eb4905fd08bde45b31e9
import wx.lib.wxcairo as wxcairo\n\nfrom .backend_cairo import cairo, FigureCanvasCairo\nfrom .backend_wx import _BackendWx, _FigureCanvasWxBase\nfrom .backend_wx import ( # noqa: F401 # pylint: disable=W0611\n NavigationToolbar2Wx as NavigationToolbar2WxCairo)\n\n\nclass FigureCanvasWxCairo(FigureCanvasCairo, _FigureCanvasWxBase):\n def draw(self, drawDC=None):\n size = self.figure.bbox.size.astype(int)\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)\n self._renderer.set_context(cairo.Context(surface))\n self._renderer.dpi = self.figure.dpi\n self.figure.draw(self._renderer)\n self.bitmap = wxcairo.BitmapFromImageSurface(surface)\n self._isDrawn = True\n self.gui_repaint(drawDC=drawDC)\n\n\n@_BackendWx.export\nclass _BackendWxCairo(_BackendWx):\n FigureCanvas = FigureCanvasWxCairo\n
.venv\Lib\site-packages\matplotlib\backends\backend_wxcairo.py
backend_wxcairo.py
Python
848
0.95
0.130435
0
python-kit
888
2024-07-08T22:49:47.499650
Apache-2.0
false
cb0ac9d2bac1a92c77a33d4d10720e21
"""\nQt binding and backend selector.\n\nThe selection logic is as follows:\n- if any of PyQt6, PySide6, PyQt5, or PySide2 have already been\n imported (checked in that order), use it;\n- otherwise, if the QT_API environment variable (used by Enthought) is set, use\n it to determine which binding to use;\n- otherwise, use whatever the rcParams indicate.\n"""\n\nimport operator\nimport os\nimport platform\nimport sys\n\nfrom packaging.version import parse as parse_version\n\nimport matplotlib as mpl\n\nfrom . import _QT_FORCE_QT5_BINDING\n\nQT_API_PYQT6 = "PyQt6"\nQT_API_PYSIDE6 = "PySide6"\nQT_API_PYQT5 = "PyQt5"\nQT_API_PYSIDE2 = "PySide2"\nQT_API_ENV = os.environ.get("QT_API")\nif QT_API_ENV is not None:\n QT_API_ENV = QT_API_ENV.lower()\n_ETS = { # Mapping of QT_API_ENV to requested binding.\n "pyqt6": QT_API_PYQT6, "pyside6": QT_API_PYSIDE6,\n "pyqt5": QT_API_PYQT5, "pyside2": QT_API_PYSIDE2,\n}\n# First, check if anything is already imported.\nif sys.modules.get("PyQt6.QtCore"):\n QT_API = QT_API_PYQT6\nelif sys.modules.get("PySide6.QtCore"):\n QT_API = QT_API_PYSIDE6\nelif sys.modules.get("PyQt5.QtCore"):\n QT_API = QT_API_PYQT5\nelif sys.modules.get("PySide2.QtCore"):\n QT_API = QT_API_PYSIDE2\n# Otherwise, check the QT_API environment variable (from Enthought). This can\n# only override the binding, not the backend (in other words, we check that the\n# requested backend actually matches). Use _get_backend_or_none to avoid\n# triggering backend resolution (which can result in a partially but\n# incompletely imported backend_qt5).\nelif (mpl.rcParams._get_backend_or_none() or "").lower().startswith("qt5"):\n if QT_API_ENV in ["pyqt5", "pyside2"]:\n QT_API = _ETS[QT_API_ENV]\n else:\n _QT_FORCE_QT5_BINDING = True # noqa: F811\n QT_API = None\n# A non-Qt backend was selected but we still got there (possible, e.g., when\n# fully manually embedding Matplotlib in a Qt app without using pyplot).\nelif QT_API_ENV is None:\n QT_API = None\nelif QT_API_ENV in _ETS:\n QT_API = _ETS[QT_API_ENV]\nelse:\n raise RuntimeError(\n "The environment variable QT_API has the unrecognized value {!r}; "\n "valid values are {}".format(QT_API_ENV, ", ".join(_ETS)))\n\n\ndef _setup_pyqt5plus():\n global QtCore, QtGui, QtWidgets, __version__\n global _isdeleted, _to_int\n\n if QT_API == QT_API_PYQT6:\n from PyQt6 import QtCore, QtGui, QtWidgets, sip\n __version__ = QtCore.PYQT_VERSION_STR\n QtCore.Signal = QtCore.pyqtSignal\n QtCore.Slot = QtCore.pyqtSlot\n QtCore.Property = QtCore.pyqtProperty\n _isdeleted = sip.isdeleted\n _to_int = operator.attrgetter('value')\n elif QT_API == QT_API_PYSIDE6:\n from PySide6 import QtCore, QtGui, QtWidgets, __version__\n import shiboken6\n def _isdeleted(obj): return not shiboken6.isValid(obj)\n if parse_version(__version__) >= parse_version('6.4'):\n _to_int = operator.attrgetter('value')\n else:\n _to_int = int\n elif QT_API == QT_API_PYQT5:\n from PyQt5 import QtCore, QtGui, QtWidgets\n import sip\n __version__ = QtCore.PYQT_VERSION_STR\n QtCore.Signal = QtCore.pyqtSignal\n QtCore.Slot = QtCore.pyqtSlot\n QtCore.Property = QtCore.pyqtProperty\n _isdeleted = sip.isdeleted\n _to_int = int\n elif QT_API == QT_API_PYSIDE2:\n from PySide2 import QtCore, QtGui, QtWidgets, __version__\n try:\n from PySide2 import shiboken2\n except ImportError:\n import shiboken2\n def _isdeleted(obj):\n return not shiboken2.isValid(obj)\n _to_int = int\n else:\n raise AssertionError(f"Unexpected QT_API: {QT_API}")\n\n\nif QT_API in [QT_API_PYQT6, QT_API_PYQT5, QT_API_PYSIDE6, QT_API_PYSIDE2]:\n _setup_pyqt5plus()\nelif QT_API is None: # See above re: dict.__getitem__.\n if _QT_FORCE_QT5_BINDING:\n _candidates = [\n (_setup_pyqt5plus, QT_API_PYQT5),\n (_setup_pyqt5plus, QT_API_PYSIDE2),\n ]\n else:\n _candidates = [\n (_setup_pyqt5plus, QT_API_PYQT6),\n (_setup_pyqt5plus, QT_API_PYSIDE6),\n (_setup_pyqt5plus, QT_API_PYQT5),\n (_setup_pyqt5plus, QT_API_PYSIDE2),\n ]\n for _setup, QT_API in _candidates:\n try:\n _setup()\n except ImportError:\n continue\n break\n else:\n raise ImportError(\n "Failed to import any of the following Qt binding modules: {}"\n .format(", ".join([QT_API for _, QT_API in _candidates]))\n )\nelse: # We should not get there.\n raise AssertionError(f"Unexpected QT_API: {QT_API}")\n_version_info = tuple(QtCore.QLibraryInfo.version().segments())\n\n\nif _version_info < (5, 12):\n raise ImportError(\n f"The Qt version imported is "\n f"{QtCore.QLibraryInfo.version().toString()} but Matplotlib requires "\n f"Qt>=5.12")\n\n\n# Fixes issues with Big Sur\n# https://bugreports.qt.io/browse/QTBUG-87014, fixed in qt 5.15.2\nif (sys.platform == 'darwin' and\n parse_version(platform.mac_ver()[0]) >= parse_version("10.16") and\n _version_info < (5, 15, 2)):\n os.environ.setdefault("QT_MAC_WANTS_LAYER", "1")\n\n\n# Backports.\n\n\ndef _exec(obj):\n # exec on PyQt6, exec_ elsewhere.\n obj.exec() if hasattr(obj, "exec") else obj.exec_()\n
.venv\Lib\site-packages\matplotlib\backends\qt_compat.py
qt_compat.py
Python
5,346
0.95
0.132075
0.085714
awesome-app
947
2024-11-15T13:09:40.834428
BSD-3-Clause
false
5bcda13fc212858d180b5514b8578ebb
from enum import Enum\nimport importlib\n\n\nclass BackendFilter(Enum):\n """\n Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin`\n\n .. versionadded:: 3.9\n """\n INTERACTIVE = 0\n NON_INTERACTIVE = 1\n\n\nclass BackendRegistry:\n """\n Registry of backends available within Matplotlib.\n\n This is the single source of truth for available backends.\n\n All use of ``BackendRegistry`` should be via the singleton instance\n ``backend_registry`` which can be imported from ``matplotlib.backends``.\n\n Each backend has a name, a module name containing the backend code, and an\n optional GUI framework that must be running if the backend is interactive.\n There are three sources of backends: built-in (source code is within the\n Matplotlib repository), explicit ``module://some.backend`` syntax (backend is\n obtained by loading the module), or via an entry point (self-registering\n backend in an external package).\n\n .. versionadded:: 3.9\n """\n # Mapping of built-in backend name to GUI framework, or "headless" for no\n # GUI framework. Built-in backends are those which are included in the\n # Matplotlib repo. A backend with name 'name' is located in the module\n # f"matplotlib.backends.backend_{name.lower()}"\n _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = {\n "gtk3agg": "gtk3",\n "gtk3cairo": "gtk3",\n "gtk4agg": "gtk4",\n "gtk4cairo": "gtk4",\n "macosx": "macosx",\n "nbagg": "nbagg",\n "notebook": "nbagg",\n "qtagg": "qt",\n "qtcairo": "qt",\n "qt5agg": "qt5",\n "qt5cairo": "qt5",\n "tkagg": "tk",\n "tkcairo": "tk",\n "webagg": "webagg",\n "wx": "wx",\n "wxagg": "wx",\n "wxcairo": "wx",\n "agg": "headless",\n "cairo": "headless",\n "pdf": "headless",\n "pgf": "headless",\n "ps": "headless",\n "svg": "headless",\n "template": "headless",\n }\n\n # Reverse mapping of gui framework to preferred built-in backend.\n _GUI_FRAMEWORK_TO_BACKEND = {\n "gtk3": "gtk3agg",\n "gtk4": "gtk4agg",\n "headless": "agg",\n "macosx": "macosx",\n "qt": "qtagg",\n "qt5": "qt5agg",\n "qt6": "qtagg",\n "tk": "tkagg",\n "wx": "wxagg",\n }\n\n def __init__(self):\n # Only load entry points when first needed.\n self._loaded_entry_points = False\n\n # Mapping of non-built-in backend to GUI framework, added dynamically from\n # entry points and from matplotlib.use("module://some.backend") format.\n # New entries have an "unknown" GUI framework that is determined when first\n # needed by calling _get_gui_framework_by_loading.\n self._backend_to_gui_framework = {}\n\n # Mapping of backend name to module name, where different from\n # f"matplotlib.backends.backend_{backend_name.lower()}". These are either\n # hardcoded for backward compatibility, or loaded from entry points or\n # "module://some.backend" syntax.\n self._name_to_module = {\n "notebook": "nbagg",\n }\n\n def _backend_module_name(self, backend):\n if backend.startswith("module://"):\n return backend[9:]\n\n # Return name of module containing the specified backend.\n # Does not check if the backend is valid, use is_valid_backend for that.\n backend = backend.lower()\n\n # Check if have specific name to module mapping.\n backend = self._name_to_module.get(backend, backend)\n\n return (backend[9:] if backend.startswith("module://")\n else f"matplotlib.backends.backend_{backend}")\n\n def _clear(self):\n # Clear all dynamically-added data, used for testing only.\n self.__init__()\n\n def _ensure_entry_points_loaded(self):\n # Load entry points, if they have not already been loaded.\n if not self._loaded_entry_points:\n entries = self._read_entry_points()\n self._validate_and_store_entry_points(entries)\n self._loaded_entry_points = True\n\n def _get_gui_framework_by_loading(self, backend):\n # Determine GUI framework for a backend by loading its module and reading the\n # FigureCanvas.required_interactive_framework attribute.\n # Returns "headless" if there is no GUI framework.\n module = self.load_backend_module(backend)\n canvas_class = module.FigureCanvas\n return canvas_class.required_interactive_framework or "headless"\n\n def _read_entry_points(self):\n # Read entry points of modules that self-advertise as Matplotlib backends.\n # Expects entry points like this one from matplotlib-inline (in pyproject.toml\n # format):\n # [project.entry-points."matplotlib.backend"]\n # inline = "matplotlib_inline.backend_inline"\n import importlib.metadata as im\n\n entry_points = im.entry_points(group="matplotlib.backend")\n entries = [(entry.name, entry.value) for entry in entry_points]\n\n # For backward compatibility, if matplotlib-inline and/or ipympl are installed\n # but too old to include entry points, create them. Do not import ipympl\n # directly as this calls matplotlib.use() whilst in this function.\n def backward_compatible_entry_points(\n entries, module_name, threshold_version, names, target):\n from matplotlib import _parse_to_version_info\n try:\n module_version = im.version(module_name)\n if _parse_to_version_info(module_version) < threshold_version:\n for name in names:\n entries.append((name, target))\n except im.PackageNotFoundError:\n pass\n\n names = [entry[0] for entry in entries]\n if "inline" not in names:\n backward_compatible_entry_points(\n entries, "matplotlib_inline", (0, 1, 7), ["inline"],\n "matplotlib_inline.backend_inline")\n if "ipympl" not in names:\n backward_compatible_entry_points(\n entries, "ipympl", (0, 9, 4), ["ipympl", "widget"],\n "ipympl.backend_nbagg")\n\n return entries\n\n def _validate_and_store_entry_points(self, entries):\n # Validate and store entry points so that they can be used via matplotlib.use()\n # in the normal manner. Entry point names cannot be of module:// format, cannot\n # shadow a built-in backend name, and there cannot be multiple entry points\n # with the same name but different modules. Multiple entry points with the same\n # name and value are permitted (it can sometimes happen outside of our control,\n # see https://github.com/matplotlib/matplotlib/issues/28367).\n for name, module in set(entries):\n name = name.lower()\n if name.startswith("module://"):\n raise RuntimeError(\n f"Entry point name '{name}' cannot start with 'module://'")\n if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK:\n raise RuntimeError(f"Entry point name '{name}' is a built-in backend")\n if name in self._backend_to_gui_framework:\n raise RuntimeError(f"Entry point name '{name}' duplicated")\n\n self._name_to_module[name] = "module://" + module\n # Do not yet know backend GUI framework, determine it only when necessary.\n self._backend_to_gui_framework[name] = "unknown"\n\n def backend_for_gui_framework(self, framework):\n """\n Return the name of the backend corresponding to the specified GUI framework.\n\n Parameters\n ----------\n framework : str\n GUI framework such as "qt".\n\n Returns\n -------\n str or None\n Backend name or None if GUI framework not recognised.\n """\n return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower())\n\n def is_valid_backend(self, backend):\n """\n Return True if the backend name is valid, False otherwise.\n\n A backend name is valid if it is one of the built-in backends or has been\n dynamically added via an entry point. Those beginning with ``module://`` are\n always considered valid and are added to the current list of all backends\n within this function.\n\n Even if a name is valid, it may not be importable or usable. This can only be\n determined by loading and using the backend module.\n\n Parameters\n ----------\n backend : str\n Name of backend.\n\n Returns\n -------\n bool\n True if backend is valid, False otherwise.\n """\n if not backend.startswith("module://"):\n backend = backend.lower()\n\n # For backward compatibility, convert ipympl and matplotlib-inline long\n # module:// names to their shortened forms.\n backwards_compat = {\n "module://ipympl.backend_nbagg": "widget",\n "module://matplotlib_inline.backend_inline": "inline",\n }\n backend = backwards_compat.get(backend, backend)\n\n if (backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or\n backend in self._backend_to_gui_framework):\n return True\n\n if backend.startswith("module://"):\n self._backend_to_gui_framework[backend] = "unknown"\n return True\n\n # Only load entry points if really need to and not already done so.\n self._ensure_entry_points_loaded()\n if backend in self._backend_to_gui_framework:\n return True\n\n return False\n\n def list_all(self):\n """\n Return list of all known backends.\n\n These include built-in backends and those obtained at runtime either from entry\n points or explicit ``module://some.backend`` syntax.\n\n Entry points will be loaded if they haven't been already.\n\n Returns\n -------\n list of str\n Backend names.\n """\n self._ensure_entry_points_loaded()\n return [*self.list_builtin(), *self._backend_to_gui_framework]\n\n def list_builtin(self, filter_=None):\n """\n Return list of backends that are built into Matplotlib.\n\n Parameters\n ----------\n filter_ : `~.BackendFilter`, optional\n Filter to apply to returned backends. For example, to return only\n non-interactive backends use `.BackendFilter.NON_INTERACTIVE`.\n\n Returns\n -------\n list of str\n Backend names.\n """\n if filter_ == BackendFilter.INTERACTIVE:\n return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items()\n if v != "headless"]\n elif filter_ == BackendFilter.NON_INTERACTIVE:\n return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items()\n if v == "headless"]\n\n return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK]\n\n def list_gui_frameworks(self):\n """\n Return list of GUI frameworks used by Matplotlib backends.\n\n Returns\n -------\n list of str\n GUI framework names.\n """\n return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != "headless"]\n\n def load_backend_module(self, backend):\n """\n Load and return the module containing the specified backend.\n\n Parameters\n ----------\n backend : str\n Name of backend to load.\n\n Returns\n -------\n Module\n Module containing backend.\n """\n module_name = self._backend_module_name(backend)\n return importlib.import_module(module_name)\n\n def resolve_backend(self, backend):\n """\n Return the backend and GUI framework for the specified backend name.\n\n If the GUI framework is not yet known then it will be determined by loading the\n backend module and checking the ``FigureCanvas.required_interactive_framework``\n attribute.\n\n This function only loads entry points if they have not already been loaded and\n the backend is not built-in and not of ``module://some.backend`` format.\n\n Parameters\n ----------\n backend : str or None\n Name of backend, or None to use the default backend.\n\n Returns\n -------\n backend : str\n The backend name.\n framework : str or None\n The GUI framework, which will be None for a backend that is non-interactive.\n """\n if isinstance(backend, str):\n if not backend.startswith("module://"):\n backend = backend.lower()\n else: # Might be _auto_backend_sentinel or None\n # Use whatever is already running...\n from matplotlib import get_backend\n backend = get_backend()\n\n # Is backend already known (built-in or dynamically loaded)?\n gui = (self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or\n self._backend_to_gui_framework.get(backend))\n\n # Is backend "module://something"?\n if gui is None and isinstance(backend, str) and backend.startswith("module://"):\n gui = "unknown"\n\n # Is backend a possible entry point?\n if gui is None and not self._loaded_entry_points:\n self._ensure_entry_points_loaded()\n gui = self._backend_to_gui_framework.get(backend)\n\n # Backend known but not its gui framework.\n if gui == "unknown":\n gui = self._get_gui_framework_by_loading(backend)\n self._backend_to_gui_framework[backend] = gui\n\n if gui is None:\n raise RuntimeError(f"'{backend}' is not a recognised backend name")\n\n return backend, gui if gui != "headless" else None\n\n def resolve_gui_or_backend(self, gui_or_backend):\n """\n Return the backend and GUI framework for the specified string that may be\n either a GUI framework or a backend name, tested in that order.\n\n This is for use with the IPython %matplotlib magic command which may be a GUI\n framework such as ``%matplotlib qt`` or a backend name such as\n ``%matplotlib qtagg``.\n\n This function only loads entry points if they have not already been loaded and\n the backend is not built-in and not of ``module://some.backend`` format.\n\n Parameters\n ----------\n gui_or_backend : str or None\n Name of GUI framework or backend, or None to use the default backend.\n\n Returns\n -------\n backend : str\n The backend name.\n framework : str or None\n The GUI framework, which will be None for a backend that is non-interactive.\n """\n if not gui_or_backend.startswith("module://"):\n gui_or_backend = gui_or_backend.lower()\n\n # First check if it is a gui loop name.\n backend = self.backend_for_gui_framework(gui_or_backend)\n if backend is not None:\n return backend, gui_or_backend if gui_or_backend != "headless" else None\n\n # Then check if it is a backend name.\n try:\n return self.resolve_backend(gui_or_backend)\n except Exception: # KeyError ?\n raise RuntimeError(\n f"'{gui_or_backend}' is not a recognised GUI loop or backend name")\n\n\n# Singleton\nbackend_registry = BackendRegistry()\n
.venv\Lib\site-packages\matplotlib\backends\registry.py
registry.py
Python
15,480
0.95
0.207729
0.140762
react-lib
790
2025-03-05T23:35:26.068592
GPL-3.0
false
f92c2a5ddfd8775f2101ca3e79f2afc1
"""\nCommon code for GTK3 and GTK4 backends.\n"""\n\nimport logging\nimport sys\n\nimport matplotlib as mpl\nfrom matplotlib import _api, backend_tools, cbook\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,\n TimerBase)\nfrom matplotlib.backend_tools import Cursors\n\nimport gi\n# The GTK3/GTK4 backends will have already called `gi.require_version` to set\n# the desired GTK.\nfrom gi.repository import Gdk, Gio, GLib, Gtk\n\n\ntry:\n gi.require_foreign("cairo")\nexcept ImportError as e:\n raise ImportError("Gtk-based backends require cairo") from e\n\n_log = logging.getLogger(__name__)\n_application = None # Placeholder\n\n\ndef _shutdown_application(app):\n # The application might prematurely shut down if Ctrl-C'd out of IPython,\n # so close all windows.\n for win in app.get_windows():\n win.close()\n # The PyGObject wrapper incorrectly thinks that None is not allowed, or we\n # would call this:\n # Gio.Application.set_default(None)\n # Instead, we set this property and ignore default applications with it:\n app._created_by_matplotlib = True\n global _application\n _application = None\n\n\ndef _create_application():\n global _application\n\n if _application is None:\n app = Gio.Application.get_default()\n if app is None or getattr(app, '_created_by_matplotlib', False):\n # display_is_valid returns False only if on Linux and neither X11\n # nor Wayland display can be opened.\n if not mpl._c_internal_utils.display_is_valid():\n raise RuntimeError('Invalid DISPLAY variable')\n _application = Gtk.Application.new('org.matplotlib.Matplotlib3',\n Gio.ApplicationFlags.NON_UNIQUE)\n # The activate signal must be connected, but we don't care for\n # handling it, since we don't do any remote processing.\n _application.connect('activate', lambda *args, **kwargs: None)\n _application.connect('shutdown', _shutdown_application)\n _application.register()\n cbook._setup_new_guiapp()\n else:\n _application = app\n\n return _application\n\n\ndef mpl_to_gtk_cursor_name(mpl_cursor):\n return _api.check_getitem({\n Cursors.MOVE: "move",\n Cursors.HAND: "pointer",\n Cursors.POINTER: "default",\n Cursors.SELECT_REGION: "crosshair",\n Cursors.WAIT: "wait",\n Cursors.RESIZE_HORIZONTAL: "ew-resize",\n Cursors.RESIZE_VERTICAL: "ns-resize",\n }, cursor=mpl_cursor)\n\n\nclass TimerGTK(TimerBase):\n """Subclass of `.TimerBase` using GTK timer events."""\n\n def __init__(self, *args, **kwargs):\n self._timer = None\n super().__init__(*args, **kwargs)\n\n def _timer_start(self):\n # Need to stop it, otherwise we potentially leak a timer id that will\n # never be stopped.\n self._timer_stop()\n self._timer = GLib.timeout_add(self._interval, self._on_timer)\n\n def _timer_stop(self):\n if self._timer is not None:\n GLib.source_remove(self._timer)\n self._timer = None\n\n def _timer_set_interval(self):\n # Only stop and restart it if the timer has already been started.\n if self._timer is not None:\n self._timer_stop()\n self._timer_start()\n\n def _on_timer(self):\n super()._on_timer()\n\n # Gtk timeout_add() requires that the callback returns True if it\n # is to be called again.\n if self.callbacks and not self._single:\n return True\n else:\n self._timer = None\n return False\n\n\nclass _FigureCanvasGTK(FigureCanvasBase):\n _timer_cls = TimerGTK\n\n\nclass _FigureManagerGTK(FigureManagerBase):\n """\n Attributes\n ----------\n canvas : `FigureCanvas`\n The FigureCanvas instance\n num : int or str\n The Figure number\n toolbar : Gtk.Toolbar or Gtk.Box\n The toolbar\n vbox : Gtk.VBox\n The Gtk.VBox containing the canvas and toolbar\n window : Gtk.Window\n The Gtk.Window\n """\n\n def __init__(self, canvas, num):\n self._gtk_ver = gtk_ver = Gtk.get_major_version()\n\n app = _create_application()\n self.window = Gtk.Window()\n app.add_window(self.window)\n super().__init__(canvas, num)\n\n if gtk_ver == 3:\n icon_ext = "png" if sys.platform == "win32" else "svg"\n self.window.set_icon_from_file(\n str(cbook._get_data_path(f"images/matplotlib.{icon_ext}")))\n\n self.vbox = Gtk.Box()\n self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)\n\n if gtk_ver == 3:\n self.window.add(self.vbox)\n self.vbox.show()\n self.canvas.show()\n self.vbox.pack_start(self.canvas, True, True, 0)\n elif gtk_ver == 4:\n self.window.set_child(self.vbox)\n self.vbox.prepend(self.canvas)\n\n # calculate size for window\n w, h = self.canvas.get_width_height()\n\n if self.toolbar is not None:\n if gtk_ver == 3:\n self.toolbar.show()\n self.vbox.pack_end(self.toolbar, False, False, 0)\n elif gtk_ver == 4:\n sw = Gtk.ScrolledWindow(vscrollbar_policy=Gtk.PolicyType.NEVER)\n sw.set_child(self.toolbar)\n self.vbox.append(sw)\n min_size, nat_size = self.toolbar.get_preferred_size()\n h += nat_size.height\n\n self.window.set_default_size(w, h)\n\n self._destroying = False\n self.window.connect("destroy", lambda *args: Gcf.destroy(self))\n self.window.connect({3: "delete_event", 4: "close-request"}[gtk_ver],\n lambda *args: Gcf.destroy(self))\n if mpl.is_interactive():\n self.window.show()\n self.canvas.draw_idle()\n\n self.canvas.grab_focus()\n\n def destroy(self, *args):\n if self._destroying:\n # Otherwise, this can be called twice when the user presses 'q',\n # which calls Gcf.destroy(self), then this destroy(), then triggers\n # Gcf.destroy(self) once again via\n # `connect("destroy", lambda *args: Gcf.destroy(self))`.\n return\n self._destroying = True\n self.window.destroy()\n self.canvas.destroy()\n\n @classmethod\n def start_main_loop(cls):\n global _application\n if _application is None:\n return\n\n try:\n _application.run() # Quits when all added windows close.\n except KeyboardInterrupt:\n # Ensure all windows can process their close event from\n # _shutdown_application.\n context = GLib.MainContext.default()\n while context.pending():\n context.iteration(True)\n raise\n finally:\n # Running after quit is undefined, so create a new one next time.\n _application = None\n\n def show(self):\n # show the figure window\n self.window.show()\n self.canvas.draw()\n if mpl.rcParams["figure.raise_window"]:\n meth_name = {3: "get_window", 4: "get_surface"}[self._gtk_ver]\n if getattr(self.window, meth_name)():\n self.window.present()\n else:\n # If this is called by a callback early during init,\n # self.window (a GtkWindow) may not have an associated\n # low-level GdkWindow (on GTK3) or GdkSurface (on GTK4) yet,\n # and present() would crash.\n _api.warn_external("Cannot raise window yet to be setup")\n\n def full_screen_toggle(self):\n is_fullscreen = {\n 3: lambda w: (w.get_window().get_state()\n & Gdk.WindowState.FULLSCREEN),\n 4: lambda w: w.is_fullscreen(),\n }[self._gtk_ver]\n if is_fullscreen(self.window):\n self.window.unfullscreen()\n else:\n self.window.fullscreen()\n\n def get_window_title(self):\n return self.window.get_title()\n\n def set_window_title(self, title):\n self.window.set_title(title)\n\n def resize(self, width, height):\n width = int(width / self.canvas.device_pixel_ratio)\n height = int(height / self.canvas.device_pixel_ratio)\n if self.toolbar:\n min_size, nat_size = self.toolbar.get_preferred_size()\n height += nat_size.height\n canvas_size = self.canvas.get_allocation()\n if self._gtk_ver >= 4 or canvas_size.width == canvas_size.height == 1:\n # A canvas size of (1, 1) cannot exist in most cases, because\n # window decorations would prevent such a small window. This call\n # must be before the window has been mapped and widgets have been\n # sized, so just change the window's starting size.\n self.window.set_default_size(width, height)\n else:\n self.window.resize(width, height)\n\n\nclass _NavigationToolbar2GTK(NavigationToolbar2):\n # Must be implemented in GTK3/GTK4 backends:\n # * __init__\n # * save_figure\n\n def set_message(self, s):\n escaped = GLib.markup_escape_text(s)\n self.message.set_markup(f'<small>{escaped}</small>')\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n height = self.canvas.figure.bbox.height\n y1 = height - y1\n y0 = height - y0\n rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]\n self.canvas._draw_rubberband(rect)\n\n def remove_rubberband(self):\n self.canvas._draw_rubberband(None)\n\n def _update_buttons_checked(self):\n for name, active in [("Pan", "PAN"), ("Zoom", "ZOOM")]:\n button = self._gtk_ids.get(name)\n if button:\n with button.handler_block(button._signal_handler):\n button.set_active(self.mode.name == active)\n\n def pan(self, *args):\n super().pan(*args)\n self._update_buttons_checked()\n\n def zoom(self, *args):\n super().zoom(*args)\n self._update_buttons_checked()\n\n def set_history_buttons(self):\n can_backward = self._nav_stack._pos > 0\n can_forward = self._nav_stack._pos < len(self._nav_stack) - 1\n if 'Back' in self._gtk_ids:\n self._gtk_ids['Back'].set_sensitive(can_backward)\n if 'Forward' in self._gtk_ids:\n self._gtk_ids['Forward'].set_sensitive(can_forward)\n\n\nclass RubberbandGTK(backend_tools.RubberbandBase):\n def draw_rubberband(self, x0, y0, x1, y1):\n _NavigationToolbar2GTK.draw_rubberband(\n self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)\n\n def remove_rubberband(self):\n _NavigationToolbar2GTK.remove_rubberband(\n self._make_classic_style_pseudo_toolbar())\n\n\nclass ConfigureSubplotsGTK(backend_tools.ConfigureSubplotsBase):\n def trigger(self, *args):\n _NavigationToolbar2GTK.configure_subplots(self, None)\n\n\nclass _BackendGTK(_Backend):\n backend_version = "{}.{}.{}".format(\n Gtk.get_major_version(),\n Gtk.get_minor_version(),\n Gtk.get_micro_version(),\n )\n mainloop = _FigureManagerGTK.start_main_loop\n
.venv\Lib\site-packages\matplotlib\backends\_backend_gtk.py
_backend_gtk.py
Python
11,274
0.95
0.205438
0.136531
react-lib
50
2025-05-23T09:14:30.542157
MIT
false
3df53e0f680b4129c53d85587d05260d
"""\nCommon functionality between the PDF and PS backends.\n"""\n\nfrom io import BytesIO\nimport functools\nimport logging\n\nfrom fontTools import subset\n\nimport matplotlib as mpl\nfrom .. import font_manager, ft2font\nfrom .._afm import AFM\nfrom ..backend_bases import RendererBase\n\n\n@functools.lru_cache(50)\ndef _cached_get_afm_from_fname(fname):\n with open(fname, "rb") as fh:\n return AFM(fh)\n\n\ndef get_glyphs_subset(fontfile, characters):\n """\n Subset a TTF font\n\n Reads the named fontfile and restricts the font to the characters.\n\n Parameters\n ----------\n fontfile : str\n Path to the font file\n characters : str\n Continuous set of characters to include in subset\n\n Returns\n -------\n fontTools.ttLib.ttFont.TTFont\n An open font object representing the subset, which needs to\n be closed by the caller.\n """\n\n options = subset.Options(glyph_names=True, recommended_glyphs=True)\n\n # Prevent subsetting extra tables.\n options.drop_tables += [\n 'FFTM', # FontForge Timestamp.\n 'PfEd', # FontForge personal table.\n 'BDF', # X11 BDF header.\n 'meta', # Metadata stores design/supported languages (meaningless for subsets).\n 'MERG', # Merge Table.\n 'TSIV', # Microsoft Visual TrueType extension.\n 'Zapf', # Information about the individual glyphs in the font.\n 'bdat', # The bitmap data table.\n 'bloc', # The bitmap location table.\n 'cidg', # CID to Glyph ID table (Apple Advanced Typography).\n 'fdsc', # The font descriptors table.\n 'feat', # Feature name table (Apple Advanced Typography).\n 'fmtx', # The Font Metrics Table.\n 'fond', # Data-fork font information (Apple Advanced Typography).\n 'just', # The justification table (Apple Advanced Typography).\n 'kerx', # An extended kerning table (Apple Advanced Typography).\n 'ltag', # Language Tag.\n 'morx', # Extended Glyph Metamorphosis Table.\n 'trak', # Tracking table.\n 'xref', # The cross-reference table (some Apple font tooling information).\n ]\n # if fontfile is a ttc, specify font number\n if fontfile.endswith(".ttc"):\n options.font_number = 0\n\n font = subset.load_font(fontfile, options)\n subsetter = subset.Subsetter(options=options)\n subsetter.populate(text=characters)\n subsetter.subset(font)\n return font\n\n\ndef font_as_file(font):\n """\n Convert a TTFont object into a file-like object.\n\n Parameters\n ----------\n font : fontTools.ttLib.ttFont.TTFont\n A font object\n\n Returns\n -------\n BytesIO\n A file object with the font saved into it\n """\n fh = BytesIO()\n font.save(fh, reorderTables=False)\n return fh\n\n\nclass CharacterTracker:\n """\n Helper for font subsetting by the pdf and ps backends.\n\n Maintains a mapping of font paths to the set of character codepoints that\n are being used from that font.\n """\n\n def __init__(self):\n self.used = {}\n\n def track(self, font, s):\n """Record that string *s* is being typeset using font *font*."""\n char_to_font = font._get_fontmap(s)\n for _c, _f in char_to_font.items():\n self.used.setdefault(_f.fname, set()).add(ord(_c))\n\n def track_glyph(self, font, glyph):\n """Record that codepoint *glyph* is being typeset using font *font*."""\n self.used.setdefault(font.fname, set()).add(glyph)\n\n\nclass RendererPDFPSBase(RendererBase):\n # The following attributes must be defined by the subclasses:\n # - _afm_font_dir\n # - _use_afm_rc_name\n\n def __init__(self, width, height):\n super().__init__()\n self.width = width\n self.height = height\n\n def flipy(self):\n # docstring inherited\n return False # y increases from bottom to top.\n\n def option_scale_image(self):\n # docstring inherited\n return True # PDF and PS support arbitrary image scaling.\n\n def option_image_nocomposite(self):\n # docstring inherited\n # Decide whether to composite image based on rcParam value.\n return not mpl.rcParams["image.composite_image"]\n\n def get_canvas_width_height(self):\n # docstring inherited\n return self.width * 72.0, self.height * 72.0\n\n def get_text_width_height_descent(self, s, prop, ismath):\n # docstring inherited\n if ismath == "TeX":\n return super().get_text_width_height_descent(s, prop, ismath)\n elif ismath:\n parse = self._text2path.mathtext_parser.parse(s, 72, prop)\n return parse.width, parse.height, parse.depth\n elif mpl.rcParams[self._use_afm_rc_name]:\n font = self._get_font_afm(prop)\n l, b, w, h, d = font.get_str_bbox_and_descent(s)\n scale = prop.get_size_in_points() / 1000\n w *= scale\n h *= scale\n d *= scale\n return w, h, d\n else:\n font = self._get_font_ttf(prop)\n font.set_text(s, 0.0, flags=ft2font.LoadFlags.NO_HINTING)\n w, h = font.get_width_height()\n d = font.get_descent()\n scale = 1 / 64\n w *= scale\n h *= scale\n d *= scale\n return w, h, d\n\n def _get_font_afm(self, prop):\n fname = font_manager.findfont(\n prop, fontext="afm", directory=self._afm_font_dir)\n return _cached_get_afm_from_fname(fname)\n\n def _get_font_ttf(self, prop):\n fnames = font_manager.fontManager._find_fonts_by_props(prop)\n try:\n font = font_manager.get_font(fnames)\n font.clear()\n font.set_size(prop.get_size_in_points(), 72)\n return font\n except RuntimeError:\n logging.getLogger(__name__).warning(\n "The PostScript/PDF backend does not currently "\n "support the selected font (%s).", fnames)\n raise\n
.venv\Lib\site-packages\matplotlib\backends\_backend_pdf_ps.py
_backend_pdf_ps.py
Python
5,968
0.95
0.121693
0.070513
awesome-app
86
2024-09-08T02:26:05.021738
GPL-3.0
false
1a1dc4b8c5b43418868f5b15e7cb3330
import uuid\nimport weakref\nfrom contextlib import contextmanager\nimport logging\nimport math\nimport os.path\nimport pathlib\nimport sys\nimport tkinter as tk\nimport tkinter.filedialog\nimport tkinter.font\nimport tkinter.messagebox\nfrom tkinter.simpledialog import SimpleDialog\n\nimport numpy as np\nfrom PIL import Image, ImageTk\n\nimport matplotlib as mpl\nfrom matplotlib import _api, backend_tools, cbook, _c_internal_utils\nfrom matplotlib.backend_bases import (\n _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,\n TimerBase, ToolContainerBase, cursors, _Mode, MouseButton,\n CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)\nfrom matplotlib._pylab_helpers import Gcf\nfrom . import _tkagg\nfrom ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET\n\n\n_log = logging.getLogger(__name__)\ncursord = {\n cursors.MOVE: "fleur",\n cursors.HAND: "hand2",\n cursors.POINTER: "arrow",\n cursors.SELECT_REGION: "crosshair",\n cursors.WAIT: "watch",\n cursors.RESIZE_HORIZONTAL: "sb_h_double_arrow",\n cursors.RESIZE_VERTICAL: "sb_v_double_arrow",\n}\n\n\n@contextmanager\ndef _restore_foreground_window_at_end():\n foreground = _c_internal_utils.Win32_GetForegroundWindow()\n try:\n yield\n finally:\n if foreground and mpl.rcParams['tk.window_focus']:\n _c_internal_utils.Win32_SetForegroundWindow(foreground)\n\n\n_blit_args = {}\n# Initialize to a non-empty string that is not a Tcl command\n_blit_tcl_name = "mpl_blit_" + uuid.uuid4().hex\n\n\ndef _blit(argsid):\n """\n Thin wrapper to blit called via tkapp.call.\n\n *argsid* is a unique string identifier to fetch the correct arguments from\n the ``_blit_args`` dict, since arguments cannot be passed directly.\n """\n photoimage, data, offsets, bbox, comp_rule = _blit_args.pop(argsid)\n if not photoimage.tk.call("info", "commands", photoimage):\n return\n _tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets,\n bbox)\n\n\ndef blit(photoimage, aggimage, offsets, bbox=None):\n """\n Blit *aggimage* to *photoimage*.\n\n *offsets* is a tuple describing how to fill the ``offset`` field of the\n ``Tk_PhotoImageBlock`` struct: it should be (0, 1, 2, 3) for RGBA8888 data,\n (2, 1, 0, 3) for little-endian ARBG32 (i.e. GBRA8888) data and (1, 2, 3, 0)\n for big-endian ARGB32 (i.e. ARGB8888) data.\n\n If *bbox* is passed, it defines the region that gets blitted. That region\n will be composed with the previous data according to the alpha channel.\n Blitting will be clipped to pixels inside the canvas, including silently\n doing nothing if the *bbox* region is entirely outside the canvas.\n\n Tcl events must be dispatched to trigger a blit from a non-Tcl thread.\n """\n data = np.asarray(aggimage)\n height, width = data.shape[:2]\n if bbox is not None:\n (x1, y1), (x2, y2) = bbox.__array__()\n x1 = max(math.floor(x1), 0)\n x2 = min(math.ceil(x2), width)\n y1 = max(math.floor(y1), 0)\n y2 = min(math.ceil(y2), height)\n if (x1 > x2) or (y1 > y2):\n return\n bboxptr = (x1, x2, y1, y2)\n comp_rule = TK_PHOTO_COMPOSITE_OVERLAY\n else:\n bboxptr = (0, width, 0, height)\n comp_rule = TK_PHOTO_COMPOSITE_SET\n\n # NOTE: _tkagg.blit is thread unsafe and will crash the process if called\n # from a thread (GH#13293). Instead of blanking and blitting here,\n # use tkapp.call to post a cross-thread event if this function is called\n # from a non-Tcl thread.\n\n # tkapp.call coerces all arguments to strings, so to avoid string parsing\n # within _blit, pack up the arguments into a global data structure.\n args = photoimage, data, offsets, bboxptr, comp_rule\n # Need a unique key to avoid thread races.\n # Again, make the key a string to avoid string parsing in _blit.\n argsid = str(id(args))\n _blit_args[argsid] = args\n\n try:\n photoimage.tk.call(_blit_tcl_name, argsid)\n except tk.TclError as e:\n if "invalid command name" not in str(e):\n raise\n photoimage.tk.createcommand(_blit_tcl_name, _blit)\n photoimage.tk.call(_blit_tcl_name, argsid)\n\n\nclass TimerTk(TimerBase):\n """Subclass of `backend_bases.TimerBase` using Tk timer events."""\n\n def __init__(self, parent, *args, **kwargs):\n self._timer = None\n super().__init__(*args, **kwargs)\n self.parent = parent\n\n def _timer_start(self):\n self._timer_stop()\n self._timer = self.parent.after(self._interval, self._on_timer)\n\n def _timer_stop(self):\n if self._timer is not None:\n self.parent.after_cancel(self._timer)\n self._timer = None\n\n def _on_timer(self):\n super()._on_timer()\n # Tk after() is only a single shot, so we need to add code here to\n # reset the timer if we're not operating in single shot mode. However,\n # if _timer is None, this means that _timer_stop has been called; so\n # don't recreate the timer in that case.\n if not self._single and self._timer:\n if self._interval > 0:\n self._timer = self.parent.after(self._interval, self._on_timer)\n else:\n # Edge case: Tcl after 0 *prepends* events to the queue\n # so a 0 interval does not allow any other events to run.\n # This incantation is cancellable and runs as fast as possible\n # while also allowing events and drawing every frame. GH#18236\n self._timer = self.parent.after_idle(\n lambda: self.parent.after(self._interval, self._on_timer)\n )\n else:\n self._timer = None\n\n\nclass FigureCanvasTk(FigureCanvasBase):\n required_interactive_framework = "tk"\n manager_class = _api.classproperty(lambda cls: FigureManagerTk)\n\n def __init__(self, figure=None, master=None):\n super().__init__(figure)\n self._idle_draw_id = None\n self._event_loop_id = None\n w, h = self.get_width_height(physical=True)\n self._tkcanvas = tk.Canvas(\n master=master, background="white",\n width=w, height=h, borderwidth=0, highlightthickness=0)\n self._tkphoto = tk.PhotoImage(\n master=self._tkcanvas, width=w, height=h)\n self._tkcanvas_image_region = self._tkcanvas.create_image(\n w//2, h//2, image=self._tkphoto)\n self._tkcanvas.bind("<Configure>", self.resize)\n self._tkcanvas.bind("<Map>", self._update_device_pixel_ratio)\n self._tkcanvas.bind("<Key>", self.key_press)\n self._tkcanvas.bind("<Motion>", self.motion_notify_event)\n self._tkcanvas.bind("<Enter>", self.enter_notify_event)\n self._tkcanvas.bind("<Leave>", self.leave_notify_event)\n self._tkcanvas.bind("<KeyRelease>", self.key_release)\n for name in ["<Button-1>", "<Button-2>", "<Button-3>"]:\n self._tkcanvas.bind(name, self.button_press_event)\n for name in [\n "<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>"]:\n self._tkcanvas.bind(name, self.button_dblclick_event)\n for name in [\n "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>"]:\n self._tkcanvas.bind(name, self.button_release_event)\n\n # Mouse wheel on Linux generates button 4/5 events\n for name in "<Button-4>", "<Button-5>":\n self._tkcanvas.bind(name, self.scroll_event)\n # Mouse wheel for windows goes to the window with the focus.\n # Since the canvas won't usually have the focus, bind the\n # event to the window containing the canvas instead.\n # See https://wiki.tcl-lang.org/3893 (mousewheel) for details\n root = self._tkcanvas.winfo_toplevel()\n\n # Prevent long-lived references via tkinter callback structure GH-24820\n weakself = weakref.ref(self)\n weakroot = weakref.ref(root)\n\n def scroll_event_windows(event):\n self = weakself()\n if self is None:\n root = weakroot()\n if root is not None:\n root.unbind("<MouseWheel>", scroll_event_windows_id)\n return\n return self.scroll_event_windows(event)\n scroll_event_windows_id = root.bind("<MouseWheel>", scroll_event_windows, "+")\n\n # Can't get destroy events by binding to _tkcanvas. Therefore, bind\n # to the window and filter.\n def filter_destroy(event):\n self = weakself()\n if self is None:\n root = weakroot()\n if root is not None:\n root.unbind("<Destroy>", filter_destroy_id)\n return\n if event.widget is self._tkcanvas:\n CloseEvent("close_event", self)._process()\n filter_destroy_id = root.bind("<Destroy>", filter_destroy, "+")\n\n self._tkcanvas.focus_set()\n\n self._rubberband_rect_black = None\n self._rubberband_rect_white = None\n\n def _update_device_pixel_ratio(self, event=None):\n ratio = None\n if sys.platform == 'win32':\n # Tk gives scaling with respect to 72 DPI, but Windows screens are\n # scaled vs 96 dpi, and pixel ratio settings are given in whole\n # percentages, so round to 2 digits.\n ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2)\n elif sys.platform == "linux":\n ratio = self._tkcanvas.winfo_fpixels('1i') / 96\n if ratio is not None and self._set_device_pixel_ratio(ratio):\n # The easiest way to resize the canvas is to resize the canvas\n # widget itself, since we implement all the logic for resizing the\n # canvas backing store on that event.\n w, h = self.get_width_height(physical=True)\n self._tkcanvas.configure(width=w, height=h)\n\n def resize(self, event):\n width, height = event.width, event.height\n\n # compute desired figure size in inches\n dpival = self.figure.dpi\n winch = width / dpival\n hinch = height / dpival\n self.figure.set_size_inches(winch, hinch, forward=False)\n\n self._tkcanvas.delete(self._tkcanvas_image_region)\n self._tkphoto.configure(width=int(width), height=int(height))\n self._tkcanvas_image_region = self._tkcanvas.create_image(\n int(width / 2), int(height / 2), image=self._tkphoto)\n ResizeEvent("resize_event", self)._process()\n self.draw_idle()\n\n def draw_idle(self):\n # docstring inherited\n if self._idle_draw_id:\n return\n\n def idle_draw(*args):\n try:\n self.draw()\n finally:\n self._idle_draw_id = None\n\n self._idle_draw_id = self._tkcanvas.after_idle(idle_draw)\n\n def get_tk_widget(self):\n """\n Return the Tk widget used to implement FigureCanvasTkAgg.\n\n Although the initial implementation uses a Tk canvas, this routine\n is intended to hide that fact.\n """\n return self._tkcanvas\n\n def _event_mpl_coords(self, event):\n # calling canvasx/canvasy allows taking scrollbars into account (i.e.\n # the top of the widget may have been scrolled out of view).\n return (self._tkcanvas.canvasx(event.x),\n # flipy so y=0 is bottom of canvas\n self.figure.bbox.height - self._tkcanvas.canvasy(event.y))\n\n def motion_notify_event(self, event):\n MouseEvent("motion_notify_event", self,\n *self._event_mpl_coords(event),\n buttons=self._mpl_buttons(event),\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def enter_notify_event(self, event):\n LocationEvent("figure_enter_event", self,\n *self._event_mpl_coords(event),\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def leave_notify_event(self, event):\n LocationEvent("figure_leave_event", self,\n *self._event_mpl_coords(event),\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def button_press_event(self, event, dblclick=False):\n # set focus to the canvas so that it can receive keyboard events\n self._tkcanvas.focus_set()\n\n num = getattr(event, 'num', None)\n if sys.platform == 'darwin': # 2 and 3 are reversed.\n num = {2: 3, 3: 2}.get(num, num)\n MouseEvent("button_press_event", self,\n *self._event_mpl_coords(event), num, dblclick=dblclick,\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def button_dblclick_event(self, event):\n self.button_press_event(event, dblclick=True)\n\n def button_release_event(self, event):\n num = getattr(event, 'num', None)\n if sys.platform == 'darwin': # 2 and 3 are reversed.\n num = {2: 3, 3: 2}.get(num, num)\n MouseEvent("button_release_event", self,\n *self._event_mpl_coords(event), num,\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def scroll_event(self, event):\n num = getattr(event, 'num', None)\n step = 1 if num == 4 else -1 if num == 5 else 0\n MouseEvent("scroll_event", self,\n *self._event_mpl_coords(event), step=step,\n modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n def scroll_event_windows(self, event):\n """MouseWheel event processor"""\n # need to find the window that contains the mouse\n w = event.widget.winfo_containing(event.x_root, event.y_root)\n if w != self._tkcanvas:\n return\n x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx())\n y = (self.figure.bbox.height\n - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty()))\n step = event.delta / 120\n MouseEvent("scroll_event", self,\n x, y, step=step, modifiers=self._mpl_modifiers(event),\n guiEvent=event)._process()\n\n @staticmethod\n def _mpl_buttons(event): # See _mpl_modifiers.\n # NOTE: This fails to report multiclicks on macOS; only one button is\n # reported (multiclicks work correctly on Linux & Windows).\n modifiers = [\n # macOS appears to swap right and middle (look for "Swap buttons\n # 2/3" in tk/macosx/tkMacOSXMouseEvent.c).\n (MouseButton.LEFT, 1 << 8),\n (MouseButton.RIGHT, 1 << 9),\n (MouseButton.MIDDLE, 1 << 10),\n (MouseButton.BACK, 1 << 11),\n (MouseButton.FORWARD, 1 << 12),\n ] if sys.platform == "darwin" else [\n (MouseButton.LEFT, 1 << 8),\n (MouseButton.MIDDLE, 1 << 9),\n (MouseButton.RIGHT, 1 << 10),\n (MouseButton.BACK, 1 << 11),\n (MouseButton.FORWARD, 1 << 12),\n ]\n # State *before* press/release.\n return [name for name, mask in modifiers if event.state & mask]\n\n @staticmethod\n def _mpl_modifiers(event, *, exclude=None):\n # Add modifier keys to the key string. Bit values are inferred from\n # the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... =\n # Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5)\n # In general, the modifier key is excluded from the modifier flag,\n # however this is not the case on "darwin", so double check that\n # we aren't adding repeat modifier flags to a modifier key.\n modifiers = [\n ("ctrl", 1 << 2, "control"),\n ("alt", 1 << 17, "alt"),\n ("shift", 1 << 0, "shift"),\n ] if sys.platform == "win32" else [\n ("ctrl", 1 << 2, "control"),\n ("alt", 1 << 4, "alt"),\n ("shift", 1 << 0, "shift"),\n ("cmd", 1 << 3, "cmd"),\n ] if sys.platform == "darwin" else [\n ("ctrl", 1 << 2, "control"),\n ("alt", 1 << 3, "alt"),\n ("shift", 1 << 0, "shift"),\n ("super", 1 << 6, "super"),\n ]\n return [name for name, mask, key in modifiers\n if event.state & mask and exclude != key]\n\n def _get_key(self, event):\n unikey = event.char\n key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym)\n if key is not None:\n mods = self._mpl_modifiers(event, exclude=key)\n # shift is not added to the keys as this is already accounted for.\n if "shift" in mods and unikey:\n mods.remove("shift")\n return "+".join([*mods, key])\n\n def key_press(self, event):\n KeyEvent("key_press_event", self,\n self._get_key(event), *self._event_mpl_coords(event),\n guiEvent=event)._process()\n\n def key_release(self, event):\n KeyEvent("key_release_event", self,\n self._get_key(event), *self._event_mpl_coords(event),\n guiEvent=event)._process()\n\n def new_timer(self, *args, **kwargs):\n # docstring inherited\n return TimerTk(self._tkcanvas, *args, **kwargs)\n\n def flush_events(self):\n # docstring inherited\n self._tkcanvas.update()\n\n def start_event_loop(self, timeout=0):\n # docstring inherited\n if timeout > 0:\n milliseconds = int(1000 * timeout)\n if milliseconds > 0:\n self._event_loop_id = self._tkcanvas.after(\n milliseconds, self.stop_event_loop)\n else:\n self._event_loop_id = self._tkcanvas.after_idle(\n self.stop_event_loop)\n self._tkcanvas.mainloop()\n\n def stop_event_loop(self):\n # docstring inherited\n if self._event_loop_id:\n self._tkcanvas.after_cancel(self._event_loop_id)\n self._event_loop_id = None\n self._tkcanvas.quit()\n\n def set_cursor(self, cursor):\n try:\n self._tkcanvas.configure(cursor=cursord[cursor])\n except tkinter.TclError:\n pass\n\n\nclass FigureManagerTk(FigureManagerBase):\n """\n Attributes\n ----------\n canvas : `FigureCanvas`\n The FigureCanvas instance\n num : int or str\n The Figure number\n toolbar : tk.Toolbar\n The tk.Toolbar\n window : tk.Window\n The tk.Window\n """\n\n _owns_mainloop = False\n\n def __init__(self, canvas, num, window):\n self.window = window\n super().__init__(canvas, num)\n self.window.withdraw()\n # packing toolbar first, because if space is getting low, last packed\n # widget is getting shrunk first (-> the canvas)\n self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\n # If the window has per-monitor DPI awareness, then setup a Tk variable\n # to store the DPI, which will be updated by the C code, and the trace\n # will handle it on the Python side.\n window_frame = int(window.wm_frame(), 16)\n self._window_dpi = tk.IntVar(master=window, value=96,\n name=f'window_dpi{window_frame}')\n self._window_dpi_cbname = ''\n if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()):\n self._window_dpi_cbname = self._window_dpi.trace_add(\n 'write', self._update_window_dpi)\n\n self._shown = False\n\n @classmethod\n def create_with_canvas(cls, canvas_class, figure, num):\n # docstring inherited\n with _restore_foreground_window_at_end():\n if cbook._get_running_interactive_framework() is None:\n cbook._setup_new_guiapp()\n _c_internal_utils.Win32_SetProcessDpiAwareness_max()\n window = tk.Tk(className="matplotlib")\n window.withdraw()\n\n # Put a Matplotlib icon on the window rather than the default tk\n # icon. See https://www.tcl.tk/man/tcl/TkCmd/wm.html#M50\n #\n # `ImageTk` can be replaced with `tk` whenever the minimum\n # supported Tk version is increased to 8.6, as Tk 8.6+ natively\n # supports PNG images.\n icon_fname = str(cbook._get_data_path(\n 'images/matplotlib.png'))\n icon_img = ImageTk.PhotoImage(file=icon_fname, master=window)\n\n icon_fname_large = str(cbook._get_data_path(\n 'images/matplotlib_large.png'))\n icon_img_large = ImageTk.PhotoImage(\n file=icon_fname_large, master=window)\n\n window.iconphoto(False, icon_img_large, icon_img)\n\n canvas = canvas_class(figure, master=window)\n manager = cls(canvas, num, window)\n if mpl.is_interactive():\n manager.show()\n canvas.draw_idle()\n return manager\n\n @classmethod\n def start_main_loop(cls):\n managers = Gcf.get_all_fig_managers()\n if managers:\n first_manager = managers[0]\n manager_class = type(first_manager)\n if manager_class._owns_mainloop:\n return\n manager_class._owns_mainloop = True\n try:\n first_manager.window.mainloop()\n finally:\n manager_class._owns_mainloop = False\n\n def _update_window_dpi(self, *args):\n newdpi = self._window_dpi.get()\n self.window.call('tk', 'scaling', newdpi / 72)\n if self.toolbar and hasattr(self.toolbar, '_rescale'):\n self.toolbar._rescale()\n self.canvas._update_device_pixel_ratio()\n\n def resize(self, width, height):\n max_size = 1_400_000 # the measured max on xorg 1.20.8 was 1_409_023\n\n if (width > max_size or height > max_size) and sys.platform == 'linux':\n raise ValueError(\n 'You have requested to resize the '\n f'Tk window to ({width}, {height}), one of which '\n f'is bigger than {max_size}. At larger sizes xorg will '\n 'either exit with an error on newer versions (~1.20) or '\n 'cause corruption on older version (~1.19). We '\n 'do not expect a window over a million pixel wide or tall '\n 'to be intended behavior.')\n self.canvas._tkcanvas.configure(width=width, height=height)\n\n def show(self):\n with _restore_foreground_window_at_end():\n if not self._shown:\n def destroy(*args):\n Gcf.destroy(self)\n self.window.protocol("WM_DELETE_WINDOW", destroy)\n self.window.deiconify()\n self.canvas._tkcanvas.focus_set()\n else:\n self.canvas.draw_idle()\n if mpl.rcParams['figure.raise_window']:\n self.canvas.manager.window.attributes('-topmost', 1)\n self.canvas.manager.window.attributes('-topmost', 0)\n self._shown = True\n\n def destroy(self, *args):\n if self.canvas._idle_draw_id:\n self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)\n if self.canvas._event_loop_id:\n self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id)\n if self._window_dpi_cbname:\n self._window_dpi.trace_remove('write', self._window_dpi_cbname)\n\n # NOTE: events need to be flushed before issuing destroy (GH #9956),\n # however, self.window.update() can break user code. An async callback\n # is the safest way to achieve a complete draining of the event queue,\n # but it leaks if no tk event loop is running. Therefore we explicitly\n # check for an event loop and choose our best guess.\n def delayed_destroy():\n self.window.destroy()\n\n if self._owns_mainloop and not Gcf.get_num_fig_managers():\n self.window.quit()\n\n if cbook._get_running_interactive_framework() == "tk":\n # "after idle after 0" avoids Tcl error/race (GH #19940)\n self.window.after_idle(self.window.after, 0, delayed_destroy)\n else:\n self.window.update()\n delayed_destroy()\n\n def get_window_title(self):\n return self.window.wm_title()\n\n def set_window_title(self, title):\n self.window.wm_title(title)\n\n def full_screen_toggle(self):\n is_fullscreen = bool(self.window.attributes('-fullscreen'))\n self.window.attributes('-fullscreen', not is_fullscreen)\n\n\nclass NavigationToolbar2Tk(NavigationToolbar2, tk.Frame):\n def __init__(self, canvas, window=None, *, pack_toolbar=True):\n """\n Parameters\n ----------\n canvas : `FigureCanvas`\n The figure canvas on which to operate.\n window : tk.Window\n The tk.Window which owns this toolbar.\n pack_toolbar : bool, default: True\n If True, add the toolbar to the parent's pack manager's packing\n list during initialization with ``side="bottom"`` and ``fill="x"``.\n If you want to use the toolbar with a different layout manager, use\n ``pack_toolbar=False``.\n """\n\n if window is None:\n window = canvas.get_tk_widget().master\n tk.Frame.__init__(self, master=window, borderwidth=2,\n width=int(canvas.figure.bbox.width), height=50)\n\n self._buttons = {}\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n # Add a spacer; return value is unused.\n self._Spacer()\n else:\n self._buttons[text] = button = self._Button(\n text,\n str(cbook._get_data_path(f"images/{image_file}.png")),\n toggle=callback in ["zoom", "pan"],\n command=getattr(self, callback),\n )\n if tooltip_text is not None:\n add_tooltip(button, tooltip_text)\n\n self._label_font = tkinter.font.Font(root=window, size=10)\n\n # This filler item ensures the toolbar is always at least two text\n # lines high. Otherwise the canvas gets redrawn as the mouse hovers\n # over images because those use two-line messages which resize the\n # toolbar.\n label = tk.Label(master=self, font=self._label_font,\n text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')\n label.pack(side=tk.RIGHT)\n\n self.message = tk.StringVar(master=self)\n self._message_label = tk.Label(master=self, font=self._label_font,\n textvariable=self.message,\n justify=tk.RIGHT)\n self._message_label.pack(side=tk.RIGHT)\n\n NavigationToolbar2.__init__(self, canvas)\n if pack_toolbar:\n self.pack(side=tk.BOTTOM, fill=tk.X)\n\n def _rescale(self):\n """\n Scale all children of the toolbar to current DPI setting.\n\n Before this is called, the Tk scaling setting will have been updated to\n match the new DPI. Tk widgets do not update for changes to scaling, but\n all measurements made after the change will match the new scaling. Thus\n this function re-applies all the same sizes in points, which Tk will\n scale correctly to pixels.\n """\n for widget in self.winfo_children():\n if isinstance(widget, (tk.Button, tk.Checkbutton)):\n if hasattr(widget, '_image_file'):\n # Explicit class because ToolbarTk calls _rescale.\n NavigationToolbar2Tk._set_image_for_button(self, widget)\n else:\n # Text-only button is handled by the font setting instead.\n pass\n elif isinstance(widget, tk.Frame):\n widget.configure(height='18p')\n widget.pack_configure(padx='3p')\n elif isinstance(widget, tk.Label):\n pass # Text is handled by the font setting instead.\n else:\n _log.warning('Unknown child class %s', widget.winfo_class)\n self._label_font.configure(size=10)\n\n def _update_buttons_checked(self):\n # sync button checkstates to match active mode\n for text, mode in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]:\n if text in self._buttons:\n if self.mode == mode:\n self._buttons[text].select() # NOT .invoke()\n else:\n self._buttons[text].deselect()\n\n def pan(self, *args):\n super().pan(*args)\n self._update_buttons_checked()\n\n def zoom(self, *args):\n super().zoom(*args)\n self._update_buttons_checked()\n\n def set_message(self, s):\n self.message.set(s)\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n # Block copied from remove_rubberband for backend_tools convenience.\n if self.canvas._rubberband_rect_white:\n self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)\n if self.canvas._rubberband_rect_black:\n self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)\n height = self.canvas.figure.bbox.height\n y0 = height - y0\n y1 = height - y1\n self.canvas._rubberband_rect_black = (\n self.canvas._tkcanvas.create_rectangle(\n x0, y0, x1, y1))\n self.canvas._rubberband_rect_white = (\n self.canvas._tkcanvas.create_rectangle(\n x0, y0, x1, y1, outline='white', dash=(3, 3)))\n\n def remove_rubberband(self):\n if self.canvas._rubberband_rect_white:\n self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)\n self.canvas._rubberband_rect_white = None\n if self.canvas._rubberband_rect_black:\n self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)\n self.canvas._rubberband_rect_black = None\n\n def _set_image_for_button(self, button):\n """\n Set the image for a button based on its pixel size.\n\n The pixel size is determined by the DPI scaling of the window.\n """\n if button._image_file is None:\n return\n\n # Allow _image_file to be relative to Matplotlib's "images" data\n # directory.\n path_regular = cbook._get_data_path('images', button._image_file)\n path_large = path_regular.with_name(\n path_regular.name.replace('.png', '_large.png'))\n size = button.winfo_pixels('18p')\n\n # Nested functions because ToolbarTk calls _Button.\n def _get_color(color_name):\n # `winfo_rgb` returns an (r, g, b) tuple in the range 0-65535\n return button.winfo_rgb(button.cget(color_name))\n\n def _is_dark(color):\n if isinstance(color, str):\n color = _get_color(color)\n return max(color) < 65535 / 2\n\n def _recolor_icon(image, color):\n image_data = np.asarray(image).copy()\n black_mask = (image_data[..., :3] == 0).all(axis=-1)\n image_data[black_mask, :3] = color\n return Image.fromarray(image_data, mode="RGBA")\n\n # Use the high-resolution (48x48 px) icon if it exists and is needed\n with Image.open(path_large if (size > 24 and path_large.exists())\n else path_regular) as im:\n # assure a RGBA image as foreground color is RGB\n im = im.convert("RGBA")\n image = ImageTk.PhotoImage(im.resize((size, size)), master=self)\n button._ntimage = image\n\n # create a version of the icon with the button's text color\n foreground = (255 / 65535) * np.array(\n button.winfo_rgb(button.cget("foreground")))\n im_alt = _recolor_icon(im, foreground)\n image_alt = ImageTk.PhotoImage(\n im_alt.resize((size, size)), master=self)\n button._ntimage_alt = image_alt\n\n if _is_dark("background"):\n # For Checkbuttons, we need to set `image` and `selectimage` at\n # the same time. Otherwise, when updating the `image` option\n # (such as when changing DPI), if the old `selectimage` has\n # just been overwritten, Tk will throw an error.\n image_kwargs = {"image": image_alt}\n else:\n image_kwargs = {"image": image}\n # Checkbuttons may switch the background to `selectcolor` in the\n # checked state, so check separately which image it needs to use in\n # that state to still ensure enough contrast with the background.\n if (\n isinstance(button, tk.Checkbutton)\n and button.cget("selectcolor") != ""\n ):\n if self._windowingsystem != "x11":\n selectcolor = "selectcolor"\n else:\n # On X11, selectcolor isn't used directly for indicator-less\n # buttons. See `::tk::CheckEnter` in the Tk button.tcl source\n # code for details.\n r1, g1, b1 = _get_color("selectcolor")\n r2, g2, b2 = _get_color("activebackground")\n selectcolor = ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2)\n if _is_dark(selectcolor):\n image_kwargs["selectimage"] = image_alt\n else:\n image_kwargs["selectimage"] = image\n\n button.configure(**image_kwargs, height='18p', width='18p')\n\n def _Button(self, text, image_file, toggle, command):\n if not toggle:\n b = tk.Button(\n master=self, text=text, command=command,\n relief="flat", overrelief="groove", borderwidth=1,\n )\n else:\n # There is a bug in tkinter included in some python 3.6 versions\n # that without this variable, produces a "visual" toggling of\n # other near checkbuttons\n # https://bugs.python.org/issue29402\n # https://bugs.python.org/issue25684\n var = tk.IntVar(master=self)\n b = tk.Checkbutton(\n master=self, text=text, command=command, indicatoron=False,\n variable=var, offrelief="flat", overrelief="groove",\n borderwidth=1\n )\n b.var = var\n b._image_file = image_file\n if image_file is not None:\n # Explicit class because ToolbarTk calls _Button.\n NavigationToolbar2Tk._set_image_for_button(self, b)\n else:\n b.configure(font=self._label_font)\n b.pack(side=tk.LEFT)\n return b\n\n def _Spacer(self):\n # Buttons are also 18pt high.\n s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray')\n s.pack(side=tk.LEFT, padx='3p')\n return s\n\n def save_figure(self, *args):\n filetypes = self.canvas.get_supported_filetypes_grouped()\n tk_filetypes = [\n (name, " ".join(f"*.{ext}" for ext in exts))\n for name, exts in sorted(filetypes.items())\n ]\n\n default_extension = self.canvas.get_default_filetype()\n default_filetype = self.canvas.get_supported_filetypes()[default_extension]\n filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype)\n\n # adding a default extension seems to break the\n # asksaveasfilename dialog when you choose various save types\n # from the dropdown. Passing in the empty string seems to\n # work - JDH!\n # defaultextension = self.canvas.get_default_filetype()\n defaultextension = ''\n initialdir = os.path.expanduser(mpl.rcParams['savefig.directory'])\n # get_default_filename() contains the default extension. On some platforms,\n # choosing a different extension from the dropdown does not overwrite it,\n # so we need to remove it to make the dropdown functional.\n initialfile = pathlib.Path(self.canvas.get_default_filename()).stem\n fname = tkinter.filedialog.asksaveasfilename(\n master=self.canvas.get_tk_widget().master,\n title='Save the figure',\n filetypes=tk_filetypes,\n defaultextension=defaultextension,\n initialdir=initialdir,\n initialfile=initialfile,\n typevariable=filetype_variable\n )\n\n if fname in ["", ()]:\n return None\n # Save dir for next time, unless empty str (i.e., use cwd).\n if initialdir != "":\n mpl.rcParams['savefig.directory'] = (\n os.path.dirname(str(fname)))\n\n # If the filename contains an extension, let savefig() infer the file\n # format from that. If it does not, use the selected dropdown option.\n if pathlib.Path(fname).suffix[1:] != "":\n extension = None\n else:\n extension = filetypes[filetype_variable.get()][0]\n\n try:\n self.canvas.figure.savefig(fname, format=extension)\n return fname\n except Exception as e:\n tkinter.messagebox.showerror("Error saving file", str(e))\n\n def set_history_buttons(self):\n state_map = {True: tk.NORMAL, False: tk.DISABLED}\n can_back = self._nav_stack._pos > 0\n can_forward = self._nav_stack._pos < len(self._nav_stack) - 1\n if "Back" in self._buttons:\n self._buttons['Back']['state'] = state_map[can_back]\n if "Forward" in self._buttons:\n self._buttons['Forward']['state'] = state_map[can_forward]\n\n\ndef add_tooltip(widget, text):\n tipwindow = None\n\n def showtip(event):\n """Display text in tooltip window."""\n nonlocal tipwindow\n if tipwindow or not text:\n return\n x, y, _, _ = widget.bbox("insert")\n x = x + widget.winfo_rootx() + widget.winfo_width()\n y = y + widget.winfo_rooty()\n tipwindow = tk.Toplevel(widget)\n tipwindow.overrideredirect(1)\n tipwindow.geometry(f"+{x}+{y}")\n try: # For Mac OS\n tipwindow.tk.call("::tk::unsupported::MacWindowStyle",\n "style", tipwindow._w,\n "help", "noActivates")\n except tk.TclError:\n pass\n label = tk.Label(tipwindow, text=text, justify=tk.LEFT,\n relief=tk.SOLID, borderwidth=1)\n label.pack(ipadx=1)\n\n def hidetip(event):\n nonlocal tipwindow\n if tipwindow:\n tipwindow.destroy()\n tipwindow = None\n\n widget.bind("<Enter>", showtip)\n widget.bind("<Leave>", hidetip)\n\n\n@backend_tools._register_tool_class(FigureCanvasTk)\nclass RubberbandTk(backend_tools.RubberbandBase):\n def draw_rubberband(self, x0, y0, x1, y1):\n NavigationToolbar2Tk.draw_rubberband(\n self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)\n\n def remove_rubberband(self):\n NavigationToolbar2Tk.remove_rubberband(\n self._make_classic_style_pseudo_toolbar())\n\n\nclass ToolbarTk(ToolContainerBase, tk.Frame):\n def __init__(self, toolmanager, window=None):\n ToolContainerBase.__init__(self, toolmanager)\n if window is None:\n window = self.toolmanager.canvas.get_tk_widget().master\n xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx\n height, width = 50, xmax - xmin\n tk.Frame.__init__(self, master=window,\n width=int(width), height=int(height),\n borderwidth=2)\n self._label_font = tkinter.font.Font(size=10)\n # This filler item ensures the toolbar is always at least two text\n # lines high. Otherwise the canvas gets redrawn as the mouse hovers\n # over images because those use two-line messages which resize the\n # toolbar.\n label = tk.Label(master=self, font=self._label_font,\n text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')\n label.pack(side=tk.RIGHT)\n self._message = tk.StringVar(master=self)\n self._message_label = tk.Label(master=self, font=self._label_font,\n textvariable=self._message)\n self._message_label.pack(side=tk.RIGHT)\n self._toolitems = {}\n self.pack(side=tk.TOP, fill=tk.X)\n self._groups = {}\n\n def _rescale(self):\n return NavigationToolbar2Tk._rescale(self)\n\n def add_toolitem(\n self, name, group, position, image_file, description, toggle):\n frame = self._get_groupframe(group)\n buttons = frame.pack_slaves()\n if position >= len(buttons) or position < 0:\n before = None\n else:\n before = buttons[position]\n button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle,\n lambda: self._button_click(name))\n button.pack_configure(before=before)\n if description is not None:\n add_tooltip(button, description)\n self._toolitems.setdefault(name, [])\n self._toolitems[name].append(button)\n\n def _get_groupframe(self, group):\n if group not in self._groups:\n if self._groups:\n self._add_separator()\n frame = tk.Frame(master=self, borderwidth=0)\n frame.pack(side=tk.LEFT, fill=tk.Y)\n frame._label_font = self._label_font\n self._groups[group] = frame\n return self._groups[group]\n\n def _add_separator(self):\n return NavigationToolbar2Tk._Spacer(self)\n\n def _button_click(self, name):\n self.trigger_tool(name)\n\n def toggle_toolitem(self, name, toggled):\n if name not in self._toolitems:\n return\n for toolitem in self._toolitems[name]:\n if toggled:\n toolitem.select()\n else:\n toolitem.deselect()\n\n def remove_toolitem(self, name):\n for toolitem in self._toolitems.pop(name, []):\n toolitem.pack_forget()\n\n def set_message(self, s):\n self._message.set(s)\n\n\n@backend_tools._register_tool_class(FigureCanvasTk)\nclass SaveFigureTk(backend_tools.SaveFigureBase):\n def trigger(self, *args):\n NavigationToolbar2Tk.save_figure(\n self._make_classic_style_pseudo_toolbar())\n\n\n@backend_tools._register_tool_class(FigureCanvasTk)\nclass ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase):\n def trigger(self, *args):\n NavigationToolbar2Tk.configure_subplots(self)\n\n\n@backend_tools._register_tool_class(FigureCanvasTk)\nclass HelpTk(backend_tools.ToolHelpBase):\n def trigger(self, *args):\n dialog = SimpleDialog(\n self.figure.canvas._tkcanvas, self._get_help_text(), ["OK"])\n dialog.done = lambda num: dialog.frame.master.withdraw()\n\n\nToolbar = ToolbarTk\nFigureManagerTk._toolbar2_class = NavigationToolbar2Tk\nFigureManagerTk._toolmanager_toolbar_class = ToolbarTk\n\n\n@_Backend.export\nclass _BackendTk(_Backend):\n backend_version = tk.TkVersion\n FigureCanvas = FigureCanvasTk\n FigureManager = FigureManagerTk\n mainloop = FigureManagerTk.start_main_loop\n
.venv\Lib\site-packages\matplotlib\backends\_backend_tk.py
_backend_tk.py
Python
43,291
0.95
0.204271
0.137931
node-utils
804
2023-12-03T08:33:09.027765
GPL-3.0
false
8884fb102b6634c8ea777209db8f7fab
import numpy as np\nfrom numpy.typing import NDArray\n\nTK_PHOTO_COMPOSITE_OVERLAY: int\nTK_PHOTO_COMPOSITE_SET: int\n\ndef blit(\n interp: int,\n photo_name: str,\n data: NDArray[np.uint8],\n comp_rule: int,\n offset: tuple[int, int, int, int],\n bbox: tuple[int, int, int, int],\n) -> None: ...\ndef enable_dpi_awareness(frame_handle: int, interp: int) -> bool | None: ...\n
.venv\Lib\site-packages\matplotlib\backends\_tkagg.pyi
_tkagg.pyi
Other
379
0.85
0.133333
0
node-utils
835
2024-02-21T07:07:15.349274
BSD-3-Clause
false
0d1c85fb64e6cb17abd2e5a451c677d3
from .registry import BackendFilter, backend_registry # noqa: F401\n\n# NOTE: plt.switch_backend() (called at import time) will add a "backend"\n# attribute here for backcompat.\n_QT_FORCE_QT5_BINDING = False\n
.venv\Lib\site-packages\matplotlib\backends\__init__.py
__init__.py
Python
206
0.95
0.2
0.5
react-lib
525
2024-06-12T08:18:11.507233
BSD-3-Clause
false
66bbdbd7f1111e0f21ab673887d23b9a
# Copyright © 2009 Pierre Raybaut\n# Licensed under the terms of the MIT License\n# see the Matplotlib licenses directory for a copy of the license\n\n\n"""Module that provides a GUI-based editor for Matplotlib's figure options."""\n\nfrom itertools import chain\nfrom matplotlib import cbook, cm, colors as mcolors, markers, image as mimage\nfrom matplotlib.backends.qt_compat import QtGui\nfrom matplotlib.backends.qt_editor import _formlayout\nfrom matplotlib.dates import DateConverter, num2date\n\nLINESTYLES = {'-': 'Solid',\n '--': 'Dashed',\n '-.': 'DashDot',\n ':': 'Dotted',\n 'None': 'None',\n }\n\nDRAWSTYLES = {\n 'default': 'Default',\n 'steps-pre': 'Steps (Pre)', 'steps': 'Steps (Pre)',\n 'steps-mid': 'Steps (Mid)',\n 'steps-post': 'Steps (Post)'}\n\nMARKERS = markers.MarkerStyle.markers\n\n\ndef figure_edit(axes, parent=None):\n """Edit matplotlib figure options"""\n sep = (None, None) # separator\n\n # Get / General\n def convert_limits(lim, converter):\n """Convert axis limits for correct input editors."""\n if isinstance(converter, DateConverter):\n return map(num2date, lim)\n # Cast to builtin floats as they have nicer reprs.\n return map(float, lim)\n\n axis_map = axes._axis_map\n axis_limits = {\n name: tuple(convert_limits(\n getattr(axes, f'get_{name}lim')(), axis.get_converter()\n ))\n for name, axis in axis_map.items()\n }\n general = [\n ('Title', axes.get_title()),\n sep,\n *chain.from_iterable([\n (\n (None, f"<b>{name.title()}-Axis</b>"),\n ('Min', axis_limits[name][0]),\n ('Max', axis_limits[name][1]),\n ('Label', axis.label.get_text()),\n ('Scale', [axis.get_scale(),\n 'linear', 'log', 'symlog', 'logit']),\n sep,\n )\n for name, axis in axis_map.items()\n ]),\n ('(Re-)Generate automatic legend', False),\n ]\n\n # Save the converter and unit data\n axis_converter = {\n name: axis.get_converter()\n for name, axis in axis_map.items()\n }\n axis_units = {\n name: axis.get_units()\n for name, axis in axis_map.items()\n }\n\n # Get / Curves\n labeled_lines = []\n for line in axes.get_lines():\n label = line.get_label()\n if label == '_nolegend_':\n continue\n labeled_lines.append((label, line))\n curves = []\n\n def prepare_data(d, init):\n """\n Prepare entry for FormLayout.\n\n *d* is a mapping of shorthands to style names (a single style may\n have multiple shorthands, in particular the shorthands `None`,\n `"None"`, `"none"` and `""` are synonyms); *init* is one shorthand\n of the initial style.\n\n This function returns an list suitable for initializing a\n FormLayout combobox, namely `[initial_name, (shorthand,\n style_name), (shorthand, style_name), ...]`.\n """\n if init not in d:\n d = {**d, init: str(init)}\n # Drop duplicate shorthands from dict (by overwriting them during\n # the dict comprehension).\n name2short = {name: short for short, name in d.items()}\n # Convert back to {shorthand: name}.\n short2name = {short: name for name, short in name2short.items()}\n # Find the kept shorthand for the style specified by init.\n canonical_init = name2short[d[init]]\n # Sort by representation and prepend the initial value.\n return ([canonical_init] +\n sorted(short2name.items(),\n key=lambda short_and_name: short_and_name[1]))\n\n for label, line in labeled_lines:\n color = mcolors.to_hex(\n mcolors.to_rgba(line.get_color(), line.get_alpha()),\n keep_alpha=True)\n ec = mcolors.to_hex(\n mcolors.to_rgba(line.get_markeredgecolor(), line.get_alpha()),\n keep_alpha=True)\n fc = mcolors.to_hex(\n mcolors.to_rgba(line.get_markerfacecolor(), line.get_alpha()),\n keep_alpha=True)\n curvedata = [\n ('Label', label),\n sep,\n (None, '<b>Line</b>'),\n ('Line style', prepare_data(LINESTYLES, line.get_linestyle())),\n ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())),\n ('Width', line.get_linewidth()),\n ('Color (RGBA)', color),\n sep,\n (None, '<b>Marker</b>'),\n ('Style', prepare_data(MARKERS, line.get_marker())),\n ('Size', line.get_markersize()),\n ('Face color (RGBA)', fc),\n ('Edge color (RGBA)', ec)]\n curves.append([curvedata, label, ""])\n # Is there a curve displayed?\n has_curve = bool(curves)\n\n # Get ScalarMappables.\n labeled_mappables = []\n for mappable in [*axes.images, *axes.collections]:\n label = mappable.get_label()\n if label == '_nolegend_' or mappable.get_array() is None:\n continue\n labeled_mappables.append((label, mappable))\n mappables = []\n cmaps = [(cmap, name) for name, cmap in sorted(cm._colormaps.items())]\n for label, mappable in labeled_mappables:\n cmap = mappable.get_cmap()\n if cmap.name not in cm._colormaps:\n cmaps = [(cmap, cmap.name), *cmaps]\n low, high = mappable.get_clim()\n mappabledata = [\n ('Label', label),\n ('Colormap', [cmap.name] + cmaps),\n ('Min. value', low),\n ('Max. value', high),\n ]\n if hasattr(mappable, "get_interpolation"): # Images.\n interpolations = [\n (name, name) for name in sorted(mimage.interpolations_names)]\n mappabledata.append((\n 'Interpolation',\n [mappable.get_interpolation(), *interpolations]))\n\n interpolation_stages = ['data', 'rgba', 'auto']\n mappabledata.append((\n 'Interpolation stage',\n [mappable.get_interpolation_stage(), *interpolation_stages]))\n\n mappables.append([mappabledata, label, ""])\n # Is there a scalarmappable displayed?\n has_sm = bool(mappables)\n\n datalist = [(general, "Axes", "")]\n if curves:\n datalist.append((curves, "Curves", ""))\n if mappables:\n datalist.append((mappables, "Images, etc.", ""))\n\n def apply_callback(data):\n """A callback to apply changes."""\n orig_limits = {\n name: getattr(axes, f"get_{name}lim")()\n for name in axis_map\n }\n\n general = data.pop(0)\n curves = data.pop(0) if has_curve else []\n mappables = data.pop(0) if has_sm else []\n if data:\n raise ValueError("Unexpected field")\n\n title = general.pop(0)\n axes.set_title(title)\n generate_legend = general.pop()\n\n for i, (name, axis) in enumerate(axis_map.items()):\n axis_min = general[4*i]\n axis_max = general[4*i + 1]\n axis_label = general[4*i + 2]\n axis_scale = general[4*i + 3]\n if axis.get_scale() != axis_scale:\n getattr(axes, f"set_{name}scale")(axis_scale)\n\n axis._set_lim(axis_min, axis_max, auto=False)\n axis.set_label_text(axis_label)\n\n # Restore the unit data\n axis._set_converter(axis_converter[name])\n axis.set_units(axis_units[name])\n\n # Set / Curves\n for index, curve in enumerate(curves):\n line = labeled_lines[index][1]\n (label, linestyle, drawstyle, linewidth, color, marker, markersize,\n markerfacecolor, markeredgecolor) = curve\n line.set_label(label)\n line.set_linestyle(linestyle)\n line.set_drawstyle(drawstyle)\n line.set_linewidth(linewidth)\n rgba = mcolors.to_rgba(color)\n line.set_alpha(None)\n line.set_color(rgba)\n if marker != 'none':\n line.set_marker(marker)\n line.set_markersize(markersize)\n line.set_markerfacecolor(markerfacecolor)\n line.set_markeredgecolor(markeredgecolor)\n\n # Set ScalarMappables.\n for index, mappable_settings in enumerate(mappables):\n mappable = labeled_mappables[index][1]\n if len(mappable_settings) == 6:\n label, cmap, low, high, interpolation, interpolation_stage = \\n mappable_settings\n mappable.set_interpolation(interpolation)\n mappable.set_interpolation_stage(interpolation_stage)\n elif len(mappable_settings) == 4:\n label, cmap, low, high = mappable_settings\n mappable.set_label(label)\n mappable.set_cmap(cmap)\n mappable.set_clim(*sorted([low, high]))\n\n # re-generate legend, if checkbox is checked\n if generate_legend:\n draggable = None\n ncols = 1\n if axes.legend_ is not None:\n old_legend = axes.get_legend()\n draggable = old_legend._draggable is not None\n ncols = old_legend._ncols\n new_legend = axes.legend(ncols=ncols)\n if new_legend:\n new_legend.set_draggable(draggable)\n\n # Redraw\n figure = axes.get_figure()\n figure.canvas.draw()\n for name in axis_map:\n if getattr(axes, f"get_{name}lim")() != orig_limits[name]:\n figure.canvas.toolbar.push_current()\n break\n\n _formlayout.fedit(\n datalist, title="Figure options", parent=parent,\n icon=QtGui.QIcon(\n str(cbook._get_data_path('images', 'qt4_editor_options.svg'))),\n apply=apply_callback)\n
.venv\Lib\site-packages\matplotlib\backends\qt_editor\figureoptions.py
figureoptions.py
Python
9,851
0.95
0.173432
0.091667
node-utils
830
2025-03-22T19:38:04.381442
BSD-3-Clause
false
352a354842e6d82a89a4ae0f4a55ae82
"""\nformlayout\n==========\n\nModule creating Qt form dialogs/layouts to edit various type of parameters\n\n\nformlayout License Agreement (MIT License)\n------------------------------------------\n\nCopyright (c) 2009 Pierre Raybaut\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the "Software"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n"""\n\n# History:\n# 1.0.10: added float validator\n# (disable "Ok" and "Apply" button when not valid)\n# 1.0.7: added support for "Apply" button\n# 1.0.6: code cleaning\n\n__version__ = '1.0.10'\n__license__ = __doc__\n\nfrom ast import literal_eval\n\nimport copy\nimport datetime\nimport logging\nfrom numbers import Integral, Real\n\nfrom matplotlib import _api, colors as mcolors\nfrom matplotlib.backends.qt_compat import _to_int, QtGui, QtWidgets, QtCore\n\n_log = logging.getLogger(__name__)\n\nBLACKLIST = {"title", "label"}\n\n\nclass ColorButton(QtWidgets.QPushButton):\n """\n Color choosing push button\n """\n colorChanged = QtCore.Signal(QtGui.QColor)\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setFixedSize(20, 20)\n self.setIconSize(QtCore.QSize(12, 12))\n self.clicked.connect(self.choose_color)\n self._color = QtGui.QColor()\n\n def choose_color(self):\n color = QtWidgets.QColorDialog.getColor(\n self._color, self.parentWidget(), "",\n QtWidgets.QColorDialog.ColorDialogOption.ShowAlphaChannel)\n if color.isValid():\n self.set_color(color)\n\n def get_color(self):\n return self._color\n\n @QtCore.Slot(QtGui.QColor)\n def set_color(self, color):\n if color != self._color:\n self._color = color\n self.colorChanged.emit(self._color)\n pixmap = QtGui.QPixmap(self.iconSize())\n pixmap.fill(color)\n self.setIcon(QtGui.QIcon(pixmap))\n\n color = QtCore.Property(QtGui.QColor, get_color, set_color)\n\n\ndef to_qcolor(color):\n """Create a QColor from a matplotlib color"""\n qcolor = QtGui.QColor()\n try:\n rgba = mcolors.to_rgba(color)\n except ValueError:\n _api.warn_external(f'Ignoring invalid color {color!r}')\n return qcolor # return invalid QColor\n qcolor.setRgbF(*rgba)\n return qcolor\n\n\nclass ColorLayout(QtWidgets.QHBoxLayout):\n """Color-specialized QLineEdit layout"""\n def __init__(self, color, parent=None):\n super().__init__()\n assert isinstance(color, QtGui.QColor)\n self.lineedit = QtWidgets.QLineEdit(\n mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)\n self.lineedit.editingFinished.connect(self.update_color)\n self.addWidget(self.lineedit)\n self.colorbtn = ColorButton(parent)\n self.colorbtn.color = color\n self.colorbtn.colorChanged.connect(self.update_text)\n self.addWidget(self.colorbtn)\n\n def update_color(self):\n color = self.text()\n qcolor = to_qcolor(color) # defaults to black if not qcolor.isValid()\n self.colorbtn.color = qcolor\n\n def update_text(self, color):\n self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True))\n\n def text(self):\n return self.lineedit.text()\n\n\ndef font_is_installed(font):\n """Check if font is installed"""\n return [fam for fam in QtGui.QFontDatabase().families()\n if str(fam) == font]\n\n\ndef tuple_to_qfont(tup):\n """\n Create a QFont from tuple:\n (family [string], size [int], italic [bool], bold [bool])\n """\n if not (isinstance(tup, tuple) and len(tup) == 4\n and font_is_installed(tup[0])\n and isinstance(tup[1], Integral)\n and isinstance(tup[2], bool)\n and isinstance(tup[3], bool)):\n return None\n font = QtGui.QFont()\n family, size, italic, bold = tup\n font.setFamily(family)\n font.setPointSize(size)\n font.setItalic(italic)\n font.setBold(bold)\n return font\n\n\ndef qfont_to_tuple(font):\n return (str(font.family()), int(font.pointSize()),\n font.italic(), font.bold())\n\n\nclass FontLayout(QtWidgets.QGridLayout):\n """Font selection"""\n def __init__(self, value, parent=None):\n super().__init__()\n font = tuple_to_qfont(value)\n assert font is not None\n\n # Font family\n self.family = QtWidgets.QFontComboBox(parent)\n self.family.setCurrentFont(font)\n self.addWidget(self.family, 0, 0, 1, -1)\n\n # Font size\n self.size = QtWidgets.QComboBox(parent)\n self.size.setEditable(True)\n sizelist = [*range(6, 12), *range(12, 30, 2), 36, 48, 72]\n size = font.pointSize()\n if size not in sizelist:\n sizelist.append(size)\n sizelist.sort()\n self.size.addItems([str(s) for s in sizelist])\n self.size.setCurrentIndex(sizelist.index(size))\n self.addWidget(self.size, 1, 0)\n\n # Italic or not\n self.italic = QtWidgets.QCheckBox(self.tr("Italic"), parent)\n self.italic.setChecked(font.italic())\n self.addWidget(self.italic, 1, 1)\n\n # Bold or not\n self.bold = QtWidgets.QCheckBox(self.tr("Bold"), parent)\n self.bold.setChecked(font.bold())\n self.addWidget(self.bold, 1, 2)\n\n def get_font(self):\n font = self.family.currentFont()\n font.setItalic(self.italic.isChecked())\n font.setBold(self.bold.isChecked())\n font.setPointSize(int(self.size.currentText()))\n return qfont_to_tuple(font)\n\n\ndef is_edit_valid(edit):\n text = edit.text()\n state = edit.validator().validate(text, 0)[0]\n return state == QtGui.QDoubleValidator.State.Acceptable\n\n\nclass FormWidget(QtWidgets.QWidget):\n update_buttons = QtCore.Signal()\n\n def __init__(self, data, comment="", with_margin=False, parent=None):\n """\n Parameters\n ----------\n data : list of (label, value) pairs\n The data to be edited in the form.\n comment : str, optional\n with_margin : bool, default: False\n If False, the form elements reach to the border of the widget.\n This is the desired behavior if the FormWidget is used as a widget\n alongside with other widgets such as a QComboBox, which also do\n not have a margin around them.\n However, a margin can be desired if the FormWidget is the only\n widget within a container, e.g. a tab in a QTabWidget.\n parent : QWidget or None\n The parent widget.\n """\n super().__init__(parent)\n self.data = copy.deepcopy(data)\n self.widgets = []\n self.formlayout = QtWidgets.QFormLayout(self)\n if not with_margin:\n self.formlayout.setContentsMargins(0, 0, 0, 0)\n if comment:\n self.formlayout.addRow(QtWidgets.QLabel(comment))\n self.formlayout.addRow(QtWidgets.QLabel(" "))\n\n def get_dialog(self):\n """Return FormDialog instance"""\n dialog = self.parent()\n while not isinstance(dialog, QtWidgets.QDialog):\n dialog = dialog.parent()\n return dialog\n\n def setup(self):\n for label, value in self.data:\n if label is None and value is None:\n # Separator: (None, None)\n self.formlayout.addRow(QtWidgets.QLabel(" "),\n QtWidgets.QLabel(" "))\n self.widgets.append(None)\n continue\n elif label is None:\n # Comment\n self.formlayout.addRow(QtWidgets.QLabel(value))\n self.widgets.append(None)\n continue\n elif tuple_to_qfont(value) is not None:\n field = FontLayout(value, self)\n elif (label.lower() not in BLACKLIST\n and mcolors.is_color_like(value)):\n field = ColorLayout(to_qcolor(value), self)\n elif isinstance(value, str):\n field = QtWidgets.QLineEdit(value, self)\n elif isinstance(value, (list, tuple)):\n if isinstance(value, tuple):\n value = list(value)\n # Note: get() below checks the type of value[0] in self.data so\n # it is essential that value gets modified in-place.\n # This means that the code is actually broken in the case where\n # value is a tuple, but fortunately we always pass a list...\n selindex = value.pop(0)\n field = QtWidgets.QComboBox(self)\n if isinstance(value[0], (list, tuple)):\n keys = [key for key, _val in value]\n value = [val for _key, val in value]\n else:\n keys = value\n field.addItems(value)\n if selindex in value:\n selindex = value.index(selindex)\n elif selindex in keys:\n selindex = keys.index(selindex)\n elif not isinstance(selindex, Integral):\n _log.warning(\n "index '%s' is invalid (label: %s, value: %s)",\n selindex, label, value)\n selindex = 0\n field.setCurrentIndex(selindex)\n elif isinstance(value, bool):\n field = QtWidgets.QCheckBox(self)\n field.setChecked(value)\n elif isinstance(value, Integral):\n field = QtWidgets.QSpinBox(self)\n field.setRange(-10**9, 10**9)\n field.setValue(value)\n elif isinstance(value, Real):\n field = QtWidgets.QLineEdit(repr(value), self)\n field.setCursorPosition(0)\n field.setValidator(QtGui.QDoubleValidator(field))\n field.validator().setLocale(QtCore.QLocale("C"))\n dialog = self.get_dialog()\n dialog.register_float_field(field)\n field.textChanged.connect(lambda text: dialog.update_buttons())\n elif isinstance(value, datetime.datetime):\n field = QtWidgets.QDateTimeEdit(self)\n field.setDateTime(value)\n elif isinstance(value, datetime.date):\n field = QtWidgets.QDateEdit(self)\n field.setDate(value)\n else:\n field = QtWidgets.QLineEdit(repr(value), self)\n self.formlayout.addRow(label, field)\n self.widgets.append(field)\n\n def get(self):\n valuelist = []\n for index, (label, value) in enumerate(self.data):\n field = self.widgets[index]\n if label is None:\n # Separator / Comment\n continue\n elif tuple_to_qfont(value) is not None:\n value = field.get_font()\n elif isinstance(value, str) or mcolors.is_color_like(value):\n value = str(field.text())\n elif isinstance(value, (list, tuple)):\n index = int(field.currentIndex())\n if isinstance(value[0], (list, tuple)):\n value = value[index][0]\n else:\n value = value[index]\n elif isinstance(value, bool):\n value = field.isChecked()\n elif isinstance(value, Integral):\n value = int(field.value())\n elif isinstance(value, Real):\n value = float(str(field.text()))\n elif isinstance(value, datetime.datetime):\n datetime_ = field.dateTime()\n if hasattr(datetime_, "toPyDateTime"):\n value = datetime_.toPyDateTime()\n else:\n value = datetime_.toPython()\n elif isinstance(value, datetime.date):\n date_ = field.date()\n if hasattr(date_, "toPyDate"):\n value = date_.toPyDate()\n else:\n value = date_.toPython()\n else:\n value = literal_eval(str(field.text()))\n valuelist.append(value)\n return valuelist\n\n\nclass FormComboWidget(QtWidgets.QWidget):\n update_buttons = QtCore.Signal()\n\n def __init__(self, datalist, comment="", parent=None):\n super().__init__(parent)\n layout = QtWidgets.QVBoxLayout()\n self.setLayout(layout)\n self.combobox = QtWidgets.QComboBox()\n layout.addWidget(self.combobox)\n\n self.stackwidget = QtWidgets.QStackedWidget(self)\n layout.addWidget(self.stackwidget)\n self.combobox.currentIndexChanged.connect(\n self.stackwidget.setCurrentIndex)\n\n self.widgetlist = []\n for data, title, comment in datalist:\n self.combobox.addItem(title)\n widget = FormWidget(data, comment=comment, parent=self)\n self.stackwidget.addWidget(widget)\n self.widgetlist.append(widget)\n\n def setup(self):\n for widget in self.widgetlist:\n widget.setup()\n\n def get(self):\n return [widget.get() for widget in self.widgetlist]\n\n\nclass FormTabWidget(QtWidgets.QWidget):\n update_buttons = QtCore.Signal()\n\n def __init__(self, datalist, comment="", parent=None):\n super().__init__(parent)\n layout = QtWidgets.QVBoxLayout()\n self.tabwidget = QtWidgets.QTabWidget()\n layout.addWidget(self.tabwidget)\n layout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(layout)\n self.widgetlist = []\n for data, title, comment in datalist:\n if len(data[0]) == 3:\n widget = FormComboWidget(data, comment=comment, parent=self)\n else:\n widget = FormWidget(data, with_margin=True, comment=comment,\n parent=self)\n index = self.tabwidget.addTab(widget, title)\n self.tabwidget.setTabToolTip(index, comment)\n self.widgetlist.append(widget)\n\n def setup(self):\n for widget in self.widgetlist:\n widget.setup()\n\n def get(self):\n return [widget.get() for widget in self.widgetlist]\n\n\nclass FormDialog(QtWidgets.QDialog):\n """Form Dialog"""\n def __init__(self, data, title="", comment="",\n icon=None, parent=None, apply=None):\n super().__init__(parent)\n\n self.apply_callback = apply\n\n # Form\n if isinstance(data[0][0], (list, tuple)):\n self.formwidget = FormTabWidget(data, comment=comment,\n parent=self)\n elif len(data[0]) == 3:\n self.formwidget = FormComboWidget(data, comment=comment,\n parent=self)\n else:\n self.formwidget = FormWidget(data, comment=comment,\n parent=self)\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.formwidget)\n\n self.float_fields = []\n self.formwidget.setup()\n\n # Button box\n self.bbox = bbox = QtWidgets.QDialogButtonBox(\n QtWidgets.QDialogButtonBox.StandardButton(\n _to_int(QtWidgets.QDialogButtonBox.StandardButton.Ok) |\n _to_int(QtWidgets.QDialogButtonBox.StandardButton.Cancel)\n ))\n self.formwidget.update_buttons.connect(self.update_buttons)\n if self.apply_callback is not None:\n apply_btn = bbox.addButton(\n QtWidgets.QDialogButtonBox.StandardButton.Apply)\n apply_btn.clicked.connect(self.apply)\n\n bbox.accepted.connect(self.accept)\n bbox.rejected.connect(self.reject)\n layout.addWidget(bbox)\n\n self.setLayout(layout)\n\n self.setWindowTitle(title)\n if not isinstance(icon, QtGui.QIcon):\n icon = QtWidgets.QWidget().style().standardIcon(\n QtWidgets.QStyle.SP_MessageBoxQuestion)\n self.setWindowIcon(icon)\n\n def register_float_field(self, field):\n self.float_fields.append(field)\n\n def update_buttons(self):\n valid = True\n for field in self.float_fields:\n if not is_edit_valid(field):\n valid = False\n for btn_type in ["Ok", "Apply"]:\n btn = self.bbox.button(\n getattr(QtWidgets.QDialogButtonBox.StandardButton,\n btn_type))\n if btn is not None:\n btn.setEnabled(valid)\n\n def accept(self):\n self.data = self.formwidget.get()\n self.apply_callback(self.data)\n super().accept()\n\n def reject(self):\n self.data = None\n super().reject()\n\n def apply(self):\n self.apply_callback(self.formwidget.get())\n\n def get(self):\n """Return form result"""\n return self.data\n\n\ndef fedit(data, title="", comment="", icon=None, parent=None, apply=None):\n """\n Create form dialog\n\n data: datalist, datagroup\n title: str\n comment: str\n icon: QIcon instance\n parent: parent QWidget\n apply: apply callback (function)\n\n datalist: list/tuple of (field_name, field_value)\n datagroup: list/tuple of (datalist *or* datagroup, title, comment)\n\n -> one field for each member of a datalist\n -> one tab for each member of a top-level datagroup\n -> one page (of a multipage widget, each page can be selected with a combo\n box) for each member of a datagroup inside a datagroup\n\n Supported types for field_value:\n - int, float, str, bool\n - colors: in Qt-compatible text form, i.e. in hex format or name\n (red, ...) (automatically detected from a string)\n - list/tuple:\n * the first element will be the selected index (or value)\n * the other elements can be couples (key, value) or only values\n """\n\n # Create a QApplication instance if no instance currently exists\n # (e.g., if the module is used directly from the interpreter)\n if QtWidgets.QApplication.startingUp():\n _app = QtWidgets.QApplication([])\n dialog = FormDialog(data, title, comment, icon, parent, apply)\n\n if parent is not None:\n if hasattr(parent, "_fedit_dialog"):\n parent._fedit_dialog.close()\n parent._fedit_dialog = dialog\n\n dialog.show()\n\n\nif __name__ == "__main__":\n\n _app = QtWidgets.QApplication([])\n\n def create_datalist_example():\n return [('str', 'this is a string'),\n ('list', [0, '1', '3', '4']),\n ('list2', ['--', ('none', 'None'), ('--', 'Dashed'),\n ('-.', 'DashDot'), ('-', 'Solid'),\n ('steps', 'Steps'), (':', 'Dotted')]),\n ('float', 1.2),\n (None, 'Other:'),\n ('int', 12),\n ('font', ('Arial', 10, False, True)),\n ('color', '#123409'),\n ('bool', True),\n ('date', datetime.date(2010, 10, 10)),\n ('datetime', datetime.datetime(2010, 10, 10)),\n ]\n\n def create_datagroup_example():\n datalist = create_datalist_example()\n return ((datalist, "Category 1", "Category 1 comment"),\n (datalist, "Category 2", "Category 2 comment"),\n (datalist, "Category 3", "Category 3 comment"))\n\n # --------- datalist example\n datalist = create_datalist_example()\n\n def apply_test(data):\n print("data:", data)\n fedit(datalist, title="Example",\n comment="This is just an <b>example</b>.",\n apply=apply_test)\n\n _app.exec()\n\n # --------- datagroup example\n datagroup = create_datagroup_example()\n fedit(datagroup, "Global title",\n apply=apply_test)\n _app.exec()\n\n # --------- datagroup inside a datagroup example\n datalist = create_datalist_example()\n datagroup = create_datagroup_example()\n fedit(((datagroup, "Title 1", "Tab 1 comment"),\n (datalist, "Title 2", "Tab 2 comment"),\n (datalist, "Title 3", "Tab 3 comment")),\n "Global title",\n apply=apply_test)\n _app.exec()\n
.venv\Lib\site-packages\matplotlib\backends\qt_editor\_formlayout.py
_formlayout.py
Python
20,953
0.95
0.162162
0.050302
react-lib
992
2023-07-21T01:16:42.416431
Apache-2.0
false
546a61024dbb36fd90c03d0a7c3da9b6
\n\n
.venv\Lib\site-packages\matplotlib\backends\qt_editor\__pycache__\figureoptions.cpython-313.pyc
figureoptions.cpython-313.pyc
Other
12,706
0.95
0.033557
0.007143
node-utils
480
2024-01-12T09:45:49.401472
BSD-3-Clause
false
e3f6b9792c29c1087abc476af7cbfd6e
\n\n
.venv\Lib\site-packages\matplotlib\backends\qt_editor\__pycache__\_formlayout.cpython-313.pyc
_formlayout.cpython-313.pyc
Other
32,668
0.95
0.030888
0.012712
node-utils
263
2024-12-11T03:45:00.984250
Apache-2.0
false
b82ca487f44cdd041764ea2ddb3600fa
\n\n
.venv\Lib\site-packages\matplotlib\backends\qt_editor\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
204
0.7
0
0
node-utils
862
2023-09-16T02:41:54.475306
BSD-3-Clause
false
bb1d229dd067957991439e1aeb9e865a
<!DOCTYPE html>\n<html lang="en">\n <head>\n <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/mpl.css" type="text/css">\n <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script>\n <script src="{{ prefix }}/js/mpl.js"></script>\n\n <script>\n function ready(fn) {\n if (document.readyState != "loading") {\n fn();\n } else {\n document.addEventListener("DOMContentLoaded", fn);\n }\n }\n\n function figure_ready(fig_id) {\n return function () {\n var main_div = document.querySelector("div#figures");\n var figure_div = document.createElement("div");\n figure_div.id = "figure-div";\n main_div.appendChild(figure_div);\n var websocket_type = mpl.get_websocket_type();\n var uri = "{{ ws_uri }}" + fig_id + "/ws";\n if (window.location.protocol === "https:") uri = uri.replace('ws:', 'wss:')\n var websocket = new websocket_type(uri);\n var fig = new mpl.figure(fig_id, websocket, mpl_ondownload, figure_div);\n\n fig.focus_on_mouseover = true;\n\n fig.canvas.setAttribute("tabindex", fig_id);\n }\n };\n\n {% for (fig_id, fig_manager) in figures %}\n ready(figure_ready({{ str(fig_id) }}));\n {% end %}\n </script>\n\n <title>MPL | WebAgg current figures</title>\n\n </head>\n <body>\n <div id="mpl-warnings" class="mpl-warnings"></div>\n\n <div id="figures" style="margin: 10px 10px;"></div>\n\n </body>\n</html>\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\all_figures.html
all_figures.html
HTML
1,753
0.95
0.134615
0
python-kit
530
2024-09-29T08:48:12.244584
BSD-3-Clause
false
8cea6a7c800fba6803837dd62aa1824d
<!-- Within the kernel, we don't know the address of the matplotlib\n websocket server, so we have to get in client-side and fetch our\n resources that way. -->\n<script>\n // We can't proceed until these JavaScript files are fetched, so\n // we fetch them synchronously\n $.ajaxSetup({async: false});\n $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/_static/js/mpl_tornado.js");\n $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/js/mpl.js");\n $.ajaxSetup({async: true});\n\n function init_figure{{ fig_id }}(e) {\n $('div.output').off('resize');\n\n var output_div = e.target.querySelector('div.output_subarea');\n var websocket_type = mpl.get_websocket_type();\n var websocket = new websocket_type(\n "ws://" + window.location.hostname + ":{{ port }}{{ prefix}}/" +\n {{ repr(str(fig_id)) }} + "/ws");\n\n var fig = new mpl.figure(\n {{repr(str(fig_id))}}, websocket, mpl_ondownload, output_div);\n\n // Fetch the first image\n fig.context.drawImage(fig.imageObj, 0, 0);\n\n fig.focus_on_mouseover = true;\n }\n\n // We can't initialize the figure contents until our content\n // has been added to the DOM. This is a bit of hack to get an\n // event for that.\n $('div.output').resize(init_figure{{ fig_id }});\n</script>\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\ipython_inline_figure.html
ipython_inline_figure.html
HTML
1,311
0.95
0.058824
0.214286
python-kit
133
2024-02-03T14:59:19.834065
GPL-3.0
false
b7e79800afdcd237de9d11e3da9daead
<!DOCTYPE html>\n<html lang="en">\n <head>\n <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css">\n <link rel="stylesheet" href="{{ prefix }}/_static/css/mpl.css" type="text/css">\n <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script>\n <script src="{{ prefix }}/js/mpl.js"></script>\n <script>\n function ready(fn) {\n if (document.readyState != "loading") {\n fn();\n } else {\n document.addEventListener("DOMContentLoaded", fn);\n }\n }\n\n ready(\n function () {\n var websocket_type = mpl.get_websocket_type();\n var uri = "{{ ws_uri }}" + {{ str(fig_id) }} + "/ws";\n if (window.location.protocol === 'https:') uri = uri.replace('ws:', 'wss:')\n var websocket = new websocket_type(uri);\n var fig = new mpl.figure(\n {{ str(fig_id) }}, websocket, mpl_ondownload,\n document.getElementById("figure"));\n }\n );\n </script>\n\n <title>matplotlib</title>\n </head>\n\n <body>\n <div id="mpl-warnings" class="mpl-warnings"></div>\n <div id="figure" style="margin: 10px 10px;"></div>\n </body>\n</html>\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\single_figure.html
single_figure.html
HTML
1,357
0.85
0.128205
0
awesome-app
59
2024-03-11T14:01:03.379666
BSD-3-Clause
false
8ff1acf87a06e3c7d93b486ea1540459
/**\n * HTML5 ✰ Boilerplate\n *\n * style.css contains a reset, font normalization and some base styles.\n *\n * Credit is left where credit is due.\n * Much inspiration was taken from these projects:\n * - yui.yahooapis.com/2.8.1/build/base/base.css\n * - camendesign.com/design/\n * - praegnanz.de/weblog/htmlcssjs-kickstart\n */\n\n\n/**\n * html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline)\n * v1.6.1 2010-09-17 | Authors: Eric Meyer & Richard Clark\n * html5doctor.com/html-5-reset-stylesheet/\n */\n\nhtml, body, div, span, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\nabbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,\nsmall, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, figcaption, figure,\nfooter, header, hgroup, menu, nav, section, summary,\ntime, mark, audio, video {\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n\nsup { vertical-align: super; }\nsub { vertical-align: sub; }\n\narticle, aside, details, figcaption, figure,\nfooter, header, hgroup, menu, nav, section {\n display: block;\n}\n\nblockquote, q { quotes: none; }\n\nblockquote:before, blockquote:after,\nq:before, q:after { content: ""; content: none; }\n\nins { background-color: #ff9; color: #000; text-decoration: none; }\n\nmark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; }\n\ndel { text-decoration: line-through; }\n\nabbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; }\n\ntable { border-collapse: collapse; border-spacing: 0; }\n\nhr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }\n\ninput, select { vertical-align: middle; }\n\n\n/**\n * Font normalization inspired by YUI Library's fonts.css: developer.yahoo.com/yui/\n */\n\nbody { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */\nselect, input, textarea, button { font:99% sans-serif; }\n\n/* Normalize monospace sizing:\n en.wikipedia.org/wiki/MediaWiki_talk:Common.css/Archive_11#Teletype_style_fix_for_Chrome */\npre, code, kbd, samp { font-family: monospace, sans-serif; }\n\nem,i { font-style: italic; }\nb,strong { font-weight: bold; }\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\css\boilerplate.css
boilerplate.css
Other
2,310
0.8
0
0.344828
react-lib
568
2024-12-22T02:32:40.015822
GPL-3.0
false
40aefaa4b20fae2dfb1d552693e5a4f9
\n/* Flexible box model classes */\n/* Taken from Alex Russell https://infrequently.org/2009/08/css-3-progress/ */\n\n.hbox {\n display: -webkit-box;\n -webkit-box-orient: horizontal;\n -webkit-box-align: stretch;\n\n display: -moz-box;\n -moz-box-orient: horizontal;\n -moz-box-align: stretch;\n\n display: box;\n box-orient: horizontal;\n box-align: stretch;\n}\n\n.hbox > * {\n -webkit-box-flex: 0;\n -moz-box-flex: 0;\n box-flex: 0;\n}\n\n.vbox {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-box-align: stretch;\n\n display: -moz-box;\n -moz-box-orient: vertical;\n -moz-box-align: stretch;\n\n display: box;\n box-orient: vertical;\n box-align: stretch;\n}\n\n.vbox > * {\n -webkit-box-flex: 0;\n -moz-box-flex: 0;\n box-flex: 0;\n}\n\n.reverse {\n -webkit-box-direction: reverse;\n -moz-box-direction: reverse;\n box-direction: reverse;\n}\n\n.box-flex0 {\n -webkit-box-flex: 0;\n -moz-box-flex: 0;\n box-flex: 0;\n}\n\n.box-flex1, .box-flex {\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n}\n\n.box-flex2 {\n -webkit-box-flex: 2;\n -moz-box-flex: 2;\n box-flex: 2;\n}\n\n.box-group1 {\n -webkit-box-flex-group: 1;\n -moz-box-flex-group: 1;\n box-flex-group: 1;\n}\n\n.box-group2 {\n -webkit-box-flex-group: 2;\n -moz-box-flex-group: 2;\n box-flex-group: 2;\n}\n\n.start {\n -webkit-box-pack: start;\n -moz-box-pack: start;\n box-pack: start;\n}\n\n.end {\n -webkit-box-pack: end;\n -moz-box-pack: end;\n box-pack: end;\n}\n\n.center {\n -webkit-box-pack: center;\n -moz-box-pack: center;\n box-pack: center;\n}\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\css\fbm.css
fbm.css
Other
1,456
0.8
0
0.025316
awesome-app
903
2025-06-18T22:09:14.879721
GPL-3.0
false
001fc45a5f8a73e3423f1f2c0582105e
/* General styling */\n.ui-helper-clearfix:before,\n.ui-helper-clearfix:after {\n content: "";\n display: table;\n border-collapse: collapse;\n}\n.ui-helper-clearfix:after {\n clear: both;\n}\n\n/* Header */\n.ui-widget-header {\n border: 1px solid #dddddd;\n border-top-left-radius: 6px;\n border-top-right-radius: 6px;\n background: #e9e9e9;\n color: #333333;\n font-weight: bold;\n}\n\n/* Toolbar and items */\n.mpl-toolbar {\n width: 100%;\n}\n\n.mpl-toolbar div.mpl-button-group {\n display: inline-block;\n}\n\n.mpl-button-group + .mpl-button-group {\n margin-left: 0.5em;\n}\n\n.mpl-widget {\n background-color: #fff;\n border: 1px solid #ccc;\n display: inline-block;\n cursor: pointer;\n color: #333;\n padding: 6px;\n vertical-align: middle;\n}\n\n.mpl-widget:disabled,\n.mpl-widget[disabled] {\n background-color: #ddd;\n border-color: #ddd !important;\n cursor: not-allowed;\n}\n\n.mpl-widget:disabled img,\n.mpl-widget[disabled] img {\n /* Convert black to grey */\n filter: contrast(0%);\n}\n\n.mpl-widget.active img {\n /* Convert black to tab:blue, approximately */\n filter: invert(34%) sepia(97%) saturate(468%) hue-rotate(162deg) brightness(96%) contrast(91%);\n}\n\nbutton.mpl-widget:focus,\nbutton.mpl-widget:hover {\n background-color: #ddd;\n border-color: #aaa;\n}\n\n.mpl-button-group button.mpl-widget {\n margin-left: -1px;\n}\n.mpl-button-group button.mpl-widget:first-child {\n border-top-left-radius: 6px;\n border-bottom-left-radius: 6px;\n margin-left: 0px;\n}\n.mpl-button-group button.mpl-widget:last-child {\n border-top-right-radius: 6px;\n border-bottom-right-radius: 6px;\n}\n\nselect.mpl-widget {\n cursor: default;\n}\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\css\mpl.css
mpl.css
Other
1,611
0.95
0
0.068493
node-utils
421
2025-05-23T18:25:24.198874
Apache-2.0
false
b44a0eb2540a08e53f13ba1df771f2fb
/**\n * Primary styles\n *\n * Author: IPython Development Team\n */\n\n\nbody {\n background-color: white;\n /* This makes sure that the body covers the entire window and needs to\n be in a different element than the display: box in wrapper below */\n position: absolute;\n left: 0px;\n right: 0px;\n top: 0px;\n bottom: 0px;\n overflow: visible;\n}\n\n\ndiv#header {\n /* Initially hidden to prevent FLOUC */\n display: none;\n position: relative;\n height: 40px;\n padding: 5px;\n margin: 0px;\n width: 100%;\n}\n\nspan#ipython_notebook {\n position: absolute;\n padding: 2px 2px 2px 5px;\n}\n\nspan#ipython_notebook img {\n font-family: Verdana, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;\n height: 24px;\n text-decoration:none;\n display: inline;\n color: black;\n}\n\n#site {\n width: 100%;\n display: none;\n}\n\n/* We set the fonts by hand here to override the values in the theme */\n.ui-widget {\n font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif;\n}\n\n.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button {\n font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif;\n}\n\n/* Smaller buttons */\n.ui-button .ui-button-text {\n padding: 0.2em 0.8em;\n font-size: 77%;\n}\n\ninput.ui-button {\n padding: 0.3em 0.9em;\n}\n\nspan#login_widget {\n float: right;\n}\n\n.border-box-sizing {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n#figure-div {\n display: inline-block;\n margin: 10px;\n vertical-align: top;\n}\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\css\page.css
page.css
Other
1,623
0.8
0
0.161765
react-lib
896
2024-02-13T10:49:38.916540
MIT
false
9647487bd65e3c1ad898926d3a298a96
/* Put everything inside the global mpl namespace */\n/* global mpl */\nwindow.mpl = {};\n\nmpl.get_websocket_type = function () {\n if (typeof WebSocket !== 'undefined') {\n return WebSocket;\n } else if (typeof MozWebSocket !== 'undefined') {\n return MozWebSocket;\n } else {\n alert(\n 'Your browser does not have WebSocket support. ' +\n 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n 'Firefox 4 and 5 are also supported but you ' +\n 'have to enable WebSockets in about:config.'\n );\n }\n};\n\nmpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n this.id = figure_id;\n\n this.ws = websocket;\n\n this.supports_binary = this.ws.binaryType !== undefined;\n\n if (!this.supports_binary) {\n var warnings = document.getElementById('mpl-warnings');\n if (warnings) {\n warnings.style.display = 'block';\n warnings.textContent =\n 'This browser does not support binary websocket messages. ' +\n 'Performance may be slow.';\n }\n }\n\n this.imageObj = new Image();\n\n this.context = undefined;\n this.message = undefined;\n this.canvas = undefined;\n this.rubberband_canvas = undefined;\n this.rubberband_context = undefined;\n this.format_dropdown = undefined;\n\n this.image_mode = 'full';\n\n this.root = document.createElement('div');\n this.root.setAttribute('style', 'display: inline-block');\n this._root_extra_style(this.root);\n\n parent_element.appendChild(this.root);\n\n this._init_header(this);\n this._init_canvas(this);\n this._init_toolbar(this);\n\n var fig = this;\n\n this.waiting = false;\n\n this.ws.onopen = function () {\n fig.send_message('supports_binary', { value: fig.supports_binary });\n fig.send_message('send_image_mode', {});\n if (fig.ratio !== 1) {\n fig.send_message('set_device_pixel_ratio', {\n device_pixel_ratio: fig.ratio,\n });\n }\n fig.send_message('refresh', {});\n };\n\n this.imageObj.onload = function () {\n if (fig.image_mode === 'full') {\n // Full images could contain transparency (where diff images\n // almost always do), so we need to clear the canvas so that\n // there is no ghosting.\n fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n }\n fig.context.drawImage(fig.imageObj, 0, 0);\n };\n\n this.imageObj.onunload = function () {\n fig.ws.close();\n };\n\n this.ws.onmessage = this._make_on_message_function(this);\n\n this.ondownload = ondownload;\n};\n\nmpl.figure.prototype._init_header = function () {\n var titlebar = document.createElement('div');\n titlebar.classList =\n 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n var titletext = document.createElement('div');\n titletext.classList = 'ui-dialog-title';\n titletext.setAttribute(\n 'style',\n 'width: 100%; text-align: center; padding: 3px;'\n );\n titlebar.appendChild(titletext);\n this.root.appendChild(titlebar);\n this.header = titletext;\n};\n\nmpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n\nmpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n\nmpl.figure.prototype._init_canvas = function () {\n var fig = this;\n\n var canvas_div = (this.canvas_div = document.createElement('div'));\n canvas_div.setAttribute('tabindex', '0');\n canvas_div.setAttribute(\n 'style',\n 'border: 1px solid #ddd;' +\n 'box-sizing: content-box;' +\n 'clear: both;' +\n 'min-height: 1px;' +\n 'min-width: 1px;' +\n 'outline: 0;' +\n 'overflow: hidden;' +\n 'position: relative;' +\n 'resize: both;' +\n 'z-index: 2;'\n );\n\n function on_keyboard_event_closure(name) {\n return function (event) {\n return fig.key_event(event, name);\n };\n }\n\n canvas_div.addEventListener(\n 'keydown',\n on_keyboard_event_closure('key_press')\n );\n canvas_div.addEventListener(\n 'keyup',\n on_keyboard_event_closure('key_release')\n );\n\n this._canvas_extra_style(canvas_div);\n this.root.appendChild(canvas_div);\n\n var canvas = (this.canvas = document.createElement('canvas'));\n canvas.classList.add('mpl-canvas');\n canvas.setAttribute(\n 'style',\n 'box-sizing: content-box;' +\n 'pointer-events: none;' +\n 'position: relative;' +\n 'z-index: 0;'\n );\n\n this.context = canvas.getContext('2d');\n\n var backingStore =\n this.context.backingStorePixelRatio ||\n this.context.webkitBackingStorePixelRatio ||\n this.context.mozBackingStorePixelRatio ||\n this.context.msBackingStorePixelRatio ||\n this.context.oBackingStorePixelRatio ||\n this.context.backingStorePixelRatio ||\n 1;\n\n this.ratio = (window.devicePixelRatio || 1) / backingStore;\n\n var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n 'canvas'\n ));\n rubberband_canvas.setAttribute(\n 'style',\n 'box-sizing: content-box;' +\n 'left: 0;' +\n 'pointer-events: none;' +\n 'position: absolute;' +\n 'top: 0;' +\n 'z-index: 1;'\n );\n\n // Apply a ponyfill if ResizeObserver is not implemented by browser.\n if (this.ResizeObserver === undefined) {\n if (window.ResizeObserver !== undefined) {\n this.ResizeObserver = window.ResizeObserver;\n } else {\n var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n this.ResizeObserver = obs.ResizeObserver;\n }\n }\n\n this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n // There's no need to resize if the WebSocket is not connected:\n // - If it is still connecting, then we will get an initial resize from\n // Python once it connects.\n // - If it has disconnected, then resizing will clear the canvas and\n // never get anything back to refill it, so better to not resize and\n // keep something visible.\n if (fig.ws.readyState != 1) {\n return;\n }\n var nentries = entries.length;\n for (var i = 0; i < nentries; i++) {\n var entry = entries[i];\n var width, height;\n if (entry.contentBoxSize) {\n if (entry.contentBoxSize instanceof Array) {\n // Chrome 84 implements new version of spec.\n width = entry.contentBoxSize[0].inlineSize;\n height = entry.contentBoxSize[0].blockSize;\n } else {\n // Firefox implements old version of spec.\n width = entry.contentBoxSize.inlineSize;\n height = entry.contentBoxSize.blockSize;\n }\n } else {\n // Chrome <84 implements even older version of spec.\n width = entry.contentRect.width;\n height = entry.contentRect.height;\n }\n\n // Keep the size of the canvas and rubber band canvas in sync with\n // the canvas container.\n if (entry.devicePixelContentBoxSize) {\n // Chrome 84 implements new version of spec.\n canvas.setAttribute(\n 'width',\n entry.devicePixelContentBoxSize[0].inlineSize\n );\n canvas.setAttribute(\n 'height',\n entry.devicePixelContentBoxSize[0].blockSize\n );\n } else {\n canvas.setAttribute('width', width * fig.ratio);\n canvas.setAttribute('height', height * fig.ratio);\n }\n /* This rescales the canvas back to display pixels, so that it\n * appears correct on HiDPI screens. */\n canvas.style.width = width + 'px';\n canvas.style.height = height + 'px';\n\n rubberband_canvas.setAttribute('width', width);\n rubberband_canvas.setAttribute('height', height);\n\n // And update the size in Python. We ignore the initial 0/0 size\n // that occurs as the element is placed into the DOM, which should\n // otherwise not happen due to the minimum size styling.\n if (width != 0 && height != 0) {\n fig.request_resize(width, height);\n }\n }\n });\n this.resizeObserverInstance.observe(canvas_div);\n\n function on_mouse_event_closure(name) {\n /* User Agent sniffing is bad, but WebKit is busted:\n * https://bugs.webkit.org/show_bug.cgi?id=144526\n * https://bugs.webkit.org/show_bug.cgi?id=181818\n * The worst that happens here is that they get an extra browser\n * selection when dragging, if this check fails to catch them.\n */\n var UA = navigator.userAgent;\n var isWebKit = /AppleWebKit/.test(UA) && !/Chrome/.test(UA);\n if(isWebKit) {\n return function (event) {\n /* This prevents the web browser from automatically changing to\n * the text insertion cursor when the button is pressed. We\n * want to control all of the cursor setting manually through\n * the 'cursor' event from matplotlib */\n event.preventDefault()\n return fig.mouse_event(event, name);\n };\n } else {\n return function (event) {\n return fig.mouse_event(event, name);\n };\n }\n }\n\n canvas_div.addEventListener(\n 'mousedown',\n on_mouse_event_closure('button_press')\n );\n canvas_div.addEventListener(\n 'mouseup',\n on_mouse_event_closure('button_release')\n );\n canvas_div.addEventListener(\n 'dblclick',\n on_mouse_event_closure('dblclick')\n );\n // Throttle sequential mouse events to 1 every 20ms.\n canvas_div.addEventListener(\n 'mousemove',\n on_mouse_event_closure('motion_notify')\n );\n\n canvas_div.addEventListener(\n 'mouseenter',\n on_mouse_event_closure('figure_enter')\n );\n canvas_div.addEventListener(\n 'mouseleave',\n on_mouse_event_closure('figure_leave')\n );\n\n canvas_div.addEventListener('wheel', function (event) {\n if (event.deltaY < 0) {\n event.step = 1;\n } else {\n event.step = -1;\n }\n on_mouse_event_closure('scroll')(event);\n });\n\n canvas_div.appendChild(canvas);\n canvas_div.appendChild(rubberband_canvas);\n\n this.rubberband_context = rubberband_canvas.getContext('2d');\n this.rubberband_context.strokeStyle = '#000000';\n\n this._resize_canvas = function (width, height, forward) {\n if (forward) {\n canvas_div.style.width = width + 'px';\n canvas_div.style.height = height + 'px';\n }\n };\n\n // Disable right mouse context menu.\n canvas_div.addEventListener('contextmenu', function (_e) {\n event.preventDefault();\n return false;\n });\n\n function set_focus() {\n canvas.focus();\n canvas_div.focus();\n }\n\n window.setTimeout(set_focus, 100);\n};\n\nmpl.figure.prototype._init_toolbar = function () {\n var fig = this;\n\n var toolbar = document.createElement('div');\n toolbar.classList = 'mpl-toolbar';\n this.root.appendChild(toolbar);\n\n function on_click_closure(name) {\n return function (_event) {\n return fig.toolbar_button_onclick(name);\n };\n }\n\n function on_mouseover_closure(tooltip) {\n return function (event) {\n if (!event.currentTarget.disabled) {\n return fig.toolbar_button_onmouseover(tooltip);\n }\n };\n }\n\n fig.buttons = {};\n var buttonGroup = document.createElement('div');\n buttonGroup.classList = 'mpl-button-group';\n for (var toolbar_ind in mpl.toolbar_items) {\n var name = mpl.toolbar_items[toolbar_ind][0];\n var tooltip = mpl.toolbar_items[toolbar_ind][1];\n var image = mpl.toolbar_items[toolbar_ind][2];\n var method_name = mpl.toolbar_items[toolbar_ind][3];\n\n if (!name) {\n /* Instead of a spacer, we start a new button group. */\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n buttonGroup = document.createElement('div');\n buttonGroup.classList = 'mpl-button-group';\n continue;\n }\n\n var button = (fig.buttons[name] = document.createElement('button'));\n button.classList = 'mpl-widget';\n button.setAttribute('role', 'button');\n button.setAttribute('aria-disabled', 'false');\n button.addEventListener('click', on_click_closure(method_name));\n button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n\n var icon_img = document.createElement('img');\n icon_img.src = '_images/' + image + '.png';\n icon_img.srcset = '_images/' + image + '_large.png 2x';\n icon_img.alt = tooltip;\n button.appendChild(icon_img);\n\n buttonGroup.appendChild(button);\n }\n\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n\n var fmt_picker = document.createElement('select');\n fmt_picker.classList = 'mpl-widget';\n toolbar.appendChild(fmt_picker);\n this.format_dropdown = fmt_picker;\n\n for (var ind in mpl.extensions) {\n var fmt = mpl.extensions[ind];\n var option = document.createElement('option');\n option.selected = fmt === mpl.default_extension;\n option.innerHTML = fmt;\n fmt_picker.appendChild(option);\n }\n\n var status_bar = document.createElement('span');\n status_bar.classList = 'mpl-message';\n toolbar.appendChild(status_bar);\n this.message = status_bar;\n};\n\nmpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n // which will in turn request a refresh of the image.\n this.send_message('resize', { width: x_pixels, height: y_pixels });\n};\n\nmpl.figure.prototype.send_message = function (type, properties) {\n properties['type'] = type;\n properties['figure_id'] = this.id;\n this.ws.send(JSON.stringify(properties));\n};\n\nmpl.figure.prototype.send_draw_message = function () {\n if (!this.waiting) {\n this.waiting = true;\n this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n }\n};\n\nmpl.figure.prototype.handle_save = function (fig, _msg) {\n var format_dropdown = fig.format_dropdown;\n var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n fig.ondownload(fig, format);\n};\n\nmpl.figure.prototype.handle_resize = function (fig, msg) {\n var size = msg['size'];\n if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n fig._resize_canvas(size[0], size[1], msg['forward']);\n fig.send_message('refresh', {});\n }\n};\n\nmpl.figure.prototype.handle_rubberband = function (fig, msg) {\n var x0 = msg['x0'] / fig.ratio;\n var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n var x1 = msg['x1'] / fig.ratio;\n var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n x0 = Math.floor(x0) + 0.5;\n y0 = Math.floor(y0) + 0.5;\n x1 = Math.floor(x1) + 0.5;\n y1 = Math.floor(y1) + 0.5;\n var min_x = Math.min(x0, x1);\n var min_y = Math.min(y0, y1);\n var width = Math.abs(x1 - x0);\n var height = Math.abs(y1 - y0);\n\n fig.rubberband_context.clearRect(\n 0,\n 0,\n fig.canvas.width / fig.ratio,\n fig.canvas.height / fig.ratio\n );\n\n fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n};\n\nmpl.figure.prototype.handle_figure_label = function (fig, msg) {\n // Updates the figure title.\n fig.header.textContent = msg['label'];\n};\n\nmpl.figure.prototype.handle_cursor = function (fig, msg) {\n fig.canvas_div.style.cursor = msg['cursor'];\n};\n\nmpl.figure.prototype.handle_message = function (fig, msg) {\n fig.message.textContent = msg['message'];\n};\n\nmpl.figure.prototype.handle_draw = function (fig, _msg) {\n // Request the server to send over a new figure.\n fig.send_draw_message();\n};\n\nmpl.figure.prototype.handle_image_mode = function (fig, msg) {\n fig.image_mode = msg['mode'];\n};\n\nmpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n for (var key in msg) {\n if (!(key in fig.buttons)) {\n continue;\n }\n fig.buttons[key].disabled = !msg[key];\n fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n }\n};\n\nmpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n if (msg['mode'] === 'PAN') {\n fig.buttons['Pan'].classList.add('active');\n fig.buttons['Zoom'].classList.remove('active');\n } else if (msg['mode'] === 'ZOOM') {\n fig.buttons['Pan'].classList.remove('active');\n fig.buttons['Zoom'].classList.add('active');\n } else {\n fig.buttons['Pan'].classList.remove('active');\n fig.buttons['Zoom'].classList.remove('active');\n }\n};\n\nmpl.figure.prototype.updated_canvas_event = function () {\n // Called whenever the canvas gets updated.\n this.send_message('ack', {});\n};\n\n// A function to construct a web socket function for onmessage handling.\n// Called in the figure constructor.\nmpl.figure.prototype._make_on_message_function = function (fig) {\n return function socket_on_message(evt) {\n if (evt.data instanceof Blob) {\n var img = evt.data;\n if (img.type !== 'image/png') {\n /* FIXME: We get "Resource interpreted as Image but\n * transferred with MIME type text/plain:" errors on\n * Chrome. But how to set the MIME type? It doesn't seem\n * to be part of the websocket stream */\n img.type = 'image/png';\n }\n\n /* Free the memory for the previous frames */\n if (fig.imageObj.src) {\n (window.URL || window.webkitURL).revokeObjectURL(\n fig.imageObj.src\n );\n }\n\n fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n img\n );\n fig.updated_canvas_event();\n fig.waiting = false;\n return;\n } else if (\n typeof evt.data === 'string' &&\n evt.data.slice(0, 21) === 'data:image/png;base64'\n ) {\n fig.imageObj.src = evt.data;\n fig.updated_canvas_event();\n fig.waiting = false;\n return;\n }\n\n var msg = JSON.parse(evt.data);\n var msg_type = msg['type'];\n\n // Call the "handle_{type}" callback, which takes\n // the figure and JSON message as its only arguments.\n try {\n var callback = fig['handle_' + msg_type];\n } catch (e) {\n console.log(\n "No handler for the '" + msg_type + "' message type: ",\n msg\n );\n return;\n }\n\n if (callback) {\n try {\n // console.log("Handling '" + msg_type + "' message: ", msg);\n callback(fig, msg);\n } catch (e) {\n console.log(\n "Exception inside the 'handler_" + msg_type + "' callback:",\n e,\n e.stack,\n msg\n );\n }\n }\n };\n};\n\nfunction getModifiers(event) {\n var mods = [];\n if (event.ctrlKey) {\n mods.push('ctrl');\n }\n if (event.altKey) {\n mods.push('alt');\n }\n if (event.shiftKey) {\n mods.push('shift');\n }\n if (event.metaKey) {\n mods.push('meta');\n }\n return mods;\n}\n\n/*\n * return a copy of an object with only non-object keys\n * we need this to avoid circular references\n * https://stackoverflow.com/a/24161582/3208463\n */\nfunction simpleKeys(original) {\n return Object.keys(original).reduce(function (obj, key) {\n if (typeof original[key] !== 'object') {\n obj[key] = original[key];\n }\n return obj;\n }, {});\n}\n\nmpl.figure.prototype.mouse_event = function (event, name) {\n if (name === 'button_press') {\n this.canvas.focus();\n this.canvas_div.focus();\n }\n\n // from https://stackoverflow.com/q/1114465\n var boundingRect = this.canvas.getBoundingClientRect();\n var x = (event.clientX - boundingRect.left) * this.ratio;\n var y = (event.clientY - boundingRect.top) * this.ratio;\n\n this.send_message(name, {\n x: x,\n y: y,\n button: event.button,\n step: event.step,\n buttons: event.buttons,\n modifiers: getModifiers(event),\n guiEvent: simpleKeys(event),\n });\n\n return false;\n};\n\nmpl.figure.prototype._key_event_extra = function (_event, _name) {\n // Handle any extra behaviour associated with a key event\n};\n\nmpl.figure.prototype.key_event = function (event, name) {\n // Prevent repeat events\n if (name === 'key_press') {\n if (event.key === this._key) {\n return;\n } else {\n this._key = event.key;\n }\n }\n if (name === 'key_release') {\n this._key = null;\n }\n\n var value = '';\n if (event.ctrlKey && event.key !== 'Control') {\n value += 'ctrl+';\n }\n else if (event.altKey && event.key !== 'Alt') {\n value += 'alt+';\n }\n else if (event.shiftKey && event.key !== 'Shift') {\n value += 'shift+';\n }\n\n value += 'k' + event.key;\n\n this._key_event_extra(event, name);\n\n this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n return false;\n};\n\nmpl.figure.prototype.toolbar_button_onclick = function (name) {\n if (name === 'download') {\n this.handle_save(this, null);\n } else {\n this.send_message('toolbar_button', { name: name });\n }\n};\n\nmpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n this.message.textContent = tooltip;\n};\n\n///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n// prettier-ignore\nvar _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError("Constructor requires 'new' operator");i.set(this,e)}function h(){throw new TypeError("Function is not a constructor")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\js\mpl.js
mpl.js
JavaScript
24,408
0.95
0.175887
0.100164
react-lib
92
2024-10-27T12:40:32.122699
GPL-3.0
false
33f90318b847040aa9a96015e0c6fe4f
/* This .js file contains functions for matplotlib's built-in\n tornado-based server, that are not relevant when embedding WebAgg\n in another web application. */\n\n/* exported mpl_ondownload */\nfunction mpl_ondownload(figure, format) {\n window.open(figure.id + '/download.' + format, '_blank');\n}\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\js\mpl_tornado.js
mpl_tornado.js
JavaScript
302
0.95
0.25
0.285714
python-kit
135
2024-02-18T09:45:13.584782
BSD-3-Clause
false
bf7bd4fa46d01c8c67175c3168986812
/* global mpl */\n\nvar comm_websocket_adapter = function (comm) {\n // Create a "websocket"-like object which calls the given IPython comm\n // object with the appropriate methods. Currently this is a non binary\n // socket, so there is still some room for performance tuning.\n var ws = {};\n\n ws.binaryType = comm.kernel.ws.binaryType;\n ws.readyState = comm.kernel.ws.readyState;\n function updateReadyState(_event) {\n if (comm.kernel.ws) {\n ws.readyState = comm.kernel.ws.readyState;\n } else {\n ws.readyState = 3; // Closed state.\n }\n }\n comm.kernel.ws.addEventListener('open', updateReadyState);\n comm.kernel.ws.addEventListener('close', updateReadyState);\n comm.kernel.ws.addEventListener('error', updateReadyState);\n\n ws.close = function () {\n comm.close();\n };\n ws.send = function (m) {\n //console.log('sending', m);\n comm.send(m);\n };\n // Register the callback with on_msg.\n comm.on_msg(function (msg) {\n //console.log('receiving', msg['content']['data'], msg);\n var data = msg['content']['data'];\n if (data['blob'] !== undefined) {\n data = {\n data: new Blob(msg['buffers'], { type: data['blob'] }),\n };\n }\n // Pass the mpl event to the overridden (by mpl) onmessage function.\n ws.onmessage(data);\n });\n return ws;\n};\n\nmpl.mpl_figure_comm = function (comm, msg) {\n // This is the function which gets called when the mpl process\n // starts-up an IPython Comm through the "matplotlib" channel.\n\n var id = msg.content.data.id;\n // Get hold of the div created by the display call when the Comm\n // socket was opened in Python.\n var element = document.getElementById(id);\n var ws_proxy = comm_websocket_adapter(comm);\n\n function ondownload(figure, _format) {\n window.open(figure.canvas.toDataURL());\n }\n\n var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n\n // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n // web socket which is closed, not our websocket->open comm proxy.\n ws_proxy.onopen();\n\n fig.parent_element = element;\n fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");\n if (!fig.cell_info) {\n console.error('Failed to find cell for figure', id, fig);\n return;\n }\n fig.cell_info[0].output_area.element.on(\n 'cleared',\n { fig: fig },\n fig._remove_fig_handler\n );\n};\n\nmpl.figure.prototype.handle_close = function (fig, msg) {\n var width = fig.canvas.width / fig.ratio;\n fig.cell_info[0].output_area.element.off(\n 'cleared',\n fig._remove_fig_handler\n );\n fig.resizeObserverInstance.unobserve(fig.canvas_div);\n\n // Update the output cell to use the data from the current canvas.\n fig.push_to_output();\n var dataURL = fig.canvas.toDataURL();\n // Re-enable the keyboard manager in IPython - without this line, in FF,\n // the notebook keyboard shortcuts fail.\n IPython.keyboard_manager.enable();\n fig.parent_element.innerHTML =\n '<img src="' + dataURL + '" width="' + width + '">';\n fig.close_ws(fig, msg);\n};\n\nmpl.figure.prototype.close_ws = function (fig, msg) {\n fig.send_message('closing', msg);\n // fig.ws.close()\n};\n\nmpl.figure.prototype.push_to_output = function (_remove_interactive) {\n // Turn the data on the canvas into data in the output cell.\n var width = this.canvas.width / this.ratio;\n var dataURL = this.canvas.toDataURL();\n this.cell_info[1]['text/html'] =\n '<img src="' + dataURL + '" width="' + width + '">';\n};\n\nmpl.figure.prototype.updated_canvas_event = function () {\n // Tell IPython that the notebook contents must change.\n IPython.notebook.set_dirty(true);\n this.send_message('ack', {});\n var fig = this;\n // Wait a second, then push the new image to the DOM so\n // that it is saved nicely (might be nice to debounce this).\n setTimeout(function () {\n fig.push_to_output();\n }, 1000);\n};\n\nmpl.figure.prototype._init_toolbar = function () {\n var fig = this;\n\n var toolbar = document.createElement('div');\n toolbar.classList = 'btn-toolbar';\n this.root.appendChild(toolbar);\n\n function on_click_closure(name) {\n return function (_event) {\n return fig.toolbar_button_onclick(name);\n };\n }\n\n function on_mouseover_closure(tooltip) {\n return function (event) {\n if (!event.currentTarget.disabled) {\n return fig.toolbar_button_onmouseover(tooltip);\n }\n };\n }\n\n fig.buttons = {};\n var buttonGroup = document.createElement('div');\n buttonGroup.classList = 'btn-group';\n var button;\n for (var toolbar_ind in mpl.toolbar_items) {\n var name = mpl.toolbar_items[toolbar_ind][0];\n var tooltip = mpl.toolbar_items[toolbar_ind][1];\n var image = mpl.toolbar_items[toolbar_ind][2];\n var method_name = mpl.toolbar_items[toolbar_ind][3];\n\n if (!name) {\n /* Instead of a spacer, we start a new button group. */\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n buttonGroup = document.createElement('div');\n buttonGroup.classList = 'btn-group';\n continue;\n }\n\n button = fig.buttons[name] = document.createElement('button');\n button.classList = 'btn btn-default';\n button.href = '#';\n button.title = name;\n button.innerHTML = '<i class="fa ' + image + ' fa-lg"></i>';\n button.addEventListener('click', on_click_closure(method_name));\n button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n buttonGroup.appendChild(button);\n }\n\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n\n // Add the status bar.\n var status_bar = document.createElement('span');\n status_bar.classList = 'mpl-message pull-right';\n toolbar.appendChild(status_bar);\n this.message = status_bar;\n\n // Add the close button to the window.\n var buttongrp = document.createElement('div');\n buttongrp.classList = 'btn-group inline pull-right';\n button = document.createElement('button');\n button.classList = 'btn btn-mini btn-primary';\n button.href = '#';\n button.title = 'Stop Interaction';\n button.innerHTML = '<i class="fa fa-power-off icon-remove icon-large"></i>';\n button.addEventListener('click', function (_evt) {\n fig.handle_close(fig, {});\n });\n button.addEventListener(\n 'mouseover',\n on_mouseover_closure('Stop Interaction')\n );\n buttongrp.appendChild(button);\n var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n titlebar.insertBefore(buttongrp, titlebar.firstChild);\n};\n\nmpl.figure.prototype._remove_fig_handler = function (event) {\n var fig = event.data.fig;\n if (event.target !== this) {\n // Ignore bubbled events from children.\n return;\n }\n fig.close_ws(fig, {});\n};\n\nmpl.figure.prototype._root_extra_style = function (el) {\n el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n};\n\nmpl.figure.prototype._canvas_extra_style = function (el) {\n // this is important to make the div 'focusable\n el.setAttribute('tabindex', 0);\n // reach out to IPython and tell the keyboard manager to turn it's self\n // off when our div gets focus\n\n // location in version 3\n if (IPython.notebook.keyboard_manager) {\n IPython.notebook.keyboard_manager.register_events(el);\n } else {\n // location in version 2\n IPython.keyboard_manager.register_events(el);\n }\n};\n\nmpl.figure.prototype._key_event_extra = function (event, _name) {\n // Check for shift+enter\n if (event.shiftKey && event.which === 13) {\n this.canvas_div.blur();\n // select the cell after this one\n var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n IPython.notebook.select(index + 1);\n }\n};\n\nmpl.figure.prototype.handle_save = function (fig, _msg) {\n fig.ondownload(fig, null);\n};\n\nmpl.find_output_cell = function (html_output) {\n // Return the cell and output element which can be found *uniquely* in the notebook.\n // Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"\n // IPython event is triggered only after the cells have been serialised, which for\n // our purposes (turning an active figure into a static one), is too late.\n var cells = IPython.notebook.get_cells();\n var ncells = cells.length;\n for (var i = 0; i < ncells; i++) {\n var cell = cells[i];\n if (cell.cell_type === 'code') {\n for (var j = 0; j < cell.output_area.outputs.length; j++) {\n var data = cell.output_area.outputs[j];\n if (data.data) {\n // IPython >= 3 moved mimebundle to data attribute of output\n data = data.data;\n }\n if (data['text/html'] === html_output) {\n return [cell, data, j];\n }\n }\n }\n }\n};\n\n// Register the function which deals with the matplotlib target/channel.\n// The kernel may be null if the page has been refreshed.\nif (IPython.notebook.kernel !== null) {\n IPython.notebook.kernel.comm_manager.register_target(\n 'matplotlib',\n mpl.mpl_figure_comm\n );\n}\n
.venv\Lib\site-packages\matplotlib\backends\web_backend\js\nbagg_mpl.js
nbagg_mpl.js
JavaScript
9,514
0.95
0.185455
0.164609
vue-tools
531
2024-12-01T07:59:57.025239
GPL-3.0
false
ab8108ad6caaff8e35b5725d2370e1a5
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_agg.cpython-313.pyc
backend_agg.cpython-313.pyc
Other
25,308
0.95
0.037975
0.071174
node-utils
213
2025-01-04T00:00:07.619402
MIT
false
462e44a18d3e12168e7de74be137e4a4
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_cairo.cpython-313.pyc
backend_cairo.cpython-313.pyc
Other
30,481
0.95
0.003788
0.008333
vue-tools
570
2023-08-02T09:18:26.458581
MIT
false
fba1e1fc858a55d672975bf0baa9b821
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk3.cpython-313.pyc
backend_gtk3.cpython-313.pyc
Other
36,761
0.95
0.012397
0.004525
vue-tools
567
2023-11-28T21:52:23.819140
MIT
false
618bccfb44d0cb65414a40edb74568b5
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk3agg.cpython-313.pyc
backend_gtk3agg.cpython-313.pyc
Other
4,641
0.8
0
0
awesome-app
994
2024-05-17T10:42:45.570920
MIT
false
0dc6305d9f92cfd12702d1746f135462
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk3cairo.cpython-313.pyc
backend_gtk3cairo.cpython-313.pyc
Other
2,516
0.8
0
0
python-kit
508
2025-04-10T07:29:36.476341
BSD-3-Clause
false
d2491beac23080c9514ecc65d70978b6
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk4.cpython-313.pyc
backend_gtk4.cpython-313.pyc
Other
36,373
0.95
0.01
0.011194
node-utils
462
2023-12-22T00:44:28.440670
GPL-3.0
false
a868531f5fa6692d162b0842bbcabcf0
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk4agg.cpython-313.pyc
backend_gtk4agg.cpython-313.pyc
Other
2,642
0.8
0
0
react-lib
369
2024-07-20T11:00:35.993934
MIT
false
e88528169cffc337033004d671998072
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_gtk4cairo.cpython-313.pyc
backend_gtk4cairo.cpython-313.pyc
Other
2,335
0.8
0
0
python-kit
165
2024-09-26T08:25:10.473416
BSD-3-Clause
false
316f1a7557ea3f2d1f44d841113cccbb
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_macosx.cpython-313.pyc
backend_macosx.cpython-313.pyc
Other
11,969
0.95
0.022727
0.047619
node-utils
422
2025-01-12T16:23:28.335537
BSD-3-Clause
false
8291fdc25a525d45ea8bc07b893673d9
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_mixed.cpython-313.pyc
backend_mixed.cpython-313.pyc
Other
4,815
0.95
0.074074
0.019608
node-utils
132
2023-11-20T09:52:10.101112
MIT
false
4cdf2db0dddd7c0f819cc7bd4992cfe7
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_nbagg.cpython-313.pyc
backend_nbagg.cpython-313.pyc
Other
12,283
0.8
0.019608
0
node-utils
206
2023-10-23T04:33:06.406816
Apache-2.0
false
5645f93412b28329d12c3fb03840a012
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_pgf.cpython-313.pyc
backend_pgf.cpython-313.pyc
Other
49,692
0.95
0.030488
0.006494
python-kit
463
2024-04-25T02:47:51.482884
BSD-3-Clause
false
2894ad612f8dde8367a91654877333fc
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_ps.cpython-313.pyc
backend_ps.cpython-313.pyc
Other
64,806
0.75
0.060254
0.003382
node-utils
974
2023-09-17T18:39:26.939454
BSD-3-Clause
false
950de593e0d0fdfd1ead7875ea7fcabe
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_qt.cpython-313.pyc
backend_qt.cpython-313.pyc
Other
65,207
0.75
0.004292
0.02
python-kit
18
2025-06-15T12:26:07.873763
MIT
false
6dc4bba52a703c94dd17408be16863ad
\n\n
.venv\Lib\site-packages\matplotlib\backends\__pycache__\backend_qt5.cpython-313.pyc
backend_qt5.cpython-313.pyc
Other
1,545
0.7
0
0
awesome-app
732
2023-07-18T13:03:43.473955
BSD-3-Clause
false
fad84fd8dd94095e633ba36e3bb4be52