Ind* indicators: CSV/series support on all 250 kinds
Transpile the C component ind_* function for every kind into lightgui/xframe/indicators.py (tools/transpile_indicators.py), verified 250/250 against the C++ reference dump (<=1e-9, NaN patterns included). IndicatorWidget gains the StockWidget series API (set_series, populate, get_series, add_point, clear, load_csv, item_count, get_lines) and draws the computed lines (14-colour palette, NaN gaps, dots for isolated marker points) with the demo series as fallback. Docs in docs/indicators-data.md; tests/test_indicators_csv.py (17 tests, golden spot values vs the C++ reference); Xvfb shots via tools/ind_csv_shots.py.
This commit is contained in:
1 parent
d0f430f88c
commit
3b67cbf9de
6 files changed
+7447
-1
No files matched your search
@@ -0,0 +1,219 @@
|
|||||||
|
# Ind* indicator widgets: plotting your own data
|
||||||
|
|
||||||
|
The 250 Ind* indicators -- RSI, MACD, Bollinger Bands, ADX, Guppy
|
||||||
|
MMA, the whole palette -- all draw from the same data model as the
|
||||||
|
Stock chart widgets, and all take real data the same way:
|
||||||
|
`set_series()` for bars you already hold in Python, or `load_csv()`
|
||||||
|
for an OHLCV file. Each kind recomputes its own lines from the loaded
|
||||||
|
bars; nothing is hard-coded to the demo series any more.
|
||||||
|
|
||||||
|
This is the companion to `stock-charts-data.md`: same bar model, same
|
||||||
|
CSV spec, same series API (single slot -- indicators have no
|
||||||
|
second/third symbol). Read that doc for the CSV format details; this
|
||||||
|
doc covers what is different about indicators.
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
|
||||||
|
A bar is a 5-tuple of floats:
|
||||||
|
|
||||||
|
```python
|
||||||
|
(open, high, low, close, volume)
|
||||||
|
```
|
||||||
|
|
||||||
|
That is the whole model. There is no timestamp on a bar: the x-axis
|
||||||
|
plots bar index (0, 1, 2, ...), like the C demo. The CSV loader
|
||||||
|
parses and validates the date column but does not store it.
|
||||||
|
|
||||||
|
## Template data: what ships inside each widget
|
||||||
|
|
||||||
|
With no data fed in, every indicator renders the built-in
|
||||||
|
deterministic demo series, so the designer and the generated example
|
||||||
|
draw immediately:
|
||||||
|
|
||||||
|
- `lightgui.xframe.stock.demo_series(n=250, seed=42)` -- an exact
|
||||||
|
port of C `xframe::make_seeded_series(250)` (StockData.h): a
|
||||||
|
xorshift64* random walk starting at 100.0. Same `(n, seed)` gives
|
||||||
|
identical bars on every run.
|
||||||
|
|
||||||
|
## How the lines are computed
|
||||||
|
|
||||||
|
`lightgui/xframe/indicators.py` is generated, not hand-written: the
|
||||||
|
transpiler in `tools/transpile_indicators.py` translates the C
|
||||||
|
component `ind_*` function for each kind
|
||||||
|
(`widgets/components/Ind*/Ind*.h` in the C repo) into Python, one
|
||||||
|
function per kind, plus the shared helpers they call. The generated
|
||||||
|
module carries a `INDICATOR_INFO` registry per kind: which function
|
||||||
|
to call, whether it takes whole bars or closes, its default
|
||||||
|
parameters, and which of its outputs are plotted lines.
|
||||||
|
|
||||||
|
The transpiled code is numerically verified against the C++ reference:
|
||||||
|
all 250 kinds, on the seeded demo series, agree with the C++
|
||||||
|
component dump to within 1e-9 relative, including the NaN warm-up
|
||||||
|
patterns (see "Tests and screenshots" below). The Python port follows
|
||||||
|
the per-component `ind_*` functions, not the separate StockChart
|
||||||
|
overlay registry in the C repo -- the two disagree systematically
|
||||||
|
(different warm-up and seeding), and the components are the ones the
|
||||||
|
widgets actually plot.
|
||||||
|
|
||||||
|
Most kinds plot one line. The multi-line kinds plot all of theirs:
|
||||||
|
|
||||||
|
| Kinds | Lines |
|
||||||
|
| --- | --- |
|
||||||
|
| MACD, Bollinger Bands, Keltner Channels, Donchian Channels, and other band/channel kinds | 2-3 (e.g. macd/signal/histogram, upper/middle/lower) |
|
||||||
|
| Guppy MMA | 12 (six fast + six slow EMAs) |
|
||||||
|
| Moving Average Ribbon | 6 |
|
||||||
|
| Klinger Volume Oscillator | 2 (KVO + signal) |
|
||||||
|
|
||||||
|
Line colours cycle through the 14-colour palette from the Rust
|
||||||
|
`xframe-indicators` `plot.rs` `PLOT_PALETTE` (blue, orange, purple,
|
||||||
|
teal, magenta, brown, green, red, steel blue, olive, grey, gold,
|
||||||
|
indigo, brick). Lines are polylines with gaps where the indicator has
|
||||||
|
no value yet (NaN warm-up). Pattern/marker kinds whose values are
|
||||||
|
isolated single-bar pivots (FractalUp/Down, ZigZag) draw those points
|
||||||
|
as filled dots -- a polyline alone would leave no mark.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
All of this lives on `IndicatorWidget` (`lightgui/xframe/core.py`),
|
||||||
|
mirroring the `StockWidget` API with a single series slot:
|
||||||
|
|
||||||
|
```python
|
||||||
|
widget.set_series(bars) # replace the series
|
||||||
|
widget.get_series() # bars currently plotted (a copy)
|
||||||
|
widget.populate(bars) # alias for set_series
|
||||||
|
widget.clear() # empty the series
|
||||||
|
widget.add_point(bar) # append one bar, return new count
|
||||||
|
widget.load_csv(path) # load an OHLCV CSV, return bar count
|
||||||
|
widget.item_count() # number of bars plotted
|
||||||
|
widget.get_lines(params=None) # plotted lines for the current series
|
||||||
|
```
|
||||||
|
|
||||||
|
- `bars` is a list of `(open, high, low, close, volume)` tuples/lists
|
||||||
|
of numbers, or dicts with `open`/`high`/`low`/`close`/`volume`
|
||||||
|
keys. Bad bars raise `ValueError` (same validation as the chart
|
||||||
|
widgets: wrong length, non-numeric, `high` below open/close, `low`
|
||||||
|
above open/close, negative volume).
|
||||||
|
- `set_series(None)` reverts to the built-in demo series.
|
||||||
|
- `clear()` empties the series; the widget then draws a "No data --
|
||||||
|
call set_series() or load_csv()" placeholder instead of lines until
|
||||||
|
`populate()` / `set_series()` refills it (or `set_series(None)`
|
||||||
|
restores the demo).
|
||||||
|
- `add_point()` appends to the series. If no own series was set yet
|
||||||
|
it starts a fresh series -- it does NOT extend the demo series.
|
||||||
|
- `get_lines()` returns the plotted lines for the current series: a
|
||||||
|
list of float lists, one value per bar, NaN where the indicator has
|
||||||
|
no value yet, in plot order. `params` overrides the kind's default
|
||||||
|
parameters positionally (e.g. `get_lines([7])` for RSI(7)).
|
||||||
|
Returns `[]` when the series was cleared. This is the same
|
||||||
|
computation the widget draws; use it in tests or in a generated
|
||||||
|
program that needs the numbers, not just the picture.
|
||||||
|
- Series data is runtime state only: it is NOT saved in `.fdj`
|
||||||
|
files, and it has no Inspector row. A project reloaded in the
|
||||||
|
designer shows the demo series again until the generated program
|
||||||
|
loads its data.
|
||||||
|
|
||||||
|
The compute functions are also usable directly, without a widget:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from lightgui.xframe import indicators
|
||||||
|
from lightgui.xframe.stock import demo_series, load_csv
|
||||||
|
|
||||||
|
bars = load_csv("prices.csv")
|
||||||
|
lines = indicators.compute_lines("IndRSI", bars) # [rsi]
|
||||||
|
macd = indicators.compute_lines("IndMACD", bars) # [macd, signal, hist]
|
||||||
|
indicators.indicator_names() # all 250 kinds, in palette order
|
||||||
|
```
|
||||||
|
|
||||||
|
`compute_lines(kind, bars, params=None)` takes OHLCV bars (or, for
|
||||||
|
the closes-only kinds, it extracts closes internally). The default
|
||||||
|
parameters are the ones the C smoke tests use for that kind.
|
||||||
|
|
||||||
|
## CSV format
|
||||||
|
|
||||||
|
Identical to the chart widgets: `load_csv(source)` in
|
||||||
|
`lightgui/xframe/stock.py`, `source` a path or a file-like object,
|
||||||
|
`date,open,high,low,close,volume` with an optional header matched by
|
||||||
|
name (aliases `timestamp`/`time`/`datetime`, `o`/`h`/`l`/`c`,
|
||||||
|
`vol`/`v`). See `stock-charts-data.md` for the full spec and
|
||||||
|
validation rules. A ready-made file lives in the repo:
|
||||||
|
`tests/data/ohlcv_30.csv` -- 30 weekday bars, 2026-01-05 to
|
||||||
|
2026-02-13, opening at 100.00 and closing at 95.71.
|
||||||
|
|
||||||
|
## Working example
|
||||||
|
|
||||||
|
A complete program: one window, one RSI indicator, CSV data. Run it
|
||||||
|
from the repo root:
|
||||||
|
|
||||||
|
```python
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Plot an OHLCV CSV file in an IndRSI indicator."""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
from lightgui.xframe import core # noqa: E402
|
||||||
|
|
||||||
|
widget = core.create("IndRSI", "rsi_001", 0, 0, 400, 300)
|
||||||
|
widget.load_csv("tests/data/ohlcv_30.csv")
|
||||||
|
print("bars:", widget.item_count())
|
||||||
|
print("rsi[29]:", widget.get_lines()[0][29])
|
||||||
|
|
||||||
|
# ... hand widget to a window/canvas as usual; it draws the RSI line
|
||||||
|
# for the loaded bars. Without load_csv it would draw the RSI of the
|
||||||
|
# built-in demo series instead.
|
||||||
|
```
|
||||||
|
|
||||||
|
Every committed example in `examples/ind*.py` draws its kind on the
|
||||||
|
demo series; adding one `widget.load_csv(...)` line after the
|
||||||
|
`create(...)` call (as `tools/ind_csv_shots.py` does) switches it to
|
||||||
|
file data.
|
||||||
|
|
||||||
|
## Clear / populate workflow
|
||||||
|
|
||||||
|
```python
|
||||||
|
widget.clear() # placeholder: "No data -- ..."
|
||||||
|
widget.populate(bars) # back to lines
|
||||||
|
widget.set_series(None) # back to the demo series
|
||||||
|
```
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
- **Warm-up:** most indicators need some bars before their first
|
||||||
|
finite value (RSI(14) from bar 14, Bollinger from bar 20, ADX from
|
||||||
|
bar 26). On a short file the lines start with NaNs -- that is the
|
||||||
|
indicator, not missing data. 36 of the 250 kinds need more than 30
|
||||||
|
bars for any finite value at all (multi-stage smoothing such as
|
||||||
|
TEMA/TRIX/KST, 52-bar Senkou Span B, Klinger slow EMA 55, Guppy
|
||||||
|
long leg 60); feed them a longer file.
|
||||||
|
- **Parameters:** the defaults are the C smoke-test parameters for
|
||||||
|
each kind. `get_lines(params)` overrides them positionally, but
|
||||||
|
there is no per-kind parameter editor on the widget yet -- the
|
||||||
|
values are not Inspector props.
|
||||||
|
- **One series per indicator:** unlike the multi-symbol charts, an
|
||||||
|
indicator has a single series slot; there is no second/third
|
||||||
|
symbol.
|
||||||
|
- **Series is runtime state only** (see API above): not saved in
|
||||||
|
`.fdj`, no Inspector row.
|
||||||
|
|
||||||
|
## Tests and screenshots
|
||||||
|
|
||||||
|
- `tests/test_indicators_csv.py` (17 tests): the series API
|
||||||
|
(set/get round-trip, `set_series(None)` restores the demo,
|
||||||
|
`add_point`, `clear`/`populate`, `item_count`, `load_csv` and its
|
||||||
|
error paths), golden spot values against the C++ reference (RSI,
|
||||||
|
MACD, Bollinger, SMA, EMA, ATR), a parameter override, load +
|
||||||
|
recompute for all 250 kinds on the demo series and the 30-bar CSV,
|
||||||
|
and rendering -- every kind draws demo and CSV data headless, the
|
||||||
|
CSV render differs from the demo render, a one-bar series draws,
|
||||||
|
and a cleared series draws the placeholder.
|
||||||
|
- `tools/transpile_indicators.py` -- the transpiler that generates
|
||||||
|
`lightgui/xframe/indicators.py` from the C repo. Its verification
|
||||||
|
pass (compare every kind's `compute_lines` output against the C++
|
||||||
|
component dump on the seeded demo series) must read **250 / 250
|
||||||
|
kinds match** before the generated module is committed.
|
||||||
|
- `tools/ind_csv_shots.py` -- Xvfb screenshots of all 250 kinds with
|
||||||
|
the 30-bar CSV loaded, each compared (ImageMagick RMSE) against its
|
||||||
|
template-data golden in `tools/visreg/goldens/`. A large RMSE means
|
||||||
|
the CSV data is what is plotted. Run from the repo root:
|
||||||
|
`python3 tools/ind_csv_shots.py`.
|
||||||
+215
-1
@@ -2020,10 +2020,223 @@ class ChartWidget(Widget):
|
|||||||
|
|
||||||
|
|
||||||
class IndicatorWidget(Widget):
|
class IndicatorWidget(Widget):
|
||||||
|
"""One of the 250 Ind* indicators (archetype Indicator).
|
||||||
|
|
||||||
|
Draws the indicator's computed lines from OHLCV bars. The bars
|
||||||
|
come from the widget's own series when set (``set_series`` /
|
||||||
|
``load_csv`` / ``populate``), else from the built-in deterministic
|
||||||
|
demo series -- the same fallback the StockWidget chart widgets
|
||||||
|
use. The series is runtime state only, never saved in .fdj.
|
||||||
|
|
||||||
|
The lines themselves are computed by
|
||||||
|
``lightgui.xframe.indicators.compute_lines`` (transpiled from the
|
||||||
|
C component ``ind_*`` functions; see tools/transpile_indicators.py
|
||||||
|
and lightgui/xframe/indicators.py), so every kind recomputes from
|
||||||
|
the loaded data instead of the built-in demo lines.
|
||||||
|
"""
|
||||||
|
|
||||||
ARCHETYPE = "Indicator"
|
ARCHETYPE = "Indicator"
|
||||||
|
|
||||||
|
# Plot palette: the 14 line colours from the Rust
|
||||||
|
# xframe-indicators plot.rs PLOT_PALETTE, in order. Line j of a
|
||||||
|
# kind uses _PLOT_PALETTE[j % 14].
|
||||||
|
_PLOT_PALETTE = (
|
||||||
|
(0.13, 0.35, 0.85), # blue
|
||||||
|
(0.95, 0.55, 0.10), # orange
|
||||||
|
(0.55, 0.25, 0.80), # purple
|
||||||
|
(0.00, 0.60, 0.60), # teal
|
||||||
|
(0.85, 0.20, 0.55), # magenta
|
||||||
|
(0.55, 0.35, 0.15), # brown
|
||||||
|
(0.20, 0.65, 0.25), # green
|
||||||
|
(0.80, 0.15, 0.15), # red
|
||||||
|
(0.10, 0.55, 0.80), # steel blue
|
||||||
|
(0.65, 0.65, 0.10), # olive
|
||||||
|
(0.35, 0.35, 0.35), # grey
|
||||||
|
(0.90, 0.70, 0.10), # gold
|
||||||
|
(0.25, 0.25, 0.70), # indigo
|
||||||
|
(0.60, 0.20, 0.20), # brick
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
# Own series: None means "use the built-in demo series";
|
||||||
|
# a list (possibly empty) is data the user fed in.
|
||||||
|
self._series = None
|
||||||
|
|
||||||
|
# --- data ingestion (mirrors StockWidget, single slot) --------------
|
||||||
|
def set_series(self, bars):
|
||||||
|
"""Replace the series this indicator computes from.
|
||||||
|
|
||||||
|
*bars* is a list of (open, high, low, close, volume) tuples
|
||||||
|
(or dicts with those keys), or None to revert to the built-in
|
||||||
|
demo series. The indicator recomputes its lines from the new
|
||||||
|
data on the next draw. Marks the widget dirty so the host
|
||||||
|
redraws.
|
||||||
|
"""
|
||||||
|
self._series = _stock_mod._validate_bars(bars)
|
||||||
|
self._mark_dirty()
|
||||||
|
|
||||||
|
def populate(self, bars):
|
||||||
|
"""Alias for ``set_series``: fill the indicator with *bars*.
|
||||||
|
|
||||||
|
The clear/populate pair: ``widget.clear()`` empties the
|
||||||
|
series, ``widget.populate(bars)`` (or ``set_series``) refills
|
||||||
|
it.
|
||||||
|
"""
|
||||||
|
self.set_series(bars)
|
||||||
|
|
||||||
|
def get_series(self):
|
||||||
|
"""The bars this indicator currently plots: the widget's own
|
||||||
|
series when set, else the built-in demo series. Returns a
|
||||||
|
copy, so callers cannot mutate the plotted data.
|
||||||
|
"""
|
||||||
|
return list(_ind_mod._bars(self))
|
||||||
|
|
||||||
|
def add_point(self, bar):
|
||||||
|
"""Append one (open, high, low, close, volume) bar to the
|
||||||
|
series and return the new bar count.
|
||||||
|
|
||||||
|
If no own series was set yet, this starts a fresh series
|
||||||
|
(it does NOT extend the demo series).
|
||||||
|
"""
|
||||||
|
bar = _stock_mod._validate_bars([bar], what="add_point")[0]
|
||||||
|
if self._series is None:
|
||||||
|
self._series = []
|
||||||
|
self._series.append(bar)
|
||||||
|
self._mark_dirty()
|
||||||
|
return len(self._series)
|
||||||
|
|
||||||
|
def clear(self):
|
||||||
|
"""Empty the series. A cleared widget draws the no-data
|
||||||
|
placeholder until ``populate`` / ``set_series`` refills it
|
||||||
|
(or ``set_series(None)`` restores the demo series).
|
||||||
|
"""
|
||||||
|
self._series = []
|
||||||
|
self._mark_dirty()
|
||||||
|
|
||||||
|
def load_csv(self, source):
|
||||||
|
"""Load OHLCV bars from a CSV file into this indicator.
|
||||||
|
|
||||||
|
*source* is a path or a file-like object; see
|
||||||
|
``lightgui.xframe.stock.load_csv`` for the format (the same
|
||||||
|
``date,open,high,low,close,volume`` spec the chart widgets
|
||||||
|
use). Returns the number of bars loaded. Raises ValueError
|
||||||
|
naming the offending row on bad data, and leaves the previous
|
||||||
|
series untouched in that case.
|
||||||
|
"""
|
||||||
|
bars = _stock_mod.load_csv(source)
|
||||||
|
self.set_series(bars)
|
||||||
|
return len(bars)
|
||||||
|
|
||||||
|
def item_count(self):
|
||||||
|
"""Number of bars this indicator currently plots."""
|
||||||
|
return len(_ind_mod._bars(self))
|
||||||
|
|
||||||
|
def get_lines(self, params=None):
|
||||||
|
"""The plotted lines for the current series, as a list of
|
||||||
|
float lists (one per bar, NaN where the indicator has no
|
||||||
|
value yet), in plot order. *params* overrides the kind's
|
||||||
|
default parameters positionally. An empty list means the
|
||||||
|
series was cleared; a kind this widget does not know returns
|
||||||
|
the panel fallback (no lines).
|
||||||
|
"""
|
||||||
|
kind = self._ind_kind()
|
||||||
|
if kind is None:
|
||||||
|
return []
|
||||||
|
bars = _ind_mod._bars(self)
|
||||||
|
if not bars:
|
||||||
|
return []
|
||||||
|
return _ind_mod.compute_lines(kind, bars, params)
|
||||||
|
|
||||||
|
def _ind_kind(self):
|
||||||
|
"""Registry name (``IndRSI``) for this widget's kind, or None
|
||||||
|
when the kind is not one of the 250 indicators."""
|
||||||
|
kind = self.kind
|
||||||
|
if kind in _ind_mod.INDICATOR_INFO:
|
||||||
|
return kind
|
||||||
|
if ("Ind" + kind) in _ind_mod.INDICATOR_INFO:
|
||||||
|
return "Ind" + kind
|
||||||
|
return None
|
||||||
|
|
||||||
def _draw(self, cr):
|
def _draw(self, cr):
|
||||||
_draw_panel(cr, self)
|
# A cleared series draws the no-data placeholder instead of
|
||||||
|
# lines: compute_lines would index into an empty series.
|
||||||
|
if self._series is not None and len(self._series) == 0:
|
||||||
|
_stock_mod._no_data(cr, self)
|
||||||
|
return
|
||||||
|
kind = self._ind_kind()
|
||||||
|
if kind is None:
|
||||||
|
_draw_panel(cr, self)
|
||||||
|
return
|
||||||
|
bars = _ind_mod._bars(self)
|
||||||
|
lines = _ind_mod.compute_lines(kind, bars)
|
||||||
|
_bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
||||||
|
_wtext(cr, self, self.pkind, self.width / 2, 16, size=12,
|
||||||
|
align="center", rgb=(0.4, 0.4, 0.4),
|
||||||
|
max_width=self.width - 12)
|
||||||
|
# Plot area below the header.
|
||||||
|
px, py = 6, 24
|
||||||
|
pw, ph = max(1, self.width - 12), max(1, self.height - 30)
|
||||||
|
n = len(bars)
|
||||||
|
if n == 0 or ph <= 0:
|
||||||
|
return
|
||||||
|
lo, hi = None, None
|
||||||
|
for values in lines:
|
||||||
|
for v in values:
|
||||||
|
if v is None or v != v:
|
||||||
|
continue
|
||||||
|
lo = v if lo is None else min(lo, v)
|
||||||
|
hi = v if hi is None else max(hi, v)
|
||||||
|
if lo is None:
|
||||||
|
return
|
||||||
|
if hi <= lo:
|
||||||
|
hi = lo + 1.0
|
||||||
|
pad = (hi - lo) * 0.05 or 0.5
|
||||||
|
lo -= pad
|
||||||
|
hi += pad
|
||||||
|
|
||||||
|
def _x(i):
|
||||||
|
return px + (i + 0.5) * pw / n
|
||||||
|
|
||||||
|
def _y(v):
|
||||||
|
return py + ph - (v - lo) / (hi - lo) * ph
|
||||||
|
|
||||||
|
for j, values in enumerate(lines):
|
||||||
|
colour = self._PLOT_PALETTE[j % len(self._PLOT_PALETTE)]
|
||||||
|
cr.save()
|
||||||
|
_rgb(cr, colour)
|
||||||
|
cr.set_line_width(2.0)
|
||||||
|
started = False
|
||||||
|
for i in range(min(n, len(values))):
|
||||||
|
v = values[i]
|
||||||
|
if v is None or v != v:
|
||||||
|
started = False
|
||||||
|
continue
|
||||||
|
if not started:
|
||||||
|
cr.move_to(_x(i), _y(v))
|
||||||
|
started = True
|
||||||
|
else:
|
||||||
|
cr.line_to(_x(i), _y(v))
|
||||||
|
cr.stroke()
|
||||||
|
cr.restore()
|
||||||
|
# Isolated finite points (pattern/marker kinds such as
|
||||||
|
# FractalUp/Down and ZigZag, whose values are single-bar
|
||||||
|
# pivots) would otherwise draw nothing: a move_to with no
|
||||||
|
# line_to leaves no mark. Draw them as filled dots.
|
||||||
|
cr.save()
|
||||||
|
_rgb(cr, colour)
|
||||||
|
for i in range(min(n, len(values))):
|
||||||
|
v = values[i]
|
||||||
|
if v is None or v != v:
|
||||||
|
continue
|
||||||
|
prev_nan = i == 0 or values[i - 1] is None \
|
||||||
|
or values[i - 1] != values[i - 1]
|
||||||
|
next_nan = i + 1 >= len(values) or values[i + 1] is None \
|
||||||
|
or values[i + 1] != values[i + 1]
|
||||||
|
if prev_nan and next_nan:
|
||||||
|
cr.arc(_x(i), _y(v), 3, 0, 2 * math.pi)
|
||||||
|
cr.fill()
|
||||||
|
cr.restore()
|
||||||
|
|
||||||
|
|
||||||
class InstrumentWidget(Widget):
|
class InstrumentWidget(Widget):
|
||||||
@@ -2428,6 +2641,7 @@ def is_known_kind(kind):
|
|||||||
_KIND_CLASSES = {}
|
_KIND_CLASSES = {}
|
||||||
|
|
||||||
from lightgui.xframe import stock as _stock_mod
|
from lightgui.xframe import stock as _stock_mod
|
||||||
|
from lightgui.xframe import indicators as _ind_mod
|
||||||
from lightgui.xframe import instruments as _inst_mod
|
from lightgui.xframe import instruments as _inst_mod
|
||||||
# Keyed by registry NAME (see lookup()): the Stock* names draw in
|
# Keyed by registry NAME (see lookup()): the Stock* names draw in
|
||||||
# StockWidget, the Inst* names in InstWidget. Everything else keeps
|
# StockWidget, the Inst* names in InstWidget. Everything else keeps
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,256 @@
|
|||||||
|
"""Ind* indicator data ingestion: CSV loading + set_series/clear/populate.
|
||||||
|
|
||||||
|
- ``IndicatorWidget.load_csv`` / ``set_series`` / ``get_series`` /
|
||||||
|
``add_point`` / ``clear`` / ``populate`` / ``item_count``: the same
|
||||||
|
series API (and the same ``date,open,high,low,close,volume`` CSV
|
||||||
|
spec) the StockWidget chart widgets got, but for the 250 Ind*
|
||||||
|
indicators.
|
||||||
|
- ``compute_lines``: every one of the 250 kinds recomputes its lines
|
||||||
|
from loaded OHLCV data without crashing (demo series and the 30-bar
|
||||||
|
CSV fixture), each line is one value per bar, and the loaded-data
|
||||||
|
lines differ from the demo lines. Spot values are golden-checked
|
||||||
|
against the C++ component reference (``ind_*`` functions on the
|
||||||
|
seeded demo series, seed 42); the full 250-kind cross-check lives
|
||||||
|
in tools/transpile_indicators.py's verification pass.
|
||||||
|
- Rendering: every kind draws CSV data headless without raising, the
|
||||||
|
CSV render differs from the demo render, a one-bar series draws,
|
||||||
|
and a cleared series draws the no-data placeholder.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import cairo
|
||||||
|
|
||||||
|
from lightgui.xframe import core
|
||||||
|
from lightgui.xframe import indicators as ind_mod
|
||||||
|
from lightgui.xframe import stock as stock_mod
|
||||||
|
|
||||||
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
CSV_PATH = os.path.join(REPO, "tests", "data", "ohlcv_30.csv")
|
||||||
|
|
||||||
|
KINDS = ind_mod.indicator_names()
|
||||||
|
|
||||||
|
# Golden spot values from the C++ component reference (ind_* on the
|
||||||
|
# seeded demo series, seed 42): (kind, line, bar, value).
|
||||||
|
GOLDEN = (
|
||||||
|
("IndRSI", 0, 25, 46.880370427479114),
|
||||||
|
("IndMACD", 0, 40, -0.7883630259220524),
|
||||||
|
("IndMACD", 1, 40, -0.7673869019079353),
|
||||||
|
("IndMACD", 2, 40, -0.02097612401411708),
|
||||||
|
("IndBollingerBands", 0, 40, 100.71938861058676),
|
||||||
|
("IndBollingerBands", 1, 40, 97.25597274343893),
|
||||||
|
("IndBollingerBands", 2, 40, 93.7925568762911),
|
||||||
|
("IndSMA", 0, 30, 98.70914778880885),
|
||||||
|
("IndEMA", 0, 30, 98.15064907635568),
|
||||||
|
("IndATR", 0, 30, 1.4632890946762565),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _make(name, width=400, height=300):
|
||||||
|
widget = core.create(name, name + "_001", 0, 0, width, height)
|
||||||
|
assert widget is not None, name
|
||||||
|
return widget
|
||||||
|
|
||||||
|
|
||||||
|
def _draw(widget):
|
||||||
|
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
|
||||||
|
widget.width + 4, widget.height + 4)
|
||||||
|
cr = cairo.Context(surface)
|
||||||
|
cr.set_source_rgb(1, 1, 1)
|
||||||
|
cr.paint()
|
||||||
|
widget.draw(cr)
|
||||||
|
return surface
|
||||||
|
|
||||||
|
|
||||||
|
def _png_bytes(surface):
|
||||||
|
buf = io.BytesIO()
|
||||||
|
surface.write_to_png(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _finite(values):
|
||||||
|
return [v for v in values if v is not None and v == v]
|
||||||
|
|
||||||
|
|
||||||
|
class TestIndicatorSeriesApi(unittest.TestCase):
|
||||||
|
def test_kinds(self):
|
||||||
|
self.assertEqual(len(KINDS), 250)
|
||||||
|
self.assertEqual(len(set(KINDS)), 250)
|
||||||
|
|
||||||
|
def test_demo_fallback(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
self.assertEqual(w.item_count(), 250)
|
||||||
|
self.assertEqual(len(w.get_series()), 250)
|
||||||
|
lines = w.get_lines()
|
||||||
|
self.assertEqual(len(lines), 1)
|
||||||
|
self.assertEqual(len(lines[0]), 250)
|
||||||
|
self.assertTrue(_finite(lines[0]))
|
||||||
|
|
||||||
|
def test_set_series_round_trip(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
bars = stock_mod.load_csv(CSV_PATH)
|
||||||
|
w.set_series(bars)
|
||||||
|
self.assertEqual(w.item_count(), 30)
|
||||||
|
self.assertEqual(w.get_series(), bars)
|
||||||
|
# get_series returns a copy: mutating it must not move the plot
|
||||||
|
got = w.get_series()
|
||||||
|
got.append(got[-1])
|
||||||
|
self.assertEqual(w.item_count(), 30)
|
||||||
|
|
||||||
|
def test_set_series_none_restores_demo(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
w.set_series(stock_mod.load_csv(CSV_PATH))
|
||||||
|
self.assertEqual(w.item_count(), 30)
|
||||||
|
w.set_series(None)
|
||||||
|
self.assertEqual(w.item_count(), 250)
|
||||||
|
|
||||||
|
def test_add_point(self):
|
||||||
|
w = _make("IndSMA")
|
||||||
|
w.set_series(stock_mod.load_csv(CSV_PATH))
|
||||||
|
self.assertEqual(w.add_point((100.0, 101.0, 99.0, 100.5, 1000.0)),
|
||||||
|
31)
|
||||||
|
self.assertEqual(w.item_count(), 31)
|
||||||
|
# No own series yet: starts fresh, does not extend the demo.
|
||||||
|
w2 = _make("IndSMA")
|
||||||
|
self.assertEqual(w2.add_point((100.0, 101.0, 99.0, 100.5, 1000.0)),
|
||||||
|
1)
|
||||||
|
self.assertEqual(w2.item_count(), 1)
|
||||||
|
|
||||||
|
def test_clear_populate(self):
|
||||||
|
w = _make("IndEMA")
|
||||||
|
w.set_series(stock_mod.load_csv(CSV_PATH))
|
||||||
|
w.clear()
|
||||||
|
self.assertEqual(w.item_count(), 0)
|
||||||
|
self.assertEqual(w.get_lines(), [])
|
||||||
|
w.populate(stock_mod.load_csv(CSV_PATH))
|
||||||
|
self.assertEqual(w.item_count(), 30)
|
||||||
|
self.assertTrue(_finite(w.get_lines()[0]))
|
||||||
|
|
||||||
|
def test_load_csv(self):
|
||||||
|
w = _make("IndMACD")
|
||||||
|
self.assertEqual(w.load_csv(CSV_PATH), 30)
|
||||||
|
self.assertEqual(w.item_count(), 30)
|
||||||
|
self.assertEqual(len(w.get_lines()), 3)
|
||||||
|
|
||||||
|
def test_load_csv_bad_data_leaves_series(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
before = w.get_series()
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
w.load_csv(io.StringIO("date,open,high,low,close,volume\n"
|
||||||
|
"2026-01-01,1,2,3,xx,5\n"))
|
||||||
|
self.assertEqual(w.get_series(), before)
|
||||||
|
|
||||||
|
def test_set_series_rejects_bad_bars(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
w.set_series([(1.0, 2.0, 3.0)]) # not a 5-tuple bar
|
||||||
|
|
||||||
|
def test_golden_values(self):
|
||||||
|
bars = stock_mod.demo_series()
|
||||||
|
for kind, line, bar, value in GOLDEN:
|
||||||
|
got = ind_mod.compute_lines(kind, bars)[line][bar]
|
||||||
|
self.assertAlmostEqual(got, value, places=9,
|
||||||
|
msg="%s line %d bar %d" % (kind, line, bar))
|
||||||
|
|
||||||
|
def test_params_override(self):
|
||||||
|
bars = stock_mod.demo_series()
|
||||||
|
default = ind_mod.compute_lines("IndRSI", bars)[0]
|
||||||
|
other = ind_mod.compute_lines("IndRSI", bars, [7])[0]
|
||||||
|
self.assertNotEqual(default, other)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAllKindsRecompute(unittest.TestCase):
|
||||||
|
def test_all_kinds_load_and_recompute(self):
|
||||||
|
demo = stock_mod.demo_series()
|
||||||
|
csv_bars = stock_mod.load_csv(CSV_PATH)
|
||||||
|
no_finite_csv = []
|
||||||
|
for kind in KINDS:
|
||||||
|
demo_lines = ind_mod.compute_lines(kind, demo)
|
||||||
|
self.assertTrue(demo_lines, kind)
|
||||||
|
for values in demo_lines:
|
||||||
|
self.assertEqual(len(values), 250, kind)
|
||||||
|
csv_lines = ind_mod.compute_lines(kind, csv_bars)
|
||||||
|
self.assertEqual(len(csv_lines), len(demo_lines), kind)
|
||||||
|
for values in csv_lines:
|
||||||
|
self.assertEqual(len(values), 30, kind)
|
||||||
|
# Loaded data must change the output (where the kind has
|
||||||
|
# any finite value on the short CSV at all).
|
||||||
|
if any(_finite(v) for v in csv_lines):
|
||||||
|
self.assertNotEqual(
|
||||||
|
[v for line in csv_lines for v in line],
|
||||||
|
[v for line in demo_lines[:len(csv_lines)]
|
||||||
|
for v in line[:30]], kind)
|
||||||
|
else:
|
||||||
|
no_finite_csv.append(kind)
|
||||||
|
# The kinds with no finite value on the 30-bar CSV are the
|
||||||
|
# long-warm-up family (multi-stage smoothing, 52-bar Senkou
|
||||||
|
# Span B, Klinger slow EMA 55, Guppy long leg 60, ...). Each
|
||||||
|
# of them must still produce finite values on the 250-bar
|
||||||
|
# demo series -- otherwise it would be a broken kind, not a
|
||||||
|
# warm-up.
|
||||||
|
self.assertLessEqual(len(no_finite_csv), 40,
|
||||||
|
sorted(no_finite_csv))
|
||||||
|
for kind in no_finite_csv:
|
||||||
|
demo_lines = ind_mod.compute_lines(kind, demo)
|
||||||
|
self.assertTrue(any(v == v for line in demo_lines
|
||||||
|
for v in line), kind)
|
||||||
|
|
||||||
|
def test_all_kinds_widget_api(self):
|
||||||
|
csv_bars = stock_mod.load_csv(CSV_PATH)
|
||||||
|
for kind in KINDS:
|
||||||
|
w = _make(kind)
|
||||||
|
self.assertEqual(w.item_count(), 250, kind)
|
||||||
|
w.load_csv(CSV_PATH)
|
||||||
|
self.assertEqual(w.item_count(), 30, kind)
|
||||||
|
lines = w.get_lines()
|
||||||
|
self.assertTrue(lines, kind)
|
||||||
|
for values in lines:
|
||||||
|
self.assertEqual(len(values), 30, kind)
|
||||||
|
w.clear()
|
||||||
|
self.assertEqual(w.item_count(), 0, kind)
|
||||||
|
self.assertEqual(w.get_lines(), [], kind)
|
||||||
|
w.set_series(csv_bars)
|
||||||
|
self.assertEqual(w.item_count(), 30, kind)
|
||||||
|
|
||||||
|
|
||||||
|
class TestIndicatorRendering(unittest.TestCase):
|
||||||
|
def test_all_kinds_draw_demo_and_csv(self):
|
||||||
|
for kind in KINDS:
|
||||||
|
w = _make(kind)
|
||||||
|
_draw(w) # demo series, must not raise
|
||||||
|
w.load_csv(CSV_PATH)
|
||||||
|
_draw(w) # loaded CSV data, must not raise
|
||||||
|
|
||||||
|
def test_csv_render_differs_from_demo(self):
|
||||||
|
same = []
|
||||||
|
for kind in KINDS:
|
||||||
|
w = _make(kind)
|
||||||
|
demo_png = _png_bytes(_draw(w))
|
||||||
|
w.load_csv(CSV_PATH)
|
||||||
|
csv_png = _png_bytes(_draw(w))
|
||||||
|
if demo_png == csv_png:
|
||||||
|
same.append(kind)
|
||||||
|
# A kind whose CSV lines are all NaN (long warm-up on 30 bars)
|
||||||
|
# draws the same empty plot as... no: the demo plot has lines,
|
||||||
|
# so every kind must differ. Report the stragglers if any.
|
||||||
|
self.assertEqual(same, [], same)
|
||||||
|
|
||||||
|
def test_one_bar_draws(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
w.set_series([(100.0, 101.0, 99.0, 100.5, 1000.0)])
|
||||||
|
_draw(w)
|
||||||
|
|
||||||
|
def test_cleared_draws_placeholder(self):
|
||||||
|
w = _make("IndRSI")
|
||||||
|
demo_png = _png_bytes(_draw(w))
|
||||||
|
w.clear()
|
||||||
|
cleared_png = _png_bytes(_draw(w))
|
||||||
|
self.assertNotEqual(demo_png, cleared_png)
|
||||||
|
w.populate(stock_mod.load_csv(CSV_PATH))
|
||||||
|
self.assertNotEqual(cleared_png, _png_bytes(_draw(w)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Screenshot every Ind* indicator widget with CSV data loaded.
|
||||||
|
|
||||||
|
Takes each committed example in examples/<slug>.py, injects a
|
||||||
|
``widget.load_csv(...)`` call into its _build_widgets(), runs it under
|
||||||
|
Xvfb, and screenshots the root window cropped to the example window
|
||||||
|
size -- the same render path as the pythondoc sweep (drive.py run_one)
|
||||||
|
and the visreg harness, so the shots are directly comparable to the
|
||||||
|
template-data goldens in tools/visreg/goldens/.
|
||||||
|
|
||||||
|
Usage (on hot_newyork, from the repo root):
|
||||||
|
python3 tools/ind_csv_shots.py [--out-dir DIR] [--workers N]
|
||||||
|
[--csv PATH] [Kind ...]
|
||||||
|
|
||||||
|
Writes <slug>.png per widget into the out dir (default
|
||||||
|
/opt/lightgui-docs/pythondoc/work/ind-csv-shots), plus report.json
|
||||||
|
with the ImageMagick RMSE of each CSV shot against its template golden
|
||||||
|
(large = the CSV data really is what is plotted).
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, REPO)
|
||||||
|
|
||||||
|
from lightgui.xframe import indicators as ind_mod # noqa: E402
|
||||||
|
|
||||||
|
KINDS = ind_mod.indicator_names()
|
||||||
|
DEFAULT_OUT = "/opt/lightgui-docs/pythondoc/work/ind-csv-shots"
|
||||||
|
DEFAULT_CSV = os.path.join(REPO, "tests", "data", "ohlcv_30.csv")
|
||||||
|
|
||||||
|
|
||||||
|
def win_size(kind):
|
||||||
|
from lightgui.xframe.palette import PALETTE
|
||||||
|
entry = next(e for e in PALETTE if e.name == kind)
|
||||||
|
return (max(entry.default_w + 32, 220),
|
||||||
|
max(entry.default_h + 32, 120))
|
||||||
|
|
||||||
|
|
||||||
|
def patched_example(kind, csv_path, tmpdir):
|
||||||
|
"""Copy the committed example, inject load_csv, return path."""
|
||||||
|
slug = kind.lower()
|
||||||
|
src = os.path.join(REPO, "examples", slug + ".py")
|
||||||
|
with open(src, encoding="utf-8") as f:
|
||||||
|
code = f.read()
|
||||||
|
lines = [" widget.load_csv(%r)" % csv_path]
|
||||||
|
anchor = " widget = create('%s', " % kind
|
||||||
|
out_lines = []
|
||||||
|
injected = False
|
||||||
|
for line in code.split("\n"):
|
||||||
|
out_lines.append(line)
|
||||||
|
if not injected and line.startswith(anchor):
|
||||||
|
out_lines.extend(lines)
|
||||||
|
injected = True
|
||||||
|
if not injected:
|
||||||
|
raise RuntimeError("create() line not found in %s" % src)
|
||||||
|
path = os.path.join(tmpdir, slug + "_csv.py")
|
||||||
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
|
f.write("\n".join(out_lines))
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_x(display, timeout=15):
|
||||||
|
sock = "/tmp/.X11-unix/X%d" % display
|
||||||
|
t0 = time.time()
|
||||||
|
while time.time() - t0 < timeout:
|
||||||
|
if os.path.exists(sock):
|
||||||
|
return True
|
||||||
|
time.sleep(0.2)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def crop_to_window(path, kind):
|
||||||
|
from PIL import Image
|
||||||
|
w, h = win_size(kind)
|
||||||
|
im = Image.open(path)
|
||||||
|
im.crop((0, 0, min(w, im.width), min(h, im.height))).save(path)
|
||||||
|
|
||||||
|
|
||||||
|
def rmse_pct(golden, shot):
|
||||||
|
"""Normalised RMSE % between two PNGs (ImageMagick compare)."""
|
||||||
|
proc = subprocess.run(
|
||||||
|
["compare", "-metric", "RMSE", golden, shot, "null:"],
|
||||||
|
capture_output=True, text=True, timeout=60)
|
||||||
|
text = (proc.stderr or proc.stdout).strip()
|
||||||
|
m = re.search(r"\(([\d.]+)\)", text)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
return round(float(m.group(1)) * 100, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def run_one(kind, display, csv_path, outdir, tmpdir):
|
||||||
|
slug = kind.lower()
|
||||||
|
result = {"kind": kind, "name": kind, "slug": slug, "ok": False,
|
||||||
|
"reason": "", "shot": os.path.join(outdir, slug + ".png"),
|
||||||
|
"rmse_vs_template_pct": None}
|
||||||
|
try:
|
||||||
|
ex = patched_example(kind, csv_path, tmpdir)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
result["reason"] = "patch failed: %r" % (exc,)
|
||||||
|
return result
|
||||||
|
chk = subprocess.run([sys.executable, "-m", "py_compile", ex],
|
||||||
|
capture_output=True, text=True, timeout=60)
|
||||||
|
if chk.returncode != 0:
|
||||||
|
result["reason"] = "py_compile failed: " + chk.stderr.strip()[:300]
|
||||||
|
return result
|
||||||
|
env = dict(os.environ)
|
||||||
|
env["DISPLAY"] = ":%d" % display
|
||||||
|
env["PYTHONPATH"] = REPO + os.pathsep + env.get("PYTHONPATH", "")
|
||||||
|
logp = os.path.join(tmpdir, slug + ".log")
|
||||||
|
png = result["shot"]
|
||||||
|
with open(logp, "w", encoding="utf-8") as logf:
|
||||||
|
proc = subprocess.Popen(
|
||||||
|
[sys.executable, ex], env=env,
|
||||||
|
stdout=logf, stderr=subprocess.STDOUT,
|
||||||
|
start_new_session=True)
|
||||||
|
try:
|
||||||
|
time.sleep(2.5)
|
||||||
|
if proc.poll() is not None:
|
||||||
|
result["reason"] = "exited early rc=%s; log: %s" % (
|
||||||
|
proc.returncode,
|
||||||
|
open(logp, encoding="utf-8",
|
||||||
|
errors="replace").read()[-400:])
|
||||||
|
return result
|
||||||
|
shot = subprocess.run(
|
||||||
|
["import", "-window", "root", png], env=env,
|
||||||
|
capture_output=True, text=True, timeout=30)
|
||||||
|
if shot.returncode != 0 or not os.path.exists(png):
|
||||||
|
result["reason"] = "screenshot failed: " + shot.stderr[:300]
|
||||||
|
return result
|
||||||
|
crop_to_window(png, kind)
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
os.killpg(proc.pid, signal.SIGTERM)
|
||||||
|
except ProcessLookupError:
|
||||||
|
pass
|
||||||
|
golden = os.path.join(REPO, "tools", "visreg", "goldens",
|
||||||
|
slug + ".png")
|
||||||
|
if os.path.exists(golden):
|
||||||
|
result["rmse_vs_template_pct"] = rmse_pct(golden, png)
|
||||||
|
result["ok"] = True
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--out-dir", default=DEFAULT_OUT)
|
||||||
|
parser.add_argument("--workers", type=int, default=6)
|
||||||
|
parser.add_argument("--csv", default=DEFAULT_CSV)
|
||||||
|
parser.add_argument("kinds", nargs="*", default=KINDS)
|
||||||
|
args = parser.parse_args()
|
||||||
|
kinds = [k for k in args.kinds if k in KINDS]
|
||||||
|
if not kinds:
|
||||||
|
print("no in-scope kinds requested")
|
||||||
|
return 1
|
||||||
|
os.makedirs(args.out_dir, exist_ok=True)
|
||||||
|
tmpdir = os.path.join(args.out_dir, ".tmp")
|
||||||
|
os.makedirs(tmpdir, exist_ok=True)
|
||||||
|
displays = [141 + i for i in range(args.workers)]
|
||||||
|
procs = []
|
||||||
|
for d in displays:
|
||||||
|
procs.append(subprocess.Popen(
|
||||||
|
["Xvfb", ":%d" % d, "-screen", "0", "1280x900x24"],
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
|
||||||
|
try:
|
||||||
|
for d in displays:
|
||||||
|
if not wait_for_x(d):
|
||||||
|
print("Xvfb :%d did not come up" % d)
|
||||||
|
return 1
|
||||||
|
# Round-robin the kinds over the displays, sequentially per
|
||||||
|
# display (each run needs its own display; 2.5 s settle each).
|
||||||
|
results = []
|
||||||
|
for i, kind in enumerate(kinds):
|
||||||
|
display = displays[i % len(displays)]
|
||||||
|
print("[%d/%d] %s on :%d" % (i + 1, len(kinds), kind, display),
|
||||||
|
flush=True)
|
||||||
|
results.append(run_one(kind, display, args.csv,
|
||||||
|
args.out_dir, tmpdir))
|
||||||
|
finally:
|
||||||
|
for p in procs:
|
||||||
|
p.terminate()
|
||||||
|
ok = [r for r in results if r["ok"]]
|
||||||
|
print("shots: ok=%d fail=%d" % (len(ok), len(results) - len(ok)))
|
||||||
|
for r in results:
|
||||||
|
if r["ok"]:
|
||||||
|
print(" OK %-28s RMSE vs template: %s%%" % (
|
||||||
|
r["kind"],
|
||||||
|
r["rmse_vs_template_pct"] if r["rmse_vs_template_pct"]
|
||||||
|
is not None else "?"))
|
||||||
|
else:
|
||||||
|
print(" FAIL %-28s %s" % (r["kind"], r["reason"]))
|
||||||
|
with open(os.path.join(args.out_dir, "report.json"), "w",
|
||||||
|
encoding="utf-8") as f:
|
||||||
|
json.dump(results, f, indent=1)
|
||||||
|
return 0 if len(ok) == len(results) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user