Skip to content

fileLoader_csv

Load canonical CSV-like .sanpy recordings.

Classes¤

fileLoader_text ¤

Bases: fileLoader_base

Load a canonical .sanpy recording without raising into the GUI.

Source code in sanpy/fileloaders/fileLoader_csv.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class fileLoader_text(fileLoader_base):
    """Load a canonical ``.sanpy`` recording without raising into the GUI."""

    loadFileType = ".sanpy"

    def loadFile(self) -> None:
        """Load ``self.filepath`` and contain malformed-file failures."""
        try:
            self._load_file()
        except Exception as error:
            logger.error(
                'Could not load .sanpy file "%s": %s', self.filepath, error
            )
            self._loadError = True

    def _load_file(self) -> None:
        dataframe = pd.read_csv(self.filepath)
        if dataframe.empty:
            raise ValueError("file contains no recording rows")

        columns = [str(name) for name in dataframe.columns]
        recording_token, y_columns, c_columns, has_epoch_index = _parse_sanpy_columns(
            columns
        )

        seconds = dataframe["seconds"].to_numpy(dtype=np.float64)
        if len(seconds) < 2:
            raise ValueError("'seconds' must contain at least two samples")
        if not np.isfinite(seconds).all():
            raise ValueError("'seconds' must contain only finite numeric values")
        if not np.isclose(seconds[0], 0.0, rtol=0.0, atol=_ATOL):
            raise ValueError("'seconds' must begin at zero")

        time_steps = np.diff(seconds)
        if np.any(time_steps <= 0):
            raise ValueError("'seconds' must be strictly increasing")
        sample_interval = float(time_steps[0])
        if not np.allclose(time_steps, sample_interval, rtol=_RTOL, atol=_ATOL):
            raise ValueError("'seconds' must be uniformly sampled")

        sweep_y = dataframe[y_columns].to_numpy(dtype=np.float64)
        if not np.isfinite(sweep_y).all():
            raise ValueError("recording columns must contain only finite numeric values")

        sweep_c: Optional[np.ndarray] = None
        if c_columns:
            sweep_c = dataframe[c_columns].to_numpy(dtype=np.float64)
            if not np.isfinite(sweep_c).all():
                raise ValueError("command columns must contain only finite numeric values")

        epoch_tables: Optional[list[epochTable]] = None
        if has_epoch_index:
            if not pd.api.types.is_integer_dtype(dataframe["epoch_index"].dtype):
                raise ValueError("'epoch_index' must contain integer values")
            epoch_indices = dataframe["epoch_index"].to_numpy(dtype=np.int64)
            if epoch_indices[0] != 0:
                raise ValueError("'epoch_index' must begin at 0")
            epoch_steps = np.diff(epoch_indices)
            if not np.isin(epoch_steps, (0, 1)).all():
                raise ValueError(
                    "'epoch_index' may only remain unchanged or increase by 1"
                )
            if sweep_c is None:  # Guaranteed by column validation; keeps typing explicit.
                raise ValueError("'epoch_index' requires command columns")
            epoch_tables = self._build_epoch_tables(
                epoch_indices, sweep_c, sample_interval
            )

        recording_mode = (
            recordingModes.iclamp
            if recording_token == "mv"
            else recordingModes.vclamp
        )
        self.setLoadedData(
            sweepX=seconds[:, np.newaxis],
            sweepY=sweep_y,
            sweepC=sweep_c,
            recordingMode=recording_mode,
            xLabel="seconds",
            yLabel=recording_token,
        )
        self._epochTableList = epoch_tables

    @staticmethod
    def _build_epoch_tables(
        epoch_indices: np.ndarray,
        sweep_c: np.ndarray,
        sample_interval: float,
    ) -> list[epochTable]:
        """Build one epoch table per sweep from shared point labels."""
        transition_points = np.flatnonzero(np.diff(epoch_indices)) + 1
        boundaries = np.concatenate(([0], transition_points, [len(epoch_indices)]))
        data_points_per_ms = 1.0 / (sample_interval * 1000.0)
        tables: list[epochTable] = []

        for sweep in range(sweep_c.shape[1]):
            table = epochTable()
            for epoch_index, (start_point, stop_point) in enumerate(
                zip(boundaries[:-1], boundaries[1:])
            ):
                command = sweep_c[start_point:stop_point, sweep]
                level = float(command[0])
                if not np.allclose(command, level, rtol=_RTOL, atol=_ATOL):
                    raise ValueError(
                        f"command for sweep {sweep}, epoch {epoch_index} is not constant"
                    )

                start_sec = float(start_point * sample_interval)
                stop_sec = float(stop_point * sample_interval)
                table.addEpoch(
                    sweepNumber=sweep,
                    startSec=start_sec,
                    stopSec=stop_sec,
                    dataPointsPerMs=data_points_per_ms,
                    level=level,
                )
                added_epoch = table.getEpochList()[-1]
                if (
                    added_epoch["startPoint"] != start_point
                    or added_epoch["stopPoint"] != stop_point
                ):
                    raise ValueError(
                        "epoch boundary conversion mismatch for "
                        f"sweep {sweep}, epoch {epoch_index}: expected "
                        f"[{start_point}, {stop_point}), got "
                        f"[{added_epoch['startPoint']}, {added_epoch['stopPoint']})"
                    )
            tables.append(table)

        return tables

Methods:¤

loadFile() ¤

Load self.filepath and contain malformed-file failures.

Source code in sanpy/fileloaders/fileLoader_csv.py
68
69
70
71
72
73
74
75
76
def loadFile(self) -> None:
    """Load ``self.filepath`` and contain malformed-file failures."""
    try:
        self._load_file()
    except Exception as error:
        logger.error(
            'Could not load .sanpy file "%s": %s', self.filepath, error
        )
        self._loadError = True

Functions:¤

All material is Copyright 2019-2026 Robert H. Cudmore