forked from javierlopez6466/Slide-Rule
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SlideRule.py
executable file
·1989 lines (1696 loc) · 87.2 KB
/
SlideRule.py
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
#!/usr/bin/env python3
"""
Slide Rule Scale Generator 2.0 by Javier Lopez 2020
v3.0 Brian T. Rice <briantrice@gmail.com> 2024
Available Scales: A B C D K R1 R2 CI DI CF DF CIF L S T ST
Table of Contents
1. Setup
2. Fundamental Functions
3. Scale Generating Function
4. Line Drawing Functions
5. Stickers
6. Models
7. Commands
"""
# ----------------------1. Setup----------------------------
import math
import os
import re
import time
import unicodedata
from dataclasses import dataclass, field, replace
from enum import Enum
from functools import cache
from itertools import chain
from typing import Callable
import toml
from PIL import Image, ImageFont, ImageDraw
def keys_of(obj: object):
return [k for k, v in obj.__dict__.items() if not k.startswith('__')]
# Angular constants:
TAU = math.tau
PI = math.pi
PI_HALF = PI / 2
DEG_FULL = 360
DEG_SEMI = DEG_FULL // 2
DEG_RT = DEG_SEMI // 2
BYTE_MAX = 255
WH = tuple[int, int]
class Color(Enum):
WHITE, BLACK = (BYTE_MAX, BYTE_MAX, BYTE_MAX), (0, 0, 0)
RED, GREEN, BLUE = (BYTE_MAX, 0, 0), (0, BYTE_MAX, 0), (0, 0, BYTE_MAX)
CUT = BLUE # color which indicates CUT
CUTOFF = (230, 230, 230)
CUTOFF2 = (234, 36, 98)
SYM_GREEN = (34, 139, 30) # Override PIL for green for slide rule symbol conventions
FC_LIGHT_BLUE_BG = (194, 235, 247) # Faber-Castell scale background
FC_LIGHT_GREEN_BG = (203, 243, 225) # Faber-Castell scale background
PICKETT_EYE_SAVER_YELLOW = (253, 253, 150) # pastel yellow
LIGHT_BLUE = 'lightblue'
RED_WHITE_1 = (BYTE_MAX, 224, 224)
RED_WHITE_2 = (BYTE_MAX, 192, 192)
RED_WHITE_3 = (BYTE_MAX, 160, 160)
DEBUG = 'grey'
@staticmethod
@cache
def to_pil(col_spec):
return col_spec.value if isinstance(col_spec, Color) else col_spec
@classmethod
def from_str(cls, color: str):
return getattr(cls, color.upper(), color)
class FontSize(Enum):
TITLE = 140
SUBTITLE = 120
SC_LBL = 90
N_XL = 75
N_LG = 60
N_MD = 55
N_MD2 = 50
N_SM = 45
N_XS = 35
class FontStyle(Enum):
REG, ITALIC, BOLD, BOLD_ITALIC = 0, 1, 2, 3
class Font:
"""Fonts are families per https://cm-unicode.sourceforge.io/font_table.html"""
Family = tuple[str, str, str, str]
CMUTypewriter: Family = ('cmuntt.ttf', 'cmunit.ttf', 'cmuntb.ttf', 'cmuntx.ttf')
# = CMUTypewriter-Regular, CMUTypewriter-Italic, CMUTypewriter-Bold, CMUTypewriter-BoldItalic
CMUSansSerif: Family = ('cmunss.ttf', 'cmunsi.ttf', 'cmunsx.ttf', 'cmunso.ttf')
# = CMUSansSerif, CMUSansSerif-Oblique, CMUSansSerif-Bold, CMUSansSerif-BoldOblique
CMUConcrete: Family = ('cmunorm.ttf', 'cmunoti.ttf', 'cmunobx.ttf', 'cmunobi.ttf')
# = CMUConcrete-Roman, CMUConcrete-Italic, CMUConcrete-Bold, CMUConcrete-BoldItalic
CMUBright: Family = ('cmunbsr.ttf', 'cmunbso.ttf', 'cmunbsr.ttf', 'cmunbso.ttf')
# = CMUBright-SemiBold, CMUBright-SemiBoldOblique, CMUBright-SemiBold, CMUBright-SemiBoldOblique
# 'cmunbmr.ttf', 'cmunbmo.ttf', # CMUBright-Roman, CMUBright-Oblique
@classmethod
@cache
def get_font(cls, font_family: Family, fs: int, font_style: int):
font_name = font_family[font_style]
return ImageFont.truetype(font_name, fs)
@classmethod
def font_for(cls, font_family: Family, font_size, font_style=FontStyle.REG, h_ratio: float = None):
fs: int = font_size.value if isinstance(font_size, FontSize) else font_size
if h_ratio and h_ratio != 1:
fs = round(fs * h_ratio)
return cls.get_font(font_family, fs, font_style.value)
@dataclass(frozen=True)
class Style:
fg: Color = Color.BLACK
"""foreground color black"""
bg: Color = Color.WHITE
"""background color white"""
decreasing_color: Color = Color.RED
"""color for a decreasing value scale"""
decimal_color: Color = Color.BLACK
"""color for sub-decimal points"""
bg_colors: dict[str, Color] = field(default_factory=dict)
"""background color overrides for particular scale keys"""
font_family: Font.Family = Font.CMUTypewriter
overrides: dict[str, dict[str, object]] = field(default_factory=dict)
right_sym: bool = True
"""Whether to draw the right legend, usually formula, omitted for pocket slide rules."""
@classmethod
def from_dict(cls, style_def: dict):
if 'font_family' in style_def:
style_def['font_family'] = getattr(Font, style_def['font_family'])
for key in ('fg', 'bg', 'decreasing_color', 'decimal_color'):
if key in style_def:
style_def[key] = Color.from_str(style_def[key])
if 'overrides' in style_def:
for k, v in style_def['overrides'].items():
for attr, value in v.items():
if attr == 'color':
style_def['overrides'][k][attr] = Color.from_str(value)
if 'bg_colors' in style_def:
for k, v in style_def['bg_colors'].items():
style_def['bg_colors'][k] = Color.from_str(v)
return cls(**style_def)
def fg_col(self, element: str, is_increasing=True):
return self.override_for(element, 'color',
self.fg if is_increasing else self.decreasing_color)
def bg_col(self, element: str):
return self.bg_colors.get(element)
def overrides_for(self, element: str) -> dict:
return self.overrides.get(element)
def override_for(self, element: str, key: str, default):
sc_overrides = self.overrides_for(element)
return sc_overrides.get(key, default) if sc_overrides else default
def numeral_decimal_color(self):
return self.decimal_color
def font_for(self, font_size, h_ratio: float = None, italic: bool = False):
return Font.font_for(self.font_family, font_size, FontStyle.ITALIC if italic else FontStyle.REG, h_ratio)
@staticmethod
def sym_dims(symbol: str, font: ImageFont) -> WH:
"""Gets the size dimensions (width, height) of the input text"""
(x1, y1, x2, y2) = font.getbbox(symbol)
return x2 - x1, y2 - y1 + 20
@classmethod
def sym_w(cls, symbol: str, font: ImageFont) -> int:
(x1, _, x2, _) = font.getbbox(symbol)
return x2 - x1
class HMod(Enum):
"""Tick height size factors (h_mod in pat)"""
DOT, XS, SM, MED, LG, LG2, XL = 0.25, 0.5, 0.85, 1, 1.15, 1.2, 1.3
class Side(Enum):
"""Side of the slide (front or rear)"""
FRONT, REAR = 'front', 'rear'
class RulePart(Enum):
STATOR_TOP, SLIDE, STATOR_BOTTOM = 'stator_top', 'slide', 'stator_bottom'
class BraceShape(Enum):
L, C = 'L', 'C'
@dataclass(frozen=True)
class Geometry:
"""Slide Rule Geometric Parameters"""
oX: int = 100 # x margins
oY: int = 100 # y margins
side_w: int = 8000 # 30cm = 11.8in
side_h: int = 1600 # 6cm = 2.36in
slide_h: int = 640 # 2.4cm = 0.945in
SH: int = 160 # 6mm
"""scale height"""
SL: int = 5600 # 21cm = 8.27in
"""scale length"""
SM: int = 0
"""Scale margin"""
# Ticks, Labels, are referenced from li as to be consistent
STH: int = 70 # 2.62mm
"""standard tick height"""
STT: int = 3 # 0.1125mm
"""standard tick thickness"""
PixelsPerCM = 1600 / 6
PixelsPerIN = PixelsPerCM * 2.54
top_margin: int = 110
@staticmethod
def _overrides_factory(): return {Side.FRONT: {}, Side.REAR: {}}
scale_h_overrides: dict[Side, dict[str, int]] = field(default_factory=_overrides_factory)
margin_overrides: dict[Side, dict[str, int]] = field(default_factory=_overrides_factory)
overhang_overrides: dict[Side, dict[str, int]] = field(default_factory=_overrides_factory)
brace_shape: BraceShape = BraceShape.L
brace_offset: int = 30 # offset of metal from boundary
brace_hole_r: int = 34 # screw hole diameter (2.5mm)
NO_MARGINS = (0, 0)
DEFAULT_SCALE_WH = (SL, SH)
DEFAULT_TICK_WH = (STT, STH)
@classmethod
def flip_overrides(cls, overrides: dict[Side, dict[int: [str]]] = None):
result = cls._overrides_factory()
if overrides:
for side in Side:
side_overrides = overrides.get(side, {})
for h, sc_keys in side_overrides.items():
for sc_key in sc_keys:
result[side][sc_key] = int(h)
return result
@classmethod
def dim_to_pixels(cls, dim) -> int:
if matches := re.match(r'^\s*([\d.]+)\s*(\w*)\s*$', dim) if isinstance(dim, str) else None:
num, units = matches.group(1), matches.group(2)
result = float(num) if '.' in num else int(num)
if units == 'cm':
result *= cls.PixelsPerCM
elif units == 'mm':
result *= cls.PixelsPerCM / 10
elif units == 'in':
result *= cls.PixelsPerIN
elif units == 'pt':
result *= cls.PixelsPerIN / 72
return int(result)
return dim
@classmethod
def make(cls, side_wh: WH, margins_xy: WH, scale_wh: WH = DEFAULT_SCALE_WH, tick_wh: WH = DEFAULT_TICK_WH,
slide_h: int = slide_h, top_margin: int = top_margin,
scale_h_overrides: dict[Side, dict[int: [str]]] = None,
margin_overrides: dict[Side, dict[int: [str]]] = None,
overhang_overrides: dict[Side, dict[int: [str]]] = None,
brace_shape: str = brace_shape.value, brace_offset: int = brace_offset, brace_hole_r: int = brace_hole_r):
return cls(oX=margins_xy[0], oY=margins_xy[1], side_w=side_wh[0], side_h=side_wh[1], slide_h=slide_h,
top_margin=top_margin, SH=scale_wh[1], SL=scale_wh[0], STH=tick_wh[1], STT=tick_wh[0],
scale_h_overrides=cls.flip_overrides(scale_h_overrides),
margin_overrides=cls.flip_overrides(margin_overrides),
overhang_overrides=cls.flip_overrides(overhang_overrides),
brace_shape=next((x for x in BraceShape if x.value == brace_shape), brace_shape),
brace_offset=brace_offset, brace_hole_r=brace_hole_r)
@classmethod
def from_dict(cls, geometry_def: dict):
for key in ('scale_h_overrides', 'margin_overrides', 'overhang_overrides'):
if key in geometry_def:
result = {}
for side in Side:
result[side] = geometry_def[key].get(side.value, {})
geometry_def[key] = result
for k, v in geometry_def.items():
if isinstance(v, list):
geometry_def[k] = [cls.dim_to_pixels(x) for x in v]
elif isinstance(v, str):
geometry_def[k] = cls.dim_to_pixels(v)
if 'scale_wh' not in geometry_def:
geometry_def['scale_wh'] = cls.DEFAULT_SCALE_WH
if 'tick_wh' not in geometry_def:
geometry_def['tick_wh'] = cls.DEFAULT_TICK_WH
return cls.make(**geometry_def)
@property
def total_w(self):
return self.side_w + 2 * self.oX
@property
def midpoint_x(self):
return int(self.total_w // 2)
@property
def print_h(self):
return self.side_h * 2 + 3 * self.oY
@property
def stator_h(self):
return int((self.side_h - self.slide_h) // 2)
@property
def brace_w(self):
"""Brace width default, to ensure a square anchor piece."""
return 0 if self.brace_shape is None else self.stator_h
@property
def li(self):
"""left index offset from left edge"""
return (self.total_w - self.SL) // 2
@property
def min_tick_offset(self):
"""minimum tick horizontal offset"""
return self.STT * 3 # separate each tick by at least the space of its width
def tick_h(self, h_mod: HMod, h_ratio=None) -> int:
result = self.STH * h_mod.value
if h_ratio and h_ratio != 1:
result *= h_ratio
return round(result)
def part_h(self, part: RulePart):
return self.slide_h if part == RulePart.SLIDE else self.stator_h
def edge_h(self, part: RulePart, top):
if part == RulePart.STATOR_TOP and top:
return 0
if part == RulePart.SLIDE and top or part == RulePart.STATOR_TOP:
return self.stator_h
if part == RulePart.STATOR_BOTTOM and top:
return self.stator_h + self.slide_h
return self.side_h
def scale_h(self, sc, side: Side = None, default: int = None) -> int:
key = sc.key
if side:
return self.scale_h_overrides[side].get(key, default or self.SH)
return self.scale_h_overrides[Side.FRONT].get(
key, self.scale_h_overrides[Side.REAR].get(key, default or self.SH))
def scale_margin(self, sc, side: Side = None, default=SM) -> int:
key = sc.key
if side:
return self.margin_overrides[side].get(key, default or self.SM)
return self.margin_overrides[Side.FRONT].get(
key, self.margin_overrides[Side.REAR].get(key, default or self.SM))
def scale_h_ratio(self, sc, side=None):
if (scale_h := self.scale_h(sc, side=side)) != (default_scale_h := self.DEFAULT_SCALE_WH[1]):
return scale_h / default_scale_h
return None
@staticmethod
def label_offset_frac(sc) -> float:
"""fraction of total width to overhang each side to label"""
return (0.05 if sc.can_overhang() or sc.can_spiral() else 0) + 0.02
def scale_w(self, sc, with_labels=False) -> int:
if isinstance(sc, Scale):
return int(self.SL * (sc.overhang_ratio() + (self.label_offset_frac(sc) if with_labels else 0)))
elif isinstance(sc, Ruler):
return int(sc.scale_w(self))
def brace_outline(self, y_off):
"""Creates and returns the left front brace piece outline in vectors as: (x1,x2,y1,y2)"""
b = self.brace_offset # offset of metal from boundary
x_left = b + self.oX
x_mid = x_left + self.brace_w // 2
x_right = self.brace_w - b + self.oX
y_top = b + y_off
y_slide_top = y_off + self.stator_h - b
y_slide_bottom = y_top + self.side_h - self.stator_h
y_bottom = self.side_h - b + y_off
if self.brace_shape == BraceShape.L:
# x_left x_mid x_right
# 0 ↓ ↓ ↓
# ↓ 1↓ ← 0
# ┌────┐ ← y_top
# │ │
# │ │
# 4→ │ │ ←6
# │ │
# │ │
# 2↓ │ │
# ┌────┘ │ ← y_slide_bottom
# 5→ │ │
# │ │
# └─────────┘ ← y_bottom
# 3↑ ← side_h
return [(x_mid, x_right, y_top, y_top), # 1
(x_left, x_mid, y_slide_bottom, y_slide_bottom), # 2
(x_left, x_right, y_bottom, y_bottom), # 3
(x_mid, x_mid, y_top, y_slide_bottom), # 4
(x_left, x_left, y_slide_bottom, y_bottom), # 5
(x_right, x_right, y_top, y_bottom)] # 6
elif self.brace_shape == BraceShape.C:
return [(x_right, x_right, y_top, y_bottom), # inside
(x_left, x_right, y_top, y_top), # top
(x_left, x_right, y_bottom, y_bottom), # bottom
(x_left, x_left, y_top, y_slide_top), # outside top
(x_left, x_left, y_slide_bottom, y_bottom), # outside bottom
# TODO extend Renderer to handle arcs + replace with arc:
(x_left, x_mid, y_slide_top, y_slide_top), # arc top
(x_mid, x_mid, y_slide_top, y_slide_bottom), # arc inside
(x_left, x_mid, y_slide_bottom, y_slide_bottom)] # arc bottom
return None
def mirror_vectors_h(self, vectors: list[tuple[int, int, int, int]]):
"""(x1, x2, y1, y2) mirrored across the centerline"""
total_w = self.total_w
return [(total_w - x2, total_w - x1, y1, y2) for (x1, x2, y1, y2) in vectors]
@staticmethod
def mirror_vectors_v(vectors: list[tuple[int, int, int, int]], mid_y):
"""(x1, x2, y1, y2) mirrored across a horizontal line"""
return [(x1, x2, mid_y - y2, mid_y - y1) for (x1, x2, y1, y2) in vectors]
class Align(Enum):
"""Scale Alignment (ticks and labels against upper or lower bounds)"""
UPPER, LOWER = 'upper', 'lower'
TEN = 10
HUNDRED = TEN * TEN
@dataclass(frozen=True)
class GaugeMark:
sym: str
value: float = None
comment: str = None
class Marks:
e = GaugeMark('e', math.e, comment='base of natural logarithms')
inv_e = GaugeMark('1/e', 1 / math.e, comment='base of natural logarithms')
tau = GaugeMark('τ', TAU, comment='ratio of circle circumference to radius')
pi = GaugeMark('π', PI, comment='ratio of circle circumference to diameter')
pi_half = GaugeMark('π/2', PI_HALF, comment='ratio of quarter arc length to radius')
pi_quarter = GaugeMark('π/4', PI / 4, comment='ratio of circle area to diameter²')
inv_pi = GaugeMark('M', 1 / PI, comment='reciprocal of π')
c = GaugeMark('c', math.sqrt(4 / PI), comment='ratio diameter to √area (square to base scale) √(4/π)')
c1 = GaugeMark('c′', math.sqrt(4 * TEN / PI), comment='ratio diameter to √area (square to base scale) √(40/π)')
deg_per_rad = GaugeMark('r', DEG_FULL / TAU / TEN, comment='degrees per radian')
rad_per_deg = GaugeMark('ρ', TAU / DEG_FULL, comment='radians per degree')
rad_per_min = GaugeMark('ρ′', TAU / DEG_FULL * 60, comment='radians per minute')
rad_per_sec = GaugeMark('ρ″', TAU / DEG_FULL * 60 * 60, comment='radians per second')
ln_over_log10 = GaugeMark('L', 1 / math.log10(math.e), comment='ratio of natural log to log base 10')
sqrt_ten = GaugeMark('√10', math.sqrt(TEN), comment='square root of 10')
cube_root_ten = GaugeMark('c', math.pow(TEN, 1 / 3), comment='cube root of 10')
inf = GaugeMark('∞', math.inf, comment='infinity')
class ConversionMarks:
cm_per_in = GaugeMark('in', 2.54, comment='cm per in')
sq_cm_per_in = GaugeMark('sq in', cm_per_in.value**2, comment='cm² per in²')
cu_cm_per_in = GaugeMark('cu in', cm_per_in.value**3, comment='cm³ per in³')
ft_per_m = GaugeMark('ft', HUNDRED/(cm_per_in.value*12), comment='ft per m')
yd_per_m = GaugeMark('yd', 3/ft_per_m.value, comment='yd per m')
km_per_mi = GaugeMark('mi', cm_per_in.value*12*5280/1000, comment='mi per km')
qt_per_l = GaugeMark('qt', 0.9463525, comment='US qt per l')
gal_per_l = GaugeMark('gal', qt_per_l.value*4, 'US gal per l')
lb_per_kg = GaugeMark('lb', 2.2046, comment='lbs per kg')
hp_per_kw = GaugeMark('N', 1.341022, comment='mechanical horsepower per kW')
g = GaugeMark('g', 9.80665, comment='gravity acceleration on Earth in m/s²')
# ----------------------2. Fundamental Functions----------------------------
TickFactors = tuple[int, int, int]
TF_BY_MIN: dict[int, TickFactors] = { # Best tick subdivision pattern for a given minimum overall division
1000: (TEN, TEN, TEN),
500: (TEN, TEN, 5),
250: (TEN, 5, 5),
100: (TEN, 2, 5),
50: (2, 5, 5),
25: (1, 5, 5),
20: (2, 5, 2),
10: (2, 5, 1),
5: (1, 5, 1),
2: (1, 2, 1),
1: (1, 1, 1)
}
TF_MIN = sorted(TF_BY_MIN.keys(), reverse=True)
TF_BIN: TickFactors = (4, 4, 4)
def t_s(s1: int, f: TickFactors):
"""tick iterative subdivision"""
s2 = s1 if f[0] == 1 else s1 // f[0]
s3 = s2 if f[1] == 1 else s2 // f[1]
s4 = s3 if f[2] == 1 else s3 // f[2]
return s1, s2, s3, s4
DEBUG = False
@dataclass(frozen=True)
class Renderer:
r: ImageDraw.ImageDraw = None
geometry: Geometry = None
style: Style = None
no_fonts = (None, None, None)
@classmethod
def make(cls, i: Image.Image, g: Geometry, s: Style):
return cls(ImageDraw.Draw(i), g, s)
def draw_box(self, x0, y0, dx, dy, col, width=1):
self.r.rectangle((x0, y0, x0 + dx, y0 + dy), outline=Color.to_pil(col), width=width)
def fill_rect(self, x0, y0, dx, dy, col):
self.r.rectangle((x0, y0, x0 + dx, y0 + dy), fill=col)
def draw_circle(self, xc, yc, r, col):
self.r.ellipse((xc - r, yc - r, xc + r, yc + r), outline=Color.to_pil(col))
def draw_tick(self, y_off: int, x: int, h: int, col, scale_h: int, al: Align):
"""Places an individual tick, aligned to top or bottom of scale"""
x0 = x + self.geometry.li - 2
y0 = y_off
if al == Align.LOWER:
y0 += scale_h - h - 1
self.fill_rect(x0, y0, self.geometry.STT, h + 1, col)
def pat(self, y_off: int, sc, al: Align, i_start, i_end, i_sf, steps_i, steps_th, steps_font, digit1):
"""
Place ticks in a graduated pattern. All options are given, not inferred.
4 levels of tick steps and sizes needed, and three optional fonts for numerals.
:param y_off: y pos
:param Scale sc:
:param Align al: alignment
:param int i_start: index across the scale to start at
:param int i_end: index across the scale to end at
:param int i_sf: scale factor - how much to divide the inputs by before scaling (to generate fine decimals)
:param tuple[int, int, int, int] steps_i: patterning steps, large to small
:param tuple[int, int, int, int] steps_th: tick sizes, large to small, per step
:param tuple[FreeTypeFont, FreeTypeFont, FreeTypeFont] steps_font: optional font sizes, for numerals above ticks
:param tuple[bool, bool, bool] digit1: whether to show the numerals as the most relevant digit only
"""
step1, step2, step3, step4 = steps_i
th1, th2, th3, th4 = steps_th
f1, f2, f3 = steps_font
d1, d2, d3 = digit1
scale_w, scale_h = self.geometry.SL, self.geometry.scale_h(sc)
col = Color.to_pil(self.style.fg_col(sc.key, is_increasing=sc.is_increasing))
tenth_col = Color.to_pil(self.style.decimal_color if sc.is_increasing else col)
for i in range(i_start, i_end, step4):
n = i / i_sf
x = sc.scale_to(n, scale_w)
if i % step1 == 0:
tick_h = th1
if f1:
self.draw_numeral(Sym.sig_digit_of(n) if d1 else n, y_off, col, scale_h, x, tick_h, f1, al)
elif i % step2 == 0:
tick_h = th2
if f2:
self.draw_numeral(Sym.sig_digit_of(n) if d2 else n, y_off, col, scale_h, x, tick_h, f2, al)
elif i % step3 == 0:
tick_h = th3
if f3:
self.draw_numeral(Sym.sig_digit_of(n) if d3 else n, y_off, tenth_col, scale_h, x, tick_h, f3, al)
else:
tick_h = th4
self.draw_tick(y_off, x, tick_h, col, scale_h, al)
def pat_auto(self, y_off, sc, al, x_start=None, x_end=None, include_last=False):
"""
Draw a graduated pattern of tick marks across the scale range, by algorithmic selection.
From some tick patterns in order and by generic suitability, pick the most detailed with a sufficient tick gap.
"""
if x_start is None:
x_start = sc.value_at_start()
if x_end is None:
x_end = sc.value_at_end()
if x_start > x_end:
x_start, x_end = x_end, x_start
elif x_start == x_end:
return
s, g = self.style, self.geometry
min_tick_offset = g.min_tick_offset
log_diff = abs(math.log10(abs((x_end - x_start) / max(x_start, x_end))))
num_digits = math.ceil(log_diff) + 3
scale_w = g.SL
sf = 10 ** num_digits # ensure enough precision for int ranges
# Ensure a reasonable visual density of numerals
frac_w = sc.offset_between(x_start, x_end, 1)
step_num = 10 ** max(int(math.log10(x_end - x_start) - 0.5 * frac_w) + num_digits, 0)
sub_div4 = next((TF_BY_MIN[i] for i in TF_MIN if i <= step_num
and sc.min_offset_for_delta(x_start, x_end, step_num / i / sf, scale_w) >= min_tick_offset),
TF_BY_MIN[1])
(_, step2, step3, step4) = t_s(step_num, sub_div4)
# Iteration Setup
i_start = int(x_start * sf)
if (i_offset := i_start % step4) > 0: # Align to first tick on or after start
i_start = i_start - i_offset + step4
# Determine numeral font size
h_ratio = g.scale_h_ratio(sc)
num_font = s.font_for(FontSize.N_LG, h_ratio)
numeral_tick_offset = sc.min_offset_for_delta(x_start, x_end, step_num / sf, scale_w)
if (max_num_chars := numeral_tick_offset // s.sym_w('_', num_font)) < 2:
num_font = s.font_for(FontSize.N_SM, h_ratio)
# If there are sub-digit ticks to draw, and enough space for single-digit numerals:
sub_num = (step4 < step3 < step_num) and max_num_chars > 8
# Tick Heights:
dot_th = g.tick_h(HMod.DOT, h_ratio)
self.pat(y_off, sc, al,
i_start, int(x_end * sf + (1 if include_last else 0)), sf,
(step_num, step2, step3, step4),
(
g.tick_h(HMod.MED, h_ratio),
g.tick_h(HMod.XL if step3 == step_num // 2 and step4 < step3 else HMod.XS, h_ratio),
g.tick_h(HMod.XS, h_ratio) if step4 < step3 else dot_th,
dot_th),
(num_font,
s.font_for(FontSize.N_SM, h_ratio) if (sub_num and step2 == step_num // 10
or step2 == step_num // 2) else None,
s.font_for(FontSize.N_XS, h_ratio) if sub_num and step3 == step_num // 10 else None),
(max_num_chars < 3, max_num_chars < 16, max_num_chars < 128))
def draw_symbol(self, symbol: str, color, x_left: float, y_top: float, font: ImageFont, draw_radicals=True):
color = Color.to_pil(color)
symbol = symbol.translate(Sym.UNICODE_SUBS)
if DEBUG:
w, h = self.style.sym_dims(symbol, font)
self.draw_box(x_left, y_top, w, h, Color.DEBUG)
self.r.text((x_left, y_top), symbol, font=font, fill=color)
radicals = draw_radicals and re.search(r'[√∛∜]', symbol)
if radicals:
w, h = self.style.sym_dims(symbol, font)
n_ch = radicals.start() + 1
(w_ch, h_rad) = self.style.sym_dims('√', font)
(_, h_num) = self.style.sym_dims('1', font)
line_w = h_rad // 14
y_bar = y_top + max(10, round(h - h_num - line_w * 2))
self.r.line((x_left + w_ch * n_ch - w_ch // 10, y_bar, x_left + w, y_bar), width=line_w, fill=color)
def draw_sym_al(self, symbol: str, y_off: int, color, al_h: int, x: int, y: int, font: ImageFont, al: Align):
"""
:param y_off: y pos
:param color: color that PIL recognizes
:param al_h: height (of scale or other bounding band) for alignment
:param x: offset of centerline from left index (li)
:param y: offset of base from baseline (LOWER) or top from upper line (UPPER)
"""
if not symbol:
return
(base_sym, exponent, subscript) = Sym.parts_of(symbol)
w, h = Style.sym_dims(base_sym, font)
y_top = y_off
if al == Align.UPPER:
y_top += y
elif al == Align.LOWER:
y_top += al_h - 1 - y - h * 1.2
x_left = x + self.geometry.li - w / 2 + self.geometry.STT / 2
self.draw_symbol(base_sym, color, round(x_left), y_top, font)
if exponent or subscript:
sub_font_size = FontSize.N_LG if font.size == FontSize.SC_LBL else font.size
sub_font = self.style.font_for(sub_font_size, h_ratio=0.75)
x_right = round(x_left + w)
if exponent:
self.draw_symbol_sup(exponent, color, h, x_right, y_top, sub_font)
if subscript:
self.draw_symbol_sub(subscript, color, h, x_right, y_top, sub_font)
def draw_numeral(self, num, y_off: int, color, scale_h: int, x: int, y: int, font, al: Align):
"""Draw a numeric symbol for a scale"""
self.draw_sym_al(Sym.num_sym(num), y_off, color, scale_h, x, y, font, al)
def draw_numeral_sc(self, sc, num, y_off: int, color, scale_h: int, y: int, font, al: Align):
self.draw_numeral(num, y_off, color, scale_h, sc.pos_of(num, self.geometry), y, font, al)
def draw_symbol_sup(self, sup_sym, color, h_base, x_left, y_base, font):
if len(sup_sym) == 1 and unicodedata.category(sup_sym) == 'No':
sup_sym = str(unicodedata.digit(sup_sym))
self.draw_symbol(sup_sym, color, x_left, y_base - (0 if sup_sym in Sym.PRIMES else int(h_base * 0.4)), font)
def draw_symbol_sub(self, sub_sym, color, h_base, x_left, y_base, font):
self.draw_symbol(sub_sym, color, x_left, y_base + h_base / 2, font)
def draw_mark(self, mark: GaugeMark, y_off: int, sc, font, al, col=None, shift_adj=0, side=None):
s, g = self.style, self.geometry
if col is None:
col = s.fg_col(sc.key, is_increasing=sc.is_increasing)
x = sc.scale_to(mark.value, g.SL, shift_adj=shift_adj)
scale_h = g.scale_h(sc, side=side)
tick_h = g.tick_h(HMod.XL if al == Align.LOWER else HMod.MED, h_ratio=g.scale_h_ratio(sc, side=side))
self.draw_tick(y_off, x, tick_h, col, scale_h, al)
self.draw_sym_al(mark.sym, y_off, col, scale_h, x, tick_h, font, al)
# ----------------------4. Line Drawing Functions----------------------------
def draw_borders(self, y0: int, side: Side, color=Color.BLACK):
"""Place initial borders around scales"""
# Main Frame
g = self.geometry
total_w = g.total_w
o_x = g.oX
color = Color.to_pil(color)
for i, part in enumerate(RulePart):
self.fill_rect(o_x, y0 + g.edge_h(part, True) - (i + 1) // 2, g.side_w, 1, color)
self.fill_rect(o_x, y0 + g.side_h - 2, g.side_w, 1, color)
for vertical_x in [o_x, total_w - o_x]:
self.fill_rect(vertical_x, y0, 1, g.side_h, color)
# Top Stator Cut-outs
if g.brace_shape == BraceShape.L:
stator_h = g.stator_h
part = RulePart.STATOR_BOTTOM if side == Side.REAR else RulePart.STATOR_TOP
stator_cutout_w = stator_h // 2
for horizontal_x in [stator_cutout_w + o_x, (total_w - stator_cutout_w) - o_x]:
self.fill_rect(horizontal_x, y0 + g.edge_h(part, True), 1, stator_h, color)
def draw_brace_pieces(self, y_off: int, side: Side):
"""Draw the metal bracket locations for viewing"""
# Initial Boundary verticals
g = self.geometry
verticals = [g.brace_w + g.oX, g.total_w - g.brace_w - g.oX]
for i, start in enumerate(verticals):
self.fill_rect(start - 1, y_off, 2, i, Color.CUTOFF.value)
brace_fl = g.brace_outline(y_off)
if brace_fl is None:
return
# Symmetrically create the right piece
coords = brace_fl + g.mirror_vectors_h(brace_fl)
# If backside, first apply a vertical reflection
if side == Side.REAR:
mid_y = 2 * y_off + g.side_h
coords = g.mirror_vectors_v(coords, mid_y)
for (x1, x2, y1, y2) in coords:
self.r.rectangle((x1 - 1, y1 - 1, x2 + 1, y2 + 1), fill=Color.CUTOFF2.value)
# ---------------------- 5. Stickers -----------------------------
def draw_corners(self, x0: float, y0: float, dx: float, dy: float, col, arm_w=20):
"""Draw cross arms at each corner of the rectangle defined."""
for (cx, cy) in ((x0, y0), (x0, y0 + dy), (x0 + dx, y0), (x0 + dx, y0 + dy)):
self.r.line((cx - arm_w, cy, cx + arm_w, cy), col) # horizontal cross arm
self.r.line((cx, cy - arm_w, cx, cy + arm_w), col) # vertical cross arm
class Sym:
RE_EXPON_CARET = re.compile(r'^(.+)\^([-0-9.A-Za-z]+)$')
RE_SUB_UNDERSCORE = re.compile(r'^(.+)_(\w+)$')
RE_EXPON_UNICODE = re.compile(r'^([^⁻⁰¹²³⁴⁵⁶⁷⁸⁹]+)([⁻⁰¹²³⁴⁵⁶⁷⁸⁹]+)$')
RE_SUB_UNICODE = re.compile(r'^([^₀₁₂₃]+)([₀₁₂₃]+)$')
@staticmethod
def num_char_convert(char):
if char == '⁻':
return '-'
return unicodedata.digit(char)
@classmethod
def unicode_sub_convert(cls, symbol: str):
return ''.join(map(str, map(cls.num_char_convert, symbol)))
@classmethod
def num_sym(cls, num):
if isinstance(num, int):
return str(num)
elif num.is_integer():
if num == 0:
return '0'
else:
expon = math.log10(num)
if expon.is_integer() and abs(expon) > 2:
return f'10^{int(expon)}'
else:
return str(int(num))
else:
num_sym = str(num)
if num_sym.startswith('0.'):
expon = math.log10(num)
if expon.is_integer() and expon < -2:
return f'10^{int(expon)}'
else:
return num_sym[1:] # Omit leading zero digit
else:
return num_sym
@classmethod
def split_by(cls, symbol: str, text_re: re.Pattern, unicode_re: re.Pattern):
base_sym = symbol
subpart_sym = None
if matches := re.match(text_re, symbol):
base_sym = matches.group(1)
subpart_sym = matches.group(2)
elif matches := re.match(unicode_re, symbol):
base_sym = matches.group(1)
subpart_sym = cls.unicode_sub_convert(matches.group(2))
return base_sym, subpart_sym
PRIMES = "'ʹʺ′″‴"
UNICODE_SUBS = str.maketrans({ # Workaround for incomplete Unicode character support; needs font metadata.
'′': "ʹ",
'∡': 'a',
'½': '1/2',
'⅓': '1/3',
'∛': '√',
'∞': 'inf',
})
@classmethod
def split_expon(cls, symbol: str):
if len(symbol) > 1 and symbol[-1] in cls.PRIMES:
return symbol[:-1], symbol[-1:]
return cls.split_by(symbol, cls.RE_EXPON_CARET, cls.RE_EXPON_UNICODE)
@classmethod
def split_subscript(cls, symbol: str):
return cls.split_by(symbol, cls.RE_SUB_UNDERSCORE, cls.RE_SUB_UNICODE)
@classmethod
def parts_of(cls, symbol: str):
(base_sym, subscript) = cls.split_subscript(symbol)
(base_sym, expon) = cls.split_expon(base_sym)
return base_sym, expon, subscript
@staticmethod
def first_digit_of(x) -> int:
return int(str(x)[0])
@staticmethod
def last_digit_of(x) -> int:
if int(x) == x:
x = int(x)
return int(str(x)[-1])
@classmethod
def sig_digit_of(cls, num: float):
"""When only one digit will fit on a major scale's numerals, pick the most significant."""
if not (num > 0 and math.log10(num).is_integer()):
if num % 10 == 0:
return cls.first_digit_of(num)
else:
return cls.last_digit_of(num)
else:
return cls.first_digit_of(num)
class BleedDir(Enum):
UP, DOWN = 'up', 'down'
def extend(image: Image, total_w: int, y: int, direction: BleedDir, amplitude: int):
"""
Used to create bleed for sticker cutouts
y: pixel row to duplicate
amplitude: number of pixels to extend
"""
assert y < image.height
for x in range(0, int(total_w)):
bleed_color = image.getpixel((x, y))
for yi in range(y - amplitude, y) if direction == BleedDir.UP else range(y, y + amplitude):
image.putpixel((x, yi), bleed_color)
# ----------------------3. Scale Generating Function----------------------------
LN_TEN = math.log(TEN)
LOG10_E = math.log10(math.e)
LOG_0 = -math.inf
E0 = 1e-20
E1N = 1 - 1e-16
E1P = 1 + 1e-15
def unit(x): return x
def gen_base(x: float): return math.log10(x)
def pos_base(p: float): return math.pow(TEN, p)
def scale_sin_tan(x: float):
return gen_base(HUNDRED * (math.sin(x) + math.tan(x)) / 2)
def angle_opp(x: float):
"""The opposite angle in degrees across a right triangle."""
return DEG_RT - x
@dataclass(frozen=True)
class ScaleFN:
"""Encapsulates a generating function and its inverse.
The generating function takes X and returns the fractional position in the unit output space it should locate.
The inverse function takes a fraction of a unit output space, returning the value to indicate at that position.
These should be monotonic over their intended range.
"""
fn: Callable[[float], float]
"""Position of x: Returns the fractional position in the unit output space to put the input value."""
inverse: Callable[[float], float]
"""Value at p: Returns the value to indicate at the fractional position in the output space."""
is_increasing: bool = True
min_x: float = -math.inf
max_x: float = math.inf
def __call__(self, x: float):
return self.fn(x)
def clamp_input(self, x: float):
return max(min(x, self.max_x), self.min_x)
def inverted(self):
return ScaleFN(self.inverse, self.fn, not self.is_increasing)
def position_of(self, value):
return self.fn(value)
def value_at(self, position):
return self.inverse(position)
def value_at_start(self):
return self.value_at(0)
def value_at_end(self):
return self.value_at(1)
class ScaleFNs:
Unit = ScaleFN(unit, unit)
F_to_C = ScaleFN(lambda f: (f - 32) * 5 / 9, lambda c: (c * 9 / 5) + 32)
neper_to_db = ScaleFN(lambda x_db: x_db / (20 / math.log(TEN)), lambda x_n: x_n * 20 / math.log(TEN))
Base = ScaleFN(gen_base, pos_base, min_x=E0)
Square = ScaleFN(lambda x: gen_base(x) / 2, lambda p: pos_base(p * 2))
Cube = ScaleFN(lambda x: gen_base(x) / 3, lambda p: pos_base(p * 3))
Inverse = ScaleFN(lambda x: 1 - gen_base(x), lambda p: pos_base(1 - p), is_increasing=False, min_x=E0)
InverseSquare = ScaleFN(lambda x: 1 - gen_base(x) / 2, lambda p: pos_base(1 - p * 2), is_increasing=False, min_x=E0)
InverseCube = ScaleFN(lambda x: 1 - gen_base(x) / 3, lambda p: pos_base(1 - p * 3), is_increasing=False, min_x=E0)
SquareRoot = ScaleFN(lambda x: gen_base(x) * 2, lambda p: pos_base(p / 2), min_x=E0)
CubeRoot = ScaleFN(lambda x: gen_base(x) * 3, lambda p: pos_base(p / 3), min_x=E0)
Sin = ScaleFN(lambda x: gen_base(TEN * math.sin(math.radians(x))), lambda p: math.asin(pos_base(p)))
CoSin = ScaleFN(lambda x: gen_base(TEN * math.cos(math.radians(x))), lambda p: math.acos(pos_base(p)),
is_increasing=False)
Tan = ScaleFN(lambda x: gen_base(TEN * math.tan(math.radians(x))), lambda p: math.atan(pos_base(p)))
SinTan = ScaleFN(lambda x: scale_sin_tan(math.radians(x)), lambda p: math.atan(pos_base(p)))
SinTanRadians = ScaleFN(scale_sin_tan, lambda p: math.atan(pos_base(math.degrees(p))), min_x=1e-5)
CoTan = ScaleFN(lambda x: gen_base(TEN * math.tan(math.radians(angle_opp(x)))),
lambda p: math.atan(pos_base(angle_opp(p))), is_increasing=False)
SinH = ScaleFN(lambda x: gen_base(math.sinh(x)), lambda p: math.asinh(pos_base(p)), min_x=E0)
CosH = ScaleFN(lambda x: gen_base(math.cosh(x)), lambda p: math.acosh(pos_base(p)), min_x=E0)
TanH = ScaleFN(lambda x: gen_base(math.tanh(x)), lambda p: math.atanh(pos_base(p)), min_x=E0)
Pythagorean = ScaleFN(lambda x: gen_base(math.sqrt(1 - (x ** 2))) + 1,
lambda p: math.sqrt(1 - (pos_base(p) / TEN) ** 2),
is_increasing=False, min_x=-E1N, max_x=E1N)
LogLog = ScaleFN(lambda x: gen_base(math.log(x)), lambda p: math.exp(pos_base(p)), min_x=E1P)
LogLogNeg = ScaleFN(lambda x: gen_base(-math.log(x)), lambda p: math.exp(pos_base(-p)),
is_increasing=False, min_x=E0, max_x=E1N)
Hyperbolic = ScaleFN(lambda x: gen_base(math.sqrt((x ** 2) - 1)), lambda p: math.hypot(1, pos_base(p)), min_x=E1P)
@dataclass
class Scale:
"""Labeling and basic layout for a given invertible Scaler function."""
left_sym: str
"""left scale symbol"""
right_sym: str
"""right scale symbol"""
scaler: ScaleFN
gen_fn: Callable[[float], float] = None
"""generating function (producing a fraction of output width)"""
pos_fn: Callable[[float], float] = None