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

# This file is part of daf_butler. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (http://www.lsst.org). 

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with this program. If not, see <http://www.gnu.org/licenses/>. 

 

__all__ = ("ParquetFormatter", ) 

 

import json 

import re 

import collections.abc 

import itertools 

import copy 

from typing import ( 

Any, 

Dict, 

Iterable, 

Iterator, 

List, 

Optional, 

Tuple, 

Union, 

) 

 

import pyarrow.parquet as pq 

import pandas as pd 

import pyarrow as pa 

 

from lsst.daf.butler.core.utils import iterable 

from lsst.daf.butler import Formatter, Location 

 

 

class _ParquetLoader: 

"""Helper class for loading Parquet files into `pandas.DataFrame` 

instances. 

 

Parameters 

---------- 

path : `str` 

Full path to the file to be loaded. 

""" 

 

def __init__(self, path: str): 

self.file = pq.ParquetFile(path) 

self.md = json.loads(self.file.metadata.metadata[b"pandas"]) 

indexes = self.md["column_indexes"] 

if len(indexes) == 1: 

self.columns = pd.Index(name for name in self.file.metadata.schema.names 

if not name.startswith("__")) 

else: 

raw_columns = list(self._splitColumnnNames(len(indexes), self.file.metadata.schema.names)) 

self.columns = pd.MultiIndex.from_tuples(raw_columns, names=[f["name"] for f in indexes]) 

self.indexLevelNames = tuple(self.columns.names) 

 

@staticmethod 

def _splitColumnnNames(n: int, names: Iterable[str]) -> Iterator[Tuple[str]]: 

"""Split a string that represents a multi-index column. 

 

PyArrow maps Pandas' multi-index column names (which are tuples in 

Pythons) to flat strings on disk. This routine exists to 

reconstruct the original tuple. 

 

Parameters 

---------- 

n : `int` 

Number of levels in the `pd.MultiIndex` that is being 

reconstructed. 

names : `~collections.abc.Iterable` of `str` 

Strings to be split. 

 

Yields 

------ 

tuple : `tuple` of `str` 

A multi-index column name tuple. 

""" 

pattern = re.compile(r"\({}\)".format(', '.join(["'(.*)'"] * n))) 

for name in names: 

m = re.search(pattern, name) 

if m is not None: 

yield m.groups() 

 

def _standardizeColumnParameter(self, columns: Dict[str, Union[str, List[str]]]) -> Iterator[str]: 

"""Transform a dictionary index into a multi-index column into a 

string directly understandable by PyArrow. 

 

Parameters 

---------- 

columns : `dict` 

Dictionary whose elements are string multi-index level names 

and whose values are the value or values (as a list) for that 

level. 

 

Yields 

------ 

name : `str` 

Stringified tuple representing a multi-index column name. 

""" 

if not isinstance(columns, collections.abc.Mapping): 

raise ValueError("columns parameter for multi-index data frame must be a dictionary.") 

115 ↛ 116line 115 didn't jump to line 116, because the condition on line 115 was never true if not set(self.indexLevelNames).issuperset(columns.keys()): 

raise ValueError(f"Cannot use dict with keys {set(columns.keys())} " 

f"to select columns from {self.indexLevelNames}.") 

factors = [iterable(columns.get(level, self.columns.levels[i])) 

for i, level in enumerate(self.indexLevelNames)] 

for requested in itertools.product(*factors): 

for i, value in enumerate(requested): 

122 ↛ 123line 122 didn't jump to line 123, because the condition on line 122 was never true if value not in self.columns.levels[i]: 

raise ValueError(f"Unrecognized value {value!r} for index {self.indexLevelNames[i]!r}.") 

yield str(requested) 

 

def read(self, columns: Union[str, List[str], Dict[str, Union[str, List[str]]]] = None 

) -> pd.DataFrame: 

"""Read some or all of the Parquet file into a `pandas.DataFrame` 

instance. 

 

Parameters 

---------- 

columns: : `dict`, `list`, or `str`, optional 

A description of the columns to be loaded. See 

:ref:`lsst.daf.butler-concrete_storage_classes_dataframe`. 

 

Returns 

------- 

df : `pandas.DataFrame` 

A Pandas DataFrame. 

""" 

if columns is None: 

return self.file.read(use_pandas_metadata=True).to_pandas() 

elif isinstance(self.columns, pd.MultiIndex): 

columns = list(self._standardizeColumnParameter(columns)) 

else: 

for column in columns: 

if column not in self.columns: 

raise ValueError(f"Unrecognized column name {column!r}.") 

return self.file.read(columns=columns, use_pandas_metadata=True).to_pandas() 

 

 

def _writeParquet(path: str, inMemoryDataset: pd.DataFrame): 

"""Write a `pandas.DataFrame` instance as a Parquet file. 

""" 

table = pa.Table.from_pandas(inMemoryDataset) 

pq.write_table(table, path, compression='none') 

 

 

class ParquetFormatter(Formatter): 

"""Interface for reading and writing Pandas DataFrames to and from Parquet 

files. 

 

This formatter is for the 

:ref:`lsst.daf.butler-concrete_storage_classes_dataframe` StorageClass. 

""" 

extension = ".parq" 

 

def read(self, component: Optional[str] = None) -> object: 

# Docstring inherited from Formatter.read. 

loader = _ParquetLoader(self.fileDescriptor.location.path) 

if component == 'columns': 

return loader.columns 

 

if not self.fileDescriptor.parameters: 

return loader.read() 

 

return loader.read(**self.fileDescriptor.parameters) 

 

def write(self, inMemoryDataset: Any) -> str: 

# Docstring inherited from Formatter.write. 

location = self.makeUpdatedLocation(self.fileDescriptor.location) 

_writeParquet(location.path, inMemoryDataset) 

return location.pathInStore 

 

@classmethod 

def makeUpdatedLocation(cls, location: Location) -> Location: 

"""Return a new `Location` instance updated with this formatter's 

extension. 

""" 

location = copy.deepcopy(location) 

location.updateExtension(cls.extension) 

return location 

 

@classmethod 

def predictPathFromLocation(cls, location: Location) -> str: 

# Docstring inherited from Formatter.predictPathFromLocation. 

return cls.makeUpdatedLocation(location).pathInStore