quelware-tools 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.
File without changes
File without changes
@@ -0,0 +1,222 @@
1
+ """quel-echo-test: emit a pulse on a TRX port and capture the echoed response."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from typing import Annotated
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import typer
10
+ from quelware_client.client import create_quelware_client
11
+ from quelware_client.client.helpers.sequencer import Sequencer
12
+ from quelware_client.core import QuelwareClient
13
+ from quelware_client.core.instrument_driver import (
14
+ create_instrument_driver_fixed_timeline,
15
+ )
16
+ from quelware_core.entities import directives
17
+ from quelware_core.entities.directives import CaptureMode
18
+ from quelware_core.entities.instrument import (
19
+ FixedTimelineProfile,
20
+ InstrumentDefinition,
21
+ InstrumentInfo,
22
+ InstrumentMode,
23
+ InstrumentRole,
24
+ )
25
+ from quelware_core.entities.port import PortRole
26
+ from quelware_core.entities.resource import ResourceCategory, ResourceId
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ _ALIAS = "echo_test"
31
+ _HALF_BW_HZ = 2.5e6
32
+
33
+
34
+ async def _resolve_port(qc: QuelwareClient, port_id: str | None) -> ResourceId:
35
+ if port_id is not None:
36
+ return ResourceId(port_id)
37
+ for info in await qc.list_resource_infos():
38
+ if info.category is not ResourceCategory.PORT:
39
+ continue
40
+ port_info = await qc.get_port_info(info.id)
41
+ if port_info.role is PortRole.TRANSCEIVER:
42
+ return info.id
43
+ raise RuntimeError("no TRX port found on any reachable unit")
44
+
45
+
46
+ async def _deploy(
47
+ qc: QuelwareClient,
48
+ port_id: ResourceId,
49
+ frequency_hz: float,
50
+ loopback: bool,
51
+ ) -> tuple[ResourceId, InstrumentInfo]:
52
+ role = (
53
+ InstrumentRole.TRANSCEIVER_LOOPBACK if loopback else InstrumentRole.TRANSCEIVER
54
+ )
55
+ async with qc.create_session([port_id]) as session:
56
+ definition = InstrumentDefinition(
57
+ alias=_ALIAS,
58
+ mode=InstrumentMode.FIXED_TIMELINE,
59
+ role=role,
60
+ profile=FixedTimelineProfile(
61
+ frequency_range_min=frequency_hz - _HALF_BW_HZ,
62
+ frequency_range_max=frequency_hz + _HALF_BW_HZ,
63
+ ),
64
+ )
65
+ inst_infos = await session.deploy_instruments(port_id, definitions=[definition])
66
+ inst_info = inst_infos[0]
67
+ logger.info("Deployed instrument: %s", inst_info.id)
68
+ return inst_info.id, inst_info
69
+
70
+
71
+ async def _run(
72
+ qc: QuelwareClient,
73
+ inst_id: ResourceId,
74
+ inst_info: InstrumentInfo,
75
+ frequency_hz: float,
76
+ pulse_len_samples: int,
77
+ capture_start_offset_samples: int,
78
+ capture_len_samples: int,
79
+ shot_gap_ns: float,
80
+ iterations: int,
81
+ ) -> np.ndarray:
82
+ sampling_period_ns = inst_info.config.sampling_period_fs * 1e-6
83
+ pulse_len_ns = pulse_len_samples * sampling_period_ns
84
+ capture_delay_ns = capture_start_offset_samples * sampling_period_ns
85
+ capture_len_ns = capture_len_samples * sampling_period_ns
86
+ timeline_len_ns = max(pulse_len_ns, capture_delay_ns + capture_len_ns) + shot_gap_ns
87
+
88
+ async with qc.create_session([inst_id], ttl_ms=10000) as session:
89
+ driver = create_instrument_driver_fixed_timeline(session, inst_info)
90
+ seq = Sequencer(
91
+ default_sampling_period_ns=sampling_period_ns,
92
+ enforce_sample_grid=True,
93
+ )
94
+ seq.bind(
95
+ alias=_ALIAS,
96
+ sampling_period_fs=inst_info.config.sampling_period_fs,
97
+ step_samples=inst_info.config.timeline_step_samples,
98
+ )
99
+ seq.register_waveform("rect_pulse", np.ones(pulse_len_samples, dtype=complex))
100
+ seq.add_event(_ALIAS, "rect_pulse", start_offset_ns=0.0)
101
+ seq.add_capture_window(
102
+ _ALIAS,
103
+ "capture",
104
+ start_offset_ns=capture_delay_ns,
105
+ length_ns=capture_len_ns,
106
+ )
107
+ seq.extend_length_ns(timeline_len_ns)
108
+ seq.set_iterations(iterations)
109
+
110
+ await driver.initialize()
111
+ await driver.apply(
112
+ [
113
+ directives.SetFrequency(hz=frequency_hz),
114
+ directives.SetCaptureMode(mode=CaptureMode.AVERAGED_WAVEFORM),
115
+ seq.export_set_fixed_timeline_directive(_ALIAS),
116
+ ]
117
+ )
118
+ await session.trigger([inst_id])
119
+ result = await driver.fetch_result()
120
+
121
+ return result.iq_waveform_result["capture"][0].iq_array
122
+
123
+
124
+ def _plot(iq: np.ndarray, save_path: str | None) -> None:
125
+ fig, ax = plt.subplots()
126
+ ax.plot(iq.real, label="I")
127
+ ax.plot(iq.imag, label="Q")
128
+ ax.set_xlabel("sample")
129
+ ax.set_ylabel("amplitude")
130
+ ax.legend()
131
+ ax.set_title("echo test capture (averaged waveform)")
132
+ if save_path is None:
133
+ plt.show()
134
+ else:
135
+ fig.savefig(save_path)
136
+ logger.info("saved plot to %s", save_path)
137
+ plt.close(fig)
138
+
139
+
140
+ def _entry(
141
+ host: Annotated[str, typer.Argument(help="server host")],
142
+ port_id: Annotated[
143
+ str | None,
144
+ typer.Option(
145
+ help="port resource id (e.g. quel3-01-a28:trx_p00p01); "
146
+ "pick first reachable TRX port if omitted"
147
+ ),
148
+ ] = None,
149
+ port: Annotated[int, typer.Option(help="server port")] = 50051,
150
+ iterations: Annotated[
151
+ int, typer.Option("--iter", help="number of pulses to average")
152
+ ] = 1000,
153
+ pulse_len_samples: Annotated[
154
+ int, typer.Option(help="pulse length in samples")
155
+ ] = 400,
156
+ capture_start_offset: Annotated[
157
+ int, typer.Option(help="capture window offset from pulse start, in samples")
158
+ ] = 500,
159
+ capture_len_samples: Annotated[
160
+ int, typer.Option(help="capture window length in samples")
161
+ ] = 1000,
162
+ freq_hz: Annotated[float, typer.Option(help="carrier frequency in Hz")] = 6.0e9,
163
+ shot_gap_ns: Annotated[
164
+ float, typer.Option(help="gap between successive pulses, in ns")
165
+ ] = 100_000.0,
166
+ loopback: Annotated[bool, typer.Option(help="route TX into RX internally")] = False,
167
+ iq_plot: Annotated[bool, typer.Option(help="show I/Q time-series plot")] = False,
168
+ iq_plot_png: Annotated[
169
+ str | None,
170
+ typer.Option(
171
+ metavar="PATH",
172
+ help="save I/Q plot as PNG to PATH instead of displaying",
173
+ ),
174
+ ] = None,
175
+ log_level: Annotated[str, typer.Option(help="DEBUG|INFO|WARNING|ERROR")] = "INFO",
176
+ ) -> None:
177
+ """Emit a pulse on a TRX port and capture the echoed averaged response."""
178
+ logging.basicConfig(
179
+ level=getattr(logging, log_level),
180
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
181
+ )
182
+
183
+ async def _main() -> None:
184
+ qc = create_quelware_client(host, port)
185
+ async with qc:
186
+ resolved_port_id = await _resolve_port(qc, port_id)
187
+ logger.info("using TRX port: %s", resolved_port_id)
188
+ inst_id, inst_info = await _deploy(
189
+ qc, resolved_port_id, frequency_hz=freq_hz, loopback=loopback
190
+ )
191
+ iq = await _run(
192
+ qc,
193
+ inst_id,
194
+ inst_info,
195
+ frequency_hz=freq_hz,
196
+ pulse_len_samples=pulse_len_samples,
197
+ capture_start_offset_samples=capture_start_offset,
198
+ capture_len_samples=capture_len_samples,
199
+ shot_gap_ns=shot_gap_ns,
200
+ iterations=iterations,
201
+ )
202
+ print(f"captured {len(iq)} samples (mean |iq| = {np.abs(iq).mean():.6f})")
203
+ if iq_plot_png is not None:
204
+ _plot(iq, iq_plot_png)
205
+ elif iq_plot:
206
+ _plot(iq, None)
207
+
208
+ try:
209
+ asyncio.run(_main())
210
+ except Exception as exc:
211
+ # gRPC errors carry a human message; fall back to the repr otherwise
212
+ message = getattr(exc, "message", None) or str(exc)
213
+ typer.echo(f"error: {message}", err=True)
214
+ raise typer.Exit(code=1) from exc
215
+
216
+
217
+ def cli() -> None:
218
+ typer.run(_entry)
219
+
220
+
221
+ if __name__ == "__main__":
222
+ cli()
@@ -0,0 +1,88 @@
1
+ """quel-tone-test: per-port tone test for a QuEL-3 unit.
2
+
3
+ Puts the unit's monitor into loopback and, for every tx/trx port, emits a tone
4
+ and checks it appears in the monitor capture. Intended as a post-update health
5
+ check against a running system. Requires an admin PAT and an idle unit; the
6
+ monitor is restored to ``open`` on the way out. Exits non-zero if any port fails.
7
+ """
8
+
9
+ import asyncio
10
+ import logging
11
+ from typing import Annotated
12
+
13
+ import typer
14
+ from quelware_client.client import create_quelware_client
15
+ from quelware_core.entities.unit import UnitLabel
16
+
17
+ from quelware_tools.diagnostics import run_tone_test
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def _entry(
23
+ host: Annotated[str, typer.Argument(help="manager host")],
24
+ unit: Annotated[str, typer.Option(help="unit label to check")],
25
+ port: Annotated[int, typer.Option(help="manager port")] = 50051,
26
+ pat: Annotated[
27
+ str | None,
28
+ typer.Option(help="admin PAT; defaults to the configured PAT"),
29
+ ] = None,
30
+ target_port: Annotated[
31
+ str | None,
32
+ typer.Option(help="restrict to one port id (default: all tx/trx ports)"),
33
+ ] = None,
34
+ tx_hz: Annotated[float, typer.Option(help="transmit frequency in Hz")] = 5.1e9,
35
+ mon_hz: Annotated[float, typer.Option(help="monitor frequency in Hz")] = 5.0e9,
36
+ threshold_db: Annotated[
37
+ float, typer.Option(help="minimum tone peak-to-median in dB to pass")
38
+ ] = 20.0,
39
+ cw_length_ns: Annotated[
40
+ float, typer.Option(help="length of the emitted CW in ns")
41
+ ] = 4000.0,
42
+ capture_start_ns: Annotated[
43
+ float, typer.Option(help="capture window start offset in ns")
44
+ ] = 1000.0,
45
+ capture_length_ns: Annotated[
46
+ float, typer.Option(help="capture window length in ns")
47
+ ] = 800.0,
48
+ iterations: Annotated[int, typer.Option(help="capture averaging iterations")] = 1,
49
+ log_level: Annotated[str, typer.Option(help="DEBUG|INFO|WARNING|ERROR")] = "INFO",
50
+ ) -> None:
51
+ """Run the per-port tone test on one QuEL-3 unit."""
52
+ logging.basicConfig(
53
+ level=getattr(logging, log_level, logging.INFO),
54
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
55
+ )
56
+
57
+ async def _main() -> None:
58
+ qc = create_quelware_client(host, port, pat=pat)
59
+ async with qc:
60
+ report = await run_tone_test(
61
+ qc,
62
+ UnitLabel(unit),
63
+ port=target_port,
64
+ tx_hz=tx_hz,
65
+ mon_hz=mon_hz,
66
+ min_peak_to_median_db=threshold_db,
67
+ cw_length_ns=cw_length_ns,
68
+ capture_start_ns=capture_start_ns,
69
+ capture_length_ns=capture_length_ns,
70
+ iterations=iterations,
71
+ )
72
+ for r in report.results:
73
+ print(f"[{'PASS' if r.passed else 'FAIL'}] {r.port_id}: {r.detail}")
74
+ passed_n = sum(r.passed for r in report.results)
75
+ status = "PASS" if report.passed else "FAIL"
76
+ print(f"[{status}] {report.unit_label}: {passed_n}/{len(report.results)} ports")
77
+ if not report.passed:
78
+ raise typer.Exit(code=1)
79
+
80
+ asyncio.run(_main())
81
+
82
+
83
+ def cli() -> None:
84
+ typer.run(_entry)
85
+
86
+
87
+ if __name__ == "__main__":
88
+ cli()
@@ -0,0 +1,130 @@
1
+ """quel-unit-config: inspect or change QuEL-3 unit configuration controls.
2
+
3
+ ``show`` prints each control's current and allowed values; ``set`` applies one
4
+ or more ``KEY=VALUE`` controls. Setting needs an admin PAT, an idle unit (no
5
+ deployed instruments), and locks on every port of the unit, so it is a
6
+ maintenance-window operation. Keys are opaque -- discover them with ``show``.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ from collections.abc import Coroutine
12
+ from typing import Annotated, Any
13
+
14
+ import typer
15
+ from quelware_client.client import create_quelware_client
16
+ from quelware_client.core import QuelwareClient
17
+ from quelware_core.entities.resource import ResourceCategory, ResourceId
18
+ from quelware_core.entities.unit import UnitLabel
19
+
20
+ app = typer.Typer(add_completion=False, help="Show or set QuEL-3 unit configuration.")
21
+
22
+
23
+ @app.command()
24
+ def show(
25
+ host: Annotated[str, typer.Argument(help="manager host")],
26
+ unit: Annotated[str, typer.Option(help="unit label")],
27
+ port: Annotated[int, typer.Option(help="manager port")] = 50051,
28
+ pat: Annotated[
29
+ str | None, typer.Option(help="PAT; defaults to the configured PAT")
30
+ ] = None,
31
+ as_json: Annotated[bool, typer.Option("--json", help="emit JSON")] = False,
32
+ ) -> None:
33
+ """Show a unit's configuration controls."""
34
+
35
+ async def _main() -> None:
36
+ qc = create_quelware_client(host, port, pat=pat)
37
+ async with qc:
38
+ cfg = await qc.get_unit_configuration(UnitLabel(unit))
39
+ if as_json:
40
+ doc = {
41
+ s.key: {"current": s.current_value, "allowed": list(s.allowed_values)}
42
+ for s in cfg.supported
43
+ }
44
+ print(json.dumps(doc, indent=2))
45
+ else:
46
+ for s in cfg.supported:
47
+ allowed = ", ".join(s.allowed_values)
48
+ print(f"{s.key}: {s.current_value} (allowed: {allowed})")
49
+
50
+ _run(_main())
51
+
52
+
53
+ @app.command("set")
54
+ def set_(
55
+ host: Annotated[str, typer.Argument(help="manager host")],
56
+ controls: Annotated[
57
+ list[str], typer.Argument(help="controls to apply as KEY=VALUE")
58
+ ],
59
+ unit: Annotated[str, typer.Option(help="unit label")],
60
+ port: Annotated[int, typer.Option(help="manager port")] = 50051,
61
+ pat: Annotated[
62
+ str | None, typer.Option(help="admin PAT; defaults to the configured PAT")
63
+ ] = None,
64
+ discard_instruments: Annotated[
65
+ bool,
66
+ typer.Option(
67
+ "--discard-instruments",
68
+ help="discard all instruments on the unit before configuring",
69
+ ),
70
+ ] = False,
71
+ ) -> None:
72
+ """Set KEY=VALUE controls on a unit (admin PAT, idle unit)."""
73
+ parsed = _parse_controls(controls)
74
+
75
+ async def _main() -> None:
76
+ qc = create_quelware_client(host, port, pat=pat)
77
+ async with qc:
78
+ port_ids = await _unit_port_ids(qc, UnitLabel(unit))
79
+ if not port_ids:
80
+ raise RuntimeError(f"no ports found for unit '{unit}'")
81
+ async with qc.create_session(port_ids) as session:
82
+ if discard_instruments:
83
+ for port_id in port_ids:
84
+ await session.discard_instruments(port_id)
85
+ result = await session.configure_unit(UnitLabel(unit), parsed)
86
+ for key, value in result.items():
87
+ print(f"{key}: {value}")
88
+
89
+ _run(_main())
90
+
91
+
92
+ def _parse_controls(pairs: list[str]) -> dict[str, str]:
93
+ controls: dict[str, str] = {}
94
+ for pair in pairs:
95
+ key, sep, value = pair.partition("=")
96
+ if not sep or not key:
97
+ raise typer.BadParameter(f"expected KEY=VALUE, got {pair!r}")
98
+ controls[key] = value
99
+ return controls
100
+
101
+
102
+ async def _unit_port_ids(
103
+ client: QuelwareClient, unit_label: UnitLabel
104
+ ) -> list[ResourceId]:
105
+ prefix = f"{unit_label}:"
106
+ return [
107
+ r.id
108
+ for r in await client.list_resource_infos()
109
+ if r.category == ResourceCategory.PORT and str(r.id).startswith(prefix)
110
+ ]
111
+
112
+
113
+ def _run(coro: Coroutine[Any, Any, None]) -> None:
114
+ try:
115
+ asyncio.run(coro)
116
+ except typer.Exit:
117
+ raise
118
+ except Exception as exc:
119
+ # gRPC errors carry a human message; fall back to the repr otherwise
120
+ message = getattr(exc, "message", None) or str(exc)
121
+ typer.echo(f"error: {message}", err=True)
122
+ raise typer.Exit(code=1) from exc
123
+
124
+
125
+ def cli() -> None:
126
+ app()
127
+
128
+
129
+ if __name__ == "__main__":
130
+ cli()
@@ -0,0 +1,15 @@
1
+ from ._tone import ToneResult, detect_tone, top_peaks
2
+ from .tone_test import (
3
+ PortToneResult,
4
+ ToneTestReport,
5
+ run_tone_test,
6
+ )
7
+
8
+ __all__ = [
9
+ "PortToneResult",
10
+ "ToneResult",
11
+ "ToneTestReport",
12
+ "detect_tone",
13
+ "run_tone_test",
14
+ "top_peaks",
15
+ ]
@@ -0,0 +1,93 @@
1
+ from dataclasses import dataclass
2
+
3
+ import numpy as np
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class ToneResult:
8
+ """Outcome of looking for a single expected tone in a captured IQ trace."""
9
+
10
+ expected_hz: float
11
+ measured_hz: float
12
+ peak_to_median_db: float
13
+ within_tolerance: bool
14
+ above_threshold: bool
15
+
16
+ @property
17
+ def ok(self) -> bool:
18
+ return self.within_tolerance and self.above_threshold
19
+
20
+
21
+ def detect_tone(
22
+ iq: np.ndarray,
23
+ sample_rate_hz: float,
24
+ expected_hz: float,
25
+ *,
26
+ freq_tol_hz: float,
27
+ min_peak_to_median_db: float,
28
+ ) -> ToneResult:
29
+ """Locate the dominant tone in a complex IQ trace and grade it.
30
+
31
+ The trace is expected to contain a single tone (the transmitted signal seen
32
+ through the internal loopback). The dominant FFT bin gives the measured
33
+ frequency; the peak's height over the spectrum's median gives a crude SNR.
34
+ The tone passes when it sits within ``freq_tol_hz`` of ``expected_hz`` and
35
+ rises at least ``min_peak_to_median_db`` above the noise floor.
36
+
37
+ Args:
38
+ iq: Captured complex samples.
39
+ sample_rate_hz: Sample rate of ``iq``.
40
+ expected_hz: Baseband frequency the tone should appear at (the transmit
41
+ frequency down-converted by the capturing mixer).
42
+ freq_tol_hz: Allowed deviation of the measured tone from ``expected_hz``.
43
+ min_peak_to_median_db: Minimum peak-to-median magnitude, in dB.
44
+ """
45
+ samples = np.asarray(iq)
46
+ if samples.ndim != 1 or samples.size == 0:
47
+ raise ValueError("iq must be a non-empty 1-D array")
48
+
49
+ spectrum = np.abs(np.fft.fftshift(np.fft.fft(samples)))
50
+ freqs = np.fft.fftshift(np.fft.fftfreq(samples.size, d=1.0 / sample_rate_hz))
51
+
52
+ peak_idx = int(np.argmax(spectrum))
53
+ measured_hz = float(freqs[peak_idx])
54
+ peak = float(spectrum[peak_idx])
55
+ median = float(np.median(spectrum))
56
+ peak_to_median_db = (
57
+ 20.0 * float(np.log10(peak / median)) if median > 0.0 else float("inf")
58
+ )
59
+
60
+ return ToneResult(
61
+ expected_hz=expected_hz,
62
+ measured_hz=measured_hz,
63
+ peak_to_median_db=peak_to_median_db,
64
+ within_tolerance=abs(measured_hz - expected_hz) <= freq_tol_hz,
65
+ above_threshold=peak_to_median_db >= min_peak_to_median_db,
66
+ )
67
+
68
+
69
+ def top_peaks(
70
+ iq: np.ndarray, sample_rate_hz: float, count: int = 5
71
+ ) -> list[tuple[float, float]]:
72
+ """Return ``(frequency_hz, db_over_median)`` for the strongest spectral bins.
73
+
74
+ Diagnostic aid: shows where the captured energy actually sits, independent
75
+ of any expected frequency. Adjacent bins of one tone may appear together.
76
+ """
77
+ samples = np.asarray(iq)
78
+ spectrum = np.abs(np.fft.fftshift(np.fft.fft(samples)))
79
+ freqs = np.fft.fftshift(np.fft.fftfreq(samples.size, d=1.0 / sample_rate_hz))
80
+ median = float(np.median(spectrum))
81
+ order = np.argsort(spectrum)[::-1][:count]
82
+ return [
83
+ (
84
+ float(freqs[i]),
85
+ 20.0 * float(np.log10(spectrum[i] / median))
86
+ if median > 0.0
87
+ else float("inf"),
88
+ )
89
+ for i in order
90
+ ]
91
+
92
+
93
+ __all__ = ["ToneResult", "detect_tone", "top_peaks"]
@@ -0,0 +1,350 @@
1
+ """Per-port tone test for a live QuEL-3 system.
2
+
3
+ Drives the public client SDK against an already-running manager + edge server
4
+ (reachable via ``client``, using an admin PAT) to confirm the internal signal
5
+ path is healthy: it puts the unit's monitor into loopback and, for every
6
+ tx/trx port, emits a long CW tone and checks that the tone appears in a monitor
7
+ capture taken from inside the CW. Capturing well inside a long emission makes
8
+ the check robust to the (unknown) loopback + digital-pipeline delay. The
9
+ monitor is always restored to ``open`` before returning, even on failure.
10
+
11
+ This targets a real (or fidelity-simulating) backend; the model-agnostic fake
12
+ worker returns no signal, so a passing fidelity result only means something
13
+ against real hardware or the device mock. It requires an idle unit (no deployed
14
+ instruments) and admin privileges, so it is a maintenance-window operation --
15
+ e.g. a health check after an on-site software update.
16
+ """
17
+
18
+ import logging
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+ from quelware_client.client.helpers.sequencer import Sequencer
23
+ from quelware_client.core import QuelwareClient
24
+ from quelware_client.core.instrument_driver import (
25
+ create_instrument_driver_fixed_timeline,
26
+ )
27
+ from quelware_core.entities.directives import (
28
+ CaptureMode,
29
+ SetCaptureMode,
30
+ SetFrequency,
31
+ )
32
+ from quelware_core.entities.instrument import (
33
+ FixedTimelineProfile,
34
+ InstrumentDefinition,
35
+ InstrumentInfo,
36
+ InstrumentMode,
37
+ InstrumentRole,
38
+ )
39
+ from quelware_core.entities.resource import ResourceCategory, ResourceId
40
+ from quelware_core.entities.unit import UnitLabel
41
+
42
+ from ._tone import ToneResult, detect_tone, top_peaks
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # QuEL-3-specific: the monitor is a unit control keyed "quel3.monitor.mode"; the
47
+ # emitting ports are named trx*/tx*, and the monitor capture port ends ":mon".
48
+ _MONITOR_MODE_KEY = "quel3.monitor.mode"
49
+ _MON_PORT_SUFFIX = ":mon"
50
+ _EMIT_PORT_PREFIXES = ("trx", "tx")
51
+
52
+ _FS_PER_SEC = 10**15
53
+ _PROFILE_HALF_HZ = 200e6
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class PortToneResult:
58
+ port_id: str
59
+ passed: bool
60
+ detail: str
61
+ tone: ToneResult | None = None
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class ToneTestReport:
66
+ unit_label: str
67
+ passed: bool
68
+ results: tuple[PortToneResult, ...]
69
+
70
+
71
+ async def run_tone_test(
72
+ client: QuelwareClient,
73
+ unit_label: UnitLabel,
74
+ *,
75
+ port: str | None = None,
76
+ tx_hz: float = 5.1e9,
77
+ mon_hz: float = 5.0e9,
78
+ min_peak_to_median_db: float = 20.0,
79
+ cw_length_ns: float = 4000.0,
80
+ capture_start_ns: float = 1000.0,
81
+ capture_length_ns: float = 800.0,
82
+ iterations: int = 1,
83
+ ) -> ToneTestReport:
84
+ """Run the per-port tone test on one unit.
85
+
86
+ Tests every tx/trx port by default, or just ``port`` when given. For each,
87
+ emits a ``cw_length_ns`` CW and captures ``capture_length_ns`` starting at
88
+ ``capture_start_ns`` (a margin past the path delay) from inside that CW.
89
+
90
+ Preconditions: the unit is idle (no instruments) and ``client`` was built
91
+ with an admin PAT (configuring the monitor needs the CONFIGURE_UNIT
92
+ capability). The monitor is restored to ``open`` before returning, even on
93
+ failure.
94
+ """
95
+ cleanup_ports: list[ResourceId] = []
96
+ try:
97
+ logger.info("setting monitor to loopback on %s", unit_label)
98
+ async with client.create_session(await _port_ids(client)) as session:
99
+ await session.configure_unit(unit_label, {_MONITOR_MODE_KEY: "loopback"})
100
+
101
+ mon_port = await _monitor_port(client)
102
+ emit_ports = [ResourceId(port)] if port else await _emit_ports(client)
103
+ emit_ports.sort(key=str)
104
+ cleanup_ports = [*emit_ports, mon_port]
105
+ logger.info(
106
+ "monitor loopback enabled; mon=%s, testing %d emit port(s)",
107
+ mon_port,
108
+ len(emit_ports),
109
+ )
110
+
111
+ expected_hz = tx_hz - mon_hz
112
+ freq_tol_hz = 1e9 / capture_length_ns # one FFT bin (1 / capture length)
113
+
114
+ results: list[PortToneResult] = []
115
+ for emit_port in emit_ports:
116
+ try:
117
+ results.append(
118
+ await _check_port(
119
+ client,
120
+ emit_port,
121
+ mon_port,
122
+ tx_freq_hz=tx_hz,
123
+ mon_freq_hz=mon_hz,
124
+ expected_hz=expected_hz,
125
+ freq_tol_hz=freq_tol_hz,
126
+ min_peak_to_median_db=min_peak_to_median_db,
127
+ cw_length_ns=cw_length_ns,
128
+ capture_start_ns=capture_start_ns,
129
+ capture_length_ns=capture_length_ns,
130
+ iterations=iterations,
131
+ )
132
+ )
133
+ except Exception as exc:
134
+ logger.exception("error testing %s", emit_port)
135
+ results.append(PortToneResult(str(emit_port), False, f"error: {exc}"))
136
+ passed = bool(results) and all(r.passed for r in results)
137
+ return ToneTestReport(str(unit_label), passed, tuple(results))
138
+ finally:
139
+ await _restore_monitor_open(client, unit_label, cleanup_ports)
140
+
141
+
142
+ async def _check_port(
143
+ client: QuelwareClient,
144
+ emit_port: ResourceId,
145
+ mon_port: ResourceId,
146
+ *,
147
+ tx_freq_hz: float,
148
+ mon_freq_hz: float,
149
+ expected_hz: float,
150
+ freq_tol_hz: float,
151
+ min_peak_to_median_db: float,
152
+ cw_length_ns: float,
153
+ capture_start_ns: float,
154
+ capture_length_ns: float,
155
+ iterations: int,
156
+ ) -> PortToneResult:
157
+ logger.info(
158
+ "testing %s -> monitor (tx=%.6g Hz, expected baseband=%.6g Hz)",
159
+ emit_port,
160
+ tx_freq_hz,
161
+ expected_hz,
162
+ )
163
+ captured, sample_rate_hz = await _emit_and_capture(
164
+ client,
165
+ emit_port,
166
+ mon_port,
167
+ tx_freq_hz=tx_freq_hz,
168
+ mon_freq_hz=mon_freq_hz,
169
+ cw_length_ns=cw_length_ns,
170
+ capture_start_ns=capture_start_ns,
171
+ capture_length_ns=capture_length_ns,
172
+ iterations=iterations,
173
+ )
174
+ if abs(expected_hz) > sample_rate_hz / 2:
175
+ logger.warning(
176
+ " %s baseband %.4g Hz beyond Nyquist %.4g Hz (Fs=%.4g); tx/mon too far",
177
+ emit_port,
178
+ expected_hz,
179
+ sample_rate_hz / 2,
180
+ sample_rate_hz,
181
+ )
182
+ logger.info(
183
+ " %s capture: Fs=%.4g Hz, N=%d, top peaks=%s",
184
+ emit_port,
185
+ sample_rate_hz,
186
+ captured.size,
187
+ [
188
+ (f"{f / 1e6:.1f} MHz", f"{db:.1f} dB")
189
+ for f, db in top_peaks(captured, sample_rate_hz)
190
+ ],
191
+ )
192
+ tone = detect_tone(
193
+ captured,
194
+ sample_rate_hz,
195
+ expected_hz=expected_hz,
196
+ freq_tol_hz=freq_tol_hz,
197
+ min_peak_to_median_db=min_peak_to_median_db,
198
+ )
199
+ detail = (
200
+ f"tone at {tone.measured_hz:.3e} Hz (expected {tone.expected_hz:.3e}); "
201
+ f"{tone.peak_to_median_db:.1f} dB over noise"
202
+ )
203
+ logger.info(" %s: %s (%s)", emit_port, "PASS" if tone.ok else "FAIL", detail)
204
+ return PortToneResult(str(emit_port), tone.ok, detail, tone)
205
+
206
+
207
+ async def _port_ids(client: QuelwareClient) -> list[ResourceId]:
208
+ rinfos = await client.list_resource_infos()
209
+ return [r.id for r in rinfos if r.category == ResourceCategory.PORT]
210
+
211
+
212
+ def _port_name(port_id: ResourceId) -> str:
213
+ return str(port_id).rsplit(":", 1)[-1]
214
+
215
+
216
+ async def _emit_ports(client: QuelwareClient) -> list[ResourceId]:
217
+ ports = [
218
+ p
219
+ for p in await _port_ids(client)
220
+ if _port_name(p).startswith(_EMIT_PORT_PREFIXES)
221
+ ]
222
+ if not ports:
223
+ raise RuntimeError("no tx/trx ports found on the unit")
224
+ return ports
225
+
226
+
227
+ async def _monitor_port(client: QuelwareClient) -> ResourceId:
228
+ mon = next(
229
+ (p for p in await _port_ids(client) if str(p).endswith(_MON_PORT_SUFFIX)), None
230
+ )
231
+ if mon is None:
232
+ raise RuntimeError("monitor port not found after enabling loopback")
233
+ return mon
234
+
235
+
236
+ async def _emit_and_capture(
237
+ client: QuelwareClient,
238
+ emit_port: ResourceId,
239
+ mon_port: ResourceId,
240
+ *,
241
+ tx_freq_hz: float,
242
+ mon_freq_hz: float,
243
+ cw_length_ns: float,
244
+ capture_start_ns: float,
245
+ capture_length_ns: float,
246
+ iterations: int,
247
+ ) -> tuple[np.ndarray, float]:
248
+ tx_def = InstrumentDefinition(
249
+ alias="tone_test_tx",
250
+ mode=InstrumentMode.FIXED_TIMELINE,
251
+ role=InstrumentRole.TRANSMITTER,
252
+ profile=FixedTimelineProfile(
253
+ tx_freq_hz - _PROFILE_HALF_HZ, tx_freq_hz + _PROFILE_HALF_HZ
254
+ ),
255
+ )
256
+ mon_def = InstrumentDefinition(
257
+ alias="tone_test_mon",
258
+ mode=InstrumentMode.FIXED_TIMELINE,
259
+ role=InstrumentRole.RECEIVER,
260
+ profile=FixedTimelineProfile(
261
+ mon_freq_hz - _PROFILE_HALF_HZ, mon_freq_hz + _PROFILE_HALF_HZ
262
+ ),
263
+ )
264
+
265
+ async with client.create_session([emit_port, mon_port]) as deploy_session:
266
+ (tx_info,) = await deploy_session.deploy_instruments(emit_port, [tx_def])
267
+ (mon_info,) = await deploy_session.deploy_instruments(mon_port, [mon_def])
268
+
269
+ async with client.create_session([tx_info.id, mon_info.id]) as drive_session:
270
+ tx_driver = create_instrument_driver_fixed_timeline(drive_session, tx_info)
271
+ mon_driver = create_instrument_driver_fixed_timeline(drive_session, mon_info)
272
+
273
+ tx_directive, mon_directive = _build_directives(
274
+ tx_info,
275
+ mon_info,
276
+ cw_length_ns=cw_length_ns,
277
+ capture_start_ns=capture_start_ns,
278
+ capture_length_ns=capture_length_ns,
279
+ iterations=iterations,
280
+ )
281
+ await tx_driver.apply(SetFrequency(hz=tx_freq_hz))
282
+ await tx_driver.apply(tx_directive)
283
+
284
+ await mon_driver.apply(
285
+ [
286
+ SetFrequency(hz=mon_freq_hz),
287
+ SetCaptureMode(mode=CaptureMode.AVERAGED_WAVEFORM),
288
+ ]
289
+ )
290
+ await mon_driver.apply(mon_directive)
291
+
292
+ await drive_session.trigger([tx_info.id, mon_info.id])
293
+ result = await mon_driver.fetch_result()
294
+
295
+ captured = np.asarray(result.iq_waveform_result["cap"][0].iq_array)
296
+ return captured, _FS_PER_SEC / mon_info.config.sampling_period_fs
297
+
298
+
299
+ def _build_directives(
300
+ tx_info: InstrumentInfo,
301
+ mon_info: InstrumentInfo,
302
+ *,
303
+ cw_length_ns: float,
304
+ capture_start_ns: float,
305
+ capture_length_ns: float,
306
+ iterations: int,
307
+ ):
308
+ """Emit and capture share one timeline, so bind both to a single sequencer.
309
+
310
+ The tx CW sets the shared length; the mon capture window lands inside it.
311
+ """
312
+ tx_period_ns = tx_info.config.sampling_period_fs / 1_000_000
313
+ seq = Sequencer(default_sampling_period_ns=tx_period_ns, enforce_sample_grid=False)
314
+ for inst in (tx_info, mon_info):
315
+ seq.bind(
316
+ inst.definition.alias,
317
+ inst.config.sampling_period_fs,
318
+ inst.config.timeline_step_samples,
319
+ )
320
+ samples = max(1, round(cw_length_ns / tx_period_ns))
321
+ seq.register_waveform("cw", np.full(samples, 0.5 + 0.0j, dtype=complex))
322
+ seq.add_event(tx_info.definition.alias, "cw", 0.0)
323
+ seq.add_capture_window(
324
+ mon_info.definition.alias, "cap", capture_start_ns, capture_length_ns
325
+ )
326
+ seq.set_iterations(iterations)
327
+ return (
328
+ seq.export_set_fixed_timeline_directive(tx_info.definition.alias),
329
+ seq.export_set_fixed_timeline_directive(mon_info.definition.alias),
330
+ )
331
+
332
+
333
+ async def _restore_monitor_open(
334
+ client: QuelwareClient,
335
+ unit_label: UnitLabel,
336
+ deployed_ports: list[ResourceId],
337
+ ) -> None:
338
+ async with client.create_session(await _port_ids(client)) as session:
339
+ for port_id in deployed_ports:
340
+ logger.info("discarding instruments on %s", port_id)
341
+ await session.discard_instruments(port_id)
342
+ logger.info("restoring monitor to open on %s", unit_label)
343
+ await session.configure_unit(unit_label, {_MONITOR_MODE_KEY: "open"})
344
+
345
+
346
+ __all__ = [
347
+ "PortToneResult",
348
+ "ToneTestReport",
349
+ "run_tone_test",
350
+ ]
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: quelware-tools
3
+ Version: 0.1.0
4
+ Summary: Command-line tools and diagnostics for QuEL systems.
5
+ Project-URL: Repository, https://github.com/quel-inc/quelware-client
6
+ Project-URL: Documentation, https://quel-inc.github.io/quelware-client/
7
+ Project-URL: Changelog, https://github.com/quel-inc/quelware-client/blob/main/quelware-tools/CHANGELOG.md
8
+ Author-email: quelware Authors <opensource@quel-inc.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: numpy
13
+ Requires-Dist: quelware-client>=0.5.0
14
+ Requires-Dist: quelware-core>=0.5.0
15
+ Requires-Dist: typer>=0.21.1
16
+ Provides-Extra: plot
17
+ Requires-Dist: matplotlib; extra == 'plot'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # quelware-tools
21
+
22
+ Command-line tools and diagnostics for QuEL systems, built on `quelware-client`.
23
+
24
+ They run against an already-running manager + edge server (endpoint + PAT); they
25
+ start nothing themselves.
26
+
27
+ ## Commands
28
+
29
+ - `quel-tone-test` — per-port tone test: put the unit's monitor into loopback,
30
+ emit a tone on every tx/trx port, and check it appears in the monitor capture.
31
+ A post-update health check. Exits non-zero if any port fails.
32
+ - `quel-unit-config` — `show` / `set` a unit's configuration controls.
33
+ `set` needs an admin PAT and an idle unit.
34
+ - `quel-echo-test` — emit a pulse on a TRX port and capture the echoed response
35
+ (optionally plotting the I/Q trace; install with the `plot` extra).
36
+
37
+ ## Install
38
+
39
+ ```
40
+ pip install quelware-tools # tools only
41
+ pip install "quelware-tools[plot]" # + matplotlib for quel-echo-test plots
42
+ ```
@@ -0,0 +1,13 @@
1
+ quelware_tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ quelware_tools/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ quelware_tools/cli/echo_test.py,sha256=S_mRedMALbQ12ANUOHSVBuJRDhG5t0NavDdYnkj8Hb0,7760
4
+ quelware_tools/cli/tone_test.py,sha256=qhJHDN0q8R5fHd-oFIUlAbTZUkRyYpAK-JRE0iH1MiM,3208
5
+ quelware_tools/cli/unit_config.py,sha256=A0d9BUhxeMnVWP3jPk7apuzDbRpnG8hgI6dNvR0S4-c,4393
6
+ quelware_tools/diagnostics/__init__.py,sha256=MtCJYdJuXtBTtI3T7LisfutabvUY1NOauHeEvwsj6as,274
7
+ quelware_tools/diagnostics/_tone.py,sha256=a5dgVJ6oNFFmxYy104J1oQxWFDq9paWlyfeoUSaHmf0,3140
8
+ quelware_tools/diagnostics/tone_test.py,sha256=FnDpxIHRseT96EmpvhlE-6TYgS03F43sg8ggrjmVdfw,11951
9
+ quelware_tools-0.1.0.dist-info/METADATA,sha256=VtwHKiaFiz5o9t8BlLtl0avxcz7yXeKpSP_tFliG8JQ,1593
10
+ quelware_tools-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
11
+ quelware_tools-0.1.0.dist-info/entry_points.txt,sha256=1zZuwrJ04FRaD_aW_-a1YrsBgHMktHQI1vVj39-xekw,172
12
+ quelware_tools-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ quelware_tools-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ quel-echo-test = quelware_tools.cli.echo_test:cli
3
+ quel-tone-test = quelware_tools.cli.tone_test:cli
4
+ quel-unit-config = quelware_tools.cli.unit_config:cli
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.