fitle 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.
- fitle/__init__.py +9 -0
- fitle/compiler.py +681 -0
- fitle/cost.py +358 -0
- fitle/fitting.py +402 -0
- fitle/model.py +1372 -0
- fitle/param.py +542 -0
- fitle/pdfs.py +207 -0
- fitle-0.1.0.dist-info/METADATA +628 -0
- fitle-0.1.0.dist-info/RECORD +12 -0
- fitle-0.1.0.dist-info/WHEEL +5 -0
- fitle-0.1.0.dist-info/licenses/LICENSE +21 -0
- fitle-0.1.0.dist-info/top_level.txt +1 -0
fitle/param.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
"""param.py
|
|
2
|
+
=========
|
|
3
|
+
Symbolic parameters for model building.
|
|
4
|
+
|
|
5
|
+
The main interface is the `Param` builder which creates `_Param` instances:
|
|
6
|
+
|
|
7
|
+
# Shorthand with unary operators (auto-named from variable)
|
|
8
|
+
a = ~Param # unbounded, auto-named 'a'
|
|
9
|
+
sigma = +Param # positive (>0), auto-named 'sigma'
|
|
10
|
+
neg = -Param # negative (<0), auto-named 'neg'
|
|
11
|
+
|
|
12
|
+
# Explicit creation
|
|
13
|
+
a = Param(5) # unbounded, start=5, auto-named 'a'
|
|
14
|
+
b = Param('b') # unbounded, explicit name 'b'
|
|
15
|
+
c = Param(0, 10) # bounded [0,10], auto-named 'c'
|
|
16
|
+
|
|
17
|
+
# Chaining works
|
|
18
|
+
f = Param('f')(5)(0, 10) # name='f', start=5, bounds=[0,10]
|
|
19
|
+
|
|
20
|
+
# Constrained params (explicit)
|
|
21
|
+
sigma = Param.positive('sigma')
|
|
22
|
+
frac = Param.unit('frac')
|
|
23
|
+
|
|
24
|
+
# Tuple unpacking with auto-naming
|
|
25
|
+
mu, sigma = ~Param, +Param
|
|
26
|
+
"""
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from enum import Enum, auto
|
|
31
|
+
from typing import Tuple
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ParamKind",
|
|
35
|
+
"Param",
|
|
36
|
+
"_Param",
|
|
37
|
+
"INPUT",
|
|
38
|
+
"index",
|
|
39
|
+
"INDEX",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ParamKind(Enum):
|
|
44
|
+
"""Enumerates the recognised parameter roles."""
|
|
45
|
+
THETA = auto() #: free, optimisable parameter
|
|
46
|
+
INPUT = auto() #: singleton placeholder for X
|
|
47
|
+
INDEX = auto() #: integer loop variable (carries :class:`range`)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# -----------------------------------------------------------------------------
|
|
51
|
+
# Variable name detection for auto-naming
|
|
52
|
+
# -----------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
_varname_cache: dict[tuple, int] = {} # (filename, lineno) -> call index
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _split_top_level_commas(s: str) -> list[str]:
|
|
58
|
+
"""Split string by commas, but only at top level (not inside parens/brackets)."""
|
|
59
|
+
parts = []
|
|
60
|
+
current = []
|
|
61
|
+
depth = 0
|
|
62
|
+
for c in s:
|
|
63
|
+
if c in '([':
|
|
64
|
+
depth += 1
|
|
65
|
+
current.append(c)
|
|
66
|
+
elif c in ')]':
|
|
67
|
+
depth -= 1
|
|
68
|
+
current.append(c)
|
|
69
|
+
elif c == ',' and depth == 0:
|
|
70
|
+
parts.append(''.join(current))
|
|
71
|
+
current = []
|
|
72
|
+
else:
|
|
73
|
+
current.append(c)
|
|
74
|
+
if current:
|
|
75
|
+
parts.append(''.join(current))
|
|
76
|
+
return parts
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _is_simple_param_expr(rhs: str) -> bool:
|
|
80
|
+
"""Check if RHS contains only simple Param expressions.
|
|
81
|
+
|
|
82
|
+
Matches: ~Param, +Param, -Param, Param(5), Param.positive('x'), (+Param)(5), etc.
|
|
83
|
+
Does NOT match: Param(5) + Param(3), gaussian(Param()), etc.
|
|
84
|
+
"""
|
|
85
|
+
import re
|
|
86
|
+
# Pattern options:
|
|
87
|
+
# 1. Optional unary op, identifier with optional .attr, followed by optional () chains
|
|
88
|
+
# 2. Parenthesized unary expression like (+Param) followed by () chains
|
|
89
|
+
pattern = r'^\s*([~+\-]?\s*\w+(\.\w+)?|\([~+\-]\s*\w+(\.\w+)?\))(\(.*?\))*\s*$'
|
|
90
|
+
parts = _split_top_level_commas(rhs)
|
|
91
|
+
return all(re.match(pattern, part.strip()) for part in parts)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _detect_varname(depth: int = 2) -> str | None:
|
|
95
|
+
"""Detect variable name from assignment in calling frame.
|
|
96
|
+
|
|
97
|
+
Only returns a name for simple direct assignments like:
|
|
98
|
+
a = ~Param
|
|
99
|
+
a, b = ~Param, +Param
|
|
100
|
+
x = Param(5)
|
|
101
|
+
|
|
102
|
+
Returns None for complex expressions like:
|
|
103
|
+
y = ~Param + ~Param
|
|
104
|
+
m = gaussian(~Param)
|
|
105
|
+
"""
|
|
106
|
+
import inspect
|
|
107
|
+
import re
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
frame = inspect.currentframe()
|
|
111
|
+
for _ in range(depth):
|
|
112
|
+
if frame is None:
|
|
113
|
+
return None
|
|
114
|
+
frame = frame.f_back
|
|
115
|
+
if frame is None:
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
info = inspect.getframeinfo(frame)
|
|
119
|
+
if not info.code_context:
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
line = info.code_context[0]
|
|
123
|
+
key = (info.filename, info.lineno)
|
|
124
|
+
|
|
125
|
+
# Strip comments (simple approach: remove # and everything after if not in string)
|
|
126
|
+
# This handles common cases like: a = ~Param # comment
|
|
127
|
+
comment_pos = line.find('#')
|
|
128
|
+
if comment_pos != -1:
|
|
129
|
+
# Check it's not inside a string by counting quotes before it
|
|
130
|
+
before = line[:comment_pos]
|
|
131
|
+
if before.count("'") % 2 == 0 and before.count('"') % 2 == 0:
|
|
132
|
+
line = before
|
|
133
|
+
|
|
134
|
+
# Parse LHS and RHS of assignment
|
|
135
|
+
match = re.match(r'\s*([\w\s,]+)\s*=\s*(.+)$', line)
|
|
136
|
+
if not match:
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
lhs = match.group(1)
|
|
140
|
+
rhs = match.group(2)
|
|
141
|
+
|
|
142
|
+
# Only auto-name for simple Param expressions
|
|
143
|
+
if not _is_simple_param_expr(rhs):
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
names = [n.strip() for n in lhs.split(',')]
|
|
147
|
+
rhs_parts = _split_top_level_commas(rhs)
|
|
148
|
+
|
|
149
|
+
# Must have same number of LHS vars and RHS parts
|
|
150
|
+
if len(names) != len(rhs_parts):
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
if len(names) == 1:
|
|
154
|
+
return names[0]
|
|
155
|
+
|
|
156
|
+
# Tuple unpacking: track position
|
|
157
|
+
call_index = _varname_cache.get(key, 0)
|
|
158
|
+
|
|
159
|
+
# Reset if we've gone past the end (re-execution of same line)
|
|
160
|
+
if call_index >= len(names):
|
|
161
|
+
call_index = 0
|
|
162
|
+
|
|
163
|
+
_varname_cache[key] = call_index + 1
|
|
164
|
+
|
|
165
|
+
return names[call_index]
|
|
166
|
+
|
|
167
|
+
except Exception:
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# -----------------------------------------------------------------------------
|
|
172
|
+
# _Param: The actual parameter class
|
|
173
|
+
# -----------------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
class _Param:
|
|
176
|
+
"""Internal parameter class. Use `Param` builder to create instances.
|
|
177
|
+
|
|
178
|
+
Three mutually-exclusive roles:
|
|
179
|
+
- THETA: Free parameter for optimization (has min/max/start/value)
|
|
180
|
+
- INPUT: Placeholder for input data
|
|
181
|
+
- INDEX: Integer loop variable (has range)
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
theta = ParamKind.THETA
|
|
185
|
+
input = ParamKind.INPUT
|
|
186
|
+
index = ParamKind.INDEX
|
|
187
|
+
|
|
188
|
+
def __init__(
|
|
189
|
+
self,
|
|
190
|
+
name: str | None = None,
|
|
191
|
+
min: float | None = None,
|
|
192
|
+
max: float | None = None,
|
|
193
|
+
start: float | None = None,
|
|
194
|
+
*,
|
|
195
|
+
kind: ParamKind = ParamKind.THETA,
|
|
196
|
+
range: range | None = None,
|
|
197
|
+
):
|
|
198
|
+
self.kind = kind
|
|
199
|
+
self.name = name
|
|
200
|
+
|
|
201
|
+
if kind is ParamKind.INPUT:
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
if kind is ParamKind.INDEX:
|
|
205
|
+
self.range = range
|
|
206
|
+
return
|
|
207
|
+
|
|
208
|
+
# THETA
|
|
209
|
+
self.range = None
|
|
210
|
+
self.min = min if min is not None else -np.inf
|
|
211
|
+
self.max = max if max is not None else np.inf
|
|
212
|
+
|
|
213
|
+
# Compute default start
|
|
214
|
+
if start is not None:
|
|
215
|
+
self.start = start
|
|
216
|
+
elif self.min == -np.inf and self.max == np.inf:
|
|
217
|
+
self.start = 0.0
|
|
218
|
+
elif self.min == -np.inf:
|
|
219
|
+
self.start = float(self.max)
|
|
220
|
+
elif self.max == np.inf:
|
|
221
|
+
self.start = float(self.min)
|
|
222
|
+
else:
|
|
223
|
+
self.start = 0.5 * (self.min + self.max)
|
|
224
|
+
|
|
225
|
+
self.value = self.start
|
|
226
|
+
|
|
227
|
+
def __call__(self, arg0: str | float, arg1: float | None = None) -> '_Param':
|
|
228
|
+
"""Chain configuration: param('name'), param(5), param(0, 10)."""
|
|
229
|
+
if arg1 is not None:
|
|
230
|
+
# Set bounds
|
|
231
|
+
new_min, new_max = float(arg0), float(arg1)
|
|
232
|
+
# Recompute start if needed
|
|
233
|
+
if self.start < new_min or self.start > new_max:
|
|
234
|
+
if new_min == -np.inf:
|
|
235
|
+
new_start = float(new_max) if new_max != np.inf else 0.0
|
|
236
|
+
elif new_max == np.inf:
|
|
237
|
+
new_start = float(new_min)
|
|
238
|
+
else:
|
|
239
|
+
new_start = 0.5 * (new_min + new_max)
|
|
240
|
+
else:
|
|
241
|
+
new_start = self.start
|
|
242
|
+
return _Param(
|
|
243
|
+
name=self.name,
|
|
244
|
+
min=new_min,
|
|
245
|
+
max=new_max,
|
|
246
|
+
start=new_start,
|
|
247
|
+
)
|
|
248
|
+
elif isinstance(arg0, str):
|
|
249
|
+
# Set name
|
|
250
|
+
return _Param(
|
|
251
|
+
name=arg0,
|
|
252
|
+
min=self.min,
|
|
253
|
+
max=self.max,
|
|
254
|
+
start=self.start,
|
|
255
|
+
)
|
|
256
|
+
elif isinstance(arg0, (int, float)):
|
|
257
|
+
# Set start
|
|
258
|
+
new_start = float(arg0)
|
|
259
|
+
# Clamp to bounds
|
|
260
|
+
if new_start < self.min:
|
|
261
|
+
new_start = self.min
|
|
262
|
+
if new_start > self.max:
|
|
263
|
+
new_start = self.max
|
|
264
|
+
return _Param(
|
|
265
|
+
name=self.name,
|
|
266
|
+
min=self.min,
|
|
267
|
+
max=self.max,
|
|
268
|
+
start=new_start,
|
|
269
|
+
)
|
|
270
|
+
else:
|
|
271
|
+
raise TypeError(
|
|
272
|
+
f"_Param(...) expects str (name), number (start), or two numbers (bounds), "
|
|
273
|
+
f"got {type(arg0).__name__}"
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
# ------------------------------------------------------------------
|
|
277
|
+
# Identity-based equality (operators are added by bind_ops in model.py)
|
|
278
|
+
# ------------------------------------------------------------------
|
|
279
|
+
|
|
280
|
+
def __eq__(self, other: object) -> bool:
|
|
281
|
+
if not isinstance(other, _Param):
|
|
282
|
+
return False
|
|
283
|
+
if self.kind is self.input and other.kind is other.input:
|
|
284
|
+
return True
|
|
285
|
+
return self is other
|
|
286
|
+
|
|
287
|
+
def __hash__(self) -> int:
|
|
288
|
+
return id(self)
|
|
289
|
+
|
|
290
|
+
# ------------------------------------------------------------------
|
|
291
|
+
# NumPy dispatch protocols
|
|
292
|
+
# ------------------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
def __array_ufunc__(self, ufunc, method, *inputs, **ufunc_kwargs):
|
|
295
|
+
if method != '__call__':
|
|
296
|
+
return NotImplemented
|
|
297
|
+
from .model import Model
|
|
298
|
+
|
|
299
|
+
if ufunc_kwargs:
|
|
300
|
+
def inner(*inner_args):
|
|
301
|
+
return ufunc(*inner_args, **ufunc_kwargs)
|
|
302
|
+
inner._has_kwargs = True
|
|
303
|
+
inner._kwargs_info = tuple(ufunc_kwargs.keys())
|
|
304
|
+
else:
|
|
305
|
+
def inner(*inner_args):
|
|
306
|
+
return ufunc(*inner_args)
|
|
307
|
+
inner.__name__ = ufunc.__name__
|
|
308
|
+
return Model(inner, list(inputs))
|
|
309
|
+
|
|
310
|
+
def __array_function__(self, func, types, args, kwargs):
|
|
311
|
+
from .model import Model
|
|
312
|
+
|
|
313
|
+
if kwargs:
|
|
314
|
+
def inner(*inner_args):
|
|
315
|
+
return func(*inner_args, **kwargs)
|
|
316
|
+
inner._has_kwargs = True
|
|
317
|
+
inner._kwargs_info = tuple(kwargs.keys())
|
|
318
|
+
else:
|
|
319
|
+
def inner(*inner_args):
|
|
320
|
+
return func(*inner_args)
|
|
321
|
+
inner.__name__ = func.__name__
|
|
322
|
+
return Model(inner, list(args))
|
|
323
|
+
|
|
324
|
+
# ------------------------------------------------------------------
|
|
325
|
+
# Indexing
|
|
326
|
+
# ------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
def __getitem__(self, key):
|
|
329
|
+
"""Select element from this param by index.
|
|
330
|
+
|
|
331
|
+
INPUT[0] returns a Model that selects element 0 from the input array.
|
|
332
|
+
INPUT[idx] where idx is an INDEX param returns a Model for dynamic indexing.
|
|
333
|
+
"""
|
|
334
|
+
from .model import _indecise
|
|
335
|
+
return _indecise(self, key)
|
|
336
|
+
|
|
337
|
+
# ------------------------------------------------------------------
|
|
338
|
+
# String representations
|
|
339
|
+
# ------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
def _prefix(self) -> str:
|
|
342
|
+
return f"{self.name}=" if self.name else ""
|
|
343
|
+
|
|
344
|
+
def __repr__(self) -> str:
|
|
345
|
+
if self.kind is self.input:
|
|
346
|
+
return "INPUT"
|
|
347
|
+
if self.kind is self.index:
|
|
348
|
+
if self.range is None:
|
|
349
|
+
return "INDEX"
|
|
350
|
+
return f"{self._prefix()}{self.range}"
|
|
351
|
+
if self.min == self.max:
|
|
352
|
+
return f"{self._prefix()}_Param(value={self.value})"
|
|
353
|
+
return (
|
|
354
|
+
f"{self._prefix()}_Param(min={self.min}, start={self.start}, "
|
|
355
|
+
f"max={self.max}, value={self.value})"
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
def __str__(self) -> str:
|
|
359
|
+
if self.kind is self.input:
|
|
360
|
+
return "INPUT"
|
|
361
|
+
if self.kind is self.index:
|
|
362
|
+
if self.range is None:
|
|
363
|
+
return "INDEX"
|
|
364
|
+
return f"{self._prefix()}{self.range}"
|
|
365
|
+
if hasattr(self, "error"):
|
|
366
|
+
return f"{self._prefix()}{self.value:.4g} ± {self.error:.2g}"
|
|
367
|
+
return f"{self._prefix()}{self.value:.4g}"
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# -----------------------------------------------------------------------------
|
|
371
|
+
# Param: The builder class (public API)
|
|
372
|
+
# -----------------------------------------------------------------------------
|
|
373
|
+
|
|
374
|
+
_MISSING = object() # sentinel for distinguishing Param() from Param(None)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class _ParamBuilder:
|
|
378
|
+
"""Builder for creating _Param instances.
|
|
379
|
+
|
|
380
|
+
Use via the singleton `Param`:
|
|
381
|
+
a = Param(5) # _Param with start=5, auto-named 'a'
|
|
382
|
+
b = Param('b') # _Param with explicit name 'b'
|
|
383
|
+
c = Param(0, 10) # _Param with bounds [0, 10], auto-named 'c'
|
|
384
|
+
"""
|
|
385
|
+
|
|
386
|
+
def __call__(self, arg0: str | float = _MISSING, arg1: float | None = None) -> _Param:
|
|
387
|
+
"""Create a _Param with configuration."""
|
|
388
|
+
name = None
|
|
389
|
+
start = None
|
|
390
|
+
bounds = None
|
|
391
|
+
|
|
392
|
+
if arg0 is _MISSING:
|
|
393
|
+
# Param() - just auto-name
|
|
394
|
+
name = _detect_varname(depth=2)
|
|
395
|
+
elif arg1 is not None:
|
|
396
|
+
# Param(min, max) - bounds
|
|
397
|
+
bounds = (float(arg0), float(arg1))
|
|
398
|
+
name = _detect_varname(depth=2)
|
|
399
|
+
elif isinstance(arg0, str):
|
|
400
|
+
# Param('name') - explicit name
|
|
401
|
+
name = arg0
|
|
402
|
+
elif isinstance(arg0, (int, float)):
|
|
403
|
+
# Param(5) - start value
|
|
404
|
+
start = float(arg0)
|
|
405
|
+
name = _detect_varname(depth=2)
|
|
406
|
+
else:
|
|
407
|
+
raise TypeError(
|
|
408
|
+
f"Param(...) expects str (name), number (start), or two numbers (bounds), "
|
|
409
|
+
f"got {type(arg0).__name__}"
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
if bounds is not None:
|
|
413
|
+
return _Param(name=name, min=bounds[0], max=bounds[1], start=start)
|
|
414
|
+
else:
|
|
415
|
+
return _Param(name=name, start=start)
|
|
416
|
+
|
|
417
|
+
def _not_finalized_error(self):
|
|
418
|
+
raise TypeError(
|
|
419
|
+
"Param must be called before use in expressions.\n"
|
|
420
|
+
" Examples:\n"
|
|
421
|
+
" Param('x') # named\n"
|
|
422
|
+
" Param(5) # with start value\n"
|
|
423
|
+
" Param(0, 10) # with bounds\n"
|
|
424
|
+
" Param() # unbounded, auto-named"
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
def __add__(self, other): self._not_finalized_error()
|
|
428
|
+
def __radd__(self, other): self._not_finalized_error()
|
|
429
|
+
def __sub__(self, other): self._not_finalized_error()
|
|
430
|
+
def __rsub__(self, other): self._not_finalized_error()
|
|
431
|
+
def __mul__(self, other): self._not_finalized_error()
|
|
432
|
+
def __rmul__(self, other): self._not_finalized_error()
|
|
433
|
+
def __truediv__(self, other): self._not_finalized_error()
|
|
434
|
+
def __rtruediv__(self, other): self._not_finalized_error()
|
|
435
|
+
def __pow__(self, other): self._not_finalized_error()
|
|
436
|
+
def __rpow__(self, other): self._not_finalized_error()
|
|
437
|
+
|
|
438
|
+
def __invert__(self) -> _Param:
|
|
439
|
+
"""~Param: Create unbounded _Param with auto-naming."""
|
|
440
|
+
return _Param(name=_detect_varname(depth=2))
|
|
441
|
+
|
|
442
|
+
def __pos__(self) -> _Param:
|
|
443
|
+
"""+Param: Create positive _Param with auto-naming."""
|
|
444
|
+
return _Param(name=_detect_varname(depth=2), min=1e-6, max=np.inf, start=1.0)
|
|
445
|
+
|
|
446
|
+
def __neg__(self) -> _Param:
|
|
447
|
+
"""-Param: Create negative _Param with auto-naming."""
|
|
448
|
+
return _Param(name=_detect_varname(depth=2), min=-np.inf, max=-1e-6, start=-1.0)
|
|
449
|
+
|
|
450
|
+
def __repr__(self) -> str:
|
|
451
|
+
return "Param"
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
# The singleton builder
|
|
455
|
+
Param = _ParamBuilder()
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# -----------------------------------------------------------------------------
|
|
459
|
+
# Constrained param builders
|
|
460
|
+
# -----------------------------------------------------------------------------
|
|
461
|
+
|
|
462
|
+
class _PositiveBuilder:
|
|
463
|
+
"""Builder for positive params: Param.positive('name') or Param.positive(start)"""
|
|
464
|
+
def __call__(self, arg0: str | float | None = None) -> _Param:
|
|
465
|
+
if arg0 is None:
|
|
466
|
+
name = _detect_varname(depth=2)
|
|
467
|
+
return _Param(name=name, min=1e-6, max=np.inf, start=1.0)
|
|
468
|
+
elif isinstance(arg0, str):
|
|
469
|
+
return _Param(name=arg0, min=1e-6, max=np.inf, start=1.0)
|
|
470
|
+
elif isinstance(arg0, (int, float)):
|
|
471
|
+
name = _detect_varname(depth=2)
|
|
472
|
+
start = float(arg0)
|
|
473
|
+
if start <= 0:
|
|
474
|
+
start = 1.0
|
|
475
|
+
return _Param(name=name, min=1e-6, max=np.inf, start=start)
|
|
476
|
+
else:
|
|
477
|
+
raise TypeError(f"Param.positive expects str or number, got {type(arg0).__name__}")
|
|
478
|
+
|
|
479
|
+
def __repr__(self) -> str:
|
|
480
|
+
return "Param.positive"
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class _NegativeBuilder:
|
|
484
|
+
"""Builder for negative params: Param.negative('name') or Param.negative(start)"""
|
|
485
|
+
def __call__(self, arg0: str | float | None = None) -> _Param:
|
|
486
|
+
if arg0 is None:
|
|
487
|
+
name = _detect_varname(depth=2)
|
|
488
|
+
return _Param(name=name, min=-np.inf, max=-1e-6, start=-1.0)
|
|
489
|
+
elif isinstance(arg0, str):
|
|
490
|
+
return _Param(name=arg0, min=-np.inf, max=-1e-6, start=-1.0)
|
|
491
|
+
elif isinstance(arg0, (int, float)):
|
|
492
|
+
name = _detect_varname(depth=2)
|
|
493
|
+
start = float(arg0)
|
|
494
|
+
if start >= 0:
|
|
495
|
+
start = -1.0
|
|
496
|
+
return _Param(name=name, min=-np.inf, max=-1e-6, start=start)
|
|
497
|
+
else:
|
|
498
|
+
raise TypeError(f"Param.negative expects str or number, got {type(arg0).__name__}")
|
|
499
|
+
|
|
500
|
+
def __repr__(self) -> str:
|
|
501
|
+
return "Param.negative"
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class _UnitBuilder:
|
|
505
|
+
"""Builder for unit [0,1] params: Param.unit('name') or Param.unit(start)"""
|
|
506
|
+
def __call__(self, arg0: str | float | None = None) -> _Param:
|
|
507
|
+
if arg0 is None:
|
|
508
|
+
name = _detect_varname(depth=2)
|
|
509
|
+
return _Param(name=name, min=0, max=1, start=0.5)
|
|
510
|
+
elif isinstance(arg0, str):
|
|
511
|
+
return _Param(name=arg0, min=0, max=1, start=0.5)
|
|
512
|
+
elif isinstance(arg0, (int, float)):
|
|
513
|
+
name = _detect_varname(depth=2)
|
|
514
|
+
start = float(arg0)
|
|
515
|
+
if start < 0:
|
|
516
|
+
start = 0.0
|
|
517
|
+
if start > 1:
|
|
518
|
+
start = 1.0
|
|
519
|
+
return _Param(name=name, min=0, max=1, start=start)
|
|
520
|
+
else:
|
|
521
|
+
raise TypeError(f"Param.unit expects str or number, got {type(arg0).__name__}")
|
|
522
|
+
|
|
523
|
+
def __repr__(self) -> str:
|
|
524
|
+
return "Param.unit"
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
Param.positive = _PositiveBuilder()
|
|
528
|
+
Param.negative = _NegativeBuilder()
|
|
529
|
+
Param.unit = _UnitBuilder()
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
# -----------------------------------------------------------------------------
|
|
533
|
+
# Module-level helpers
|
|
534
|
+
# -----------------------------------------------------------------------------
|
|
535
|
+
|
|
536
|
+
INPUT: _Param = _Param(kind=ParamKind.INPUT)
|
|
537
|
+
|
|
538
|
+
def index(*args: int) -> _Param:
|
|
539
|
+
"""Create an INDEX parameter with range(*args)."""
|
|
540
|
+
return _Param(range=range(*args) if args else None, kind=ParamKind.INDEX)
|
|
541
|
+
|
|
542
|
+
INDEX: _Param = index()
|