half-sample 0.1.29__py3-none-win_amd64.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.
- half_sample-0.1.29.dist-info/METADATA +17 -0
- half_sample-0.1.29.dist-info/RECORD +10 -0
- half_sample-0.1.29.dist-info/WHEEL +5 -0
- half_sample-0.1.29.dist-info/top_level.txt +1 -0
- sample/__init__.py +3 -0
- sample/process.py +154 -0
- sample/protocol.py +205 -0
- sample/result.py +167 -0
- sample/sample.exe +0 -0
- sample/sample.py +226 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: half_sample
|
|
3
|
+
Version: 0.1.29
|
|
4
|
+
Summary: sample data and analysis
|
|
5
|
+
Home-page: https://github.com/KD-Group/Half.Sample
|
|
6
|
+
Author: kunde
|
|
7
|
+
Author-email: gzkunde@163.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
11
|
+
Requires-Python: >=3.6
|
|
12
|
+
Dynamic: author
|
|
13
|
+
Dynamic: author-email
|
|
14
|
+
Dynamic: classifier
|
|
15
|
+
Dynamic: home-page
|
|
16
|
+
Dynamic: requires-python
|
|
17
|
+
Dynamic: summary
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
sample/__init__.py,sha256=_1ubfCtzdROYwWIHC9AEnN6MorAH1HLkj7EqANpEvkc,93
|
|
2
|
+
sample/process.py,sha256=stEBThEEdnfQD4fz54JhL7EG12WRcUSVckk2Jw_HjX4,5842
|
|
3
|
+
sample/protocol.py,sha256=-5s-HgDH9w7ZroZehzTfVczrwwfiUPEzaSotHPqGeLQ,7707
|
|
4
|
+
sample/result.py,sha256=a6o3cuvoSZ8NHKe4OCyXOFda21mQAjfEXPgG9oEi17w,6749
|
|
5
|
+
sample/sample.exe,sha256=ynpTO63SUYk5yEo3iV3gTsvGCzFLAssBKD0m0eN4xso,501248
|
|
6
|
+
sample/sample.py,sha256=cmIv0L7Xz_b2aM7BwtXgXuHB-bfxeqV4lSQp_nsNYBA,9202
|
|
7
|
+
half_sample-0.1.29.dist-info/METADATA,sha256=l7YJeWuLYvoLGSXQTRGrhQDMugdrTWWg9eqDKRXgFco,496
|
|
8
|
+
half_sample-0.1.29.dist-info/WHEEL,sha256=dlSwLP_SaVpRiz5krjpfbY5nfB4YKbij8PFo8Ggnql0,98
|
|
9
|
+
half_sample-0.1.29.dist-info/top_level.txt,sha256=qvn_SI4HZ9peodVhGOb2WhbFYzsM78H6CJvTqxgQYT0,7
|
|
10
|
+
half_sample-0.1.29.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sample
|
sample/__init__.py
ADDED
sample/process.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import logging
|
|
3
|
+
import sys
|
|
4
|
+
import threading
|
|
5
|
+
import subprocess
|
|
6
|
+
import multiprocessing
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger('library')
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def process(target, args=(), finished=None):
|
|
13
|
+
p = multiprocessing.Process(target=target, args=args)
|
|
14
|
+
p.start()
|
|
15
|
+
|
|
16
|
+
def check_finished():
|
|
17
|
+
p.join()
|
|
18
|
+
finished()
|
|
19
|
+
|
|
20
|
+
threading.Thread(target=check_finished).start()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Process:
|
|
24
|
+
def __init__(self, cmd):
|
|
25
|
+
self.cmd = cmd
|
|
26
|
+
self.p = None
|
|
27
|
+
self._max_retries = 1
|
|
28
|
+
self._start_process()
|
|
29
|
+
|
|
30
|
+
def set_max_retry(self, max_retries):
|
|
31
|
+
self._max_retries = max_retries
|
|
32
|
+
|
|
33
|
+
def get_max_retry(self):
|
|
34
|
+
return self._max_retries
|
|
35
|
+
|
|
36
|
+
def _start_process(self):
|
|
37
|
+
"""启动或重启子进程"""
|
|
38
|
+
if self.p is not None:
|
|
39
|
+
# 如果旧进程还在运行,先终止它
|
|
40
|
+
try:
|
|
41
|
+
if self.p.poll() is None: # 进程仍在运行
|
|
42
|
+
self.p.terminate()
|
|
43
|
+
self.p.wait(timeout=3)
|
|
44
|
+
except Exception as e:
|
|
45
|
+
logger.warning(f"failed to poll: {e}")
|
|
46
|
+
try:
|
|
47
|
+
self.p.kill()
|
|
48
|
+
self.p.wait()
|
|
49
|
+
except Exception as e:
|
|
50
|
+
logger.warning(f"failed to kill: {e}")
|
|
51
|
+
pass
|
|
52
|
+
# 启动新进程
|
|
53
|
+
self.p = subprocess.Popen(self.cmd,
|
|
54
|
+
shell=False,
|
|
55
|
+
creationflags=0x00000008 if sys.platform == "win32" else 0,
|
|
56
|
+
stdin=subprocess.PIPE,
|
|
57
|
+
stdout=subprocess.PIPE,
|
|
58
|
+
stderr=subprocess.PIPE)
|
|
59
|
+
|
|
60
|
+
def _is_process_alive(self):
|
|
61
|
+
"""检查进程是否存活"""
|
|
62
|
+
if self.p is None:
|
|
63
|
+
return False
|
|
64
|
+
return self.p.poll() is None
|
|
65
|
+
|
|
66
|
+
def _ensure_process_alive(self):
|
|
67
|
+
"""确保进程存活,如果崩溃则重启"""
|
|
68
|
+
if not self._is_process_alive():
|
|
69
|
+
logger.warning(f"subprocess [{self.cmd}] crash, restarting...")
|
|
70
|
+
self._start_process()
|
|
71
|
+
logger.warning(f"subprocess [{self.cmd}] restart completed")
|
|
72
|
+
|
|
73
|
+
def write_line(self, line: str):
|
|
74
|
+
"""写入一行数据,自动处理进程重启"""
|
|
75
|
+
for attempt in range(self._max_retries):
|
|
76
|
+
try:
|
|
77
|
+
self._ensure_process_alive()
|
|
78
|
+
self.p.stdin.write(line.encode())
|
|
79
|
+
self.p.stdin.write('\n'.encode())
|
|
80
|
+
self.p.stdin.flush()
|
|
81
|
+
return # 成功写入,退出重试循环
|
|
82
|
+
except (BrokenPipeError, OSError) as e:
|
|
83
|
+
if attempt < self._max_retries - 1:
|
|
84
|
+
logger.warning(f"write line failed (attempted {attempt + 1}/{self._max_retries}): {e}")
|
|
85
|
+
self._start_process() # 重启进程
|
|
86
|
+
time.sleep(0.1) # 短暂等待新进程启动
|
|
87
|
+
else:
|
|
88
|
+
raise RuntimeError(f"无法向子进程写入数据,已重试{self._max_retries}次: {e}")
|
|
89
|
+
|
|
90
|
+
def read_line(self) -> str:
|
|
91
|
+
"""读取一行数据,自动处理进程重启"""
|
|
92
|
+
for attempt in range(self._max_retries):
|
|
93
|
+
try:
|
|
94
|
+
self._ensure_process_alive()
|
|
95
|
+
line = self.p.stdout.readline()
|
|
96
|
+
if not line: # EOF,进程可能已终止
|
|
97
|
+
if not self._is_process_alive():
|
|
98
|
+
raise RuntimeError("子进程已终止")
|
|
99
|
+
return ""
|
|
100
|
+
return line.decode().replace('\r\n', '').replace('\n', '')
|
|
101
|
+
except (OSError, RuntimeError) as e:
|
|
102
|
+
if attempt < self._max_retries - 1:
|
|
103
|
+
logger.warning(f"read line failed (attempted {attempt + 1}/{self._max_retries}): {e}")
|
|
104
|
+
self._start_process() # 重启进程
|
|
105
|
+
time.sleep(0.1) # 短暂等待新进程启动
|
|
106
|
+
else:
|
|
107
|
+
raise RuntimeError(f"无法从子进程读取数据,已重试{self._max_retries}次: {e}")
|
|
108
|
+
|
|
109
|
+
def read_until(self, until):
|
|
110
|
+
"""读取直到指定字符串,自动处理进程重启"""
|
|
111
|
+
lines = []
|
|
112
|
+
|
|
113
|
+
for attempt in range(self._max_retries):
|
|
114
|
+
try:
|
|
115
|
+
while True:
|
|
116
|
+
line = self.read_line()
|
|
117
|
+
if line == until:
|
|
118
|
+
return '\n'.join(lines)
|
|
119
|
+
elif not line:
|
|
120
|
+
break
|
|
121
|
+
else:
|
|
122
|
+
lines.append(line)
|
|
123
|
+
except (RuntimeError, OSError) as e:
|
|
124
|
+
if attempt < self._max_retries - 1:
|
|
125
|
+
logger.warning(f"read_until failed (attempted {attempt + 1}/{self._max_retries}): {e}")
|
|
126
|
+
self._start_process() # 重启进程
|
|
127
|
+
lines = [] # 清空已读取的行
|
|
128
|
+
time.sleep(0.1)
|
|
129
|
+
else:
|
|
130
|
+
raise RuntimeError(f"read_until 失败,已重试{self._max_retries}次: {e}")
|
|
131
|
+
|
|
132
|
+
return '\n'.join(lines)
|
|
133
|
+
|
|
134
|
+
def terminate(self):
|
|
135
|
+
"""终止子进程"""
|
|
136
|
+
if self.p is not None and self.p.poll() is None:
|
|
137
|
+
try:
|
|
138
|
+
self.p.terminate()
|
|
139
|
+
self.p.wait(timeout=3)
|
|
140
|
+
except subprocess.TimeoutExpired as e:
|
|
141
|
+
logger.warning(f"Timeout expired while trying to terminate [{self.cmd}]: {e}")
|
|
142
|
+
try:
|
|
143
|
+
self.p.kill()
|
|
144
|
+
self.p.wait()
|
|
145
|
+
except Exception as e:
|
|
146
|
+
logger.warning(f"Failed to kill [{self.cmd}]: {e}")
|
|
147
|
+
except Exception as e:
|
|
148
|
+
logger.warning(f"Failed to terminate [{self.cmd}]: {e}")
|
|
149
|
+
|
|
150
|
+
def get_return_code(self):
|
|
151
|
+
"""获取进程返回码"""
|
|
152
|
+
if self.p is not None:
|
|
153
|
+
return self.p.poll()
|
|
154
|
+
return None
|
sample/protocol.py
ADDED
|
@@ -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
|
sample/result.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Result:
|
|
5
|
+
ErrorMessageMapper = {
|
|
6
|
+
# 基础状态
|
|
7
|
+
"success": "成功",
|
|
8
|
+
|
|
9
|
+
# 用户操作错误
|
|
10
|
+
"command_not_found": "命令不存在",
|
|
11
|
+
"sampler_not_found": "采样器不存在",
|
|
12
|
+
"now_in_measuring": "正在测量中",
|
|
13
|
+
"file_not_found": "文件未找到",
|
|
14
|
+
|
|
15
|
+
# 采样错误
|
|
16
|
+
"voltage_not_enough": "电压不足",
|
|
17
|
+
"wave_not_found": "未找到波形",
|
|
18
|
+
"appropriate_wave_not_found": "未找到合适波形",
|
|
19
|
+
"invalid_instant_ai_config": "Instant AI配置无效",
|
|
20
|
+
"instant_ai_coverage_insufficient": "Instant AI相位覆盖不足",
|
|
21
|
+
"instant_ai_schedule_timeout": "Instant AI采集超时",
|
|
22
|
+
"instant_ai_alignment_failed": "Instant AI波形对齐失败",
|
|
23
|
+
"instant_ai_waveform_count_insufficient": "Instant AI完整波形数量不足",
|
|
24
|
+
"fit_not_identifiable": "拟合窗口不足以辨识tau",
|
|
25
|
+
"sampling_result_not_finite": "采样结果包含无效数值",
|
|
26
|
+
"waveform_processing_mode_mismatch": "波形处理模式不一致",
|
|
27
|
+
"user_cancelled": "用户已取消",
|
|
28
|
+
|
|
29
|
+
# 警告类错误
|
|
30
|
+
"warning_intr_not_available": "中断资源不可用",
|
|
31
|
+
"warning_param_out_of_range": "参数超出范围",
|
|
32
|
+
"warning_prop_value_out_of_range": "属性值超出范围",
|
|
33
|
+
"warning_prop_value_not_spted": "属性值不支持",
|
|
34
|
+
"warning_prop_value_conflict": "属性值状态冲突",
|
|
35
|
+
"warning_vrg_of_group_not_same": "通道组量程不一致",
|
|
36
|
+
|
|
37
|
+
# 系统级错误
|
|
38
|
+
"error_handle_not_valid": "句柄无效",
|
|
39
|
+
"error_param_out_of_range": "参数超出范围",
|
|
40
|
+
"error_param_not_spted": "参数不支持",
|
|
41
|
+
"error_param_fmt_unexpted": "参数格式异常",
|
|
42
|
+
"error_memory_not_enough": "内存不足",
|
|
43
|
+
"error_buffer_is_null": "缓冲区为空",
|
|
44
|
+
"error_buffer_too_small": "缓冲区过小",
|
|
45
|
+
"error_data_len_exceed_limit": "数据长度超限",
|
|
46
|
+
"error_func_not_spted": "功能不支持",
|
|
47
|
+
"error_event_not_spted": "事件不支持",
|
|
48
|
+
"error_prop_not_spted": "属性不支持",
|
|
49
|
+
"error_prop_read_only": "属性只读",
|
|
50
|
+
"error_prop_value_conflict": "属性值冲突",
|
|
51
|
+
"error_prop_value_out_of_range": "属性值超限",
|
|
52
|
+
"error_prop_value_not_spted": "属性值不支持",
|
|
53
|
+
"error_privilege_not_held": "权限未持有",
|
|
54
|
+
"error_privilege_not_available": "权限不可用",
|
|
55
|
+
"error_driver_not_found": "驱动未找到",
|
|
56
|
+
"error_driver_ver_mismatch": "驱动版本不匹配",
|
|
57
|
+
"error_driver_count_exceed_limit": "驱动数量超限",
|
|
58
|
+
"error_device_not_opened": "设备未打开",
|
|
59
|
+
"error_device_not_exist": "设备不存在",
|
|
60
|
+
"error_device_unrecognized": "设备未识别",
|
|
61
|
+
"error_config_data_lost": "配置数据丢失",
|
|
62
|
+
"error_func_not_inited": "功能未初始化",
|
|
63
|
+
"error_func_busy": "功能忙",
|
|
64
|
+
"error_intr_not_available": "中断不可用",
|
|
65
|
+
"error_dma_not_available": "DMA通道不可用",
|
|
66
|
+
"error_device_io_time_out": "设备IO超时",
|
|
67
|
+
"error_signature_not_match": "签名不匹配",
|
|
68
|
+
"error_func_conflict_with_bfd_ai": "功能与缓冲AI冲突",
|
|
69
|
+
"error_vrg_not_available_in_se_mode": "单端模式量程不可用",
|
|
70
|
+
"error_undefined": "未定义错误"
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
def __init__(self):
|
|
74
|
+
self.error = False
|
|
75
|
+
self.message = ''
|
|
76
|
+
|
|
77
|
+
self.sampler_name = ''
|
|
78
|
+
self.measuring = False
|
|
79
|
+
self.success = False
|
|
80
|
+
self.with_magnetic = False
|
|
81
|
+
|
|
82
|
+
self.sampling_interval = 0.0 # us
|
|
83
|
+
self.wave_interval = 0.0 # us
|
|
84
|
+
self.waveforms_per_sample = 0.0 # 采集卡每次采样时能得到的最大波形数量,可能采集到部分波形,因此为double类型,例如0.5
|
|
85
|
+
self.sampling_time = 1 # 采样次数,当要求的波形数量大于采集卡单次最大采样点数的时,进行多次采样直到能采集到要求的波形
|
|
86
|
+
self.sampling_length_per_sample = 0 # 采集卡单次采样点数
|
|
87
|
+
self.waveform_length = 0 # 一个完整波形的点数(包括上升沿和下降沿)
|
|
88
|
+
self.valid_length = 0 # 有效的波形点数(仅包含上升沿部分)
|
|
89
|
+
self.number_of_waveforms = 0 # 波形平均次数
|
|
90
|
+
self.acquisition_mode = ""
|
|
91
|
+
self.waveform_processing_mode = ""
|
|
92
|
+
self.error_category = ""
|
|
93
|
+
self.retryable = False
|
|
94
|
+
self.cancelled = False
|
|
95
|
+
self.planned_seconds = 0.0
|
|
96
|
+
self.elapsed_seconds = 0.0
|
|
97
|
+
self.completed_cycles = 0
|
|
98
|
+
self.target_cycles = 0
|
|
99
|
+
self.successful_reads = 0
|
|
100
|
+
self.late_reads = 0
|
|
101
|
+
self.instant_ai_complete_waveforms = 0
|
|
102
|
+
self.instant_ai_planned_duration_seconds = 0.0
|
|
103
|
+
self.instant_ai_actual_duration_seconds = 0.0
|
|
104
|
+
self.instant_ai_late_reads = 0
|
|
105
|
+
self.instant_ai_interpolated_bins = 0
|
|
106
|
+
self.wave = []
|
|
107
|
+
self.time_line = []
|
|
108
|
+
self.estimate = []
|
|
109
|
+
|
|
110
|
+
self.tau = 0.0
|
|
111
|
+
self.tau_b = 0.0
|
|
112
|
+
self.w = 0.0
|
|
113
|
+
self.b = 0.0
|
|
114
|
+
self.loss = 0.0
|
|
115
|
+
self.maximum = 0.0
|
|
116
|
+
self.minimum = 0.0
|
|
117
|
+
self.invalid_field = ''
|
|
118
|
+
|
|
119
|
+
self.v0 = 0.0
|
|
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
|
|
130
|
+
|
|
131
|
+
self.mock_tau = 0.0
|
|
132
|
+
self.mock_v0 = 0.0
|
|
133
|
+
self.mock_v_inf = 0.0
|
|
134
|
+
self.mock_noise = 0.0
|
|
135
|
+
|
|
136
|
+
self.rho = 0.0
|
|
137
|
+
self.miu = 0.0
|
|
138
|
+
self.carrier = 0.0
|
|
139
|
+
self.corrected_rho = 0.0
|
|
140
|
+
self.corrected_miu = 0.0
|
|
141
|
+
self.corrected_carrier = 0.0
|
|
142
|
+
|
|
143
|
+
def process(self):
|
|
144
|
+
self.time_line = [self.wave_interval * i for i in range(len(self.wave))]
|
|
145
|
+
|
|
146
|
+
if self.success:
|
|
147
|
+
tau, w, b = self.tau, self.w, self.b
|
|
148
|
+
self.estimate = [w * math.exp(t / -tau) + b for t in self.time_line]
|
|
149
|
+
|
|
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
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def chinese_message(self) -> str:
|
|
164
|
+
try:
|
|
165
|
+
return self.ErrorMessageMapper[self.message]
|
|
166
|
+
except Exception as e:
|
|
167
|
+
return self.message
|
sample/sample.exe
ADDED
|
Binary file
|
sample/sample.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import math
|
|
3
|
+
import shutil
|
|
4
|
+
import sys
|
|
5
|
+
import threading
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import Process
|
|
9
|
+
from . import Result
|
|
10
|
+
from .protocol import parse_assignments, ProtocolError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_SOURCE_ROOT = Path(os.path.realpath(os.path.abspath(__file__))).parent.parent
|
|
14
|
+
_SOURCE_BUILD_LOCK = threading.Lock()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _existing_file(*parts):
|
|
18
|
+
try:
|
|
19
|
+
candidate = Path(parts[0]).joinpath(*parts[1:])
|
|
20
|
+
except (TypeError, ValueError):
|
|
21
|
+
return None
|
|
22
|
+
try:
|
|
23
|
+
if candidate.is_file():
|
|
24
|
+
return str(candidate.resolve())
|
|
25
|
+
except OSError:
|
|
26
|
+
return None
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _is_source_checkout():
|
|
31
|
+
return all((
|
|
32
|
+
_existing_file(_SOURCE_ROOT, 'SConstruct'),
|
|
33
|
+
_existing_file(_SOURCE_ROOT, 'setup.py'),
|
|
34
|
+
_existing_file(_SOURCE_ROOT, 'sample', 'sample.py'),
|
|
35
|
+
))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Sampler:
|
|
39
|
+
@property
|
|
40
|
+
def execution_path(self) -> str:
|
|
41
|
+
# keep the historical current-working-directory override first
|
|
42
|
+
execution_path = _existing_file('sample.exe')
|
|
43
|
+
if execution_path:
|
|
44
|
+
return execution_path
|
|
45
|
+
|
|
46
|
+
# try to use (or build) cpp_build/sample.exe in a source checkout
|
|
47
|
+
if _is_source_checkout():
|
|
48
|
+
execution_path = _existing_file(_SOURCE_ROOT, 'cpp_build', 'sample.exe')
|
|
49
|
+
if execution_path:
|
|
50
|
+
return execution_path
|
|
51
|
+
with _SOURCE_BUILD_LOCK:
|
|
52
|
+
execution_path = _existing_file(_SOURCE_ROOT, 'cpp_build', 'sample.exe')
|
|
53
|
+
if not execution_path:
|
|
54
|
+
if os.system('cd {} && scons'.format(_SOURCE_ROOT)) != 0:
|
|
55
|
+
raise self.Error("Compile C++ Driver Error")
|
|
56
|
+
execution_path = _existing_file(_SOURCE_ROOT, 'cpp_build', 'sample.exe')
|
|
57
|
+
if execution_path:
|
|
58
|
+
return execution_path
|
|
59
|
+
|
|
60
|
+
# Installed releases keep the matching runtime inside the Python package.
|
|
61
|
+
execution_path = _existing_file(_SOURCE_ROOT, 'sample', 'sample.exe')
|
|
62
|
+
if execution_path:
|
|
63
|
+
return execution_path
|
|
64
|
+
|
|
65
|
+
# try the Python/frozen executable directory
|
|
66
|
+
try:
|
|
67
|
+
executable_directory = Path(sys.executable).parent
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
executable_directory = None
|
|
70
|
+
execution_path = _existing_file(executable_directory, 'sample.exe')
|
|
71
|
+
if execution_path:
|
|
72
|
+
return execution_path
|
|
73
|
+
|
|
74
|
+
# try the environment root used by venv/uv data-file installs
|
|
75
|
+
execution_path = _existing_file(sys.prefix, 'sample.exe')
|
|
76
|
+
if execution_path:
|
|
77
|
+
return execution_path
|
|
78
|
+
|
|
79
|
+
# try to find sample.exe in system path when release
|
|
80
|
+
try:
|
|
81
|
+
path_driver = shutil.which("sample.exe")
|
|
82
|
+
except (OSError, ValueError):
|
|
83
|
+
path_driver = None
|
|
84
|
+
execution_path = _existing_file(path_driver)
|
|
85
|
+
if execution_path:
|
|
86
|
+
return execution_path
|
|
87
|
+
|
|
88
|
+
raise self.Error('Sample Driver Not Found')
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def p(self) -> Process:
|
|
92
|
+
p = getattr(self, 'p_', None)
|
|
93
|
+
if p is not None:
|
|
94
|
+
return p
|
|
95
|
+
|
|
96
|
+
p = Process(self.execution_path)
|
|
97
|
+
setattr(self, 'p_', p)
|
|
98
|
+
return p
|
|
99
|
+
|
|
100
|
+
def communicate(self, command: str, executor: Process = None) -> Result:
|
|
101
|
+
result = Result()
|
|
102
|
+
try:
|
|
103
|
+
executor = executor or self.p
|
|
104
|
+
executor.write_line(command)
|
|
105
|
+
lines = executor.read_until('EOF')
|
|
106
|
+
if lines:
|
|
107
|
+
known_types = {
|
|
108
|
+
field: type(value) for field, value in result.__dict__.items() if not field.startswith("_")
|
|
109
|
+
}
|
|
110
|
+
assignments = parse_assignments(lines, known_types=known_types)
|
|
111
|
+
if "wave" in assignments:
|
|
112
|
+
for value in assignments["wave"]:
|
|
113
|
+
if type(value) is not float:
|
|
114
|
+
raise ProtocolError("unexpected field type", lines, field_name="wave")
|
|
115
|
+
for field, value in assignments.items():
|
|
116
|
+
setattr(result, field, value)
|
|
117
|
+
result._v_inf_reported = "v_inf" in assignments
|
|
118
|
+
except ProtocolError as error:
|
|
119
|
+
raise self.Error(str(error))
|
|
120
|
+
except Exception as e:
|
|
121
|
+
result.error = True
|
|
122
|
+
result.message = str(e)
|
|
123
|
+
raise self.Error("{}: {}".format(result.message, result.chinese_message))
|
|
124
|
+
|
|
125
|
+
if result.error:
|
|
126
|
+
raise self.Error("{}: {}".format(result.message, result.chinese_message))
|
|
127
|
+
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def is_measuring(self) -> bool:
|
|
132
|
+
return self.communicate('is_measuring').measuring
|
|
133
|
+
|
|
134
|
+
def measure(self, number_of_waveforms: int, emitting_frequency: float, auto_mode: bool = False,
|
|
135
|
+
instant_ai_frequency_threshold: float = 0.0,
|
|
136
|
+
instant_ai_target_points_per_waveform: int = 100,
|
|
137
|
+
instant_ai_max_reliable_polling_hz: float = 10.0,
|
|
138
|
+
waveform_processing_mode: str = "threshold_accumulation") -> Result:
|
|
139
|
+
command = "to_measure {} {:.12g} {}".format(number_of_waveforms, emitting_frequency, auto_mode)
|
|
140
|
+
if (instant_ai_frequency_threshold != 0.0 or instant_ai_target_points_per_waveform != 100 or
|
|
141
|
+
instant_ai_max_reliable_polling_hz != 10.0 or waveform_processing_mode != "threshold_accumulation"):
|
|
142
|
+
command += " {:.12g} {} {:.12g}".format(
|
|
143
|
+
instant_ai_frequency_threshold, instant_ai_target_points_per_waveform,
|
|
144
|
+
instant_ai_max_reliable_polling_hz)
|
|
145
|
+
if waveform_processing_mode != "threshold_accumulation":
|
|
146
|
+
command += " {}".format(waveform_processing_mode)
|
|
147
|
+
return self.communicate(command)
|
|
148
|
+
|
|
149
|
+
def dump(self, filename: str, number_of_waveforms: int, emitting_frequency: float,
|
|
150
|
+
auto_mode: bool = False, instant_ai_frequency_threshold: float = 0.0,
|
|
151
|
+
instant_ai_target_points_per_waveform: int = 100,
|
|
152
|
+
instant_ai_max_reliable_polling_hz: float = 10.0,
|
|
153
|
+
waveform_processing_mode: str = "threshold_accumulation") -> Result:
|
|
154
|
+
command = "to_dump {} {} {:.12g} {}".format(filename, number_of_waveforms, emitting_frequency, auto_mode)
|
|
155
|
+
if (instant_ai_frequency_threshold != 0.0 or instant_ai_target_points_per_waveform != 100 or
|
|
156
|
+
instant_ai_max_reliable_polling_hz != 10.0 or waveform_processing_mode != "threshold_accumulation"):
|
|
157
|
+
command += " {:.12g} {} {:.12g}".format(
|
|
158
|
+
instant_ai_frequency_threshold, instant_ai_target_points_per_waveform,
|
|
159
|
+
instant_ai_max_reliable_polling_hz)
|
|
160
|
+
if waveform_processing_mode != "threshold_accumulation":
|
|
161
|
+
command += " {}".format(waveform_processing_mode)
|
|
162
|
+
return self.communicate(command)
|
|
163
|
+
|
|
164
|
+
def process(self, filename: str, waveform_processing_mode: str = None) -> Result:
|
|
165
|
+
command = "to_process {}".format(filename)
|
|
166
|
+
if waveform_processing_mode is not None:
|
|
167
|
+
command += " {}".format(waveform_processing_mode)
|
|
168
|
+
return self.communicate(command)
|
|
169
|
+
|
|
170
|
+
def sampling_progress(self) -> Result:
|
|
171
|
+
return self.communicate("to_sampling_progress")
|
|
172
|
+
|
|
173
|
+
def cancel_sampling(self) -> Result:
|
|
174
|
+
return self.communicate("to_cancel_sampling")
|
|
175
|
+
|
|
176
|
+
def set_sampler(self, sampler_name: str) -> Result:
|
|
177
|
+
return self.communicate("set_sampler {}".format(sampler_name))
|
|
178
|
+
|
|
179
|
+
def get_sampler(self) -> Result:
|
|
180
|
+
return self.communicate("get_sampler")
|
|
181
|
+
|
|
182
|
+
def set_sampler_value(self, key: str, value: float) -> Result:
|
|
183
|
+
return self.communicate("set_sampler_value {} {}".format(key, value))
|
|
184
|
+
|
|
185
|
+
def get_sampler_value(self, key: str) -> Result:
|
|
186
|
+
return self.communicate("get_sampler_value {}".format(key))
|
|
187
|
+
|
|
188
|
+
def query(self) -> Result:
|
|
189
|
+
result = self.communicate("to_query")
|
|
190
|
+
if result.success:
|
|
191
|
+
invalid_field = self._first_non_finite_field(result)
|
|
192
|
+
if invalid_field:
|
|
193
|
+
result.success = False
|
|
194
|
+
result.message = "sampling_result_not_finite"
|
|
195
|
+
result.error_category = "state"
|
|
196
|
+
result.retryable = True
|
|
197
|
+
result.invalid_field = invalid_field
|
|
198
|
+
result.wave = []
|
|
199
|
+
result.time_line = []
|
|
200
|
+
result.estimate = []
|
|
201
|
+
result.v0 = 0.0
|
|
202
|
+
result.v_inf = 0.0
|
|
203
|
+
result.v_inf_valid = False
|
|
204
|
+
return result
|
|
205
|
+
result.process()
|
|
206
|
+
if not result.success and result.message == "success":
|
|
207
|
+
result.message = "error_undefined"
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def _first_non_finite_field(result: Result):
|
|
212
|
+
for field in ("maximum", "minimum", "sampling_interval", "wave_interval", "tau", "w", "b", "loss",
|
|
213
|
+
"v_inf", "cycle_maximum", "cycle_minimum", "cycle_vmax", "cycle_vmin", "cycle_vpp",
|
|
214
|
+
"cycle_vtop", "cycle_vbase"):
|
|
215
|
+
if not math.isfinite(getattr(result, field)):
|
|
216
|
+
return field
|
|
217
|
+
for index, value in enumerate(result.wave):
|
|
218
|
+
if not math.isfinite(value):
|
|
219
|
+
return "wave[{}]".format(index)
|
|
220
|
+
return ""
|
|
221
|
+
|
|
222
|
+
class Error(RuntimeError):
|
|
223
|
+
pass
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
sampler = Sampler()
|