Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Added

- **Navigator: NDI Cloud login indicator** (`ndi.gui.nav.cloud_pane`, MATLAB
VH-Lab/NDI-matlab@579176c88). The NDI Cloud pane gains a small button that is
green when logged in (an unexpired `NDI_CLOUD_TOKEN`), yellow when a profile
with a stored password (or `NDI_CLOUD_USERNAME`/`NDI_CLOUD_PASSWORD`) is ready
to log in, and red when nothing is configured. Hovering explains the state;
clicking opens the profile editor. It re-checks every 30 seconds.
`cloud_colors` gains `alert_red`.

- **Navigator: filter the cloud dataset browser by published state**
(`ndi.gui.nav.cloud_dataset_browser`, MATLAB VH-Lab/NDI-matlab@3f56952). The
"Browse my Cloud datasets..." window gains a Published (Yes/No) column, read
from each dataset's `isPublished` flag, and "Include published" / "Include
unpublished" checkboxes (both ticked at first). The status line says how
many datasets are shown out of how many while a filter hides any.

- **Navigator: Cloud comparison, Cloud info and a cloud dataset browser**
(`ndi.gui.nav`, MATLAB VH-Lab/NDI-matlab#1230 and #1231). A dataset's Cloud
menu is now "Cloud info...", "Upload to Cloud" and "Cloud comparison...".
Expand Down
70 changes: 60 additions & 10 deletions src/ndi/fun/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,46 +33,96 @@


def readngrid(
file_path: str | Path,
file_path: str | Path | Any,
data_size: Sequence[int],
data_type: str = "double",
) -> np.ndarray:
"""Read n-dimensional binary matrix from file.
"""Read n-dimensional binary matrix from a file path or a file object.

MATLAB equivalent: ndi.fun.data.readngrid

Args:
file_path: Path to the binary file.
data_size: Shape tuple, e.g. ``(100, 3)``.
file_path: Path to the binary file, OR a file object: a
:class:`did.file.Fileobj`, or an open binary file such as the one
``ndi_session.database_openbinarydoc`` returns. A file object that
is already open is read from its current position and left open,
so the caller can close it (e.g. with ``database_closebinarydoc``).
A ``did.file.Fileobj`` that is not open yet is opened read-only
here and closed again after reading. An object that only carries
``fullpathfilename`` (a cloud ``CachedBinaryFile``) is read by
that path.
data_size: Shape tuple, e.g. ``(100, 3)``; any number of dimensions.
data_type: ndi_element type name (``'double'``, ``'int16'``, etc.).

Returns:
numpy array with the given shape.

Raises:
ValueError: If data type is unknown or data count mismatches.
FileNotFoundError: If file does not exist.
FileNotFoundError: If the file does not exist or cannot be opened.
TypeError: If ``file_path`` is neither a path nor a file object.
"""
dtype = _TYPE_MAP.get(data_type)
if dtype is None:
raise ValueError(f"Unknown data type: '{data_type}'")

p = Path(file_path)
if not p.exists():
raise FileNotFoundError(f"File not found: {file_path}")

expected = 1
for d in data_size:
expected *= d

raw = np.fromfile(str(p), dtype=dtype)
if isinstance(file_path, (str, Path)):
raw = _read_ngrid_path(Path(file_path), dtype)
else:
raw = _read_ngrid_fileobj(file_path, expected, dtype)

if raw.size != expected:
raise ValueError(f"ndi_gui_Data count mismatch: expected {expected}, got {raw.size}")
# MATLAB's fread/fwrite serialise column-major; readngrid must match so
# multi-dimensional files round-trip between MATLAB and Python.
return raw.reshape(data_size, order="F")


def _read_ngrid_path(p: Path, dtype: np.dtype) -> np.ndarray:
"""Every element in the file at P."""
if not p.exists():
raise FileNotFoundError(f"File not found: {p}")
return np.fromfile(str(p), dtype=dtype)


def _read_ngrid_fileobj(fobj: Any, count: int, dtype: np.dtype) -> np.ndarray:
"""COUNT elements from a file object (see :func:`readngrid`).

MATLAB (readFromFileObj) reads an already-open object as it is and leaves
it open for its owner; reopening would close the caller's handle first.
"""
from did.file import Fileobj

nbytes = count * dtype.itemsize
if isinstance(fobj, Fileobj):
opened_here = False
if fobj.fid is None:
fobj.fopen("rb")
if fobj.fid is None:
raise FileNotFoundError(
f"Could not open file '{fobj.fullpathfilename}' for reading. "
"Ensure the path is correct and the file exists."
)
opened_here = True
try:
data = fobj.fid.read(nbytes)
finally:
if opened_here:
fobj.fclose()
elif callable(getattr(fobj, "read", None)):
data = fobj.read(nbytes)
elif getattr(fobj, "fullpathfilename", None):
return _read_ngrid_path(Path(fobj.fullpathfilename), dtype)
else:
raise TypeError(f"readngrid needs a file path or a file object, not {type(fobj).__name__}.")
usable = len(data) - len(data) % dtype.itemsize
return np.frombuffer(data[:usable], dtype=dtype).copy()


def writengrid(
data: np.ndarray,
file_path: str | Path,
Expand Down
17 changes: 14 additions & 3 deletions src/ndi/fun/ndi_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,12 @@ functions:
- name: readngrid
type: function
matlab_path: "+ndi/+fun/+data/readngrid.m"
matlab_last_sync_hash: "b33d8ce64"
matlab_last_sync_hash: "e3744121e"
python_path: "ndi/fun/data.py"
input_arguments:
- name: file_path
type_matlab: "char (fileName_or_fileObj)"
type_python: "str | Path"
type_matlab: "char | string | did.file.fileobj (fileName_or_fileObj)"
type_python: "str | Path | did.file.Fileobj | binary file object"
- name: data_size
type_matlab: "double (vector)"
type_python: "Sequence[int]"
Expand Down Expand Up @@ -216,6 +216,17 @@ functions:
byte is not something to infer without a MATLAB to test against;
recorded here for whoever has one.

2026-11-18: synced to NDI-matlab e3744121e (VH-Lab/NDI-matlab#1229),
which accepts a did.file.fileobj as well as a path and reads N-D sizes
by element count then reshapes. Ported: a did.file.Fileobj that is not
open is opened 'rb' and closed after; one already open, or any open
binary file object (what ndi_session.database_openbinarydoc returns),
is read from its current position and left open. An object carrying
only fullpathfilename (cloud CachedBinaryFile) is read by that path.
From a file object only prod(data_size) elements are read, as MATLAB
does; a path still reads the whole file, so a file with extra elements
is refused there (the existing mismatch divergence above).

- name: writengrid
type: function
matlab_path: "+ndi/+fun/+data/writengrid.m"
Expand Down
7 changes: 7 additions & 0 deletions src/ndi/gui/cloud_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ class CloudColors(NamedTuple):
warn_amber: tuple[float, float, float] = (0.9020, 0.6235, 0.1294)
#: #8C949E status: not yet / absent (e.g. an un-ingested on-disk session).
neutral_grey: tuple[float, float, float] = (0.5490, 0.5804, 0.6196)
#: #CC2626 status: not working / needs setting up (e.g. the navigator's
#: NDI Cloud login indicator when no login is configured).
alert_red: tuple[float, float, float] = (0.8000, 0.1500, 0.1500)

# MATLAB-cased aliases, so code written against either convention reads
# naturally -- the same dual-naming used across this port.
Expand Down Expand Up @@ -71,6 +74,10 @@ def warnAmber(self) -> tuple[float, float, float]: # noqa: N802
def neutralGrey(self) -> tuple[float, float, float]: # noqa: N802
return self.neutral_grey

@property
def alertRed(self) -> tuple[float, float, float]: # noqa: N802
return self.alert_red


_PALETTE = CloudColors()

Expand Down
Loading
Loading