Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

19348247-cfde-45b0-bb0b-447b30afee67 47 KB
Raw

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
  1. """
  2. A PostScript backend, which can produce both PostScript .ps and .eps.
  3. """
  4. import codecs
  5. import datetime
  6. from enum import Enum
  7. import functools
  8. from io import StringIO
  9. import itertools
  10. import logging
  11. import os
  12. import pathlib
  13. import shutil
  14. from tempfile import TemporaryDirectory
  15. import time
  16. import numpy as np
  17. import matplotlib as mpl
  18. from matplotlib import _api, cbook, _path, _text_helpers
  19. from matplotlib._afm import AFM
  20. from matplotlib.backend_bases import (
  21. _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
  22. from matplotlib.cbook import is_writable_file_like, file_requires_unicode
  23. from matplotlib.font_manager import get_font
  24. from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
  25. from matplotlib._ttconv import convert_ttf_to_ps
  26. from matplotlib._mathtext_data import uni2type1
  27. from matplotlib.path import Path
  28. from matplotlib.texmanager import TexManager
  29. from matplotlib.transforms import Affine2D
  30. from matplotlib.backends.backend_mixed import MixedModeRenderer
  31. from . import _backend_pdf_ps
  32. _log = logging.getLogger(__name__)
  33. debugPS = False
  34. @_api.deprecated("3.7")
  35. class PsBackendHelper:
  36. def __init__(self):
  37. self._cached = {}
  38. @_api.caching_module_getattr
  39. class __getattr__:
  40. # module-level deprecations
  41. ps_backend_helper = _api.deprecated("3.7", obj_type="")(
  42. property(lambda self: PsBackendHelper()))
  43. psDefs = _api.deprecated("3.8", obj_type="")(property(lambda self: _psDefs))
  44. papersize = {'letter': (8.5, 11),
  45. 'legal': (8.5, 14),
  46. 'ledger': (11, 17),
  47. 'a0': (33.11, 46.81),
  48. 'a1': (23.39, 33.11),
  49. 'a2': (16.54, 23.39),
  50. 'a3': (11.69, 16.54),
  51. 'a4': (8.27, 11.69),
  52. 'a5': (5.83, 8.27),
  53. 'a6': (4.13, 5.83),
  54. 'a7': (2.91, 4.13),
  55. 'a8': (2.05, 2.91),
  56. 'a9': (1.46, 2.05),
  57. 'a10': (1.02, 1.46),
  58. 'b0': (40.55, 57.32),
  59. 'b1': (28.66, 40.55),
  60. 'b2': (20.27, 28.66),
  61. 'b3': (14.33, 20.27),
  62. 'b4': (10.11, 14.33),
  63. 'b5': (7.16, 10.11),
  64. 'b6': (5.04, 7.16),
  65. 'b7': (3.58, 5.04),
  66. 'b8': (2.51, 3.58),
  67. 'b9': (1.76, 2.51),
  68. 'b10': (1.26, 1.76)}
  69. def _get_papertype(w, h):
  70. for key, (pw, ph) in sorted(papersize.items(), reverse=True):
  71. if key.startswith('l'):
  72. continue
  73. if w < pw and h < ph:
  74. return key
  75. return 'a0'
  76. def _nums_to_str(*args, sep=" "):
  77. return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
  78. def _move_path_to_path_or_stream(src, dst):
  79. """
  80. Move the contents of file at *src* to path-or-filelike *dst*.
  81. If *dst* is a path, the metadata of *src* are *not* copied.
  82. """
  83. if is_writable_file_like(dst):
  84. fh = (open(src, encoding='latin-1')
  85. if file_requires_unicode(dst)
  86. else open(src, 'rb'))
  87. with fh:
  88. shutil.copyfileobj(fh, dst)
  89. else:
  90. shutil.move(src, dst, copy_function=shutil.copyfile)
  91. def _font_to_ps_type3(font_path, chars):
  92. """
  93. Subset *chars* from the font at *font_path* into a Type 3 font.
  94. Parameters
  95. ----------
  96. font_path : path-like
  97. Path to the font to be subsetted.
  98. chars : str
  99. The characters to include in the subsetted font.
  100. Returns
  101. -------
  102. str
  103. The string representation of a Type 3 font, which can be included
  104. verbatim into a PostScript file.
  105. """
  106. font = get_font(font_path, hinting_factor=1)
  107. glyph_ids = [font.get_char_index(c) for c in chars]
  108. preamble = """\
  109. %!PS-Adobe-3.0 Resource-Font
  110. %%Creator: Converted from TrueType to Type 3 by Matplotlib.
  111. 10 dict begin
  112. /FontName /{font_name} def
  113. /PaintType 0 def
  114. /FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
  115. /FontBBox [{bbox}] def
  116. /FontType 3 def
  117. /Encoding [{encoding}] def
  118. /CharStrings {num_glyphs} dict dup begin
  119. /.notdef 0 def
  120. """.format(font_name=font.postscript_name,
  121. inv_units_per_em=1 / font.units_per_EM,
  122. bbox=" ".join(map(str, font.bbox)),
  123. encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"
  124. for glyph_id in glyph_ids),
  125. num_glyphs=len(glyph_ids) + 1)
  126. postamble = """
  127. end readonly def
  128. /BuildGlyph {
  129. exch begin
  130. CharStrings exch
  131. 2 copy known not {pop /.notdef} if
  132. true 3 1 roll get exec
  133. end
  134. } _d
  135. /BuildChar {
  136. 1 index /Encoding get exch get
  137. 1 index /BuildGlyph get exec
  138. } _d
  139. FontName currentdict end definefont pop
  140. """
  141. entries = []
  142. for glyph_id in glyph_ids:
  143. g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
  144. v, c = font.get_path()
  145. entries.append(
  146. "/%(name)s{%(bbox)s sc\n" % {
  147. "name": font.get_glyph_name(glyph_id),
  148. "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
  149. }
  150. + _path.convert_to_string(
  151. # Convert back to TrueType's internal units (1/64's).
  152. # (Other dimensions are already in these units.)
  153. Path(v * 64, c), None, None, False, None, 0,
  154. # No code for quad Beziers triggers auto-conversion to cubics.
  155. # Drop intermediate closepolys (relying on the outline
  156. # decomposer always explicitly moving to the closing point
  157. # first).
  158. [b"m", b"l", b"", b"c", b""], True).decode("ascii")
  159. + "ce} _d"
  160. )
  161. return preamble + "\n".join(entries) + postamble
  162. def _font_to_ps_type42(font_path, chars, fh):
  163. """
  164. Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
  165. Parameters
  166. ----------
  167. font_path : path-like
  168. Path to the font to be subsetted.
  169. chars : str
  170. The characters to include in the subsetted font.
  171. fh : file-like
  172. Where to write the font.
  173. """
  174. subset_str = ''.join(chr(c) for c in chars)
  175. _log.debug("SUBSET %s characters: %s", font_path, subset_str)
  176. try:
  177. fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str)
  178. _log.debug("SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
  179. fontdata.getbuffer().nbytes)
  180. # Give ttconv a subsetted font along with updated glyph_ids.
  181. font = FT2Font(fontdata)
  182. glyph_ids = [font.get_char_index(c) for c in chars]
  183. with TemporaryDirectory() as tmpdir:
  184. tmpfile = os.path.join(tmpdir, "tmp.ttf")
  185. with open(tmpfile, 'wb') as tmp:
  186. tmp.write(fontdata.getvalue())
  187. # TODO: allow convert_ttf_to_ps to input file objects (BytesIO)
  188. convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids)
  189. except RuntimeError:
  190. _log.warning(
  191. "The PostScript backend does not currently "
  192. "support the selected font.")
  193. raise
  194. def _log_if_debug_on(meth):
  195. """
  196. Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
  197. if the global flag `debugPS` is set.
  198. """
  199. @functools.wraps(meth)
  200. def wrapper(self, *args, **kwargs):
  201. if debugPS:
  202. self._pswriter.write(f"% {meth.__name__}\n")
  203. return meth(self, *args, **kwargs)
  204. return wrapper
  205. class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
  206. """
  207. The renderer handles all the drawing primitives using a graphics
  208. context instance that controls the colors/styles.
  209. """
  210. _afm_font_dir = cbook._get_data_path("fonts/afm")
  211. _use_afm_rc_name = "ps.useafm"
  212. def __init__(self, width, height, pswriter, imagedpi=72):
  213. # Although postscript itself is dpi independent, we need to inform the
  214. # image code about a requested dpi to generate high resolution images
  215. # and them scale them before embedding them.
  216. super().__init__(width, height)
  217. self._pswriter = pswriter
  218. if mpl.rcParams['text.usetex']:
  219. self.textcnt = 0
  220. self.psfrag = []
  221. self.imagedpi = imagedpi
  222. # current renderer state (None=uninitialised)
  223. self.color = None
  224. self.linewidth = None
  225. self.linejoin = None
  226. self.linecap = None
  227. self.linedash = None
  228. self.fontname = None
  229. self.fontsize = None
  230. self._hatches = {}
  231. self.image_magnification = imagedpi / 72
  232. self._clip_paths = {}
  233. self._path_collection_id = 0
  234. self._character_tracker = _backend_pdf_ps.CharacterTracker()
  235. self._logwarn_once = functools.cache(_log.warning)
  236. def _is_transparent(self, rgb_or_rgba):
  237. if rgb_or_rgba is None:
  238. return True # Consistent with rgbFace semantics.
  239. elif len(rgb_or_rgba) == 4:
  240. if rgb_or_rgba[3] == 0:
  241. return True
  242. if rgb_or_rgba[3] != 1:
  243. self._logwarn_once(
  244. "The PostScript backend does not support transparency; "
  245. "partially transparent artists will be rendered opaque.")
  246. return False
  247. else: # len() == 3.
  248. return False
  249. def set_color(self, r, g, b, store=True):
  250. if (r, g, b) != self.color:
  251. self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
  252. if r == g == b else
  253. f"{_nums_to_str(r, g, b)} setrgbcolor\n")
  254. if store:
  255. self.color = (r, g, b)
  256. def set_linewidth(self, linewidth, store=True):
  257. linewidth = float(linewidth)
  258. if linewidth != self.linewidth:
  259. self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
  260. if store:
  261. self.linewidth = linewidth
  262. @staticmethod
  263. def _linejoin_cmd(linejoin):
  264. # Support for directly passing integer values is for backcompat.
  265. linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
  266. linejoin]
  267. return f"{linejoin:d} setlinejoin\n"
  268. def set_linejoin(self, linejoin, store=True):
  269. if linejoin != self.linejoin:
  270. self._pswriter.write(self._linejoin_cmd(linejoin))
  271. if store:
  272. self.linejoin = linejoin
  273. @staticmethod
  274. def _linecap_cmd(linecap):
  275. # Support for directly passing integer values is for backcompat.
  276. linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
  277. linecap]
  278. return f"{linecap:d} setlinecap\n"
  279. def set_linecap(self, linecap, store=True):
  280. if linecap != self.linecap:
  281. self._pswriter.write(self._linecap_cmd(linecap))
  282. if store:
  283. self.linecap = linecap
  284. def set_linedash(self, offset, seq, store=True):
  285. if self.linedash is not None:
  286. oldo, oldseq = self.linedash
  287. if np.array_equal(seq, oldseq) and oldo == offset:
  288. return
  289. self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
  290. if seq is not None and len(seq) else
  291. "[] 0 setdash\n")
  292. if store:
  293. self.linedash = (offset, seq)
  294. def set_font(self, fontname, fontsize, store=True):
  295. if (fontname, fontsize) != (self.fontname, self.fontsize):
  296. self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
  297. if store:
  298. self.fontname = fontname
  299. self.fontsize = fontsize
  300. def create_hatch(self, hatch):
  301. sidelen = 72
  302. if hatch in self._hatches:
  303. return self._hatches[hatch]
  304. name = 'H%d' % len(self._hatches)
  305. linewidth = mpl.rcParams['hatch.linewidth']
  306. pageheight = self.height * 72
  307. self._pswriter.write(f"""\
  308. << /PatternType 1
  309. /PaintType 2
  310. /TilingType 2
  311. /BBox[0 0 {sidelen:d} {sidelen:d}]
  312. /XStep {sidelen:d}
  313. /YStep {sidelen:d}
  314. /PaintProc {{
  315. pop
  316. {linewidth:g} setlinewidth
  317. {self._convert_path(
  318. Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
  319. gsave
  320. fill
  321. grestore
  322. stroke
  323. }} bind
  324. >>
  325. matrix
  326. 0 {pageheight:g} translate
  327. makepattern
  328. /{name} exch def
  329. """)
  330. self._hatches[hatch] = name
  331. return name
  332. def get_image_magnification(self):
  333. """
  334. Get the factor by which to magnify images passed to draw_image.
  335. Allows a backend to have images at a different resolution to other
  336. artists.
  337. """
  338. return self.image_magnification
  339. def _convert_path(self, path, transform, clip=False, simplify=None):
  340. if clip:
  341. clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
  342. else:
  343. clip = None
  344. return _path.convert_to_string(
  345. path, transform, clip, simplify, None,
  346. 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
  347. def _get_clip_cmd(self, gc):
  348. clip = []
  349. rect = gc.get_clip_rectangle()
  350. if rect is not None:
  351. clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
  352. path, trf = gc.get_clip_path()
  353. if path is not None:
  354. key = (path, id(trf))
  355. custom_clip_cmd = self._clip_paths.get(key)
  356. if custom_clip_cmd is None:
  357. custom_clip_cmd = "c%d" % len(self._clip_paths)
  358. self._pswriter.write(f"""\
  359. /{custom_clip_cmd} {{
  360. {self._convert_path(path, trf, simplify=False)}
  361. clip
  362. newpath
  363. }} bind def
  364. """)
  365. self._clip_paths[key] = custom_clip_cmd
  366. clip.append(f"{custom_clip_cmd}\n")
  367. return "".join(clip)
  368. @_log_if_debug_on
  369. def draw_image(self, gc, x, y, im, transform=None):
  370. # docstring inherited
  371. h, w = im.shape[:2]
  372. imagecmd = "false 3 colorimage"
  373. data = im[::-1, :, :3] # Vertically flipped rgb values.
  374. hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
  375. if transform is None:
  376. matrix = "1 0 0 1 0 0"
  377. xscale = w / self.image_magnification
  378. yscale = h / self.image_magnification
  379. else:
  380. matrix = " ".join(map(str, transform.frozen().to_values()))
  381. xscale = 1.0
  382. yscale = 1.0
  383. self._pswriter.write(f"""\
  384. gsave
  385. {self._get_clip_cmd(gc)}
  386. {x:g} {y:g} translate
  387. [{matrix}] concat
  388. {xscale:g} {yscale:g} scale
  389. /DataString {w:d} string def
  390. {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
  391. {{
  392. currentfile DataString readhexstring pop
  393. }} bind {imagecmd}
  394. {hexdata}
  395. grestore
  396. """)
  397. @_log_if_debug_on
  398. def draw_path(self, gc, path, transform, rgbFace=None):
  399. # docstring inherited
  400. clip = rgbFace is None and gc.get_hatch_path() is None
  401. simplify = path.should_simplify and clip
  402. ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
  403. self._draw_ps(ps, gc, rgbFace)
  404. @_log_if_debug_on
  405. def draw_markers(
  406. self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
  407. # docstring inherited
  408. ps_color = (
  409. None
  410. if self._is_transparent(rgbFace)
  411. else f'{_nums_to_str(rgbFace[0])} setgray'
  412. if rgbFace[0] == rgbFace[1] == rgbFace[2]
  413. else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
  414. # construct the generic marker command:
  415. # don't want the translate to be global
  416. ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
  417. lw = gc.get_linewidth()
  418. alpha = (gc.get_alpha()
  419. if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
  420. else gc.get_rgb()[3])
  421. stroke = lw > 0 and alpha > 0
  422. if stroke:
  423. ps_cmd.append('%.1f setlinewidth' % lw)
  424. ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
  425. ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
  426. ps_cmd.append(self._convert_path(marker_path, marker_trans,
  427. simplify=False))
  428. if rgbFace:
  429. if stroke:
  430. ps_cmd.append('gsave')
  431. if ps_color:
  432. ps_cmd.extend([ps_color, 'fill'])
  433. if stroke:
  434. ps_cmd.append('grestore')
  435. if stroke:
  436. ps_cmd.append('stroke')
  437. ps_cmd.extend(['grestore', '} bind def'])
  438. for vertices, code in path.iter_segments(
  439. trans,
  440. clip=(0, 0, self.width*72, self.height*72),
  441. simplify=False):
  442. if len(vertices):
  443. x, y = vertices[-2:]
  444. ps_cmd.append(f"{x:g} {y:g} o")
  445. ps = '\n'.join(ps_cmd)
  446. self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
  447. @_log_if_debug_on
  448. def draw_path_collection(self, gc, master_transform, paths, all_transforms,
  449. offsets, offset_trans, facecolors, edgecolors,
  450. linewidths, linestyles, antialiaseds, urls,
  451. offset_position):
  452. # Is the optimization worth it? Rough calculation:
  453. # cost of emitting a path in-line is
  454. # (len_path + 2) * uses_per_path
  455. # cost of definition+use is
  456. # (len_path + 3) + 3 * uses_per_path
  457. len_path = len(paths[0].vertices) if len(paths) > 0 else 0
  458. uses_per_path = self._iter_collection_uses_per_path(
  459. paths, all_transforms, offsets, facecolors, edgecolors)
  460. should_do_optimization = \
  461. len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
  462. if not should_do_optimization:
  463. return RendererBase.draw_path_collection(
  464. self, gc, master_transform, paths, all_transforms,
  465. offsets, offset_trans, facecolors, edgecolors,
  466. linewidths, linestyles, antialiaseds, urls,
  467. offset_position)
  468. path_codes = []
  469. for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
  470. master_transform, paths, all_transforms)):
  471. name = 'p%d_%d' % (self._path_collection_id, i)
  472. path_bytes = self._convert_path(path, transform, simplify=False)
  473. self._pswriter.write(f"""\
  474. /{name} {{
  475. newpath
  476. translate
  477. {path_bytes}
  478. }} bind def
  479. """)
  480. path_codes.append(name)
  481. for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
  482. gc, path_codes, offsets, offset_trans,
  483. facecolors, edgecolors, linewidths, linestyles,
  484. antialiaseds, urls, offset_position):
  485. ps = f"{xo:g} {yo:g} {path_id}"
  486. self._draw_ps(ps, gc0, rgbFace)
  487. self._path_collection_id += 1
  488. @_log_if_debug_on
  489. def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
  490. # docstring inherited
  491. if self._is_transparent(gc.get_rgb()):
  492. return # Special handling for fully transparent.
  493. if not hasattr(self, "psfrag"):
  494. self._logwarn_once(
  495. "The PS backend determines usetex status solely based on "
  496. "rcParams['text.usetex'] and does not support having "
  497. "usetex=True only for some elements; this element will thus "
  498. "be rendered as if usetex=False.")
  499. self.draw_text(gc, x, y, s, prop, angle, False, mtext)
  500. return
  501. w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
  502. fontsize = prop.get_size_in_points()
  503. thetext = 'psmarker%d' % self.textcnt
  504. color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
  505. fontcmd = {'sans-serif': r'{\sffamily %s}',
  506. 'monospace': r'{\ttfamily %s}'}.get(
  507. mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
  508. s = fontcmd % s
  509. tex = r'\color[rgb]{%s} %s' % (color, s)
  510. # Stick to bottom-left alignment, so subtract descent from the text-normal
  511. # direction since text is normally positioned by its baseline.
  512. rangle = np.radians(angle + 90)
  513. pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
  514. self.psfrag.append(
  515. r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
  516. thetext, angle, fontsize, fontsize*1.25, tex))
  517. self._pswriter.write(f"""\
  518. gsave
  519. {pos} moveto
  520. ({thetext})
  521. show
  522. grestore
  523. """)
  524. self.textcnt += 1
  525. @_log_if_debug_on
  526. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  527. # docstring inherited
  528. if self._is_transparent(gc.get_rgb()):
  529. return # Special handling for fully transparent.
  530. if ismath == 'TeX':
  531. return self.draw_tex(gc, x, y, s, prop, angle)
  532. if ismath:
  533. return self.draw_mathtext(gc, x, y, s, prop, angle)
  534. stream = [] # list of (ps_name, x, char_name)
  535. if mpl.rcParams['ps.useafm']:
  536. font = self._get_font_afm(prop)
  537. ps_name = (font.postscript_name.encode("ascii", "replace")
  538. .decode("ascii"))
  539. scale = 0.001 * prop.get_size_in_points()
  540. thisx = 0
  541. last_name = None # kerns returns 0 for None.
  542. for c in s:
  543. name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
  544. try:
  545. width = font.get_width_from_char_name(name)
  546. except KeyError:
  547. name = 'question'
  548. width = font.get_width_char('?')
  549. kern = font.get_kern_dist_from_name(last_name, name)
  550. last_name = name
  551. thisx += kern * scale
  552. stream.append((ps_name, thisx, name))
  553. thisx += width * scale
  554. else:
  555. font = self._get_font_ttf(prop)
  556. self._character_tracker.track(font, s)
  557. for item in _text_helpers.layout(s, font):
  558. ps_name = (item.ft_object.postscript_name
  559. .encode("ascii", "replace").decode("ascii"))
  560. glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
  561. stream.append((ps_name, item.x, glyph_name))
  562. self.set_color(*gc.get_rgb())
  563. for ps_name, group in itertools. \
  564. groupby(stream, lambda entry: entry[0]):
  565. self.set_font(ps_name, prop.get_size_in_points(), False)
  566. thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
  567. for _, x, name in group)
  568. self._pswriter.write(f"""\
  569. gsave
  570. {self._get_clip_cmd(gc)}
  571. {x:g} {y:g} translate
  572. {angle:g} rotate
  573. {thetext}
  574. grestore
  575. """)
  576. @_log_if_debug_on
  577. def draw_mathtext(self, gc, x, y, s, prop, angle):
  578. """Draw the math text using matplotlib.mathtext."""
  579. width, height, descent, glyphs, rects = \
  580. self._text2path.mathtext_parser.parse(s, 72, prop)
  581. self.set_color(*gc.get_rgb())
  582. self._pswriter.write(
  583. f"gsave\n"
  584. f"{x:g} {y:g} translate\n"
  585. f"{angle:g} rotate\n")
  586. lastfont = None
  587. for font, fontsize, num, ox, oy in glyphs:
  588. self._character_tracker.track_glyph(font, num)
  589. if (font.postscript_name, fontsize) != lastfont:
  590. lastfont = font.postscript_name, fontsize
  591. self._pswriter.write(
  592. f"/{font.postscript_name} {fontsize} selectfont\n")
  593. glyph_name = (
  594. font.get_name_char(chr(num)) if isinstance(font, AFM) else
  595. font.get_glyph_name(font.get_char_index(num)))
  596. self._pswriter.write(
  597. f"{ox:g} {oy:g} moveto\n"
  598. f"/{glyph_name} glyphshow\n")
  599. for ox, oy, w, h in rects:
  600. self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
  601. self._pswriter.write("grestore\n")
  602. @_log_if_debug_on
  603. def draw_gouraud_triangle(self, gc, points, colors, trans):
  604. self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)),
  605. colors.reshape((1, 3, 4)), trans)
  606. @_log_if_debug_on
  607. def draw_gouraud_triangles(self, gc, points, colors, trans):
  608. assert len(points) == len(colors)
  609. if len(points) == 0:
  610. return
  611. assert points.ndim == 3
  612. assert points.shape[1] == 3
  613. assert points.shape[2] == 2
  614. assert colors.ndim == 3
  615. assert colors.shape[1] == 3
  616. assert colors.shape[2] == 4
  617. shape = points.shape
  618. flat_points = points.reshape((shape[0] * shape[1], 2))
  619. flat_points = trans.transform(flat_points)
  620. flat_colors = colors.reshape((shape[0] * shape[1], 4))
  621. points_min = np.min(flat_points, axis=0) - (1 << 12)
  622. points_max = np.max(flat_points, axis=0) + (1 << 12)
  623. factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
  624. xmin, ymin = points_min
  625. xmax, ymax = points_max
  626. data = np.empty(
  627. shape[0] * shape[1],
  628. dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
  629. data['flags'] = 0
  630. data['points'] = (flat_points - points_min) * factor
  631. data['colors'] = flat_colors[:, :3] * 255.0
  632. hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
  633. self._pswriter.write(f"""\
  634. gsave
  635. << /ShadingType 4
  636. /ColorSpace [/DeviceRGB]
  637. /BitsPerCoordinate 32
  638. /BitsPerComponent 8
  639. /BitsPerFlag 8
  640. /AntiAlias true
  641. /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
  642. /DataSource <
  643. {hexdata}
  644. >
  645. >>
  646. shfill
  647. grestore
  648. """)
  649. def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
  650. """
  651. Emit the PostScript snippet *ps* with all the attributes from *gc*
  652. applied. *ps* must consist of PostScript commands to construct a path.
  653. The *fill* and/or *stroke* kwargs can be set to False if the *ps*
  654. string already includes filling and/or stroking, in which case
  655. `_draw_ps` is just supplying properties and clipping.
  656. """
  657. write = self._pswriter.write
  658. mightstroke = (gc.get_linewidth() > 0
  659. and not self._is_transparent(gc.get_rgb()))
  660. if not mightstroke:
  661. stroke = False
  662. if self._is_transparent(rgbFace):
  663. fill = False
  664. hatch = gc.get_hatch()
  665. if mightstroke:
  666. self.set_linewidth(gc.get_linewidth())
  667. self.set_linejoin(gc.get_joinstyle())
  668. self.set_linecap(gc.get_capstyle())
  669. self.set_linedash(*gc.get_dashes())
  670. if mightstroke or hatch:
  671. self.set_color(*gc.get_rgb()[:3])
  672. write('gsave\n')
  673. write(self._get_clip_cmd(gc))
  674. write(ps.strip())
  675. write("\n")
  676. if fill:
  677. if stroke or hatch:
  678. write("gsave\n")
  679. self.set_color(*rgbFace[:3], store=False)
  680. write("fill\n")
  681. if stroke or hatch:
  682. write("grestore\n")
  683. if hatch:
  684. hatch_name = self.create_hatch(hatch)
  685. write("gsave\n")
  686. write(_nums_to_str(*gc.get_hatch_color()[:3]))
  687. write(f" {hatch_name} setpattern fill grestore\n")
  688. if stroke:
  689. write("stroke\n")
  690. write("grestore\n")
  691. class _Orientation(Enum):
  692. portrait, landscape = range(2)
  693. def swap_if_landscape(self, shape):
  694. return shape[::-1] if self.name == "landscape" else shape
  695. class FigureCanvasPS(FigureCanvasBase):
  696. fixed_dpi = 72
  697. filetypes = {'ps': 'Postscript',
  698. 'eps': 'Encapsulated Postscript'}
  699. def get_default_filetype(self):
  700. return 'ps'
  701. def _print_ps(
  702. self, fmt, outfile, *,
  703. metadata=None, papertype=None, orientation='portrait',
  704. bbox_inches_restore=None, **kwargs):
  705. dpi = self.figure.dpi
  706. self.figure.dpi = 72 # Override the dpi kwarg
  707. dsc_comments = {}
  708. if isinstance(outfile, (str, os.PathLike)):
  709. filename = pathlib.Path(outfile).name
  710. dsc_comments["Title"] = \
  711. filename.encode("ascii", "replace").decode("ascii")
  712. dsc_comments["Creator"] = (metadata or {}).get(
  713. "Creator",
  714. f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
  715. # See https://reproducible-builds.org/specs/source-date-epoch/
  716. source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
  717. dsc_comments["CreationDate"] = (
  718. datetime.datetime.fromtimestamp(
  719. int(source_date_epoch),
  720. datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
  721. if source_date_epoch
  722. else time.ctime())
  723. dsc_comments = "\n".join(
  724. f"%%{k}: {v}" for k, v in dsc_comments.items())
  725. if papertype is None:
  726. papertype = mpl.rcParams['ps.papersize']
  727. papertype = papertype.lower()
  728. _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype)
  729. orientation = _api.check_getitem(
  730. _Orientation, orientation=orientation.lower())
  731. printer = (self._print_figure_tex
  732. if mpl.rcParams['text.usetex'] else
  733. self._print_figure)
  734. printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
  735. orientation=orientation, papertype=papertype,
  736. bbox_inches_restore=bbox_inches_restore, **kwargs)
  737. def _print_figure(
  738. self, fmt, outfile, *,
  739. dpi, dsc_comments, orientation, papertype,
  740. bbox_inches_restore=None):
  741. """
  742. Render the figure to a filesystem path or a file-like object.
  743. Parameters are as for `.print_figure`, except that *dsc_comments* is a
  744. string containing Document Structuring Convention comments,
  745. generated from the *metadata* parameter to `.print_figure`.
  746. """
  747. is_eps = fmt == 'eps'
  748. if not (isinstance(outfile, (str, os.PathLike))
  749. or is_writable_file_like(outfile)):
  750. raise ValueError("outfile must be a path or a file-like object")
  751. # find the appropriate papertype
  752. width, height = self.figure.get_size_inches()
  753. if papertype == 'auto':
  754. papertype = _get_papertype(*orientation.swap_if_landscape((width, height)))
  755. if is_eps or papertype == 'figure':
  756. paper_width, paper_height = width, height
  757. else:
  758. paper_width, paper_height = orientation.swap_if_landscape(
  759. papersize[papertype])
  760. # center the figure on the paper
  761. xo = 72 * 0.5 * (paper_width - width)
  762. yo = 72 * 0.5 * (paper_height - height)
  763. llx = xo
  764. lly = yo
  765. urx = llx + self.figure.bbox.width
  766. ury = lly + self.figure.bbox.height
  767. rotation = 0
  768. if orientation is _Orientation.landscape:
  769. llx, lly, urx, ury = lly, llx, ury, urx
  770. xo, yo = 72 * paper_height - yo, xo
  771. rotation = 90
  772. bbox = (llx, lly, urx, ury)
  773. self._pswriter = StringIO()
  774. # mixed mode rendering
  775. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  776. renderer = MixedModeRenderer(
  777. self.figure, width, height, dpi, ps_renderer,
  778. bbox_inches_restore=bbox_inches_restore)
  779. self.figure.draw(renderer)
  780. def print_figure_impl(fh):
  781. # write the PostScript headers
  782. if is_eps:
  783. print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
  784. else:
  785. print("%!PS-Adobe-3.0", file=fh)
  786. if papertype != 'figure':
  787. print(f"%%DocumentPaperSizes: {papertype}", file=fh)
  788. print("%%Pages: 1", file=fh)
  789. print(f"%%LanguageLevel: 3\n"
  790. f"{dsc_comments}\n"
  791. f"%%Orientation: {orientation.name}\n"
  792. f"{get_bbox_header(bbox)[0]}\n"
  793. f"%%EndComments\n",
  794. end="", file=fh)
  795. Ndict = len(_psDefs)
  796. print("%%BeginProlog", file=fh)
  797. if not mpl.rcParams['ps.useafm']:
  798. Ndict += len(ps_renderer._character_tracker.used)
  799. print("/mpldict %d dict def" % Ndict, file=fh)
  800. print("mpldict begin", file=fh)
  801. print("\n".join(_psDefs), file=fh)
  802. if not mpl.rcParams['ps.useafm']:
  803. for font_path, chars \
  804. in ps_renderer._character_tracker.used.items():
  805. if not chars:
  806. continue
  807. fonttype = mpl.rcParams['ps.fonttype']
  808. # Can't use more than 255 chars from a single Type 3 font.
  809. if len(chars) > 255:
  810. fonttype = 42
  811. fh.flush()
  812. if fonttype == 3:
  813. fh.write(_font_to_ps_type3(font_path, chars))
  814. else: # Type 42 only.
  815. _font_to_ps_type42(font_path, chars, fh)
  816. print("end", file=fh)
  817. print("%%EndProlog", file=fh)
  818. if not is_eps:
  819. print("%%Page: 1 1", file=fh)
  820. print("mpldict begin", file=fh)
  821. print("%s translate" % _nums_to_str(xo, yo), file=fh)
  822. if rotation:
  823. print("%d rotate" % rotation, file=fh)
  824. print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
  825. # write the figure
  826. print(self._pswriter.getvalue(), file=fh)
  827. # write the trailer
  828. print("end", file=fh)
  829. print("showpage", file=fh)
  830. if not is_eps:
  831. print("%%EOF", file=fh)
  832. fh.flush()
  833. if mpl.rcParams['ps.usedistiller']:
  834. # We are going to use an external program to process the output.
  835. # Write to a temporary file.
  836. with TemporaryDirectory() as tmpdir:
  837. tmpfile = os.path.join(tmpdir, "tmp.ps")
  838. with open(tmpfile, 'w', encoding='latin-1') as fh:
  839. print_figure_impl(fh)
  840. if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
  841. _try_distill(gs_distill,
  842. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  843. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  844. _try_distill(xpdf_distill,
  845. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  846. _move_path_to_path_or_stream(tmpfile, outfile)
  847. else: # Write directly to outfile.
  848. with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
  849. if not file_requires_unicode(file):
  850. file = codecs.getwriter("latin-1")(file)
  851. print_figure_impl(file)
  852. def _print_figure_tex(
  853. self, fmt, outfile, *,
  854. dpi, dsc_comments, orientation, papertype,
  855. bbox_inches_restore=None):
  856. """
  857. If :rc:`text.usetex` is True, a temporary pair of tex/eps files
  858. are created to allow tex to manage the text layout via the PSFrags
  859. package. These files are processed to yield the final ps or eps file.
  860. The rest of the behavior is as for `._print_figure`.
  861. """
  862. is_eps = fmt == 'eps'
  863. width, height = self.figure.get_size_inches()
  864. xo = 0
  865. yo = 0
  866. llx = xo
  867. lly = yo
  868. urx = llx + self.figure.bbox.width
  869. ury = lly + self.figure.bbox.height
  870. bbox = (llx, lly, urx, ury)
  871. self._pswriter = StringIO()
  872. # mixed mode rendering
  873. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  874. renderer = MixedModeRenderer(self.figure,
  875. width, height, dpi, ps_renderer,
  876. bbox_inches_restore=bbox_inches_restore)
  877. self.figure.draw(renderer)
  878. # write to a temp file, we'll move it to outfile when done
  879. with TemporaryDirectory() as tmpdir:
  880. tmppath = pathlib.Path(tmpdir, "tmp.ps")
  881. tmppath.write_text(
  882. f"""\
  883. %!PS-Adobe-3.0 EPSF-3.0
  884. %%LanguageLevel: 3
  885. {dsc_comments}
  886. {get_bbox_header(bbox)[0]}
  887. %%EndComments
  888. %%BeginProlog
  889. /mpldict {len(_psDefs)} dict def
  890. mpldict begin
  891. {"".join(_psDefs)}
  892. end
  893. %%EndProlog
  894. mpldict begin
  895. {_nums_to_str(xo, yo)} translate
  896. 0 0 {_nums_to_str(width*72, height*72)} rectclip
  897. {self._pswriter.getvalue()}
  898. end
  899. showpage
  900. """,
  901. encoding="latin-1")
  902. if orientation is _Orientation.landscape: # now, ready to rotate
  903. width, height = height, width
  904. bbox = (lly, llx, ury, urx)
  905. # set the paper size to the figure size if is_eps. The
  906. # resulting ps file has the given size with correct bounding
  907. # box so that there is no need to call 'pstoeps'
  908. if is_eps or papertype == 'figure':
  909. paper_width, paper_height = orientation.swap_if_landscape(
  910. self.figure.get_size_inches())
  911. else:
  912. if papertype == 'auto':
  913. papertype = _get_papertype(width, height)
  914. paper_width, paper_height = papersize[papertype]
  915. psfrag_rotated = _convert_psfrags(
  916. tmppath, ps_renderer.psfrag, paper_width, paper_height,
  917. orientation.name)
  918. if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
  919. or mpl.rcParams['text.usetex']):
  920. _try_distill(gs_distill,
  921. tmppath, is_eps, ptype=papertype, bbox=bbox,
  922. rotated=psfrag_rotated)
  923. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  924. _try_distill(xpdf_distill,
  925. tmppath, is_eps, ptype=papertype, bbox=bbox,
  926. rotated=psfrag_rotated)
  927. _move_path_to_path_or_stream(tmppath, outfile)
  928. print_ps = functools.partialmethod(_print_ps, "ps")
  929. print_eps = functools.partialmethod(_print_ps, "eps")
  930. def draw(self):
  931. self.figure.draw_without_rendering()
  932. return super().draw()
  933. def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
  934. """
  935. When we want to use the LaTeX backend with postscript, we write PSFrag tags
  936. to a temporary postscript file, each one marking a position for LaTeX to
  937. render some text. convert_psfrags generates a LaTeX document containing the
  938. commands to convert those tags to text. LaTeX/dvips produces the postscript
  939. file that includes the actual text.
  940. """
  941. with mpl.rc_context({
  942. "text.latex.preamble":
  943. mpl.rcParams["text.latex.preamble"] +
  944. mpl.texmanager._usepackage_if_not_loaded("color") +
  945. mpl.texmanager._usepackage_if_not_loaded("graphicx") +
  946. mpl.texmanager._usepackage_if_not_loaded("psfrag") +
  947. r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
  948. % {"width": paper_width, "height": paper_height}
  949. }):
  950. dvifile = TexManager().make_dvi(
  951. "\n"
  952. r"\begin{figure}""\n"
  953. r" \centering\leavevmode""\n"
  954. r" %(psfrags)s""\n"
  955. r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
  956. r"\end{figure}"
  957. % {
  958. "psfrags": "\n".join(psfrags),
  959. "angle": 90 if orientation == 'landscape' else 0,
  960. "epsfile": tmppath.resolve().as_posix(),
  961. },
  962. fontsize=10) # tex's default fontsize.
  963. with TemporaryDirectory() as tmpdir:
  964. psfile = os.path.join(tmpdir, "tmp.ps")
  965. cbook._check_and_log_subprocess(
  966. ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
  967. shutil.move(psfile, tmppath)
  968. # check if the dvips created a ps in landscape paper. Somehow,
  969. # above latex+dvips results in a ps file in a landscape mode for a
  970. # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
  971. # bounding box of the final output got messed up. We check see if
  972. # the generated ps file is in landscape and return this
  973. # information. The return value is used in pstoeps step to recover
  974. # the correct bounding box. 2010-06-05 JJL
  975. with open(tmppath) as fh:
  976. psfrag_rotated = "Landscape" in fh.read(1000)
  977. return psfrag_rotated
  978. def _try_distill(func, tmppath, *args, **kwargs):
  979. try:
  980. func(str(tmppath), *args, **kwargs)
  981. except mpl.ExecutableNotFoundError as exc:
  982. _log.warning("%s. Distillation step skipped.", exc)
  983. def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  984. """
  985. Use ghostscript's pswrite or epswrite device to distill a file.
  986. This yields smaller files without illegal encapsulated postscript
  987. operators. The output is low-level, converting text to outlines.
  988. """
  989. if eps:
  990. paper_option = ["-dEPSCrop"]
  991. elif ptype == "figure":
  992. # The bbox will have its lower-left corner at (0, 0), so upper-right
  993. # corner corresponds with paper size.
  994. paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
  995. f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
  996. else:
  997. paper_option = [f"-sPAPERSIZE={ptype}"]
  998. psfile = tmpfile + '.ps'
  999. dpi = mpl.rcParams['ps.distiller.res']
  1000. cbook._check_and_log_subprocess(
  1001. [mpl._get_executable_info("gs").executable,
  1002. "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
  1003. *paper_option, f"-sOutputFile={psfile}", tmpfile],
  1004. _log)
  1005. os.remove(tmpfile)
  1006. shutil.move(psfile, tmpfile)
  1007. # While it is best if above steps preserve the original bounding
  1008. # box, there seem to be cases when it is not. For those cases,
  1009. # the original bbox can be restored during the pstoeps step.
  1010. if eps:
  1011. # For some versions of gs, above steps result in a ps file where the
  1012. # original bbox is no more correct. Do not adjust bbox for now.
  1013. pstoeps(tmpfile, bbox, rotated=rotated)
  1014. def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  1015. """
  1016. Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
  1017. This yields smaller files without illegal encapsulated postscript
  1018. operators. This distiller is preferred, generating high-level postscript
  1019. output that treats text as text.
  1020. """
  1021. mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
  1022. mpl._get_executable_info("pdftops")
  1023. if eps:
  1024. paper_option = ["-dEPSCrop"]
  1025. elif ptype == "figure":
  1026. # The bbox will have its lower-left corner at (0, 0), so upper-right
  1027. # corner corresponds with paper size.
  1028. paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
  1029. f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
  1030. else:
  1031. paper_option = [f"-sPAPERSIZE#{ptype}"]
  1032. with TemporaryDirectory() as tmpdir:
  1033. tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
  1034. tmpps = pathlib.Path(tmpdir, "tmp.ps")
  1035. # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
  1036. # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
  1037. cbook._check_and_log_subprocess(
  1038. ["ps2pdf",
  1039. "-dAutoFilterColorImages#false",
  1040. "-dAutoFilterGrayImages#false",
  1041. "-sAutoRotatePages#None",
  1042. "-sGrayImageFilter#FlateEncode",
  1043. "-sColorImageFilter#FlateEncode",
  1044. *paper_option,
  1045. tmpfile, tmppdf], _log)
  1046. cbook._check_and_log_subprocess(
  1047. ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
  1048. shutil.move(tmpps, tmpfile)
  1049. if eps:
  1050. pstoeps(tmpfile)
  1051. def get_bbox_header(lbrt, rotated=False):
  1052. """
  1053. Return a postscript header string for the given bbox lbrt=(l, b, r, t).
  1054. Optionally, return rotate command.
  1055. """
  1056. l, b, r, t = lbrt
  1057. if rotated:
  1058. rotate = f"{l+r:.2f} {0:.2f} translate\n90 rotate"
  1059. else:
  1060. rotate = ""
  1061. bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t))
  1062. hires_bbox_info = f'%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}'
  1063. return '\n'.join([bbox_info, hires_bbox_info]), rotate
  1064. def pstoeps(tmpfile, bbox=None, rotated=False):
  1065. """
  1066. Convert the postscript to encapsulated postscript. The bbox of
  1067. the eps file will be replaced with the given *bbox* argument. If
  1068. None, original bbox will be used.
  1069. """
  1070. # if rotated==True, the output eps file need to be rotated
  1071. if bbox:
  1072. bbox_info, rotate = get_bbox_header(bbox, rotated=rotated)
  1073. else:
  1074. bbox_info, rotate = None, None
  1075. epsfile = tmpfile + '.eps'
  1076. with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
  1077. write = epsh.write
  1078. # Modify the header:
  1079. for line in tmph:
  1080. if line.startswith(b'%!PS'):
  1081. write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
  1082. if bbox:
  1083. write(bbox_info.encode('ascii') + b'\n')
  1084. elif line.startswith(b'%%EndComments'):
  1085. write(line)
  1086. write(b'%%BeginProlog\n'
  1087. b'save\n'
  1088. b'countdictstack\n'
  1089. b'mark\n'
  1090. b'newpath\n'
  1091. b'/showpage {} def\n'
  1092. b'/setpagedevice {pop} def\n'
  1093. b'%%EndProlog\n'
  1094. b'%%Page 1 1\n')
  1095. if rotate:
  1096. write(rotate.encode('ascii') + b'\n')
  1097. break
  1098. elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
  1099. b'%%DocumentMedia', b'%%Pages')):
  1100. pass
  1101. else:
  1102. write(line)
  1103. # Now rewrite the rest of the file, and modify the trailer.
  1104. # This is done in a second loop such that the header of the embedded
  1105. # eps file is not modified.
  1106. for line in tmph:
  1107. if line.startswith(b'%%EOF'):
  1108. write(b'cleartomark\n'
  1109. b'countdictstack\n'
  1110. b'exch sub { end } repeat\n'
  1111. b'restore\n'
  1112. b'showpage\n'
  1113. b'%%EOF\n')
  1114. elif line.startswith(b'%%PageBoundingBox'):
  1115. pass
  1116. else:
  1117. write(line)
  1118. os.remove(tmpfile)
  1119. shutil.move(epsfile, tmpfile)
  1120. FigureManagerPS = FigureManagerBase
  1121. # The following Python dictionary psDefs contains the entries for the
  1122. # PostScript dictionary mpldict. This dictionary implements most of
  1123. # the matplotlib primitives and some abbreviations.
  1124. #
  1125. # References:
  1126. # https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
  1127. # http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
  1128. # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
  1129. #
  1130. # The usage comments use the notation of the operator summary
  1131. # in the PostScript Language reference manual.
  1132. _psDefs = [
  1133. # name proc *_d* -
  1134. # Note that this cannot be bound to /d, because when embedding a Type3 font
  1135. # we may want to define a "d" glyph using "/d{...} d" which would locally
  1136. # overwrite the definition.
  1137. "/_d { bind def } bind def",
  1138. # x y *m* -
  1139. "/m { moveto } _d",
  1140. # x y *l* -
  1141. "/l { lineto } _d",
  1142. # x y *r* -
  1143. "/r { rlineto } _d",
  1144. # x1 y1 x2 y2 x y *c* -
  1145. "/c { curveto } _d",
  1146. # *cl* -
  1147. "/cl { closepath } _d",
  1148. # *ce* -
  1149. "/ce { closepath eofill } _d",
  1150. # wx wy llx lly urx ury *setcachedevice* -
  1151. "/sc { setcachedevice } _d",
  1152. ]
  1153. @_Backend.export
  1154. class _BackendPS(_Backend):
  1155. backend_version = 'Level II'
  1156. FigureCanvas = FigureCanvasPS
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...