Coverage for ppedit/_tableio.py: 93.3%

272 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 17:40 +0000

1"""Import and export of case table rows as data files (issue #73) 

2 

3Files are read and written with pandas, which is used here only: the case 

4model stays plain lists of rows (decision #4). The format is chosen from the 

5file name extension (`table_format`), for example `bus.csv`, `bus.csv.gz`, 

6`gen.parquet` or `branch.xlsx`. Formats whose pandas engine is not installed 

7(`pyarrow` for Parquet and Feather, `openpyxl` for Excel) are not offered by 

8`table_formats` and are refused by `read_rows` and `dump_rows`. 

9 

10Import also reads the other pandas formats (`table_read_formats`) when their 

11engine is installed: JSON lines (`.jsonl`, `.ndjson`), XML, HTML (the first 

12table; `lxml`, or `bs4` and `html5lib`), fixed-width text (`.fwf`), Excel 

13`.xlsm`, `.xls`, `.xlsb` and OpenDocument `.ods` (`python-calamine`, else 

14`openpyxl`, `xlrd`, `pyxlsb` and `odfpy` respectively), 

15ORC (`pyarrow`), HDF5 (`.h5`, `.hdf5`, `.hdf`; `tables`; one data set), 

16Stata `.dta`, SAS `.sas7bdat` and `.xpt`, and SPSS `.sav` (`pyreadstat`). 

17These are not written. Pickle files are refused: loading one can run 

18arbitrary code. 

19 

20Files have one column per table column, headed by its name in 

21`ppedit.case.COLUMNS` (no index column); `Case.import_rows` checks the names. 

22 

23Time series files (`read_series`, `dump_series`; issue #124) have one row 

24per time step: an optional label column (named `time`, `timestamp`, 

25`datetime`, `date`, `step` or `index`, any case, or an unnamed first column 

26as pandas writes an index) and one column per case value named 

27`table.column.key` (see `ppedit.Case.set_series`), e.g. `bus.Pd.5`. 

28""" 

29 

30import importlib.util 

31import io 

32import math 

33import os 

34import re 

35import tempfile 

36 

37from ppedit.case import COLUMNS,CaseError 

38 

39# extension -> (pandas format, modules needed besides pandas, writable). 

40# Modules: None, a name, "a|b" (either) or "a+b" (both). Pickle is not read: 

41# loading one can run arbitrary code (as `.py` cases are never executed). 

42_FORMATS = { 

43 ".csv":("csv",None,True), 

44 ".tsv":("tsv",None,True), 

45 ".json":("json",None,True), 

46 ".parquet":("parquet","pyarrow",True), 

47 ".feather":("feather","pyarrow",True), 

48 ".xlsx":("excel","openpyxl",True), 

49 ".jsonl":("jsonl",None,False), 

50 ".ndjson":("jsonl",None,False), 

51 ".xml":("xml",None,False), 

52 ".html":("html","lxml|bs4+html5lib",False), 

53 ".htm":("html","lxml|bs4+html5lib",False), 

54 ".fwf":("fwf",None,False), 

55 ".xlsm":("excel","python_calamine|openpyxl",False), 

56 ".xls":("excel","python_calamine|xlrd",False), 

57 ".xlsb":("excel","python_calamine|pyxlsb",False), 

58 ".ods":("excel","python_calamine|odf",False), 

59 ".orc":("orc","pyarrow",False), 

60 ".h5":("hdf","tables",False), 

61 ".hdf5":("hdf","tables",False), 

62 ".hdf":("hdf","tables",False), 

63 ".dta":("stata",None,False), 

64 ".sas7bdat":("sas",None,False), 

65 ".xpt":("sas",None,False), 

66 ".sav":("spss","pyreadstat",False), 

67} 

68 

69# Excel-like extension -> pandas engine when `python-calamine` (pandas' 

70# preferred reader for all of them; xlrd is deprecated) is not installed 

71_EXCEL_ENGINES = {".xlsx":"openpyxl",".xlsm":"openpyxl",".xls":"xlrd",".xlsb":"pyxlsb",".ods":"odf"} 

72 

73# compression suffix -> (pandas compression, module needed); text formats only 

74_COMPRESSION = { 

75 ".gz":("gzip",None), 

76 ".bz2":("bz2",None), 

77 ".xz":("xz",None), 

78 ".zip":("zip",None), 

79 ".zst":("zstd","zstandard"), 

80} 

81 

82_TEXT = ("csv","tsv","json","jsonl","xml","fwf") 

83 

84def _installed(module:str|None) -> bool: 

85 if module is None: 

86 return True 

87 return any(all(importlib.util.find_spec(m) is not None for m in alt.split("+")) 

88 for alt in module.split("|")) 

89 

90def _formats(write:bool) -> list[str]: 

91 if not _installed("pandas"): 91 ↛ 92line 91 didn't jump to line 92 because the condition on line 91 was never true

92 return [] 

93 out = [] 

94 for ext,(fmt,module,writable) in _FORMATS.items(): 

95 if (write and not writable) or not _installed(module): 

96 continue 

97 out.append(ext) 

98 if fmt in _TEXT: 

99 out.extend(ext+suffix for suffix,(_,mod) in _COMPRESSION.items() if _installed(mod)) 

100 return out 

101 

102def table_formats() -> list[str]: 

103 """Return the file extensions that can be read and written 

104 

105 Returns 

106 ------- 

107 

108 - `list[str]`: extensions such as `.csv`, `.csv.gz` and `.parquet` 

109 whose pandas engine is installed; empty if pandas is not installed 

110 """ 

111 return _formats(True) 

112 

113def table_read_formats() -> list[str]: 

114 """Return the file extensions that can be read (imported) 

115 

116 Returns 

117 ------- 

118 

119 - `list[str]`: `table_formats` plus the formats pandas reads but 

120 ppedit does not write (`.jsonl`, `.xml`, `.html`, `.fwf`, `.xls`, 

121 `.xlsm`, `.xlsb`, `.ods`, `.orc`, `.h5`, `.dta`, `.sas7bdat`, 

122 `.xpt`, `.sav`, ...), each only when its engine is installed 

123 """ 

124 return _formats(False) 

125 

126def table_format(filename:str,write:bool=False) -> tuple[str,str|None]: 

127 """Return the pandas format and compression of a file name 

128 

129 Arguments 

130 --------- 

131 

132 - `filename`: file name or path, e.g. `bus.csv.gz` 

133 

134 - `write`: refuse formats that are only read 

135 

136 Returns 

137 ------- 

138 

139 - `tuple[str,str|None]`: format (`csv`, `tsv`, `json`, `jsonl`, 

140 `xml`, `html`, `fwf`, `parquet`, `feather`, `orc`, `excel`, `hdf`, 

141 `stata`, `sas` or `spss`) and compression (`gzip`, `bz2`, `xz`, 

142 `zip`, `zstd` or `None`) 

143 

144 Exceptions 

145 ---------- 

146 

147 - `CaseError`: the extension is not supported, its pandas engine is 

148 not installed, or (with `write`) it is only read 

149 """ 

150 name = filename.lower() 

151 if name.endswith((".pkl",".pickle")): 

152 raise CaseError(f"'{filename}': pickle files are not read, since loading one can " 

153 "run arbitrary code; save the data as Parquet or CSV instead") 

154 compression = None 

155 for suffix,(comp,module) in _COMPRESSION.items(): 

156 if name.endswith(suffix): 

157 if not _installed(module): 157 ↛ 158line 157 didn't jump to line 158 because the condition on line 157 was never true

158 raise CaseError(f"'{suffix}' files need the '{module}' package") 

159 name,compression = name[:-len(suffix)],comp 

160 break 

161 for ext,(fmt,module,writable) in _FORMATS.items(): 

162 if name.endswith(ext): 

163 if compression and fmt not in _TEXT: 

164 raise CaseError(f"'{ext}' files cannot be compressed") 

165 if write and not writable: 

166 raise CaseError(f"'{ext}' files can be imported but not exported " 

167 "(use " + ", ".join(table_formats() or [".csv"]) + ")") 

168 if not _installed("pandas"): 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true

169 raise CaseError("importing and exporting table data needs the 'pandas' package") 

170 if not _installed(module): 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true

171 raise CaseError(f"'{ext}' files need the " 

172 + " or ".join("'" + "' and '".join(a.split("+")) + "'" for a in module.split("|")) 

173 + " package" + ("s" if "+" in module or "|" in module else "")) 

174 return fmt,compression 

175 raise CaseError(f"'{filename}' is not a supported table data file " 

176 "(use " + ", ".join((table_read_formats() if not write else table_formats()) or [".csv"]) + ")") 

177 

178def _read_frame(filename:str,data:bytes,fmt:str,compression:str|None): 

179 """Read file contents into a pandas data frame""" 

180 import pandas as pd # pylint: disable=import-outside-toplevel 

181 buffer = io.BytesIO(data) 

182 ext = next(e for e in sorted(_FORMATS,key=len,reverse=True) 

183 if re.sub(r"\.(gz|bz2|xz|zip|zst)$","",filename.lower()).endswith(e)) 

184 if fmt in ("csv","tsv"): 

185 return pd.read_csv(buffer,sep="," if fmt == "csv" else "\t", 

186 compression=compression,skipinitialspace=True) 

187 if fmt in ("json","jsonl"): 

188 return pd.read_json(buffer,orient="records",compression=compression, 

189 precise_float=True,lines=fmt == "jsonl") 

190 if fmt == "xml": 

191 return pd.read_xml(buffer,compression=compression, 

192 parser="lxml" if _installed("lxml") else "etree") 

193 if fmt == "fwf": 

194 return pd.read_fwf(buffer,compression=compression) 

195 if fmt == "html": 

196 tables = pd.read_html(io.StringIO(data.decode("utf-8","replace")), 

197 flavor="lxml" if _installed("lxml") else "bs4") 

198 return tables[0] 

199 if fmt == "parquet": 

200 return pd.read_parquet(buffer) 

201 if fmt == "feather": 

202 return pd.read_feather(buffer) 

203 if fmt == "orc": 

204 return pd.read_orc(buffer) 

205 if fmt == "excel": 

206 engine = _EXCEL_ENGINES[ext] 

207 if ext != ".xlsx" and _installed("python_calamine"): 

208 engine = "calamine" 

209 return pd.read_excel(buffer,engine=engine) 

210 if fmt == "stata": 

211 return pd.read_stata(buffer) 

212 if fmt == "sas": 

213 return pd.read_sas(buffer,format="xport" if ext == ".xpt" else "sas7bdat") 

214 # hdf and spss readers need a file path 

215 with tempfile.TemporaryDirectory() as tmp: 

216 path = os.path.join(tmp,"data"+ext) 

217 with open(path,"wb") as fh: 

218 fh.write(data) 

219 if fmt == "spss": 

220 return pd.read_spss(path) 

221 with pd.HDFStore(path,mode="r") as store: 

222 keys = store.keys() 

223 if len(keys) != 1: 

224 raise CaseError(f"'{filename}' holds {len(keys)} data sets " 

225 f"({', '.join(keys) or 'none'}); keep one") 

226 return store[keys[0]] 

227 

228def _value(value): 

229 """Convert a pandas cell to a plain Python value (`None` when missing)""" 

230 if hasattr(value,"item"): 230 ↛ 231line 230 didn't jump to line 231 because the condition on line 230 was never true

231 value = value.item() 

232 if value is None or (isinstance(value,float) and math.isnan(value)): 

233 return None 

234 return value 

235 

236DROPNA = ("rows","columns","empty-rows","empty-columns") 

237"""`dropna` choices of `read_rows` and `read_series`: drop the rows (or 

238columns) with any missing value, or only those with no value at all""" 

239 

240def _dropna(columns:list[str],rows:list[list],dropna:str|None,keep:tuple=(), 

241 report:dict|None=None) -> tuple[list[str],list[list]]: 

242 """Drop rows or columns with missing (`None`) cells as `dropna` says 

243 (see `DROPNA`; `None` or empty keeps everything); columns `keep` 

244 (indexes) are never dropped nor looked at. Fills `report` with 

245 `dropped`: `{"rows": count, "columns": [names]}`""" 

246 if not dropna: 

247 return columns,rows 

248 if dropna not in DROPNA: 

249 raise CaseError(f"dropna must be one of {', '.join(DROPNA)}, not '{dropna}'") 

250 test = all if dropna.startswith("empty-") else any 

251 look = [j for j in range(len(columns)) if j not in keep] 

252 gone_rows,gone_cols = 0,[] 

253 if dropna.endswith("rows"): 

254 out = [r for r in rows if not (look and test(r[j] is None for j in look))] 

255 gone_rows,rows = len(rows) - len(out),out 

256 else: 

257 drop = {j for j in look if rows and test(r[j] is None for r in rows)} 

258 gone_cols = [columns[j] for j in sorted(drop)] 

259 columns = [c for j,c in enumerate(columns) if j not in drop] 

260 rows = [[v for j,v in enumerate(r) if j not in drop] for r in rows] 

261 if gone_rows and not rows: 

262 raise CaseError(f"every row has {'no' if test is all else 'a missing'} value, so dropping " 

263 f"them (dropna '{dropna}') leaves nothing to import") 

264 if gone_cols and len(gone_cols) == len(look): 

265 raise CaseError(f"every {'value ' if keep else ''}column has " 

266 f"{'no' if test is all else 'a missing'} value, so dropping them (dropna '{dropna}') " 

267 "leaves nothing to import") 

268 if report is not None: 

269 report["dropped"] = {"rows":gone_rows,"columns":gone_cols} 

270 return columns,rows 

271 

272_RANGE = re.compile(r"^\s*(\d*)\s*(?:-|:|\.\.)\s*(\d*)\s*$") 

273 

274def _row_range(rows:list[list],spec:str|None,report:dict|None=None) -> list[list]: 

275 """Keep the data rows `spec` names, counted from 1 (header aside): 

276 `N`, `A-B`, `A-` or `-B` (also `A:B`, `A..B`), inclusive""" 

277 if spec is None or not str(spec).strip(): 

278 return rows 

279 text = str(spec).strip() 

280 m = _RANGE.match(text) 

281 if text.isdigit(): 

282 first = last = int(text) 

283 elif m and (m[1] or m[2]): 

284 first = int(m[1] or 1) 

285 last = int(m[2]) if m[2] else max(first,len(rows)) 

286 else: 

287 raise CaseError(f"row range '{spec}' is not N, A-B, A- or -B (rows counted from 1)") 

288 if first < 1 or last < first: 

289 raise CaseError(f"row range '{spec}' is empty (rows are counted from 1)") 

290 if first > len(rows): 

291 raise CaseError(f"row range '{spec}' starts after the last of the {len(rows)} data row(s)") 

292 out = rows[first-1:last] 

293 if report is not None: 293 ↛ 295line 293 didn't jump to line 295 because the condition on line 293 was always true

294 report["selected"] = {"rows":len(out),"of":len(rows)} 

295 return out 

296 

297def read_rows(filename:str,data:bytes,dropna:str|None=None, 

298 report:dict|None=None,rows:str|None=None) -> tuple[list[str],list[list]]: 

299 """Read table data from file contents 

300 

301 Arguments 

302 --------- 

303 

304 - `filename`: file name, whose extension sets the format 

305 

306 - `data`: file contents 

307 

308 - `dropna`: drop missing values when read (`DROPNA`): `rows` drops 

309 each row with a missing cell, `columns` each column with one, 

310 `empty-rows` and `empty-columns` only rows or columns with no 

311 value at all; `None` (default) keeps them 

312 

313 - `report`: a dict to fill with `dropped` (`{"rows": count, 

314 "columns": [names]}`) when `dropna` is given, and `selected` 

315 (`{"rows": kept, "of": read}`) when `rows` is given 

316 

317 - `rows`: the data rows to keep, counted from 1 after the header: 

318 `N`, `A-B`, `A-` or `-B` (inclusive); applied before `dropna` 

319 

320 Returns 

321 ------- 

322 

323 - `tuple[list[str],list[list]]`: column names (stripped) and rows of 

324 plain Python values, `None` for missing cells 

325 

326 Exceptions 

327 ---------- 

328 

329 - `CaseError`: unsupported format, the file cannot be read, an 

330 unknown `dropna`, `dropna` dropping every row or column, or a bad 

331 or empty `rows` range 

332 """ 

333 fmt,compression = table_format(filename) 

334 try: 

335 frame = _read_frame(filename,data,fmt,compression) 

336 except CaseError: 

337 raise 

338 except Exception as err: # pandas raises many kinds of errors 

339 raise CaseError(f"cannot read '{filename}': {err}") from err 

340 columns = [str(c).strip() for c in frame.columns] 

341 spec,rows = rows,[[_value(v) for v in row] for row in frame.astype(object).itertuples(index=False,name=None)] 

342 rows = _row_range(rows,spec,report) 

343 return _dropna(columns,rows,dropna,report=report) 

344 

345def dump_rows(table:str,rows:list[list],filename:str, 

346 extended:tuple[list[dict],list[list]]|None=None) -> bytes: 

347 """Write table rows to file contents 

348 

349 Arguments 

350 --------- 

351 

352 - `table`: table name (sets the column names) 

353 

354 - `rows`: rows in `COLUMNS[table]` order 

355 

356 - `filename`: file name, whose extension sets the format 

357 

358 - `extended`: optional `(columns, rows)` of solution values to write 

359 after the table columns: `columns` are `RESULT_COLUMNS` entries, 

360 `rows` one per row of `rows` (`None` for a missing value, written 

361 as an empty cell) 

362 

363 Returns 

364 ------- 

365 

366 - `bytes`: file contents 

367 

368 Exceptions 

369 ---------- 

370 

371 - `CaseError`: unknown table or unsupported format 

372 """ 

373 import pandas as pd # pylint: disable=import-outside-toplevel 

374 if table not in COLUMNS: 374 ↛ 375line 374 didn't jump to line 375 because the condition on line 374 was never true

375 raise CaseError(f"unknown table '{table}'") 

376 fmt,compression = table_format(filename,write=True) 

377 columns = [c["name"] for c in COLUMNS[table]] 

378 frame = pd.DataFrame([list(r) for r in rows],columns=columns) 

379 for col in COLUMNS[table]: 

380 if col["kind"] in ("int","enum"): 

381 frame[col["name"]] = frame[col["name"]].astype("int64") 

382 elif col["kind"] == "float": 

383 frame[col["name"]] = frame[col["name"]].astype("float64") 

384 else: 

385 frame[col["name"]] = frame[col["name"]].astype(str) 

386 if extended: 

387 cols,values = extended 

388 for j,col in enumerate(cols): 

389 frame[col["name"]] = pd.Series([math.nan if v[j] is None else float(v[j]) 

390 for v in values],dtype="float64") 

391 buffer = io.BytesIO() 

392 if fmt in ("csv","tsv"): 

393 frame.to_csv(buffer,sep="," if fmt == "csv" else "\t",index=False, 

394 compression=compression) 

395 elif fmt == "json": 

396 # JSON has no infinity: write it as the strings "Inf"/"-Inf" (as in 

397 # the editor state), which Case.import_rows reads back 

398 frame = frame.astype(object).map(lambda v: ("Inf" if v > 0 else "-Inf") 

399 if isinstance(v,float) and math.isinf(v) else v) 

400 frame.to_json(buffer,orient="records",compression=compression, 

401 double_precision=15) 

402 elif fmt == "parquet": 

403 frame.to_parquet(buffer,index=False) 

404 elif fmt == "feather": 

405 frame.to_feather(buffer) 

406 else: 

407 frame.to_excel(buffer,index=False,sheet_name=table) 

408 return buffer.getvalue() 

409 

410SERIES_LABELS = ("time","timestamp","datetime","date","step","index") 

411"""Names of the step label column of a time series file (any case)""" 

412 

413def _date_range(labels:list,rows:list[list],start:str|None,end:str|None, 

414 report:dict|None=None) -> tuple[list,list[list]]: 

415 """Keep the steps whose label, read as a date and time, lies between 

416 `start` and `end` (inclusive; an `end` with no time of day takes in 

417 the whole day)""" 

418 import pandas as pd # pylint: disable=import-outside-toplevel 

419 if not (start and str(start).strip()) and not (end and str(end).strip()): 

420 return labels,rows 

421 if labels is None: 

422 raise CaseError("a date range needs a time column (time, timestamp, datetime, date, step or index)") 

423 def when(text,what): 

424 try: 

425 return pd.Timestamp(str(text).strip()) 

426 except (ValueError,TypeError) as err: 

427 raise CaseError(f"{what} '{text}' is not a date and time") from err 

428 lo = when(start,"start") if start and str(start).strip() else None 

429 hi = None 

430 if end and str(end).strip(): 

431 hi = when(end,"end") 

432 if re.fullmatch(r"\s*\d{4}-\d{1,2}-\d{1,2}\s*",str(end)) or re.fullmatch(r"\s*\d{1,2}/\d{1,2}/\d{4}\s*",str(end)): 

433 hi = hi + pd.Timedelta(days=1) - pd.Timedelta(microseconds=1) 

434 times = pd.to_datetime(pd.Series(labels,dtype=object),errors="coerce",format="mixed") 

435 bad = [labels[k] for k in range(len(labels)) if pd.isna(times[k])] 

436 if bad: 

437 raise CaseError(f"{len(bad)} step label(s) are not dates and times (e.g. '{bad[0]}'); " 

438 "use a row range instead") 

439 tz = getattr(times.dt,"tz",None) 

440 if tz is not None: 440 ↛ 441line 440 didn't jump to line 441 because the condition on line 440 was never true

441 lo = lo.tz_localize(tz) if lo is not None and lo.tzinfo is None else lo 

442 hi = hi.tz_localize(tz) if hi is not None and hi.tzinfo is None else hi 

443 keep = [k for k in range(len(labels)) if (lo is None or times[k] >= lo) and (hi is None or times[k] <= hi)] 

444 if not keep: 

445 raise CaseError(f"no step lies between {start or 'the first'} and {end or 'the last'} " 

446 f"(the file runs from {labels[0]} to {labels[-1]})") 

447 if report is not None: 447 ↛ 449line 447 didn't jump to line 449 because the condition on line 447 was always true

448 report["selected"] = {"rows":len(keep),"of":len(labels)} 

449 return [labels[k] for k in keep],[rows[k] for k in keep] 

450 

451def _number(value,what:str,default:float) -> float: 

452 """A finite number from `value` (`default` when blank)""" 

453 if value is None or (isinstance(value,str) and not value.strip()): 

454 return default 

455 try: 

456 x = float(value) 

457 except (TypeError,ValueError): 

458 x = math.nan 

459 if not math.isfinite(x): 

460 raise CaseError(f"{what} must be a finite number, not {value!r}") 

461 return x 

462 

463def _scale(rows:list[list],scale,offset,report:dict|None=None) -> list[list]: 

464 """Return `rows` with each number `x` as `x*scale + offset` (other cells unchanged)""" 

465 a,b = _number(scale,"scale",1.0),_number(offset,"offset",0.0) 

466 if a == 1 and b == 0: 

467 return rows 

468 if report is not None: 468 ↛ 470line 468 didn't jump to line 470 because the condition on line 468 was always true

469 report["scaled"] = {"scale":a,"offset":b} 

470 return [[v*a + b if isinstance(v,(int,float)) and not isinstance(v,bool) else v for v in r] for r in rows] 

471 

472def read_series(filename:str,data:bytes,dropna:str|None=None, 

473 report:dict|None=None,rows:str|None=None,start:str|None=None, 

474 end:str|None=None,scale:float|None=None, 

475 offset:float|None=None) -> tuple[list[str]|None,list[str],list[list]]: 

476 """Read a time series from file contents (see the module docstring) 

477 

478 `dropna`, `report` and `rows` are as in `read_rows`; `dropna` applies 

479 to the value columns only: the label column is never dropped, and a 

480 missing label does not make a step missing (`rows` drops steps, 

481 `columns` drops value columns). `start` and `end` keep the steps whose 

482 label, read as a date and time, lies between them (inclusive; an `end` 

483 date with no time of day takes in that whole day; needs a label column 

484 of dates). The row range, then the date range, then `dropna` apply. 

485 Last, each value `x` becomes `x*scale + offset` (`scale` 1 and 

486 `offset` 0 by default; e.g. `scale` 0.001 for kW to MW); `report` then 

487 has `scaled` (`{"scale", "offset"}`). 

488 

489 Returns 

490 ------- 

491 

492 - `tuple`: step labels (text, or `None` when the file has no label 

493 column), value column names, and one row of values per step 

494 

495 Exceptions 

496 ---------- 

497 

498 - `CaseError`: unsupported format, the file cannot be read, more 

499 than one label column, or a `scale` or `offset` that is not a 

500 finite number 

501 """ 

502 columns,rows = read_rows(filename,data,None,report,rows) 

503 label = [j for j,c in enumerate(columns) if c.lower() in SERIES_LABELS 

504 or (j == 0 and (c == "" or c.startswith("Unnamed:")))] 

505 if len(label) > 1: 

506 raise CaseError(f"'{filename}' has {len(label)} step label columns " 

507 f"({', '.join(columns[j] for j in label)}); keep one") 

508 if not label: 

509 _date_range(None,rows,start,end) 

510 columns,rows = _dropna(columns,rows,dropna,report=report) 

511 return None,columns,_scale(rows,scale,offset,report) 

512 j = label[0] # move the label column first, then keep it out of dropna 

513 columns = [columns[j]] + columns[:j] + columns[j+1:] 

514 rows = [[row[j]] + row[:j] + row[j+1:] for row in rows] 

515 # a numeric label column with a blank cell is read as floats: 1.0 -> "1" 

516 index = ["" if row[0] is None else str(int(row[0])) 

517 if isinstance(row[0],float) and row[0].is_integer() else str(row[0]) for row in rows] 

518 if (start and str(start).strip()) or (end and str(end).strip()): 

519 read = (report or {}).get("selected",{}).get("of") 

520 index,rows = _date_range(index,rows,start,end,report) 

521 if read is not None: 

522 report["selected"]["of"] = read 

523 rows = [[label] + row[1:] for label,row in zip(index,rows)] # labels travel with their rows 

524 columns,rows = _dropna(columns,rows,dropna,(0,),report) 

525 return [row[0] for row in rows],columns[1:],_scale([row[1:] for row in rows],scale,offset,report) 

526 

527def dump_series(series:dict,filename:str) -> bytes: 

528 """Write a time series (`Case.series`) to file contents: a `time` column 

529 of step labels, then one column per series column""" 

530 import pandas as pd # pylint: disable=import-outside-toplevel 

531 fmt,compression = table_format(filename,write=True) 

532 frame = pd.DataFrame(series["values"],columns=series["columns"],dtype="float64") 

533 frame.insert(0,"time",list(series["index"])) 

534 buffer = io.BytesIO() 

535 if fmt in ("csv","tsv"): 

536 frame.to_csv(buffer,sep="," if fmt == "csv" else "\t",index=False,compression=compression) 

537 elif fmt == "json": 537 ↛ 539line 537 didn't jump to line 539 because the condition on line 537 was always true

538 frame.to_json(buffer,orient="records",compression=compression,double_precision=15) 

539 elif fmt == "parquet": 

540 frame.to_parquet(buffer,index=False) 

541 elif fmt == "feather": 

542 frame.to_feather(buffer) 

543 else: 

544 frame.to_excel(buffer,index=False,sheet_name="series") 

545 return buffer.getvalue()