labcalc 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.
- labcalc/__init__.py +1 -0
- labcalc/__main__.py +3 -0
- labcalc/cli.py +356 -0
- labcalc/fit.py +230 -0
- labcalc/functions.py +298 -0
- labcalc/lang.py +1774 -0
- labcalc/session.py +2112 -0
- labcalc/solve.py +205 -0
- labcalc/stats.py +155 -0
- labcalc/ui.py +397 -0
- labcalc/units.py +396 -0
- labcalc/values.py +644 -0
- labcalc/web.html +249 -0
- labcalc/web.py +116 -0
- labcalc-0.1.0.dist-info/METADATA +387 -0
- labcalc-0.1.0.dist-info/RECORD +19 -0
- labcalc-0.1.0.dist-info/WHEEL +4 -0
- labcalc-0.1.0.dist-info/entry_points.txt +2 -0
- labcalc-0.1.0.dist-info/licenses/LICENSE +21 -0
labcalc/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Interactive error-propagation calculator."""
|
labcalc/__main__.py
ADDED
labcalc/cli.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
"""The interactive prompt: live preview, highlighting, inline completion, key bindings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from prompt_toolkit import PromptSession, print_formatted_text
|
|
10
|
+
from prompt_toolkit.application import get_app
|
|
11
|
+
from prompt_toolkit.formatted_text import FormattedText
|
|
12
|
+
from prompt_toolkit.history import InMemoryHistory
|
|
13
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
14
|
+
from prompt_toolkit.layout.processors import AfterInput, Processor, Transformation
|
|
15
|
+
from prompt_toolkit.layout.utils import explode_text_fragments
|
|
16
|
+
from prompt_toolkit.lexers import Lexer
|
|
17
|
+
from prompt_toolkit.shortcuts import clear
|
|
18
|
+
from prompt_toolkit.styles import Style
|
|
19
|
+
|
|
20
|
+
from .lang import greek_typed
|
|
21
|
+
from .session import Quit, Session, Storage
|
|
22
|
+
from .ui import ( # noqa: F401
|
|
23
|
+
COLOURS, LineStyler, completion_text, errors_from_json, errors_to_json, ghost, ghost_style, preview,
|
|
24
|
+
)
|
|
25
|
+
from .values import CalcError
|
|
26
|
+
|
|
27
|
+
STYLE = Style.from_dict(COLOURS)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CalcLexer(Lexer, LineStyler):
|
|
31
|
+
"""Colours names by what they are, so a typo shows up before Enter."""
|
|
32
|
+
|
|
33
|
+
def invalidation_hash(self):
|
|
34
|
+
return hash((tuple(self.session.vars), tuple(self.session.function_names)))
|
|
35
|
+
|
|
36
|
+
def lex_document(self, document):
|
|
37
|
+
lines = [self.style_line(line) for line in document.lines]
|
|
38
|
+
return lambda lineno: lines[lineno] if lineno < len(lines) else []
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def completion(session: Session, document) -> str:
|
|
42
|
+
"""The rest of the name being typed at the cursor, or "" if nothing fits."""
|
|
43
|
+
return completion_text(session, document.text_before_cursor, document.text_after_cursor)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GhostCompletion(Processor):
|
|
47
|
+
"""Shows `completion` greyed out at the cursor; Tab types it for real."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, session: Session):
|
|
50
|
+
self.session = session
|
|
51
|
+
|
|
52
|
+
def apply_transformation(self, ti):
|
|
53
|
+
document = ti.document
|
|
54
|
+
found = None if get_app().is_done else ghost(self.session, document.text_before_cursor, document.text_after_cursor)
|
|
55
|
+
if not found or ti.lineno != document.cursor_position_row:
|
|
56
|
+
return Transformation(ti.fragments)
|
|
57
|
+
rest, style = found
|
|
58
|
+
col = document.cursor_position_col
|
|
59
|
+
chars = explode_text_fragments(ti.fragments)
|
|
60
|
+
shift = len(rest)
|
|
61
|
+
return Transformation(
|
|
62
|
+
chars[:col] + [(style, rest)] + chars[col:],
|
|
63
|
+
source_to_display=lambda i: i if i <= col else i + shift,
|
|
64
|
+
display_to_source=lambda i: i if i <= col else max(col, i - shift),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _key_bindings(session: Session) -> KeyBindings:
|
|
69
|
+
kb = KeyBindings()
|
|
70
|
+
|
|
71
|
+
@kb.add("tab")
|
|
72
|
+
def _(event):
|
|
73
|
+
buffer = event.current_buffer
|
|
74
|
+
buffer.insert_text(completion(session, buffer.document))
|
|
75
|
+
|
|
76
|
+
@kb.add("enter")
|
|
77
|
+
def _(event):
|
|
78
|
+
"""Enter: the line is left on screen with brackets showing how it was
|
|
79
|
+
read where that could be mistaken (`1/2pi C` → `(1/(2pi)) * C`)."""
|
|
80
|
+
buffer = event.current_buffer
|
|
81
|
+
shown = session.clarify(buffer.text)
|
|
82
|
+
if shown != buffer.text:
|
|
83
|
+
buffer.text = shown
|
|
84
|
+
buffer.cursor_position = len(shown)
|
|
85
|
+
buffer.validate_and_handle()
|
|
86
|
+
|
|
87
|
+
@kb.add("-")
|
|
88
|
+
def _(event):
|
|
89
|
+
"""Typing +- or +/- turns into ±."""
|
|
90
|
+
buffer = event.current_buffer
|
|
91
|
+
before = buffer.document.text_before_cursor
|
|
92
|
+
for typed in ("+/", "+"):
|
|
93
|
+
if before.endswith(typed):
|
|
94
|
+
buffer.delete_before_cursor(len(typed))
|
|
95
|
+
buffer.insert_text("±")
|
|
96
|
+
return
|
|
97
|
+
buffer.insert_text("-")
|
|
98
|
+
|
|
99
|
+
return kb
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _preview(session: Session, history: Recall):
|
|
103
|
+
def get():
|
|
104
|
+
app = get_app()
|
|
105
|
+
if app.is_done:
|
|
106
|
+
return ""
|
|
107
|
+
buffer = app.current_buffer
|
|
108
|
+
browsing = buffer.working_index < len(buffer._working_lines) - 1
|
|
109
|
+
source = history.sources.get(buffer.text) if browsing else None
|
|
110
|
+
if source: # a value ↑ brought back: the line it came from
|
|
111
|
+
return [("class:preview", f" ← {source}")]
|
|
112
|
+
text = preview(session, buffer.text)
|
|
113
|
+
return [("class:preview", f" {text}")] if text else ""
|
|
114
|
+
|
|
115
|
+
return get
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _greek_as_typed(buffer) -> None:
|
|
119
|
+
"""`alpha ` → `α `: a Greek letter's name, once the word is finished."""
|
|
120
|
+
new = greek_typed(buffer.document.text_before_cursor)
|
|
121
|
+
if new:
|
|
122
|
+
after = buffer.document.text_after_cursor
|
|
123
|
+
buffer.text, buffer.cursor_position = new + after, len(new)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def build_prompt(session: Session, **kwargs) -> PromptSession:
|
|
127
|
+
history = Recall()
|
|
128
|
+
prompt = PromptSession(
|
|
129
|
+
message=lambda: [("class:prompt", "deg> " if session.degrees else "> ")],
|
|
130
|
+
lexer=CalcLexer(session),
|
|
131
|
+
key_bindings=_key_bindings(session),
|
|
132
|
+
input_processors=[GhostCompletion(session), AfterInput(_preview(session, history))],
|
|
133
|
+
style=STYLE,
|
|
134
|
+
history=history,
|
|
135
|
+
enable_history_search=True, # La then ↑: the last line starting La
|
|
136
|
+
**kwargs,
|
|
137
|
+
)
|
|
138
|
+
prompt.default_buffer.on_text_insert += _greek_as_typed
|
|
139
|
+
return prompt
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
EXTENSION = ".labcalc" # a saved session
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class FileStorage(Storage):
|
|
146
|
+
"""Sessions as files: `save hw3` writes hw3.labcalc in `saves`; this
|
|
147
|
+
session is kept in session.labcalc as it goes, and at startup the one
|
|
148
|
+
before becomes previous.labcalc, for `load`."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, state: Path, saves: Path):
|
|
151
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
152
|
+
self.saves = saves
|
|
153
|
+
self.current = state / f"session{EXTENSION}"
|
|
154
|
+
self.last = state / f"previous{EXTENSION}"
|
|
155
|
+
if self.current.exists() and self.current.stat().st_size:
|
|
156
|
+
self.current.replace(self.last)
|
|
157
|
+
self.current.write_text("")
|
|
158
|
+
|
|
159
|
+
def _path(self, name: str) -> Path:
|
|
160
|
+
return self.saves / (name if name.endswith(EXTENSION) else f"{name}{EXTENSION}")
|
|
161
|
+
|
|
162
|
+
def read(self, name: str) -> str:
|
|
163
|
+
try:
|
|
164
|
+
return self._path(name).read_text()
|
|
165
|
+
except OSError:
|
|
166
|
+
raise CalcError(f"no saved session {name} in {_short_path(self.saves)}") from None
|
|
167
|
+
|
|
168
|
+
def write(self, name: str, text: str) -> str:
|
|
169
|
+
path = self._path(name)
|
|
170
|
+
try:
|
|
171
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
path.write_text(text)
|
|
173
|
+
except OSError as e:
|
|
174
|
+
raise CalcError(f"couldn't save: {e.strerror}") from None
|
|
175
|
+
return _short_path(path)
|
|
176
|
+
|
|
177
|
+
def autosave(self, text: str) -> None:
|
|
178
|
+
try:
|
|
179
|
+
self.current.write_text(text)
|
|
180
|
+
except OSError:
|
|
181
|
+
pass # no saving, but the calculator still works
|
|
182
|
+
|
|
183
|
+
def previous(self) -> str | None:
|
|
184
|
+
try:
|
|
185
|
+
return self.last.read_text()
|
|
186
|
+
except OSError:
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
def start_over(self, text: str) -> None:
|
|
190
|
+
try:
|
|
191
|
+
self.last.write_text(text)
|
|
192
|
+
self.current.write_text("")
|
|
193
|
+
except OSError:
|
|
194
|
+
pass
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _short_path(path: Path) -> str:
|
|
198
|
+
home = Path.home()
|
|
199
|
+
return f"~/{path.relative_to(home)}" if path.is_relative_to(home) else str(path)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _saves_dir() -> Path:
|
|
203
|
+
"""Where `save` puts sessions: somewhere easy to find, to print."""
|
|
204
|
+
if _env("SAVES"):
|
|
205
|
+
return Path(_env("SAVES"))
|
|
206
|
+
if _env("STATE"):
|
|
207
|
+
return Path(_env("STATE")) / "saved"
|
|
208
|
+
return _moved(Path.home() / "Documents" / "errprop", Path.home() / "Documents" / "labcalc")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def load_errors(path: Path) -> dict[str, tuple]:
|
|
212
|
+
"""Saved equipment errors as name -> (percent, absolute, digits, unit); none
|
|
213
|
+
if the file is missing or unreadable."""
|
|
214
|
+
try:
|
|
215
|
+
return errors_from_json(path.read_text())
|
|
216
|
+
except OSError:
|
|
217
|
+
return {}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def save_errors(path: Path, errors: dict) -> None:
|
|
221
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
222
|
+
temporary = path.with_suffix(".tmp")
|
|
223
|
+
temporary.write_text(errors_to_json(errors))
|
|
224
|
+
temporary.replace(path)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _state_dir() -> Path:
|
|
228
|
+
if _env("STATE"):
|
|
229
|
+
return Path(_env("STATE"))
|
|
230
|
+
base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
|
|
231
|
+
return _moved(Path(base) / "errprop", Path(base) / "labcalc")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _env(name: str) -> str | None:
|
|
235
|
+
"""LABCALC_STATE, or ERRPROP_STATE from when it was called errprop."""
|
|
236
|
+
return os.environ.get(f"LABCALC_{name}") or os.environ.get(f"ERRPROP_{name}")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _moved(old: Path, new: Path) -> Path:
|
|
240
|
+
"""`new`, after moving what was kept at `old` under the old name there."""
|
|
241
|
+
if old.exists() and not new.exists():
|
|
242
|
+
try:
|
|
243
|
+
old.rename(new)
|
|
244
|
+
except OSError:
|
|
245
|
+
return old
|
|
246
|
+
return new
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _error(message: str) -> None:
|
|
250
|
+
print_formatted_text(FormattedText([("class:error", f"error: {message}")]), style=STYLE)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class Recall(InMemoryHistory):
|
|
254
|
+
"""The lines typed, each followed by the value it worked out, and for each
|
|
255
|
+
value the line it came from (shown beside it as ↑ reaches it)."""
|
|
256
|
+
|
|
257
|
+
def __init__(self):
|
|
258
|
+
super().__init__()
|
|
259
|
+
self.sources: dict[str, str] = {}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _remember(history: Recall, line: str | None, value: str) -> None:
|
|
263
|
+
"""For ↑: each line, then the value it worked out, so ↑ gives the value first.
|
|
264
|
+
`line` None: the one just typed, which Enter has put in the history."""
|
|
265
|
+
for text in (line, value):
|
|
266
|
+
typed = history.get_strings()
|
|
267
|
+
if text and (not typed or typed[-1] != text):
|
|
268
|
+
if text is value and typed:
|
|
269
|
+
history.sources[value] = typed[-1]
|
|
270
|
+
history.append_string(text)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _show_loaded(session: Session) -> None:
|
|
274
|
+
styler = LineStyler(session)
|
|
275
|
+
for line, out, _ in session.loaded:
|
|
276
|
+
print_formatted_text(FormattedText([("class:prompt", "> "), *styler.style_line(line)]), style=STYLE)
|
|
277
|
+
if out is not None:
|
|
278
|
+
print(out)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _interactive(session: Session) -> int:
|
|
282
|
+
prompt = build_prompt(session)
|
|
283
|
+
errors_file = _state_dir() / "errors.json"
|
|
284
|
+
saved = dict(session.state.errors)
|
|
285
|
+
|
|
286
|
+
def keep_errors() -> None:
|
|
287
|
+
nonlocal saved
|
|
288
|
+
if session.state.errors != saved:
|
|
289
|
+
try:
|
|
290
|
+
save_errors(errors_file, session.state.errors)
|
|
291
|
+
saved = dict(session.state.errors)
|
|
292
|
+
except OSError:
|
|
293
|
+
pass
|
|
294
|
+
|
|
295
|
+
try:
|
|
296
|
+
session.storage = FileStorage(_state_dir(), _saves_dir())
|
|
297
|
+
except OSError:
|
|
298
|
+
pass # no saving, but the calculator still works
|
|
299
|
+
print_formatted_text(FormattedText([("class:hint", "labcalc")]), style=STYLE)
|
|
300
|
+
while True:
|
|
301
|
+
try:
|
|
302
|
+
text = prompt.prompt()
|
|
303
|
+
except KeyboardInterrupt:
|
|
304
|
+
continue
|
|
305
|
+
except EOFError:
|
|
306
|
+
return 0
|
|
307
|
+
try:
|
|
308
|
+
out = session.run(text)
|
|
309
|
+
except Quit:
|
|
310
|
+
return 0
|
|
311
|
+
except CalcError as e:
|
|
312
|
+
_error(str(e))
|
|
313
|
+
except Exception as e: # a bug: say so in a line, and carry on
|
|
314
|
+
_error(f"bug: {type(e).__name__}: {e}")
|
|
315
|
+
else:
|
|
316
|
+
if session.loaded: # shown as if typed again, and ↑ reaches it
|
|
317
|
+
_show_loaded(session)
|
|
318
|
+
for line, _, value in session.loaded:
|
|
319
|
+
_remember(prompt.history, line, value)
|
|
320
|
+
session.loaded = None
|
|
321
|
+
elif session.value:
|
|
322
|
+
_remember(prompt.history, None, session.value)
|
|
323
|
+
keep_errors()
|
|
324
|
+
if session.clear_screen:
|
|
325
|
+
session.clear_screen = False
|
|
326
|
+
clear()
|
|
327
|
+
if out is not None:
|
|
328
|
+
print(out)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _batch(session: Session, lines) -> int:
|
|
332
|
+
"""Piped input: run each line, print each result."""
|
|
333
|
+
failed = False
|
|
334
|
+
for line in lines:
|
|
335
|
+
try:
|
|
336
|
+
out = session.run(line)
|
|
337
|
+
except Quit:
|
|
338
|
+
break
|
|
339
|
+
except CalcError as e:
|
|
340
|
+
print(f"error: {e}")
|
|
341
|
+
failed = True
|
|
342
|
+
else:
|
|
343
|
+
if out is not None:
|
|
344
|
+
print(out)
|
|
345
|
+
return 1 if failed else 0
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def main() -> int:
|
|
349
|
+
if sys.argv[1:] == ["web"]: # the same calculator in a browser tab
|
|
350
|
+
from .web import open_in_browser
|
|
351
|
+
|
|
352
|
+
return open_in_browser(_state_dir())
|
|
353
|
+
session = Session(load_errors(_state_dir() / "errors.json"))
|
|
354
|
+
if sys.stdin.isatty() and sys.stdout.isatty():
|
|
355
|
+
return _interactive(session)
|
|
356
|
+
return _batch(session, sys.stdin)
|
labcalc/fit.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Straight-line and quadratic fits (y = m x + c, y = a x² + b x + c), with
|
|
2
|
+
the coefficients as values that carry their uncertainties (and their
|
|
3
|
+
correlations) into later maths."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import itertools
|
|
8
|
+
import math
|
|
9
|
+
|
|
10
|
+
from . import units
|
|
11
|
+
from .stats import common_sources
|
|
12
|
+
from .values import LABELS, CalcError, UNum, combine, common_dim
|
|
13
|
+
|
|
14
|
+
_scatter_ids = itertools.count()
|
|
15
|
+
# The same fit of the same data always gets the same scatter sources, so
|
|
16
|
+
# refitting unchanged data gives identical (and identically correlated) results.
|
|
17
|
+
_scatter_sources: dict = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _powers(degree: int, origin: bool) -> list[int]:
|
|
21
|
+
"""The powers of x fitted, highest first: [1, 0] for a line."""
|
|
22
|
+
return list(range(degree, 0 if origin else -1, -1))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _value(coefficients: list[float], powers: list[int], x: float) -> float:
|
|
26
|
+
return sum(c * x**p for c, p in zip(coefficients, powers))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _gradient(coefficients: list[float], powers: list[int], x: float) -> float:
|
|
30
|
+
return sum(p * c * x ** (p - 1) for c, p in zip(coefficients, powers) if p)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _normal(xs: list[float], ws: list[float], powers: list[int]) -> list[list[float]]:
|
|
34
|
+
return [[sum(w * x ** (p + q) for w, x in zip(ws, xs)) for q in powers] for p in powers]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _solve(a: list[list[float]], b: list[float]) -> list[float] | None:
|
|
38
|
+
"""a z = b by elimination (a: a normal matrix), or None if a is singular."""
|
|
39
|
+
n = len(b)
|
|
40
|
+
# Scaled to 1s on the diagonal first, so x values far from 1 (1E-6 s)
|
|
41
|
+
# don't look singular.
|
|
42
|
+
d = [math.sqrt(a[i][i]) or 1.0 for i in range(n)]
|
|
43
|
+
a = [[a[i][j] / (d[i] * d[j]) for j in range(n)] for i in range(n)]
|
|
44
|
+
b = [b[i] / d[i] for i in range(n)]
|
|
45
|
+
m = [row[:] + [v] for row, v in zip(a, b)]
|
|
46
|
+
scale = 1.0
|
|
47
|
+
for i in range(n):
|
|
48
|
+
pivot = max(range(i, n), key=lambda r: abs(m[r][i]))
|
|
49
|
+
if abs(m[pivot][i]) <= 1e-13 * scale:
|
|
50
|
+
return None
|
|
51
|
+
m[i], m[pivot] = m[pivot], m[i]
|
|
52
|
+
for r in range(i + 1, n):
|
|
53
|
+
f = m[r][i] / m[i][i]
|
|
54
|
+
for c in range(i, n + 1):
|
|
55
|
+
m[r][c] -= f * m[i][c]
|
|
56
|
+
z = [0.0] * n
|
|
57
|
+
for i in reversed(range(n)):
|
|
58
|
+
z[i] = (m[i][n] - sum(m[i][c] * z[c] for c in range(i + 1, n))) / m[i][i]
|
|
59
|
+
return [z[i] / d[i] for i in range(n)]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _inverse(a: list[list[float]]) -> list[list[float]]:
|
|
63
|
+
n = len(a)
|
|
64
|
+
columns = [_solve(a, [float(i == j) for i in range(n)]) for j in range(n)]
|
|
65
|
+
if None in columns:
|
|
66
|
+
raise CalcError("fit: the x values can't tell the terms apart")
|
|
67
|
+
return [[columns[j][i] for j in range(n)] for i in range(n)]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _cholesky(a: list[list[float]]) -> list[list[float]]:
|
|
71
|
+
"""Lower-triangular l with l lᵀ = a (a covariance: rows of independent parts)."""
|
|
72
|
+
n = len(a)
|
|
73
|
+
low = [[0.0] * n for _ in range(n)]
|
|
74
|
+
for i in range(n):
|
|
75
|
+
for j in range(i + 1):
|
|
76
|
+
rest = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
|
|
77
|
+
if i == j:
|
|
78
|
+
low[i][i] = math.sqrt(max(rest, 0.0))
|
|
79
|
+
else:
|
|
80
|
+
low[i][j] = rest / low[j][j] if low[j][j] else 0.0
|
|
81
|
+
return low
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _estimate(xs: list[float], ys: list[float], ws: list[float], powers: list[int]) -> list[float]:
|
|
85
|
+
"""Weighted least squares coefficients, for `powers` of x."""
|
|
86
|
+
if powers == [1, 0]: # a line, in closed form
|
|
87
|
+
s = sum(ws)
|
|
88
|
+
sx = sum(w * x for w, x in zip(ws, xs))
|
|
89
|
+
sy = sum(w * y for w, y in zip(ws, ys))
|
|
90
|
+
sxx = sum(w * x * x for w, x in zip(ws, xs))
|
|
91
|
+
sxy = sum(w * x * y for w, x, y in zip(ws, xs, ys))
|
|
92
|
+
d = s * sxx - sx * sx
|
|
93
|
+
if d == 0:
|
|
94
|
+
raise CalcError("fit needs at least two different x values")
|
|
95
|
+
return [(s * sxy - sx * sy) / d, (sxx * sy - sx * sxy) / d]
|
|
96
|
+
b = [sum(w * y * x**p for w, x, y in zip(ws, xs, ys)) for p in powers]
|
|
97
|
+
z = _solve(_normal(xs, ws, powers), b)
|
|
98
|
+
if z is None:
|
|
99
|
+
if powers == [1]:
|
|
100
|
+
raise CalcError("fit needs x values that aren't all 0")
|
|
101
|
+
count = {1: "one", 2: "two", 3: "three"}[len(powers)]
|
|
102
|
+
raise CalcError(f"fit needs at least {count} different x values")
|
|
103
|
+
return z
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
NAMES = {2: "quad", 1: "slope", 0: "intercept"} # y = quad x² + slope x + intercept
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def line(
|
|
110
|
+
ys: dict[str, UNum], xs: dict[str, UNum], origin: bool, which: str = "", unweighted: bool = False
|
|
111
|
+
) -> tuple[UNum, UNum | None, float | None]:
|
|
112
|
+
"""Fit y = m x + c (or y = m x through the origin): the gradient, the
|
|
113
|
+
intercept (None through the origin) and χ²/dof. See `poly`."""
|
|
114
|
+
found, chi2 = poly(ys, xs, 1, origin, which, unweighted)
|
|
115
|
+
return found["slope"], found.get("intercept"), chi2
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def poly(
|
|
119
|
+
ys: dict[str, UNum], xs: dict[str, UNum], degree: int, origin: bool, which: str = "", unweighted: bool = False
|
|
120
|
+
) -> tuple[dict[str, UNum], float | None]:
|
|
121
|
+
"""Fit y = quad x² + slope x + intercept (up to `degree`; without the
|
|
122
|
+
intercept through the origin).
|
|
123
|
+
|
|
124
|
+
With uncertainties of their own on the points, each is weighted by 1/σ²,
|
|
125
|
+
where σ combines its y error and its x error (scaled by the gradient). The
|
|
126
|
+
result's uncertainty comes from the points' errors, and χ² per degree of
|
|
127
|
+
freedom says whether the scatter agrees with them (about 1). Errors the
|
|
128
|
+
points share (an instrument's calibration) don't set the weights, which
|
|
129
|
+
would bias the fit; they are carried into the result in full.
|
|
130
|
+
|
|
131
|
+
Without errors of their own on the points, or `unweighted`, every point
|
|
132
|
+
counts equally and the statistical error comes from the scatter about the
|
|
133
|
+
fit, plus any shared errors carried through.
|
|
134
|
+
|
|
135
|
+
Returns the coefficients by name and χ²/dof (None without uncertainties,
|
|
136
|
+
or with no degrees of freedom). `which` names the fit (its y and x), to
|
|
137
|
+
keep different fits' scatter apart.
|
|
138
|
+
"""
|
|
139
|
+
powers = _powers(degree, origin)
|
|
140
|
+
found, chi2 = _poly(ys, xs, powers, which, unweighted)
|
|
141
|
+
dy, dx = common_dim(ys.values(), "fit"), common_dim(xs.values(), "fit")
|
|
142
|
+
for p, value in zip(powers, found):
|
|
143
|
+
value.dim = None if dy is None or dx is None else units.dim_div(dy, units.dim_pow(dx, p))
|
|
144
|
+
return {NAMES[p]: value for p, value in zip(powers, found)}, chi2
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _poly(ys, xs, powers, which, unweighted):
|
|
148
|
+
if set(ys) != set(xs):
|
|
149
|
+
only = sorted(set(ys) ^ set(xs), key=lambda k: (len(k), k))
|
|
150
|
+
raise CalcError(f"fit: lists have different entries ({len(ys)} and {len(xs)}; [{', '.join(only)}] in one only)")
|
|
151
|
+
keys = list(ys)
|
|
152
|
+
Y, X = [ys[k] for k in keys], [xs[k] for k in keys]
|
|
153
|
+
n, fitted = len(keys), len(powers)
|
|
154
|
+
if n < fitted + 1:
|
|
155
|
+
raise CalcError(f"fit needs {fitted + 1} or more points")
|
|
156
|
+
yv, xv = [y.v for y in Y], [x.v for x in X]
|
|
157
|
+
|
|
158
|
+
# Each point's own errors: those not common to every point. One that's in
|
|
159
|
+
# both a point's y and its x (y = V/I against V) counts once, with both.
|
|
160
|
+
common = common_sources([set(y.parts) | set(x.parts) for y, x in zip(Y, X)])
|
|
161
|
+
own = [
|
|
162
|
+
[(y.parts.get(s, 0.0), x.parts.get(s, 0.0)) for s in (set(y.parts) | set(x.parts)) - common]
|
|
163
|
+
for y, x in zip(Y, X)
|
|
164
|
+
]
|
|
165
|
+
weighted = not unweighted and any(own)
|
|
166
|
+
coefficients = _estimate(xv, yv, [1.0] * n, powers)
|
|
167
|
+
if weighted:
|
|
168
|
+
for _ in range(20): # the x errors' weight depends on the gradient
|
|
169
|
+
slopes = [_gradient(coefficients, powers, x) for x in xv]
|
|
170
|
+
variances = [sum((cy - m * cx) ** 2 for cy, cx in point) for point, m in zip(own, slopes)]
|
|
171
|
+
if not all(variances):
|
|
172
|
+
bare = ", ".join(k for k, v in zip(keys, variances) if not v)
|
|
173
|
+
raise CalcError(f"fit: no uncertainty on [{bare}]; give every point one, or none")
|
|
174
|
+
ws = [1 / v for v in variances]
|
|
175
|
+
new = _estimate(xv, yv, ws, powers)
|
|
176
|
+
done = all(abs(a - b) <= 1e-12 * abs(a) for a, b in zip(new, coefficients))
|
|
177
|
+
coefficients = new
|
|
178
|
+
if done:
|
|
179
|
+
break
|
|
180
|
+
return _propagate(xv, yv, ws, X, Y, powers), _chi2(xv, yv, ws, coefficients, powers, n - fitted)
|
|
181
|
+
|
|
182
|
+
residuals = [y - _value(coefficients, powers, x) for x, y in zip(xv, yv)]
|
|
183
|
+
s2 = sum(r * r for r in residuals) / (n - fitted)
|
|
184
|
+
covariance = [[s2 * v for v in row] for row in _inverse(_normal(xv, [1.0] * n, powers))]
|
|
185
|
+
# Errors the points share are carried through; their own show up as scatter.
|
|
186
|
+
shared = _propagate(xv, yv, [1.0] * n, X, Y, powers)
|
|
187
|
+
parts = [{s: v for s, v in x.parts.items() if s in common} for x in shared]
|
|
188
|
+
if not any(covariance[i][i] for i in range(fitted)):
|
|
189
|
+
return [UNum(c, p) for c, p in zip(coefficients, parts)], None
|
|
190
|
+
# Independent sources that give the coefficients their variances and covariances.
|
|
191
|
+
key = (which, tuple(xv), tuple(yv), tuple(powers))
|
|
192
|
+
if key not in _scatter_sources:
|
|
193
|
+
_scatter_sources[key] = tuple(("fit", next(_scatter_ids)) for _ in powers)
|
|
194
|
+
for source in _scatter_sources[key]:
|
|
195
|
+
LABELS[source] = {"name": f"scatter about {which or 'the fit'}", "value": "", "sigma": ""}
|
|
196
|
+
sources = _scatter_sources[key]
|
|
197
|
+
low = _cholesky(covariance)
|
|
198
|
+
return [
|
|
199
|
+
UNum(c, {**p, **{s: low[i][j] for j, s in enumerate(sources[: i + 1]) if low[i][j]}})
|
|
200
|
+
for i, (c, p) in enumerate(zip(coefficients, parts))
|
|
201
|
+
], None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _propagate(xv, yv, ws, X, Y, powers) -> list[UNum]:
|
|
205
|
+
"""The fit as a function of the data, so each point's uncertainty (and any
|
|
206
|
+
correlation between points) carries through. Weights are held fixed."""
|
|
207
|
+
coefficients = _estimate(xv, yv, ws, powers)
|
|
208
|
+
dy: list[list[float]] = [] # per point, the coefficients' derivatives
|
|
209
|
+
dx: list[list[float]] = []
|
|
210
|
+
for i in range(len(xv)):
|
|
211
|
+
for values, out in ((yv, dy), (xv, dx)):
|
|
212
|
+
h = 1e-6 * (abs(values[i]) or 1.0)
|
|
213
|
+
up, down = list(values), list(values)
|
|
214
|
+
up[i] += h
|
|
215
|
+
down[i] -= h
|
|
216
|
+
at_up = _estimate(xv, up, ws, powers) if values is yv else _estimate(up, yv, ws, powers)
|
|
217
|
+
at_down = _estimate(xv, down, ws, powers) if values is yv else _estimate(down, yv, ws, powers)
|
|
218
|
+
out.append([(a - b) / (2 * h) for a, b in zip(at_up, at_down)])
|
|
219
|
+
return [
|
|
220
|
+
combine(c, *((d[j], y) for d, y in zip(dy, Y)), *((d[j], x) for d, x in zip(dx, X)))
|
|
221
|
+
for j, c in enumerate(coefficients)
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _chi2(xv, yv, ws, coefficients, powers, dof) -> float | None:
|
|
226
|
+
if dof <= 0:
|
|
227
|
+
return None
|
|
228
|
+
chi2 = sum(w * (y - _value(coefficients, powers, x)) ** 2 for w, x, y in zip(ws, xv, yv)) / dof
|
|
229
|
+
scale = max(w * y * y for w, y in zip(ws, yv))
|
|
230
|
+
return 0.0 if chi2 <= 1e-20 * scale else chi2 # points exactly on a line: 0, not 6E-27
|