half-sample 0.1.24__tar.gz → 0.1.27__tar.gz
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.
- {half_sample-0.1.24 → half_sample-0.1.27}/PKG-INFO +1 -1
- half_sample-0.1.27/cpp_build/sample.exe +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/half_sample.egg-info/PKG-INFO +1 -1
- {half_sample-0.1.24 → half_sample-0.1.27}/half_sample.egg-info/SOURCES.txt +1 -0
- half_sample-0.1.27/sample/protocol.py +205 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/sample/result.py +24 -1
- {half_sample-0.1.24 → half_sample-0.1.27}/sample/sample.py +42 -1
- {half_sample-0.1.24 → half_sample-0.1.27}/setup.py +1 -1
- half_sample-0.1.24/cpp_build/sample.exe +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/README.md +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/half_sample.egg-info/dependency_links.txt +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/half_sample.egg-info/top_level.txt +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/sample/__init__.py +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/sample/process.py +0 -0
- {half_sample-0.1.24 → half_sample-0.1.27}/setup.cfg +0 -0
|
Binary file
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Safe parser for the sampler executable's line-oriented response protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import unicode_literals
|
|
4
|
+
|
|
5
|
+
import keyword
|
|
6
|
+
import re
|
|
7
|
+
import unicodedata
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_FIELD_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
|
|
11
|
+
_INTEGER_RE = re.compile(r"^[+-]?[0-9]+$")
|
|
12
|
+
_FLOAT_RE = re.compile(
|
|
13
|
+
r"^[+-]?(?:(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)$"
|
|
14
|
+
)
|
|
15
|
+
_NAN_TOKENS = frozenset(("nan", "+nan", "-nan", "1.#ind", "-1.#ind", "1.#qnan", "-1.#qnan",
|
|
16
|
+
"1.#snan", "-1.#snan"))
|
|
17
|
+
_POSITIVE_INFINITY_TOKENS = frozenset(("inf", "+inf", "infinity", "+infinity", "1.#inf", "+1.#inf"))
|
|
18
|
+
_NEGATIVE_INFINITY_TOKENS = frozenset(("-inf", "-infinity", "-1.#inf"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _escape_character(character):
|
|
22
|
+
code = ord(character)
|
|
23
|
+
if character == "\\":
|
|
24
|
+
return "\\\\"
|
|
25
|
+
if character == "\r":
|
|
26
|
+
return "\\r"
|
|
27
|
+
if character == "\n":
|
|
28
|
+
return "\\n"
|
|
29
|
+
if character == "\t":
|
|
30
|
+
return "\\t"
|
|
31
|
+
if unicodedata.category(character) == "Cc":
|
|
32
|
+
return "\\x{0:02x}".format(code)
|
|
33
|
+
return character
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def summarize_response(response, limit=512):
|
|
37
|
+
"""Return a bounded, single-line representation of *response* using O(limit) working memory."""
|
|
38
|
+
if limit <= 0:
|
|
39
|
+
return ""
|
|
40
|
+
prefix_parts = []
|
|
41
|
+
prefix_length = 0
|
|
42
|
+
position = 0
|
|
43
|
+
while position < len(response) and prefix_length <= limit:
|
|
44
|
+
escaped_character = _escape_character(response[position])
|
|
45
|
+
prefix_parts.append(escaped_character)
|
|
46
|
+
prefix_length += len(escaped_character)
|
|
47
|
+
position += 1
|
|
48
|
+
if position == len(response) and prefix_length <= limit:
|
|
49
|
+
return "".join(prefix_parts)
|
|
50
|
+
marker = "..."
|
|
51
|
+
if limit <= len(marker):
|
|
52
|
+
return marker[:limit]
|
|
53
|
+
available = limit - len(marker)
|
|
54
|
+
head_length = (available + 1) // 2
|
|
55
|
+
tail_length = available - head_length
|
|
56
|
+
head = "".join(prefix_parts)[:head_length]
|
|
57
|
+
tail_parts = []
|
|
58
|
+
collected_tail_length = 0
|
|
59
|
+
position = len(response) - 1
|
|
60
|
+
while position >= 0 and collected_tail_length < tail_length:
|
|
61
|
+
escaped_character = _escape_character(response[position])
|
|
62
|
+
tail_parts.append(escaped_character)
|
|
63
|
+
collected_tail_length += len(escaped_character)
|
|
64
|
+
position -= 1
|
|
65
|
+
tail = "".join(reversed(tail_parts))[-tail_length:] if tail_length else ""
|
|
66
|
+
return head + marker + tail
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ProtocolError(ValueError):
|
|
70
|
+
"""An invalid sampler response with bounded diagnostic context."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, message, response, line_number=None, field_name=None):
|
|
73
|
+
self.line_number = line_number
|
|
74
|
+
self.field_name = summarize_response(field_name, 120) if field_name is not None else None
|
|
75
|
+
self.response_length = len(response)
|
|
76
|
+
self.response_summary = summarize_response(response)
|
|
77
|
+
details = "line={0}, field={1!r}, response_length={2}, response={3!r}".format(
|
|
78
|
+
line_number, self.field_name, self.response_length, self.response_summary
|
|
79
|
+
)
|
|
80
|
+
super(ProtocolError, self).__init__("{0} ({1})".format(message, details))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _ValueParser(object):
|
|
84
|
+
|
|
85
|
+
def __init__(self, text):
|
|
86
|
+
self.text = text
|
|
87
|
+
self.position = 0
|
|
88
|
+
|
|
89
|
+
def parse(self):
|
|
90
|
+
self._skip_whitespace()
|
|
91
|
+
value = self._parse_value(allow_list=True)
|
|
92
|
+
self._skip_whitespace()
|
|
93
|
+
if self.position != len(self.text):
|
|
94
|
+
raise ValueError("trailing content")
|
|
95
|
+
return value
|
|
96
|
+
|
|
97
|
+
def _parse_value(self, allow_list):
|
|
98
|
+
if self.position >= len(self.text):
|
|
99
|
+
raise ValueError("missing value")
|
|
100
|
+
character = self.text[self.position]
|
|
101
|
+
if character == '"':
|
|
102
|
+
return self._parse_string()
|
|
103
|
+
if character == "[":
|
|
104
|
+
if not allow_list:
|
|
105
|
+
raise ValueError("nested containers are not allowed")
|
|
106
|
+
return self._parse_list()
|
|
107
|
+
return self._parse_atom()
|
|
108
|
+
|
|
109
|
+
def _parse_string(self):
|
|
110
|
+
self.position += 1
|
|
111
|
+
result = []
|
|
112
|
+
escapes = {'"': '"', "\\": "\\", "r": "\r", "n": "\n", "t": "\t"}
|
|
113
|
+
while self.position < len(self.text):
|
|
114
|
+
character = self.text[self.position]
|
|
115
|
+
self.position += 1
|
|
116
|
+
if character == '"':
|
|
117
|
+
return "".join(result)
|
|
118
|
+
if character == "\\":
|
|
119
|
+
if self.position >= len(self.text) or self.text[self.position] not in escapes:
|
|
120
|
+
raise ValueError("unknown or incomplete string escape")
|
|
121
|
+
result.append(escapes[self.text[self.position]])
|
|
122
|
+
self.position += 1
|
|
123
|
+
elif ord(character) < 32:
|
|
124
|
+
raise ValueError("unescaped control character in string")
|
|
125
|
+
else:
|
|
126
|
+
result.append(character)
|
|
127
|
+
raise ValueError("unterminated string")
|
|
128
|
+
|
|
129
|
+
def _parse_list(self):
|
|
130
|
+
self.position += 1
|
|
131
|
+
values = []
|
|
132
|
+
self._skip_whitespace()
|
|
133
|
+
if self._consume("]"):
|
|
134
|
+
return values
|
|
135
|
+
while True:
|
|
136
|
+
values.append(self._parse_value(allow_list=False))
|
|
137
|
+
self._skip_whitespace()
|
|
138
|
+
if self._consume("]"):
|
|
139
|
+
return values
|
|
140
|
+
if not self._consume(","):
|
|
141
|
+
raise ValueError("expected comma or closing bracket")
|
|
142
|
+
self._skip_whitespace()
|
|
143
|
+
if self._consume("]"):
|
|
144
|
+
return values
|
|
145
|
+
|
|
146
|
+
def _parse_atom(self):
|
|
147
|
+
start = self.position
|
|
148
|
+
while self.position < len(self.text) and self.text[self.position] not in " \t,]":
|
|
149
|
+
self.position += 1
|
|
150
|
+
token = self.text[start:self.position]
|
|
151
|
+
lowered = token.lower()
|
|
152
|
+
if token == "True":
|
|
153
|
+
return True
|
|
154
|
+
if token == "False":
|
|
155
|
+
return False
|
|
156
|
+
if lowered in _NAN_TOKENS:
|
|
157
|
+
return float("nan")
|
|
158
|
+
if lowered in _POSITIVE_INFINITY_TOKENS:
|
|
159
|
+
return float("inf")
|
|
160
|
+
if lowered in _NEGATIVE_INFINITY_TOKENS:
|
|
161
|
+
return float("-inf")
|
|
162
|
+
if _INTEGER_RE.match(token):
|
|
163
|
+
return int(token, 10)
|
|
164
|
+
if _FLOAT_RE.match(token):
|
|
165
|
+
return float(token)
|
|
166
|
+
raise ValueError("unsupported value")
|
|
167
|
+
|
|
168
|
+
def _skip_whitespace(self):
|
|
169
|
+
while self.position < len(self.text) and self.text[self.position] in " \t":
|
|
170
|
+
self.position += 1
|
|
171
|
+
|
|
172
|
+
def _consume(self, expected):
|
|
173
|
+
if self.position < len(self.text) and self.text[self.position] == expected:
|
|
174
|
+
self.position += 1
|
|
175
|
+
return True
|
|
176
|
+
return False
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def parse_assignments(response, known_types=None):
|
|
180
|
+
"""Parse a sampler response without evaluating any of its contents."""
|
|
181
|
+
result = {}
|
|
182
|
+
for line_number, line in enumerate(response.splitlines(), 1):
|
|
183
|
+
if not line.strip():
|
|
184
|
+
continue
|
|
185
|
+
field_name = None
|
|
186
|
+
if "=" in line:
|
|
187
|
+
raw_field_name, raw_value = line.split("=", 1)
|
|
188
|
+
field_name = raw_field_name.strip()
|
|
189
|
+
else:
|
|
190
|
+
raw_value = ""
|
|
191
|
+
try:
|
|
192
|
+
if field_name is None or not _FIELD_RE.match(field_name) or keyword.iskeyword(field_name):
|
|
193
|
+
raise ValueError("invalid field name")
|
|
194
|
+
if field_name in result:
|
|
195
|
+
raise ValueError("duplicate field")
|
|
196
|
+
value = _ValueParser(raw_value).parse()
|
|
197
|
+
if known_types is not None and field_name in known_types:
|
|
198
|
+
expected = known_types[field_name]
|
|
199
|
+
expected_types = expected if isinstance(expected, tuple) else (expected,)
|
|
200
|
+
if not any(type(value) is expected_type for expected_type in expected_types):
|
|
201
|
+
raise ValueError("unexpected field type")
|
|
202
|
+
result[field_name] = value
|
|
203
|
+
except (TypeError, ValueError) as error:
|
|
204
|
+
raise ProtocolError(str(error), response, line_number, field_name)
|
|
205
|
+
return result
|
|
@@ -22,6 +22,7 @@ class Result:
|
|
|
22
22
|
"instant_ai_alignment_failed": "Instant AI波形对齐失败",
|
|
23
23
|
"instant_ai_waveform_count_insufficient": "Instant AI完整波形数量不足",
|
|
24
24
|
"fit_not_identifiable": "拟合窗口不足以辨识tau",
|
|
25
|
+
"sampling_result_not_finite": "采样结果包含无效数值",
|
|
25
26
|
"waveform_processing_mode_mismatch": "波形处理模式不一致",
|
|
26
27
|
"user_cancelled": "用户已取消",
|
|
27
28
|
|
|
@@ -111,9 +112,21 @@ class Result:
|
|
|
111
112
|
self.w = 0.0
|
|
112
113
|
self.b = 0.0
|
|
113
114
|
self.loss = 0.0
|
|
115
|
+
self.maximum = 0.0
|
|
116
|
+
self.minimum = 0.0
|
|
117
|
+
self.invalid_field = ''
|
|
114
118
|
|
|
115
119
|
self.v0 = 0.0
|
|
116
120
|
self.v_inf = 0.0
|
|
121
|
+
self.v_inf_valid = False
|
|
122
|
+
self._v_inf_reported = False
|
|
123
|
+
self.cycle_maximum = 0.0
|
|
124
|
+
self.cycle_minimum = 0.0
|
|
125
|
+
self.cycle_vmax = 0.0
|
|
126
|
+
self.cycle_vmin = 0.0
|
|
127
|
+
self.cycle_vpp = 0.0
|
|
128
|
+
self.cycle_vtop = 0.0
|
|
129
|
+
self.cycle_vbase = 0.0
|
|
117
130
|
|
|
118
131
|
self.mock_tau = 0.0
|
|
119
132
|
self.mock_v0 = 0.0
|
|
@@ -134,7 +147,17 @@ class Result:
|
|
|
134
147
|
tau, w, b = self.tau, self.w, self.b
|
|
135
148
|
self.estimate = [w * math.exp(t / -tau) + b for t in self.time_line]
|
|
136
149
|
|
|
137
|
-
self.v0
|
|
150
|
+
self.v0 = b + w
|
|
151
|
+
if not self._v_inf_reported:
|
|
152
|
+
self.v_inf = b
|
|
153
|
+
|
|
154
|
+
if self._v_inf_reported:
|
|
155
|
+
voltage_valid = self.v_inf_valid is True and math.isfinite(self.v_inf) and self.v_inf > 0.0
|
|
156
|
+
else:
|
|
157
|
+
voltage_valid = self.success and math.isfinite(self.v_inf) and self.v_inf > 0.0
|
|
158
|
+
if not voltage_valid:
|
|
159
|
+
self.v_inf = 0.0
|
|
160
|
+
self.v_inf_valid = voltage_valid
|
|
138
161
|
|
|
139
162
|
@property
|
|
140
163
|
def chinese_message(self) -> str:
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import os
|
|
2
|
+
import math
|
|
2
3
|
import shutil
|
|
3
4
|
import sys
|
|
4
5
|
import threading
|
|
@@ -6,6 +7,7 @@ from pathlib import Path
|
|
|
6
7
|
|
|
7
8
|
from . import Process
|
|
8
9
|
from . import Result
|
|
10
|
+
from .protocol import parse_assignments, ProtocolError
|
|
9
11
|
|
|
10
12
|
|
|
11
13
|
_SOURCE_ROOT = Path(os.path.realpath(os.path.abspath(__file__))).parent.parent
|
|
@@ -97,7 +99,19 @@ class Sampler:
|
|
|
97
99
|
executor.write_line(command)
|
|
98
100
|
lines = executor.read_until('EOF')
|
|
99
101
|
if lines:
|
|
100
|
-
|
|
102
|
+
known_types = {
|
|
103
|
+
field: type(value) for field, value in result.__dict__.items() if not field.startswith("_")
|
|
104
|
+
}
|
|
105
|
+
assignments = parse_assignments(lines, known_types=known_types)
|
|
106
|
+
if "wave" in assignments:
|
|
107
|
+
for value in assignments["wave"]:
|
|
108
|
+
if type(value) is not float:
|
|
109
|
+
raise ProtocolError("unexpected field type", lines, field_name="wave")
|
|
110
|
+
for field, value in assignments.items():
|
|
111
|
+
setattr(result, field, value)
|
|
112
|
+
result._v_inf_reported = "v_inf" in assignments
|
|
113
|
+
except ProtocolError as error:
|
|
114
|
+
raise self.Error(str(error))
|
|
101
115
|
except Exception as e:
|
|
102
116
|
result.error = True
|
|
103
117
|
result.message = str(e)
|
|
@@ -168,11 +182,38 @@ class Sampler:
|
|
|
168
182
|
|
|
169
183
|
def query(self) -> Result:
|
|
170
184
|
result = self.communicate("to_query")
|
|
185
|
+
if result.success:
|
|
186
|
+
invalid_field = self._first_non_finite_field(result)
|
|
187
|
+
if invalid_field:
|
|
188
|
+
result.success = False
|
|
189
|
+
result.message = "sampling_result_not_finite"
|
|
190
|
+
result.error_category = "state"
|
|
191
|
+
result.retryable = True
|
|
192
|
+
result.invalid_field = invalid_field
|
|
193
|
+
result.wave = []
|
|
194
|
+
result.time_line = []
|
|
195
|
+
result.estimate = []
|
|
196
|
+
result.v0 = 0.0
|
|
197
|
+
result.v_inf = 0.0
|
|
198
|
+
result.v_inf_valid = False
|
|
199
|
+
return result
|
|
171
200
|
result.process()
|
|
172
201
|
if not result.success and result.message == "success":
|
|
173
202
|
result.message = "error_undefined"
|
|
174
203
|
return result
|
|
175
204
|
|
|
205
|
+
@staticmethod
|
|
206
|
+
def _first_non_finite_field(result: Result):
|
|
207
|
+
for field in ("maximum", "minimum", "sampling_interval", "wave_interval", "tau", "w", "b", "loss",
|
|
208
|
+
"v_inf", "cycle_maximum", "cycle_minimum", "cycle_vmax", "cycle_vmin", "cycle_vpp",
|
|
209
|
+
"cycle_vtop", "cycle_vbase"):
|
|
210
|
+
if not math.isfinite(getattr(result, field)):
|
|
211
|
+
return field
|
|
212
|
+
for index, value in enumerate(result.wave):
|
|
213
|
+
if not math.isfinite(value):
|
|
214
|
+
return "wave[{}]".format(index)
|
|
215
|
+
return ""
|
|
216
|
+
|
|
176
217
|
class Error(RuntimeError):
|
|
177
218
|
pass
|
|
178
219
|
|
|
Binary file
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|