stringcalc 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
stringcalc/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ Instrument string calculations
3
+ """
4
+
5
+ try:
6
+ from ._version import __version__
7
+ except ImportError:
8
+ __version__ = "0.0.0"
stringcalc/_version.py ADDED
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.1.0'
32
+ __version_tuple__ = version_tuple = (0, 1, 0)
33
+
34
+ __commit_id__ = commit_id = None
stringcalc/cli.py ADDED
@@ -0,0 +1,503 @@
1
+ """
2
+ CLI
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import os
9
+ import re
10
+ from pathlib import Path
11
+
12
+ try:
13
+ import typer
14
+ from rich.console import Console, RenderableType
15
+ from rich.style import Style
16
+ except ImportError as e:
17
+ print("The stringcalc CLI requires typer and rich (included with the 'cli' extra).")
18
+ print(f"Error was: {e!r}")
19
+ raise SystemExit(1)
20
+
21
+ _RICH_EXPORT: str = os.environ.get("STRINGCALC_RICH_EXPORT", "0")
22
+
23
+ HERE = Path(__file__).parent
24
+ _TRAN_SUPE_DIGIT = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
25
+
26
+ console = Console(record=_RICH_EXPORT != "0")
27
+
28
+ app = typer.Typer(add_completion=False, name="stringcalc")
29
+
30
+
31
+ def _to_fancy_sci(s: str) -> str:
32
+ a, b0 = s.split("e")
33
+ b = str(int(b0)).replace("-", "⁻").translate(_TRAN_SUPE_DIGIT)
34
+
35
+ return f"{a}×10{b}"
36
+
37
+
38
+ def _maybe_export_output(cmd):
39
+ """Export CLI command's Rich output to SVG,
40
+ dependent on the value of the ``STRINGCALC_RICH_EXPORT`` environment variable.
41
+
42
+ - ``0`` or unset: Do not export.
43
+ - ``1``: Export to ``stringcalc-rich-export.svg``.
44
+ - Any other value: Export to ``<value>.svg``
45
+ (or just ``value`` if it already ends in ``.svg``).
46
+ """
47
+
48
+ @functools.wraps(cmd)
49
+ def inner(*args, **kwargs):
50
+ ret = cmd(*args, **kwargs)
51
+
52
+ p: Path | None # type: ignore[annotation-unchecked]
53
+ if _RICH_EXPORT == "1":
54
+ p = Path("stringcalc-rich-export.svg")
55
+ elif _RICH_EXPORT == "0":
56
+ p = None
57
+ else:
58
+ p = Path(_RICH_EXPORT).with_suffix(".svg")
59
+
60
+ if p is not None:
61
+ console.save_svg(p)
62
+
63
+ return ret
64
+
65
+ return inner
66
+
67
+
68
+ def error(s: str, *, rc: int = 1, markup: bool = True) -> None:
69
+ """Print error message."""
70
+ console.print(s, style=Style(color="red", bold=True), highlight=False, markup=markup)
71
+ assert rc != 0
72
+ raise typer.Exit(rc)
73
+
74
+
75
+ def info(s: str) -> None:
76
+ """Print info message."""
77
+ console.print(s, style=Style(color="cyan", bold=True), highlight=False)
78
+
79
+
80
+ def warning(s: str) -> None:
81
+ """Print warning message."""
82
+ console.print(s, style=Style(color="red", bold=False), highlight=False)
83
+
84
+
85
+ def pretty_warnings(f):
86
+ """Decorator to catch warnings and pretty-print them with Rich after running `f`."""
87
+ import warnings
88
+
89
+ @functools.wraps(f)
90
+ def inner(*args, **kwargs):
91
+ with warnings.catch_warnings(record=True) as w:
92
+ f(*args, **kwargs)
93
+
94
+ for i in range(len(w)):
95
+ warning(f"- {w[i].message}")
96
+
97
+ return inner
98
+
99
+
100
+ def _version_callback(show: bool):
101
+ if show:
102
+ from . import __version__
103
+
104
+ v = f"[rgb(184,115,51)]stringcalc[/] [bold blue]{__version__}[/]"
105
+ try:
106
+ i = v.index("+")
107
+ except ValueError:
108
+ pass
109
+ else:
110
+ v = v[:i] + "[rgb(100,100,100)]" + v[i:] + "[/]"
111
+
112
+ console.print(v, highlight=False)
113
+
114
+ raise typer.Exit(0)
115
+
116
+
117
+ @app.callback()
118
+ def main( # noqa: E704
119
+ version: bool = typer.Option(
120
+ False,
121
+ "--version/",
122
+ help="Print version and exit.",
123
+ callback=_version_callback,
124
+ is_eager=True,
125
+ )
126
+ ): ...
127
+
128
+
129
+ def _with_float_nonext_dtypes(df):
130
+ """Convert float extension dtypes (e.g. 'Float64') to standard NumPy float64."""
131
+ import numpy as np
132
+ import pandas as pd
133
+
134
+ df = df.copy()
135
+
136
+ for col in df.columns:
137
+ dtype = df[col].dtype
138
+ if pd.api.types.is_float_dtype(dtype) and pd.api.types.is_extension_array_dtype(dtype):
139
+ df[col] = df[col].astype(np.float64)
140
+
141
+ return df
142
+
143
+
144
+ def _rich_table(
145
+ df,
146
+ *,
147
+ title: str,
148
+ float_format: str,
149
+ panel: bool = False,
150
+ column_info: bool = True,
151
+ ihighlight: int | None = None,
152
+ ) -> RenderableType:
153
+ from rich.console import Group
154
+ from rich.panel import Panel
155
+ from rich.table import Table
156
+
157
+ attrs = df.attrs.copy()
158
+ df_str = _with_float_nonext_dtypes(df).to_string(
159
+ float_format=float_format,
160
+ header=False,
161
+ index=False,
162
+ )
163
+ # NOTE: `.to_string` with `float_format` doesn't seem to work for the float extension dtypes
164
+
165
+ if "e" in df_str and console.is_terminal:
166
+ df_str = re.sub(r"\S*e[+-][0-9]*", lambda m: _to_fancy_sci(m.group()), df_str)
167
+
168
+ def maybe_fancy_col_name(col: str) -> str:
169
+ fancy_col: str | None
170
+ try:
171
+ fancy_col = attrs["fancy_col"][col]
172
+ except KeyError:
173
+ fancy_col = None
174
+
175
+ if fancy_col is None or not console.is_terminal:
176
+ return col
177
+ else:
178
+ return fancy_col
179
+
180
+ # Table itself
181
+ table = Table(title=title)
182
+ hl_style = "bold"
183
+ if len(df) >= 5:
184
+ hl_style += " underline overline"
185
+ for col in df.columns:
186
+ table.add_column(
187
+ maybe_fancy_col_name(col),
188
+ style="green" if col != "n" else None,
189
+ )
190
+ for i, row in enumerate(df_str.splitlines()):
191
+ table.add_row(*re.split(r"(?<=\S) ", row), style=hl_style if i == ihighlight else None)
192
+
193
+ # Column descriptions
194
+ r: RenderableType
195
+ if "col_desc" not in attrs or not column_info:
196
+ r = table
197
+ else:
198
+ l = max(len(str(c.header)) for c in table.columns) # noqa: E741
199
+ sub_lines = []
200
+ for col in df.columns:
201
+ v = attrs["col_desc"].get(col)
202
+ if v is None:
203
+ continue
204
+ sub_lines.append(f"[bold cyan]{maybe_fancy_col_name(col):{l+2}}[/]{v}")
205
+
206
+ r = Group(table, "\n".join(sub_lines))
207
+
208
+ return Panel(r, expand=False) if panel else r
209
+
210
+
211
+ def pprint_table(df, *, title: str, float_format: str, panel=False) -> None:
212
+ """Pretty-print a pandas DataFrame as a Rich table."""
213
+ console.print(_rich_table(df, title=title, float_format=float_format, panel=panel))
214
+
215
+
216
+ @app.command()
217
+ @_maybe_export_output
218
+ def frets(
219
+ N: int = typer.Option(
220
+ 17, "-N", "--number", help="Number of frets, starting from nut (fret 0)."
221
+ ),
222
+ L: float = typer.Option(..., "-L", "--scale-length", help="Scale length."),
223
+ float_format: str = typer.Option(r"%.3f", help="Format for float-to-string conversion."),
224
+ # TODO: `method`
225
+ # TODO: `format` (rich, CSV, etc.)
226
+ ):
227
+ """Display fret distance table for `N` frets and scale length `L`."""
228
+ from .frets import distances
229
+
230
+ df = distances(N=N, L=L).reset_index()
231
+
232
+ pprint_table(df, title=f"Fret distances for L={L}", float_format=float_format)
233
+
234
+
235
+ _RE_LENGTH_SPEC = re.compile(r"(?P<a>[0-9]+|[ns])-(?P<b>[0-9]+|[ns])=(?P<d>[0-9e\.\+\-\.]+)")
236
+
237
+
238
+ def _ab_interp(s: str) -> int | None:
239
+ if s == "s":
240
+ return None
241
+ elif s == "n":
242
+ return 0
243
+ else:
244
+ return int(s)
245
+
246
+
247
+ def _ab_name(n: int | None) -> str:
248
+ if n == 0:
249
+ return "nut"
250
+ elif n is None:
251
+ return "saddle"
252
+ else:
253
+ return f"fret {n}"
254
+
255
+
256
+ @app.command()
257
+ @_maybe_export_output
258
+ def length(
259
+ spec: str = typer.Argument(...),
260
+ round_: int = typer.Option(None, "--round", help="Round result to this decimal precision."),
261
+ verbose: bool = typer.Option(False),
262
+ ):
263
+ """Calculate the scale length implied by spec 'a-b=d'.
264
+
265
+ Where `a` and `b` are fret numbers
266
+ (use '0' or 'n' for nut, 's' for saddle)
267
+ and `d` is the corresponding distance.
268
+ """
269
+ from .frets import length_from_distance
270
+
271
+ m = _RE_LENGTH_SPEC.fullmatch(spec)
272
+ if m is None:
273
+ error(
274
+ f"Input failed to match a-b=d spec format regex {_RE_LENGTH_SPEC.pattern!r}",
275
+ rc=2,
276
+ markup=False,
277
+ )
278
+
279
+ assert m is not None
280
+ dct = m.groupdict()
281
+ try:
282
+ a = _ab_interp(dct["a"])
283
+ b = _ab_interp(dct["b"])
284
+ d = float(dct["d"])
285
+ except ValueError as e:
286
+ error(f"Failed to convert input to frets. Message: {e}", rc=2)
287
+
288
+ try:
289
+ res = length_from_distance((a, b), d)
290
+ except ValueError as e:
291
+ error(f"Failed to compute scale length. Message: {e}", rc=2)
292
+
293
+ if round_ is not None:
294
+ res = round(float(res), round_)
295
+
296
+ if verbose:
297
+ a_name = _ab_name(a)
298
+ b_name = _ab_name(b)
299
+ console.print(
300
+ f"A distance from [green]{a_name}[/] to [red]{b_name}[/] "
301
+ f"of [cyan]{d}[/] implies a scale length of [bold cyan underline]{res}[/].",
302
+ highlight=False,
303
+ )
304
+ else:
305
+ console.print(res)
306
+
307
+
308
+ @app.command(name="gauge")
309
+ @pretty_warnings
310
+ @_maybe_export_output
311
+ def gauge_(
312
+ T: list[float] = typer.Option(..., "-T", "--tension", help="Desired tension"),
313
+ L: list[float] = typer.Option(..., "-L", "--length", help="String length (scale length)."),
314
+ P: list[str] = typer.Option(
315
+ ..., "-P", "--pitch", help="Pitch in scientific pitch notation (e.g. 'E4')."
316
+ ),
317
+ suggest: bool = typer.Option(
318
+ False,
319
+ help=("If true, suggest gauges (strings) to use. If false, compute exact gauge."),
320
+ ),
321
+ types: list[str] = typer.Option(
322
+ None,
323
+ "--type",
324
+ help=(
325
+ "String type. Can specify multiple times if using --suggest. "
326
+ "For --suggest, defaults to D'Addario phosphor bronze and plain steel ('DA:PB', 'DA:PL'). "
327
+ "If not using --suggest, must specify exactly one type (no default). "
328
+ ),
329
+ ),
330
+ nsuggest: int = typer.Option(
331
+ 3, "-N", "--nsuggest", help="Number of suggestions. Only relevant if using --suggest."
332
+ ),
333
+ is_fan: bool = typer.Option(
334
+ None,
335
+ "--fanned",
336
+ help=(
337
+ "Fanned calculations. Must provide two scale lengths. "
338
+ "Assumed if two scale lengths are provided."
339
+ ),
340
+ ),
341
+ nut_width: float = typer.Option(
342
+ None,
343
+ "-w",
344
+ "--nut-width",
345
+ help=(
346
+ "Neck width at (center of?) nut (for fanned calculations). "
347
+ "Required if using --fanned."
348
+ ),
349
+ ),
350
+ edge_space: list[float] = typer.Option(
351
+ None,
352
+ "-e",
353
+ "--edge-space",
354
+ help=(
355
+ "Edge space, between the edge of the neck and the center of the first string. "
356
+ "You can specify one (used for both left and right) or two (left, right). "
357
+ 'The default is 5/32" on the left and 1/8" on the right. '
358
+ "Only used for fanned calculations."
359
+ ),
360
+ ),
361
+ float_format: str = typer.Option(
362
+ r"%.3f", help="Format for float-to-string conversion. Only relevant if using --suggest."
363
+ ),
364
+ column_info: bool = typer.Option(
365
+ True,
366
+ help="Print column definitions under table. Only relevant if using --suggest.",
367
+ ),
368
+ verbose: bool = typer.Option(False),
369
+ ):
370
+ """Compute gauge(s) from string information.
371
+
372
+ IMPORTANT: currently must use `T` in lbf and `L` in inches,
373
+ returning result(s) in inches.
374
+ """
375
+ from itertools import cycle
376
+
377
+ from .tension import _STRING_TYPE_ALIAS_TO_VERBOSE, DENSITY_LB_IN, gauge, suggest_gauge
378
+
379
+ if suggest:
380
+ from rich.columns import Columns
381
+
382
+ types_set: set[str]
383
+ if not types:
384
+ if verbose:
385
+ info("No string types specified, defaulting to D'Addario PB + PL.")
386
+ types_set = {"DA:PB", "DA:PL"}
387
+ else:
388
+ types_set = set(types)
389
+
390
+ if is_fan is None:
391
+ is_fan = len(L) == 2
392
+ if is_fan:
393
+ if len(L) != 2:
394
+ error(
395
+ "Must supply two scale lengths (bass and treble sides) for fanned calculation. "
396
+ f"Got {len(L)}.",
397
+ rc=2,
398
+ )
399
+ n_str = max(len(T), len(P))
400
+ if n_str < 2:
401
+ error("Need at least two strings for fanned calculation.", rc=2)
402
+ if not nut_width:
403
+ error("Must supply nut width for fanned calculation.", rc=2)
404
+ if edge_space is None:
405
+ edge_space = [5 / 32, 1 / 8]
406
+ else:
407
+ if len(edge_space) == 1:
408
+ edge_space *= 2
409
+ elif len(edge_space) > 2:
410
+ error(f"Specify one or two edge space values. Got {len(edge_space)}.", rc=2)
411
+ e_b, e_t = edge_space
412
+ L_b, L_t = L
413
+ dLdx = (L_t - L_b) / nut_width
414
+ d = (nut_width - e_b - e_t) / (n_str - 1) # string spacing
415
+ xs = [e_b + i * d for i in range(n_str)]
416
+ L = [round(L_b + dLdx * x, 4) for x in xs]
417
+ if verbose:
418
+ info(f"Nut width: {nut_width}")
419
+ info(f"Left/bass edge space: {e_b}")
420
+ info(f"Right/treble edge space: {e_t}")
421
+ info(f"Computed string spacing: {round(d, 4)}")
422
+ info(f"Computed string nut positions: {[round(x, 4) for x in xs]}")
423
+
424
+ if verbose:
425
+ info(f"Searching string types: {types_set}")
426
+
427
+ n_cases = max(len(T), len(L), len(P))
428
+ if not all(len(x) == n_cases or len(x) == 1 for x in (T, L, P)): # type: ignore[arg-type]
429
+ error(
430
+ "Must supply single or same number of values for each of T, L, P. "
431
+ f"Got {len(T)}, {len(L)}, {len(P)}.",
432
+ rc=2,
433
+ )
434
+
435
+ tables = []
436
+ for n, (T_, L_, P_) in enumerate(zip(cycle(T), cycle(L), cycle(P))):
437
+ if n >= n_cases:
438
+ break
439
+
440
+ try:
441
+ g_df = suggest_gauge(T=T_, L=L_, pitch=P_, types=types_set, n=nsuggest)
442
+ except ValueError as e:
443
+ error(f"Failed to compute gauge suggestions. Message: {e}", rc=2)
444
+
445
+ g_df.attrs["col_desc"]["dT"] += f" ({T_} lbf)"
446
+ table = _rich_table(
447
+ g_df,
448
+ title=f'Closest gauges\nfor {L_}" @ {P_}',
449
+ float_format=float_format,
450
+ panel=n_cases > 1,
451
+ column_info=column_info,
452
+ ihighlight=int(g_df.dT.abs().argmin()) if len(g_df) >= 2 else None,
453
+ )
454
+ tables.append(table)
455
+
456
+ console.print(Columns(tables))
457
+
458
+ else:
459
+ if not types:
460
+ error(
461
+ "Must supply type to use exact gauge calculation, e.g. 'plain nylon', 'plain steel'.",
462
+ rc=2,
463
+ )
464
+
465
+ if len(types) > 1:
466
+ error(f"Only specify one type for exact gauge calculation. Got {types}.", rc=2)
467
+
468
+ try:
469
+ (T_,), (L_,), (P_,) = T, L, P
470
+ except ValueError:
471
+ error(
472
+ f"Only supply one value for each of T, L, P. Got {len(T)}, {len(L)}, {len(P)}.",
473
+ rc=2,
474
+ )
475
+
476
+ type_ = types[0]
477
+ allowed_type_keys = sorted(
478
+ list(DENSITY_LB_IN) + list(_STRING_TYPE_ALIAS_TO_VERBOSE), key=lambda s: s.lower()
479
+ )
480
+ if type_ not in allowed_type_keys:
481
+ error(f"Type {type_!r} not allowed. Use one of {allowed_type_keys}.", rc=2)
482
+
483
+ type_verbose = type_ if type_ in DENSITY_LB_IN else _STRING_TYPE_ALIAS_TO_VERBOSE[type_]
484
+ dens = DENSITY_LB_IN[type_verbose]
485
+
486
+ g = gauge(dens, T=T_, L=L_, pitch=P_)
487
+
488
+ if verbose:
489
+ console.print(
490
+ f"To get tension of [green]{T_} lbf[/] on a [green]{type_verbose}[/] string "
491
+ f'of length [green]{L_}"[/] tuned to [cyan]{P_}[/], '
492
+ f'gauge [bold cyan underline]{g:.3g}"[/] should be used.',
493
+ highlight=False,
494
+ )
495
+ else:
496
+ console.print(g)
497
+
498
+
499
+ _typer_click_object = typer.main.get_command(app) # for sphinx-click in docs
500
+
501
+
502
+ if __name__ == "__main__":
503
+ app()
@@ -0,0 +1,3 @@
1
+ """
2
+ String data files.
3
+ """
@@ -0,0 +1,32 @@
1
+ id,gauge,gauge_nylon_web,gauge_carbon_web,gauge_nylon_pdf,gauge_carbon_pdf,gauge_d,gauge_da_nylon
2
+ 36NNG,0.0142,0.0157,0.0118,0.0157,0.0118,0.0287,0.0162
3
+ 38NNG,0.015,0.0165,0.0126,0.0165,0.013,0.0299,0.0171
4
+ 40NNG,0.0157,0.0173,0.0134,0.0181,0.0138,0.0311,0.018
5
+ 42NNG,0.0165,0.0181,0.0142,0.0187,0.0146,0.0323,0.0189
6
+ 44NNG,0.0173,0.0189,0.015,0.0197,0.015,0.0335,0.0198
7
+ 46NNG,0.0181,0.0205,0.0157,0.0207,0.0157,0.0346,0.0207
8
+ 48NNG,0.0189,0.0213,0.0157,0.0213,0.0165,0.0358,0.0216
9
+ 50NNG,0.0197,0.022,0.0165,0.022,0.0173,0.037,0.0225
10
+ 52NNG,0.0205,0.0228,0.0173,0.0226,0.0181,0.0382,0.0234
11
+ 54NNG,0.0213,0.0236,0.0181,0.0236,0.0185,0.0394,0.0243
12
+ 56NNG,0.022,0.0244,0.0189,0.0246,0.0189,0.0409,0.0252
13
+ 58NNG,0.0228,0.0252,0.0197,0.0256,0.0197,0.0425,0.0261
14
+ 60NNG,0.0236,0.026,0.0205,0.0266,0.0205,0.0441,0.027
15
+ 62NNG,0.0244,0.0268,0.0205,0.0276,0.0213,0.0457,0.0279
16
+ 64NNG,0.0252,0.0276,0.0213,0.0285,0.022,0.0472,0.0288
17
+ 66NNG,0.026,0.0287,0.022,0.0295,0.0224,0.0488,0.0297
18
+ 68NNG,0.0268,0.0287,0.0228,0.0305,0.0236,0.0504,0.0306
19
+ 70NNG,0.0276,0.0299,0.0236,0.0315,0.0244,0.052,0.0315
20
+ 73NNG,0.0287,0.0311,0.0244,0.0325,0.0252,0.0535,0.0328
21
+ 76NNG,0.0299,0.0335,0.0252,0.0335,0.026,0.0551,0.0342
22
+ 79NNG,0.0311,0.0346,0.0268,0.0344,0.0268,0.0571,0.0355
23
+ 82NNG,0.0323,0.0358,0.0276,0.0364,0.0283,0.0591,0.0369
24
+ 85NNG,0.0335,0.037,0.0287,0.0374,0.0291,0.061,0.0382
25
+ 88NNG,0.0346,0.0382,0.0299,0.0384,0.0299,0.063,0.0396
26
+ 91NNG,0.0358,0.0394,0.0311,0.0394,0.0311,0.065,0.0409
27
+ 94NNG,0.037,0.0409,0.0311,0.0409,0.0327,0.0669,0.0423
28
+ 97NNG,0.0382,0.0421,0.0323,,0.0335,0.0689,0.0436
29
+ 100NNG,0.0394,0.0437,0.0335,,0.035,0.0709,0.045
30
+ 104NNG,0.0409,0.0453,0.0346,,0.0358,0.0728,0.0468
31
+ 108NNG,0.0425,0.0472,,,,0.0748,0.0486
32
+ 112NNG,0.0441,0.0488,,,,0.0768,0.0504