epymorph 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/adrio/soda.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Methods for querying SODA APIs.
|
|
3
|
+
|
|
4
|
+
See Also
|
|
5
|
+
--------
|
|
6
|
+
The API documentation at [https://dev.socrata.com/](https://dev.socrata.com/).
|
|
7
|
+
|
|
8
|
+
Examples
|
|
9
|
+
--------
|
|
10
|
+
--8<-- "docs/_examples/adrio_soda.md"
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
# NOTE: There is a package called sodapy that was created for this purpose;
|
|
14
|
+
# however at time of writing, it is no longer maintained.
|
|
15
|
+
|
|
16
|
+
from abc import abstractmethod
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import date
|
|
20
|
+
from typing import (
|
|
21
|
+
Any,
|
|
22
|
+
Callable,
|
|
23
|
+
Generator,
|
|
24
|
+
Iterable,
|
|
25
|
+
Literal,
|
|
26
|
+
Protocol,
|
|
27
|
+
Sequence,
|
|
28
|
+
TypeVar,
|
|
29
|
+
)
|
|
30
|
+
from urllib.parse import quote, urlencode
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
import pandas as pd
|
|
34
|
+
import requests
|
|
35
|
+
from numpy.typing import DTypeLike
|
|
36
|
+
from typing_extensions import override
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _parens(s: str) -> str:
|
|
40
|
+
"""Formatting util: enclose in parens.""" # noqa: D401
|
|
41
|
+
return f"({s})"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _col(s: str) -> str:
|
|
45
|
+
"""Formatting util: SOQL column name.""" # noqa: D401
|
|
46
|
+
return f"`{s}`"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _txt(s: str) -> str:
|
|
50
|
+
"""Formatting util: SOQL text.""" # noqa: D401
|
|
51
|
+
return f"'{s}'"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _date(d: date) -> str:
|
|
55
|
+
"""Formatting util: date as SOQL timestamp.""" # noqa: D401
|
|
56
|
+
return f"'{d}T00:00:00'"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_T_co = TypeVar("_T_co", covariant=True)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _list(xs: Iterable[_T_co], to_string: Callable[[_T_co], str] = str) -> str:
|
|
63
|
+
"""Formatting util: list of values.""" # noqa: D401
|
|
64
|
+
return ",".join([to_string(x) for x in xs])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
ColumnType = Literal["str", "int", "nullable_int", "float", "date", "bool"]
|
|
68
|
+
"""Simplified set of types for SOQL result columns."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _to_pandas_type(col_type: ColumnType) -> DTypeLike:
|
|
72
|
+
"""Get the pandas type that corresponds to the SOQL column type."""
|
|
73
|
+
match col_type:
|
|
74
|
+
case "str":
|
|
75
|
+
return np.str_
|
|
76
|
+
case "int":
|
|
77
|
+
return np.int64
|
|
78
|
+
case "nullable_int":
|
|
79
|
+
# allow integer columns to use Pandas' nullable integer type
|
|
80
|
+
return "Int64"
|
|
81
|
+
case "float":
|
|
82
|
+
return np.float64
|
|
83
|
+
case "date":
|
|
84
|
+
return np.datetime64
|
|
85
|
+
case "bool":
|
|
86
|
+
return np.bool_
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class SocrataResource:
|
|
91
|
+
"""
|
|
92
|
+
Defines a Socrata API resource.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
domain :
|
|
97
|
+
The domain where the API is hosted.
|
|
98
|
+
id :
|
|
99
|
+
The ID of the resource.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
domain: str
|
|
103
|
+
"""The domain where the API is hosted."""
|
|
104
|
+
id: str
|
|
105
|
+
"""The ID of the resource."""
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def url(self) -> str:
|
|
109
|
+
"""The URL for this resource."""
|
|
110
|
+
return f"https://{self.domain}/resource/{self.id}"
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def metadata_url(self) -> str:
|
|
114
|
+
"""The URL for the metadata description of the resource (JSON format)."""
|
|
115
|
+
return f"https://{self.domain}/api/views/{self.id}.json"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ARCHITECTURE NOTE: what follows is a collection of objects which model a SOQL query.
|
|
119
|
+
# Compose your query by putting together instances of these clause types.
|
|
120
|
+
# The whole query can be converted to a string -- `str(query_object)` -- which
|
|
121
|
+
# in turn calls `str` on all of the clauses as appropriate and combines the
|
|
122
|
+
# parts into a full query.
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class SelectClause(Protocol):
|
|
126
|
+
"""The common interface for SOQL select clauses."""
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
@abstractmethod
|
|
130
|
+
def result_name(self) -> str:
|
|
131
|
+
"""The name to use to refer to the result."""
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
@abstractmethod
|
|
135
|
+
def result_dtype(self) -> ColumnType:
|
|
136
|
+
"""The data type of the result."""
|
|
137
|
+
# This is really just here to avoid issues with dataclasses and inheritence.
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True, slots=True)
|
|
141
|
+
class Select(SelectClause):
|
|
142
|
+
"""
|
|
143
|
+
A SOQL select clause for selecting a column as-is.
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
name :
|
|
148
|
+
Column name.
|
|
149
|
+
dtype :
|
|
150
|
+
The data type of the column.
|
|
151
|
+
as_name :
|
|
152
|
+
Define a new name for the column; the 'AS' statement.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
name: str
|
|
156
|
+
"""Column name."""
|
|
157
|
+
dtype: ColumnType
|
|
158
|
+
"""The data type of the column."""
|
|
159
|
+
as_name: str | None = field(default=None)
|
|
160
|
+
"""Define a new name for the column; the 'AS' statement."""
|
|
161
|
+
|
|
162
|
+
def __str__(self) -> str:
|
|
163
|
+
if self.as_name is not None:
|
|
164
|
+
return f"{_col(self.name)} AS {_col(self.as_name)}"
|
|
165
|
+
return _col(self.name)
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
@override
|
|
169
|
+
def result_name(self) -> str:
|
|
170
|
+
return self.as_name or self.name
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
@override
|
|
174
|
+
def result_dtype(self) -> ColumnType:
|
|
175
|
+
return self.dtype
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True, slots=True)
|
|
179
|
+
class SelectExpression(SelectClause):
|
|
180
|
+
"""
|
|
181
|
+
A SOQL select clause for selecting the result of an expression.
|
|
182
|
+
|
|
183
|
+
Parameters
|
|
184
|
+
----------
|
|
185
|
+
expression :
|
|
186
|
+
Expression; as best practice you should escape column names in the expression
|
|
187
|
+
by surrounding them in back-ticks.
|
|
188
|
+
dtype :
|
|
189
|
+
The data type of the column.
|
|
190
|
+
as_name :
|
|
191
|
+
Define a name for the result; the 'AS' statement.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
expression: str
|
|
195
|
+
"""
|
|
196
|
+
Expression; as best practice you should escape column names in the expression
|
|
197
|
+
by surrounding them in back-ticks.
|
|
198
|
+
"""
|
|
199
|
+
dtype: ColumnType
|
|
200
|
+
"""The data type of the column."""
|
|
201
|
+
as_name: str
|
|
202
|
+
"""Define a name for the result; the 'AS' statement."""
|
|
203
|
+
|
|
204
|
+
def __str__(self) -> str:
|
|
205
|
+
return f"({self.expression}) AS {_col(self.as_name)}"
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
@override
|
|
209
|
+
def result_name(self) -> str:
|
|
210
|
+
return self.as_name
|
|
211
|
+
|
|
212
|
+
@property
|
|
213
|
+
@override
|
|
214
|
+
def result_dtype(self) -> ColumnType:
|
|
215
|
+
return self.dtype
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class WhereClause(Protocol):
|
|
219
|
+
"""The common interface for SOQL where clauses."""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True, slots=True)
|
|
223
|
+
class NotNull(WhereClause):
|
|
224
|
+
"""
|
|
225
|
+
A where-clause for rows that are not null.
|
|
226
|
+
|
|
227
|
+
Parameters
|
|
228
|
+
----------
|
|
229
|
+
column :
|
|
230
|
+
Column name.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
column: str
|
|
234
|
+
"""Column name."""
|
|
235
|
+
|
|
236
|
+
def __str__(self) -> str:
|
|
237
|
+
return f"{_col(self.column)} IS NOT NULL"
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(frozen=True, slots=True)
|
|
241
|
+
class Equals(WhereClause):
|
|
242
|
+
"""
|
|
243
|
+
A where-clause for rows whose values are equal to the given value.
|
|
244
|
+
|
|
245
|
+
Parameters
|
|
246
|
+
----------
|
|
247
|
+
column :
|
|
248
|
+
Column name.
|
|
249
|
+
value :
|
|
250
|
+
The value to test.
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
column: str
|
|
254
|
+
"""Column name."""
|
|
255
|
+
value: str
|
|
256
|
+
"""The value to test."""
|
|
257
|
+
|
|
258
|
+
def __str__(self) -> str:
|
|
259
|
+
return f"{_col(self.column)}={_txt(self.value)}"
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@dataclass(frozen=True, slots=True)
|
|
263
|
+
class In(WhereClause):
|
|
264
|
+
"""
|
|
265
|
+
A where-clause for rows whose values are in the given set of values.
|
|
266
|
+
|
|
267
|
+
Parameters
|
|
268
|
+
----------
|
|
269
|
+
column :
|
|
270
|
+
Column name.
|
|
271
|
+
values :
|
|
272
|
+
The sequence of values to test.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
column: str
|
|
276
|
+
"""Column name."""
|
|
277
|
+
values: Iterable[str]
|
|
278
|
+
"""The sequence of values to test."""
|
|
279
|
+
|
|
280
|
+
def __post_init__(self):
|
|
281
|
+
if isinstance(self.values, Iterator):
|
|
282
|
+
values = list(self.values)
|
|
283
|
+
object.__setattr__(self, "values", values)
|
|
284
|
+
|
|
285
|
+
def __str__(self) -> str:
|
|
286
|
+
return f"{_col(self.column)} IN ({_list(self.values, _txt)})"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@dataclass(frozen=True, slots=True)
|
|
290
|
+
class DateBetween(WhereClause):
|
|
291
|
+
"""
|
|
292
|
+
A where-clause for rows whose date values are between two dates.
|
|
293
|
+
Endpoints are inclusive.
|
|
294
|
+
|
|
295
|
+
Parameters
|
|
296
|
+
----------
|
|
297
|
+
column :
|
|
298
|
+
Column name.
|
|
299
|
+
start :
|
|
300
|
+
Start date.
|
|
301
|
+
end :
|
|
302
|
+
End date (inclusive).
|
|
303
|
+
"""
|
|
304
|
+
|
|
305
|
+
column: str
|
|
306
|
+
"""Column name."""
|
|
307
|
+
start: date
|
|
308
|
+
"""Start date."""
|
|
309
|
+
end: date
|
|
310
|
+
"""End date (inclusive)."""
|
|
311
|
+
|
|
312
|
+
def __str__(self) -> str:
|
|
313
|
+
return f"{_col(self.column)} BETWEEN {_date(self.start)} AND {_date(self.end)}"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
@dataclass(frozen=True, slots=True, init=False)
|
|
317
|
+
class And(WhereClause):
|
|
318
|
+
"""
|
|
319
|
+
A where-clause that joins other where clauses with "and".
|
|
320
|
+
|
|
321
|
+
Parameters
|
|
322
|
+
----------
|
|
323
|
+
clauses :
|
|
324
|
+
The clauses to join with an 'AND'.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
clauses: Sequence[WhereClause]
|
|
328
|
+
"""The clauses to join with an 'AND'."""
|
|
329
|
+
|
|
330
|
+
def __init__(self, *clauses: WhereClause):
|
|
331
|
+
object.__setattr__(self, "clauses", clauses)
|
|
332
|
+
|
|
333
|
+
def __str__(self) -> str:
|
|
334
|
+
match len(self.clauses):
|
|
335
|
+
case 0:
|
|
336
|
+
return ""
|
|
337
|
+
case 1:
|
|
338
|
+
return str(self.clauses[0])
|
|
339
|
+
case _:
|
|
340
|
+
return _parens(" AND ".join([str(x) for x in self.clauses]))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@dataclass(frozen=True, slots=True, init=False)
|
|
344
|
+
class Or(WhereClause):
|
|
345
|
+
"""
|
|
346
|
+
A where-clause that joins other where clauses with "or".
|
|
347
|
+
|
|
348
|
+
Parameters
|
|
349
|
+
----------
|
|
350
|
+
clauses :
|
|
351
|
+
The clauses to join with an 'OR'.
|
|
352
|
+
"""
|
|
353
|
+
|
|
354
|
+
clauses: Sequence[WhereClause]
|
|
355
|
+
"""The clauses to join with an 'OR'."""
|
|
356
|
+
|
|
357
|
+
def __init__(self, *clauses: WhereClause):
|
|
358
|
+
object.__setattr__(self, "clauses", clauses)
|
|
359
|
+
|
|
360
|
+
def __str__(self) -> str:
|
|
361
|
+
match len(self.clauses):
|
|
362
|
+
case 0:
|
|
363
|
+
return ""
|
|
364
|
+
case 1:
|
|
365
|
+
return str(self.clauses[0])
|
|
366
|
+
case _:
|
|
367
|
+
return _parens(" OR ".join([str(x) for x in self.clauses]))
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@dataclass(frozen=True, slots=True)
|
|
371
|
+
class Not(WhereClause):
|
|
372
|
+
"""
|
|
373
|
+
A where-clause that negates another where clause.
|
|
374
|
+
|
|
375
|
+
Parameters
|
|
376
|
+
----------
|
|
377
|
+
clause :
|
|
378
|
+
The clause to negate.
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
clause: WhereClause
|
|
382
|
+
"""The clause to negate."""
|
|
383
|
+
|
|
384
|
+
def __str__(self) -> str:
|
|
385
|
+
return f"NOT {str(self.clause)}"
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class OrderClause(Protocol):
|
|
389
|
+
"""The common interface for SOQL order-by clauses."""
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@dataclass(frozen=True, slots=True)
|
|
393
|
+
class Ascending(OrderClause):
|
|
394
|
+
"""
|
|
395
|
+
An order-by-clause that sorts the named column in ascending order.
|
|
396
|
+
|
|
397
|
+
Parameters
|
|
398
|
+
----------
|
|
399
|
+
column :
|
|
400
|
+
The column name.
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
column: str
|
|
404
|
+
"""The column name."""
|
|
405
|
+
|
|
406
|
+
def __str__(self) -> str:
|
|
407
|
+
return f"{_col(self.column)} ASC"
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
@dataclass(frozen=True, slots=True)
|
|
411
|
+
class Descending(OrderClause):
|
|
412
|
+
"""
|
|
413
|
+
An order-by-clause that sorts the named column in descending order.
|
|
414
|
+
|
|
415
|
+
Parameters
|
|
416
|
+
----------
|
|
417
|
+
column :
|
|
418
|
+
The column name.
|
|
419
|
+
"""
|
|
420
|
+
|
|
421
|
+
column: str
|
|
422
|
+
"""The column name."""
|
|
423
|
+
|
|
424
|
+
def __str__(self) -> str:
|
|
425
|
+
return f"{_col(self.column)} DESC"
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
@dataclass(frozen=True, slots=True)
|
|
429
|
+
class Query:
|
|
430
|
+
"""
|
|
431
|
+
A complete SOQL query, which includes oen or more select clauses,
|
|
432
|
+
exactly one where clause, and any number of order-by clauses.
|
|
433
|
+
|
|
434
|
+
Parameters
|
|
435
|
+
----------
|
|
436
|
+
select :
|
|
437
|
+
One or more select clauses.
|
|
438
|
+
where :
|
|
439
|
+
A where clause.
|
|
440
|
+
order_by :
|
|
441
|
+
Zero or more order-by clause.
|
|
442
|
+
"""
|
|
443
|
+
|
|
444
|
+
select: Sequence[SelectClause]
|
|
445
|
+
"""One or more select clauses."""
|
|
446
|
+
where: WhereClause
|
|
447
|
+
"""A where clause."""
|
|
448
|
+
order_by: Sequence[OrderClause] | None = field(default=None)
|
|
449
|
+
"""Zero or more order-by clauses."""
|
|
450
|
+
|
|
451
|
+
def __post_init__(self):
|
|
452
|
+
if len(self.select) == 0:
|
|
453
|
+
err = "Query must contain at least one select clause."
|
|
454
|
+
raise ValueError(err)
|
|
455
|
+
|
|
456
|
+
def __str__(self) -> str:
|
|
457
|
+
soql = f"SELECT {_list(self.select)} WHERE {self.where}"
|
|
458
|
+
if self.order_by is not None and len(self.order_by) > 0:
|
|
459
|
+
return f"{soql} ORDER BY {_list(self.order_by)}"
|
|
460
|
+
return soql
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def get_metadata(resource: SocrataResource) -> Any:
|
|
464
|
+
"""
|
|
465
|
+
Retrieve the JSON-formatted metadata for the given resource.
|
|
466
|
+
|
|
467
|
+
Parameters
|
|
468
|
+
----------
|
|
469
|
+
resource :
|
|
470
|
+
The data resource.
|
|
471
|
+
|
|
472
|
+
Returns
|
|
473
|
+
-------
|
|
474
|
+
:
|
|
475
|
+
The JSON metadata.
|
|
476
|
+
"""
|
|
477
|
+
response = requests.get(resource.metadata_url, timeout=60)
|
|
478
|
+
response.raise_for_status()
|
|
479
|
+
metadata = response.json()
|
|
480
|
+
return metadata
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def query_csv(
|
|
484
|
+
resource: SocrataResource,
|
|
485
|
+
query: Query,
|
|
486
|
+
*,
|
|
487
|
+
limit: int = 10000,
|
|
488
|
+
result_filter: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
|
|
489
|
+
api_token: str | None = None,
|
|
490
|
+
) -> pd.DataFrame:
|
|
491
|
+
"""
|
|
492
|
+
Issue `query` against the data in `resource` and return the result as a dataframe.
|
|
493
|
+
For particularly large result sets, we may need to break up the total query into
|
|
494
|
+
more than one request. This is handled automatically, as is concatenating the
|
|
495
|
+
results.
|
|
496
|
+
|
|
497
|
+
Parameters
|
|
498
|
+
----------
|
|
499
|
+
resource :
|
|
500
|
+
The data resource.
|
|
501
|
+
query :
|
|
502
|
+
The query object.
|
|
503
|
+
limit :
|
|
504
|
+
The maximum number of rows fetched per request. Changing this should not change
|
|
505
|
+
the results, but may change the number of requests (and the clock time) it takes
|
|
506
|
+
to produce the results.
|
|
507
|
+
result_filter :
|
|
508
|
+
An optional transform to apply to the results, intended to be used to filter out
|
|
509
|
+
rows from the result in situations where doing this filtering as a where-clause
|
|
510
|
+
would be impossible or impractical. This function will be run on the results of
|
|
511
|
+
each request, not the end result, since it is likely to be more efficient to
|
|
512
|
+
filter as we go when the data requires many requests to complete.
|
|
513
|
+
api_token :
|
|
514
|
+
An optional API token to include in requests.
|
|
515
|
+
|
|
516
|
+
Returns
|
|
517
|
+
-------
|
|
518
|
+
:
|
|
519
|
+
The query results.
|
|
520
|
+
"""
|
|
521
|
+
return query_csv_soql(
|
|
522
|
+
resource=resource,
|
|
523
|
+
soql=str(query),
|
|
524
|
+
column_types=[(x.result_name, x.result_dtype) for x in query.select],
|
|
525
|
+
limit=limit,
|
|
526
|
+
result_filter=result_filter,
|
|
527
|
+
api_token=api_token,
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def query_csv_soql(
|
|
532
|
+
resource: SocrataResource,
|
|
533
|
+
soql: str,
|
|
534
|
+
column_types: Sequence[tuple[str, ColumnType]],
|
|
535
|
+
*,
|
|
536
|
+
limit: int = 10000,
|
|
537
|
+
result_filter: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
|
|
538
|
+
api_token: str | None = None,
|
|
539
|
+
) -> pd.DataFrame:
|
|
540
|
+
"""
|
|
541
|
+
Issue the query (given in string form, `soql`) against the data in `resource` and
|
|
542
|
+
return the result as a dataframe. For particularly large result sets, we may need to
|
|
543
|
+
break up the total query into more than one request. This is handled automatically,
|
|
544
|
+
as is concatenating the results.
|
|
545
|
+
|
|
546
|
+
Parameters
|
|
547
|
+
----------
|
|
548
|
+
resource :
|
|
549
|
+
The data resource.
|
|
550
|
+
soql :
|
|
551
|
+
The query string.
|
|
552
|
+
column_types :
|
|
553
|
+
The expected data types of the selected columns.
|
|
554
|
+
limit :
|
|
555
|
+
The maximum number of rows fetched per request. Changing this should not change
|
|
556
|
+
the results, but may change the number of requests (and the clock time) it takes
|
|
557
|
+
to produce the results.
|
|
558
|
+
result_filter :
|
|
559
|
+
An optional transform to apply to the results, intended to be used to filter out
|
|
560
|
+
rows from the result in situations where doing this filtering as a where-clause
|
|
561
|
+
would be impossible or impractical. This function will be run on the results of
|
|
562
|
+
each request, not the end result, since it is likely to be more efficient to
|
|
563
|
+
filter as we go when the data requires many requests to complete.
|
|
564
|
+
api_token :
|
|
565
|
+
An optional API token to include in requests.
|
|
566
|
+
|
|
567
|
+
Returns
|
|
568
|
+
-------
|
|
569
|
+
:
|
|
570
|
+
The query results.
|
|
571
|
+
"""
|
|
572
|
+
|
|
573
|
+
# NOTE: type conversion is essentially non-existent,
|
|
574
|
+
# e.g., if the data has '3.0' in a column declared as an int, this will raise.
|
|
575
|
+
|
|
576
|
+
column_dtypes = {n: _to_pandas_type(t) for n, t in column_types if t != "date"}
|
|
577
|
+
column_parsedates = [n for n, t in column_types if t == "date"]
|
|
578
|
+
req_headers = None if api_token is None else {"X-App-Token": api_token}
|
|
579
|
+
|
|
580
|
+
def query_pages(offset: int = 0) -> Generator[pd.DataFrame, None, None]:
|
|
581
|
+
page_soql = f"{soql} LIMIT {limit} OFFSET {offset}"
|
|
582
|
+
query_string = urlencode(
|
|
583
|
+
quote_via=quote,
|
|
584
|
+
safe=",()'$:",
|
|
585
|
+
query={"$query": page_soql},
|
|
586
|
+
)
|
|
587
|
+
page_df = pd.read_csv(
|
|
588
|
+
f"{resource.url}.csv?{query_string}",
|
|
589
|
+
dtype=column_dtypes, # type: ignore
|
|
590
|
+
parse_dates=column_parsedates,
|
|
591
|
+
storage_options=req_headers,
|
|
592
|
+
date_format="ISO8601",
|
|
593
|
+
)
|
|
594
|
+
response_rows = len(page_df.index)
|
|
595
|
+
if result_filter is not None:
|
|
596
|
+
page_df = result_filter(page_df)
|
|
597
|
+
yield page_df
|
|
598
|
+
|
|
599
|
+
if (page_size := response_rows) >= limit:
|
|
600
|
+
yield from query_pages(offset + page_size)
|
|
601
|
+
|
|
602
|
+
return pd.concat(query_pages())
|