Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

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

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

""" 

Pandas utilities. 

 

Import this as ``pd`` instead of directly importing the ``pandas`` module. It exports the same 

symbols, with the addition of strongly-typed phantom classes for tracking the exact dimensions and 

type of each variable using ``mypy``. It also provides some additional utilities (I/O). 

""" 

 

from pandas import * # pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import 

from typing import Any 

from typing import Callable 

from typing import Collection 

from typing import List 

from typing import Optional 

from typing import Tuple 

from typing import Type 

from typing import TypeVar 

from typing import Union 

 

import tgutils.numpy as np 

 

# pylint: disable=too-many-ancestors,redefined-outer-name 

 

 

#: Short name for ``DataFrame``. 

Frame = DataFrame 

 

#: Type variable for data series. 

S = TypeVar('S', bound='BaseSeries') # pylint: disable=invalid-name 

 

#: type variable for data frames. 

F = TypeVar('F', bound='BaseFrame') # pylint: disable=invalid-name 

 

 

class BaseSeries(Series): 

""" 

Base class for all Numpy data series phantom types. 

""" 

 

#: The expected data type of a data series of the (derived) class. 

dtype: str 

 

@classmethod 

def read(cls: Type[S], path: str, mmap_mode: Optional[str] = None) -> S: 

""" 

Read a Pandas data series of the concrete type from the disk. 

 

If an additional file with an ``.index`` suffix exists, it is loaded into the index labels. 

""" 

assert not path.endswith('.npy') 

assert not path.endswith('.txt') 

 

array = np.BaseArray.read_array(path, mmap_mode) 

54 ↛ 57line 54 didn't jump to line 57, because the condition on line 54 was never false if cls != BaseSeries: 

series = cls.am(Series(array)) 

else: 

series = Series(array) # type: ignore 

 

index_path = path + '.index' 

if np.BaseArray.exists(index_path): 

index = np.BaseArray.read_array(index_path, mmap_mode) 

series.set_axis(index, axis=0, inplace=True) # type: ignore 

 

return series 

 

@classmethod 

def write(cls, series: Series, path: str) -> None: 

""" 

Write a Pandas data series of the concrete type to a file. 

 

If necessary, creates additional file with an ``.index`` suffix to preserve the index 

labels. 

""" 

cls.am(series) 

 

np.BaseArray._write(series.values, path) # pylint: disable=protected-access 

 

if not series.index.equals(RangeIndex(len(series.index))): 

np.BaseArray._write(series.index.values, # pylint: disable=protected-access 

path + '.index') 

 

@classmethod 

def am(cls: Type[S], data: Series) -> S: # pylint: disable=invalid-name 

""" 

Declare a data series as being of this type. 

""" 

BaseSeries._am_series(data) 

array = data.values 

if cls.dtype not in [array.dtype.name, array.dtype.kind]: 

raise ValueError('unexpected data type: %s instead of: %s' 

% (array.dtype, cls.dtype)) 

return data # type: ignore 

 

@classmethod 

def be(cls: Type[S], # pylint: disable=invalid-name 

data: Collection, index: Optional[Collection] = None) -> S: 

""" 

Convert an array to this type. 

""" 

if not isinstance(data, Series): 

101 ↛ 103line 101 didn't jump to line 103, because the condition on line 101 was never false if not isinstance(data, np.ndarray): 

data = np.array(data, dtype=cls.dtype) 

data = Series(data, index=index) 

 

BaseSeries._am_series(data) 

if cls.dtype not in [data.values.dtype.name, data.values.dtype.kind]: 

data = data.astype(cls.dtype) 

 

return data # type: ignore 

 

@staticmethod 

def _am_series(data: Series) -> None: 

if not isinstance(data, Series): 

raise ValueError('unexpected type: %s.%s instead of: %s.%s' 

% (data.__class__.__module__, data.__class__.__qualname__, 

Series.__module__, Series.__qualname__)) 

array = data.values 

np.BaseArray._am_shape(array, 1) # pylint: disable=protected-access 

 

@classmethod 

def zeros(cls: Type[S], index: Collection) -> S: 

""" 

Return a series full of zeros. 

""" 

return cls.am(Series(np.zeros(len(index), dtype=cls.dtype), index=index)) 

 

@classmethod 

def empty(cls: Type[S], index: Collection) -> S: # pylint: disable=arguments-differ 

""" 

Return an uninitialized series 

""" 

return cls.am(Series(np.empty(len(index), dtype=cls.dtype), index=index)) 

 

@classmethod 

def filled(cls: Type[S], value: Any, index: Collection) -> S: 

""" 

Return a series full of zeros. 

""" 

series = cls.empty(index=index) 

series.values.fill(value) 

return series 

 

@classmethod 

def shared_memory_zeros(cls: Type[S], index: Collection) -> S: 

""" 

Create a shared memory series, initialized to zeros. 

""" 

return cls.am(Series(np.ARRAY_OF_DTYPE[cls.dtype].shared_memory_zeros(len(index)), 

index=index)) 

 

 

class BaseFrame(Frame): 

""" 

Base class for all Numpy data series phantom types. 

""" 

 

#: The expected data type of a data frame of the (derived) class. 

dtype: str 

 

@property 

def _constructor_expanddim(self) -> Any: 

assert False 

 

@classmethod 

def read(cls: Type[F], path: str, mmap_mode: Optional[str] = None) -> F: 

""" 

Read a Pandas data frame of the concrete type from the disk. 

 

If additional file(s) with an ``.index`` and/or ``.columns`` suffix exist, they are loaded 

into the index and/or column labels. 

""" 

assert not path.endswith('.npy') 

assert not path.endswith('.txt') 

 

array = np.BaseArray.read_matrix(path, mmap_mode) 

176 ↛ 179line 176 didn't jump to line 179, because the condition on line 176 was never false if cls != BaseFrame: 

frame = cls.am(Frame(array)) 

else: 

frame = Frame(array) # type: ignore 

 

index_path = path + '.index' 

if np.BaseArray.exists(index_path): 

index = np.BaseArray.read_array(index_path, mmap_mode) 

frame.set_axis(index, axis=0, inplace=True) # type: ignore 

 

columns_path = path + '.columns' 

if np.BaseArray.exists(columns_path): 

columns = np.BaseArray.read_array(columns_path, mmap_mode) 

frame.set_axis(columns, axis=1, inplace=True) # type: ignore 

 

return frame 

 

@classmethod 

def write(cls, frame: Frame, path: str) -> None: 

""" 

Write a Pandas data frame of the concrete type to a file. 

 

If necessary, creates additional file(s) with an ``.index`` and/or ``.columns`` suffix to 

preserve the index and/or column labels. 

""" 

cls.am(frame) 

 

np.BaseArray._write(frame.values, path) # pylint: disable=protected-access 

 

if not frame.index.equals(RangeIndex(len(frame.index))): 

np.BaseArray._write(frame.index.values, # pylint: disable=protected-access 

path + '.index') 

 

if not frame.columns.equals(RangeIndex(len(frame.columns))): 

np.BaseArray._write(frame.columns.values, # pylint: disable=protected-access 

path + '.columns') 

 

@classmethod 

def am(cls: Type[F], data: Frame) -> F: # pylint: disable=invalid-name 

""" 

Declare a data frame as being of this type. 

""" 

BaseFrame._am_frame(data) 

array = data.values 

if cls.dtype not in [array.dtype.name, array.dtype.kind]: 

raise ValueError('unexpected data type: %s instead of: %s' 

% (array.dtype, cls.dtype)) 

return data # type: ignore 

 

@classmethod 

def be(cls: Type[F], # pylint: disable=invalid-name 

data: Union[Frame, np.ndarray, List[List[Any]]], 

index: Optional[Collection] = None, columns: Optional[Collection] = None) -> F: 

""" 

Convert an array to this type. 

""" 

if isinstance(data, list): 

data = np.array(data, dtype=cls.dtype) 

if isinstance(data, np.ndarray): 

data = Frame(data, index=index, columns=columns) 

else: 

assert index is None 

assert columns is None 

 

BaseFrame._am_frame(data) 

array = data.values 

if cls.dtype not in [array.dtype.name, array.dtype.kind]: 

data = data.astype(cls.dtype) 

return data # type: ignore 

 

@staticmethod 

def _am_frame(data: Frame) -> None: 

if not isinstance(data, Frame): 

raise ValueError('unexpected type: %s.%s instead of: %s.%s' 

% (data.__class__.__module__, data.__class__.__qualname__, 

Frame.__module__, Frame.__qualname__)) 

array = data.values 

np.BaseArray._am_shape(array, 2) # pylint: disable=protected-access 

 

@classmethod 

def zeros(cls: Type[F], *, index: Collection, columns: Collection) -> F: 

""" 

Return a frame full of zeros. 

""" 

return cls._make(np.zeros, index=index, columns=columns) 

 

@classmethod 

def empty(cls: Type[F], *, # pylint: disable=arguments-differ 

index: Collection, columns: Collection) -> F: 

""" 

Return an uninitialized frame 

""" 

return cls._make(np.empty, index=index, columns=columns) 

 

@classmethod 

def filled(cls: Type[F], value: Any, *, index: Collection, columns: Collection) -> F: 

""" 

Return a frame full of some value. 

""" 

frame = cls.empty(index=index, columns=columns) 

frame.values.fill(value) 

return frame 

 

@classmethod 

def shared_memory_zeros(cls: Type[F], *, index: Collection, columns: Collection) -> F: 

""" 

Create a shared memory frame, initialized to zeros. 

""" 

def _matrix_maker(shape: Tuple[int, int], dtype: str) -> np.ndarray: 

return np.MATRIX_OF_DTYPE[dtype].shared_memory_zeros(shape) 

return cls._make(_matrix_maker, index=index, columns=columns) 

 

@classmethod 

def _make(cls: Type[F], matrix_maker: Callable, *, index: Collection, columns: Collection) -> F: 

return cls.am(Frame(matrix_maker((len(index), len(columns)), dtype=cls.dtype), 

index=index, columns=columns)) 

 

 

class SeriesStr(BaseSeries): 

""" 

A data series of Unicode strings. 

""" 

dtype = 'O' 

 

 

class SeriesBool(BaseSeries): 

""" 

A data series of booleans. 

""" 

dtype = 'bool' 

 

 

class FrameBool(BaseFrame): 

""" 

A data frame of booleans. 

""" 

dtype = 'bool' 

 

 

class SeriesInt8(BaseSeries): 

""" 

A data series of 8-bit integers. 

""" 

dtype = 'int8' 

 

 

class FrameInt8(BaseFrame): 

""" 

A data frame of 8-bit integers. 

""" 

dtype = 'int8' 

 

 

class SeriesInt16(BaseSeries): 

""" 

A data series of 16-bit integers. 

""" 

dtype = 'int16' 

 

 

class FrameInt16(BaseFrame): 

""" 

A data frame of 16-bit integers. 

""" 

dtype = 'int16' 

 

 

class SeriesInt32(BaseSeries): 

""" 

A data series of 32-bit integers. 

""" 

dtype = 'int32' 

 

 

class FrameInt32(BaseFrame): 

""" 

A data frame of 32-bit integers. 

""" 

dtype = 'int32' 

 

 

class SeriesInt64(BaseSeries): 

""" 

A data series of 64-bit integers. 

""" 

dtype = 'int64' 

 

 

class FrameInt64(BaseFrame): 

""" 

A data frame of 64-bit integers. 

""" 

dtype = 'int64' 

 

 

class SeriesFloat32(BaseSeries): 

""" 

A data series of 32-bit floating-point numbers. 

""" 

dtype = 'float32' 

 

 

class FrameFloat32(BaseFrame): 

""" 

A data frame of 32-bit floating-point numbers. 

""" 

dtype = 'float32' 

 

 

class SeriesFloat64(BaseSeries): 

""" 

A data series of 64-bit floating-point numbers. 

""" 

dtype = 'float64' 

 

 

class FrameFloat64(BaseFrame): 

""" 

A data frame of 64-bit floating-point numbers. 

""" 

dtype = 'float64' 

 

 

#: The phantom type for a data series by its type name. 

SERIES_OF_DTYPE = dict( # 

str=SeriesStr, 

bool=SeriesBool, 

int8=SeriesInt8, 

int16=SeriesInt16, 

int32=SeriesInt32, 

int64=SeriesInt64, 

float32=SeriesFloat32, 

float64=SeriesFloat64, 

) 

 

#: The phantom type for a data frame by its type name. 

FRAME_OF_DTYPE = dict( # 

bool=FrameBool, 

int8=FrameInt8, 

int16=FrameInt16, 

int32=FrameInt32, 

int64=FrameInt64, 

float32=FrameFloat32, 

float64=FrameFloat64, 

)