kumoai 2.13.0.dev202511261731__cp310-cp310-win_amd64.whl → 2.13.0.dev202512040252__cp310-cp310-win_amd64.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.
- kumoai/_version.py +1 -1
- kumoai/connector/utils.py +23 -2
- kumoai/experimental/rfm/__init__.py +20 -45
- kumoai/experimental/rfm/backend/__init__.py +0 -0
- kumoai/experimental/rfm/backend/local/__init__.py +38 -0
- kumoai/experimental/rfm/backend/local/table.py +109 -0
- kumoai/experimental/rfm/backend/snow/__init__.py +35 -0
- kumoai/experimental/rfm/backend/snow/table.py +115 -0
- kumoai/experimental/rfm/backend/sqlite/__init__.py +30 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +101 -0
- kumoai/experimental/rfm/base/__init__.py +10 -0
- kumoai/experimental/rfm/base/column.py +66 -0
- kumoai/experimental/rfm/base/source.py +18 -0
- kumoai/experimental/rfm/{local_table.py → base/table.py} +134 -139
- kumoai/experimental/rfm/{local_graph.py → graph.py} +287 -62
- kumoai/experimental/rfm/infer/__init__.py +6 -0
- kumoai/experimental/rfm/infer/dtype.py +79 -0
- kumoai/experimental/rfm/infer/pkey.py +126 -0
- kumoai/experimental/rfm/infer/time_col.py +62 -0
- kumoai/experimental/rfm/local_graph_sampler.py +42 -1
- kumoai/experimental/rfm/local_graph_store.py +13 -27
- kumoai/experimental/rfm/rfm.py +6 -16
- kumoai/experimental/rfm/sagemaker.py +11 -3
- kumoai/kumolib.cp310-win_amd64.pyd +0 -0
- kumoai/testing/decorators.py +1 -1
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512040252.dist-info}/METADATA +9 -8
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512040252.dist-info}/RECORD +30 -18
- kumoai/experimental/rfm/utils.py +0 -344
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512040252.dist-info}/WHEEL +0 -0
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512040252.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512040252.dist-info}/top_level.txt +0 -0
|
@@ -2,8 +2,10 @@ import contextlib
|
|
|
2
2
|
import io
|
|
3
3
|
import warnings
|
|
4
4
|
from collections import defaultdict
|
|
5
|
+
from dataclasses import dataclass, field
|
|
5
6
|
from importlib.util import find_spec
|
|
6
|
-
from
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
|
|
7
9
|
|
|
8
10
|
import pandas as pd
|
|
9
11
|
from kumoapi.graph import ColumnKey, ColumnKeyGroup, GraphDefinition
|
|
@@ -12,19 +14,28 @@ from kumoapi.typing import Stype
|
|
|
12
14
|
from typing_extensions import Self
|
|
13
15
|
|
|
14
16
|
from kumoai import in_notebook
|
|
15
|
-
from kumoai.experimental.rfm import
|
|
17
|
+
from kumoai.experimental.rfm import Table
|
|
16
18
|
from kumoai.graph import Edge
|
|
19
|
+
from kumoai.mixin import CastMixin
|
|
17
20
|
|
|
18
21
|
if TYPE_CHECKING:
|
|
19
22
|
import graphviz
|
|
23
|
+
from adbc_driver_sqlite.dbapi import AdbcSqliteConnection
|
|
24
|
+
from snowflake.connector import SnowflakeConnection
|
|
20
25
|
|
|
21
26
|
|
|
22
|
-
|
|
23
|
-
|
|
27
|
+
@dataclass
|
|
28
|
+
class SqliteConnectionConfig(CastMixin):
|
|
29
|
+
uri: Union[str, Path]
|
|
30
|
+
kwargs: Dict[str, Any] = field(default_factory=dict)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Graph:
|
|
34
|
+
r"""A graph of :class:`Table` objects, akin to relationships between
|
|
24
35
|
tables in a relational database.
|
|
25
36
|
|
|
26
37
|
Creating a graph is the final step of data definition; after a
|
|
27
|
-
:class:`
|
|
38
|
+
:class:`Graph` is created, you can use it to initialize the
|
|
28
39
|
Kumo Relational Foundation Model (:class:`KumoRFM`).
|
|
29
40
|
|
|
30
41
|
.. code-block:: python
|
|
@@ -44,7 +55,7 @@ class LocalGraph:
|
|
|
44
55
|
>>> table3 = rfm.LocalTable(name="table3", data=df3)
|
|
45
56
|
|
|
46
57
|
>>> # Create a graph from a dictionary of tables:
|
|
47
|
-
>>> graph = rfm.
|
|
58
|
+
>>> graph = rfm.Graph({
|
|
48
59
|
... "table1": table1,
|
|
49
60
|
... "table2": table2,
|
|
50
61
|
... "table3": table3,
|
|
@@ -75,33 +86,47 @@ class LocalGraph:
|
|
|
75
86
|
|
|
76
87
|
def __init__(
|
|
77
88
|
self,
|
|
78
|
-
tables:
|
|
79
|
-
edges: Optional[
|
|
89
|
+
tables: Sequence[Table],
|
|
90
|
+
edges: Optional[Sequence[Edge]] = None,
|
|
80
91
|
) -> None:
|
|
81
92
|
|
|
82
|
-
self._tables: Dict[str,
|
|
93
|
+
self._tables: Dict[str, Table] = {}
|
|
83
94
|
self._edges: List[Edge] = []
|
|
84
95
|
|
|
85
96
|
for table in tables:
|
|
86
97
|
self.add_table(table)
|
|
87
98
|
|
|
99
|
+
for table in tables:
|
|
100
|
+
for fkey in table._source_foreign_key_dict.values():
|
|
101
|
+
if fkey.name not in table or fkey.dst_table not in self:
|
|
102
|
+
continue
|
|
103
|
+
if self[fkey.dst_table].primary_key is None:
|
|
104
|
+
self[fkey.dst_table].primary_key = fkey.primary_key
|
|
105
|
+
elif self[fkey.dst_table]._primary_key != fkey.primary_key:
|
|
106
|
+
raise ValueError(f"Found duplicate primary key definition "
|
|
107
|
+
f"'{self[fkey.dst_table]._primary_key}' "
|
|
108
|
+
f"and '{fkey.primary_key}' in table "
|
|
109
|
+
f"'{fkey.dst_table}'.")
|
|
110
|
+
self.link(table.name, fkey.name, fkey.dst_table)
|
|
111
|
+
|
|
88
112
|
for edge in (edges or []):
|
|
89
113
|
_edge = Edge._cast(edge)
|
|
90
114
|
assert _edge is not None
|
|
91
|
-
self.
|
|
115
|
+
if _edge not in self._edges:
|
|
116
|
+
self.link(*_edge)
|
|
92
117
|
|
|
93
118
|
@classmethod
|
|
94
119
|
def from_data(
|
|
95
120
|
cls,
|
|
96
121
|
df_dict: Dict[str, pd.DataFrame],
|
|
97
|
-
edges: Optional[
|
|
122
|
+
edges: Optional[Sequence[Edge]] = None,
|
|
98
123
|
infer_metadata: bool = True,
|
|
99
124
|
verbose: bool = True,
|
|
100
125
|
) -> Self:
|
|
101
|
-
r"""Creates a :class:`
|
|
126
|
+
r"""Creates a :class:`Graph` from a dictionary of
|
|
102
127
|
:class:`pandas.DataFrame` objects.
|
|
103
128
|
|
|
104
|
-
Automatically infers table metadata and links.
|
|
129
|
+
Automatically infers table metadata and links by default.
|
|
105
130
|
|
|
106
131
|
.. code-block:: python
|
|
107
132
|
|
|
@@ -115,55 +140,244 @@ class LocalGraph:
|
|
|
115
140
|
>>> df3 = pd.DataFrame(...)
|
|
116
141
|
|
|
117
142
|
>>> # Create a graph from a dictionary of data frames:
|
|
118
|
-
>>> graph = rfm.
|
|
143
|
+
>>> graph = rfm.Graph.from_data({
|
|
119
144
|
... "table1": df1,
|
|
120
145
|
... "table2": df2,
|
|
121
146
|
... "table3": df3,
|
|
122
147
|
... })
|
|
123
148
|
|
|
124
|
-
>>> # Inspect table metadata:
|
|
125
|
-
>>> for table in graph.tables.values():
|
|
126
|
-
... table.print_metadata()
|
|
127
|
-
|
|
128
|
-
>>> # Visualize graph (if graphviz is installed):
|
|
129
|
-
>>> graph.visualize()
|
|
130
|
-
|
|
131
149
|
Args:
|
|
132
150
|
df_dict: A dictionary of data frames, where the keys are the names
|
|
133
151
|
of the tables and the values hold table data.
|
|
152
|
+
edges: An optional list of :class:`~kumoai.graph.Edge` objects to
|
|
153
|
+
add to the graph. If not provided, edges will be automatically
|
|
154
|
+
inferred from the data in case ``infer_metadata=True``.
|
|
134
155
|
infer_metadata: Whether to infer metadata for all tables in the
|
|
135
156
|
graph.
|
|
157
|
+
verbose: Whether to print verbose output.
|
|
158
|
+
"""
|
|
159
|
+
from kumoai.experimental.rfm.backend.local import LocalTable
|
|
160
|
+
tables = [LocalTable(df, name) for name, df in df_dict.items()]
|
|
161
|
+
|
|
162
|
+
graph = cls(tables, edges=edges or [])
|
|
163
|
+
|
|
164
|
+
if infer_metadata:
|
|
165
|
+
graph.infer_metadata(False)
|
|
166
|
+
|
|
167
|
+
if edges is None:
|
|
168
|
+
graph.infer_links(False)
|
|
169
|
+
|
|
170
|
+
if verbose:
|
|
171
|
+
graph.print_metadata()
|
|
172
|
+
graph.print_links()
|
|
173
|
+
|
|
174
|
+
return graph
|
|
175
|
+
|
|
176
|
+
@classmethod
|
|
177
|
+
def from_sqlite(
|
|
178
|
+
cls,
|
|
179
|
+
connection: Union[
|
|
180
|
+
'AdbcSqliteConnection',
|
|
181
|
+
SqliteConnectionConfig,
|
|
182
|
+
str,
|
|
183
|
+
Path,
|
|
184
|
+
Dict[str, Any],
|
|
185
|
+
],
|
|
186
|
+
table_names: Optional[Sequence[str]] = None,
|
|
187
|
+
edges: Optional[Sequence[Edge]] = None,
|
|
188
|
+
infer_metadata: bool = True,
|
|
189
|
+
verbose: bool = True,
|
|
190
|
+
) -> Self:
|
|
191
|
+
r"""Creates a :class:`Graph` from a :class:`sqlite` database.
|
|
192
|
+
|
|
193
|
+
Automatically infers table metadata and links by default.
|
|
194
|
+
|
|
195
|
+
.. code-block:: python
|
|
196
|
+
|
|
197
|
+
>>> # doctest: +SKIP
|
|
198
|
+
>>> import kumoai.experimental.rfm as rfm
|
|
199
|
+
|
|
200
|
+
>>> # Create a graph from a SQLite database:
|
|
201
|
+
>>> graph = rfm.Graph.from_sqlite('data.db')
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
connection: An open connection from
|
|
205
|
+
:meth:`~kumoai.experimental.rfm.backend.sqlite.connect` or the
|
|
206
|
+
path to the database file.
|
|
207
|
+
table_names: Set of table names to include. If ``None``, will add
|
|
208
|
+
all tables present in the database.
|
|
136
209
|
edges: An optional list of :class:`~kumoai.graph.Edge` objects to
|
|
137
210
|
add to the graph. If not provided, edges will be automatically
|
|
138
|
-
inferred from the data
|
|
211
|
+
inferred from the data in case ``infer_metadata=True``.
|
|
212
|
+
infer_metadata: Whether to infer metadata for all tables in the
|
|
213
|
+
graph.
|
|
139
214
|
verbose: Whether to print verbose output.
|
|
215
|
+
"""
|
|
216
|
+
from kumoai.experimental.rfm.backend.sqlite import (
|
|
217
|
+
Connection,
|
|
218
|
+
SQLiteTable,
|
|
219
|
+
connect,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
if not isinstance(connection, Connection):
|
|
223
|
+
connection = SqliteConnectionConfig._cast(connection)
|
|
224
|
+
assert isinstance(connection, SqliteConnectionConfig)
|
|
225
|
+
connection = connect(connection.uri, **connection.kwargs)
|
|
226
|
+
assert isinstance(connection, Connection)
|
|
227
|
+
|
|
228
|
+
if table_names is None:
|
|
229
|
+
with connection.cursor() as cursor:
|
|
230
|
+
cursor.execute("SELECT name FROM sqlite_master "
|
|
231
|
+
"WHERE type='table'")
|
|
232
|
+
table_names = [row[0] for row in cursor.fetchall()]
|
|
233
|
+
|
|
234
|
+
tables = [SQLiteTable(connection, name) for name in table_names]
|
|
140
235
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
236
|
+
graph = cls(tables, edges=edges or [])
|
|
237
|
+
|
|
238
|
+
if infer_metadata:
|
|
239
|
+
graph.infer_metadata(False)
|
|
240
|
+
|
|
241
|
+
if edges is None:
|
|
242
|
+
graph.infer_links(False)
|
|
243
|
+
|
|
244
|
+
if verbose:
|
|
245
|
+
graph.print_metadata()
|
|
246
|
+
graph.print_links()
|
|
247
|
+
|
|
248
|
+
return graph
|
|
249
|
+
|
|
250
|
+
@classmethod
|
|
251
|
+
def from_snowflake(
|
|
252
|
+
cls,
|
|
253
|
+
connection: Union['SnowflakeConnection', Dict[str, Any], None] = None,
|
|
254
|
+
table_names: Optional[Sequence[str]] = None,
|
|
255
|
+
edges: Optional[Sequence[Edge]] = None,
|
|
256
|
+
infer_metadata: bool = True,
|
|
257
|
+
verbose: bool = True,
|
|
258
|
+
) -> Self:
|
|
259
|
+
r"""Creates a :class:`Graph` from a :class:`snowflake` database and
|
|
260
|
+
schema.
|
|
261
|
+
|
|
262
|
+
Automatically infers table metadata and links by default.
|
|
263
|
+
|
|
264
|
+
.. code-block:: python
|
|
144
265
|
|
|
145
|
-
Example:
|
|
146
266
|
>>> # doctest: +SKIP
|
|
147
267
|
>>> import kumoai.experimental.rfm as rfm
|
|
148
|
-
|
|
149
|
-
>>>
|
|
150
|
-
>>>
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
268
|
+
|
|
269
|
+
>>> # Create a graph directly in a Snowflake notebook:
|
|
270
|
+
>>> graph = rfm.Graph.from_snowflake()
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
connection: An open connection from
|
|
274
|
+
:meth:`~kumoai.experimental.rfm.backend.snow.connect` or the
|
|
275
|
+
:class:`snowflake` connector keyword arguments to open a new
|
|
276
|
+
connection. If ``None``, will re-use an active session in case
|
|
277
|
+
it exists, or create a new connection from credentials stored
|
|
278
|
+
in environment variables.
|
|
279
|
+
table_names: Set of table names to include. If ``None``, will add
|
|
280
|
+
all tables present in the database.
|
|
281
|
+
edges: An optional list of :class:`~kumoai.graph.Edge` objects to
|
|
282
|
+
add to the graph. If not provided, edges will be automatically
|
|
283
|
+
inferred from the data in case ``infer_metadata=True``.
|
|
284
|
+
infer_metadata: Whether to infer metadata for all tables in the
|
|
285
|
+
graph.
|
|
286
|
+
verbose: Whether to print verbose output.
|
|
157
287
|
"""
|
|
158
|
-
|
|
288
|
+
from kumoai.experimental.rfm.backend.snow import (
|
|
289
|
+
Connection,
|
|
290
|
+
SnowTable,
|
|
291
|
+
connect,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
if not isinstance(connection, Connection):
|
|
295
|
+
connection = connect(**(connection or {}))
|
|
296
|
+
assert isinstance(connection, Connection)
|
|
297
|
+
|
|
298
|
+
if table_names is None:
|
|
299
|
+
with connection.cursor() as cursor:
|
|
300
|
+
cursor.execute("SELECT CURRENT_DATABASE(), CURRENT_SCHEMA()")
|
|
301
|
+
database, schema = cursor.fetchone()
|
|
302
|
+
query = f"""
|
|
303
|
+
SELECT TABLE_NAME
|
|
304
|
+
FROM {database}.INFORMATION_SCHEMA.TABLES
|
|
305
|
+
WHERE TABLE_SCHEMA = '{schema}'
|
|
306
|
+
"""
|
|
307
|
+
cursor.execute(query)
|
|
308
|
+
table_names = [row[0] for row in cursor.fetchall()]
|
|
309
|
+
|
|
310
|
+
tables = [SnowTable(connection, name) for name in table_names]
|
|
159
311
|
|
|
160
312
|
graph = cls(tables, edges=edges or [])
|
|
161
313
|
|
|
162
314
|
if infer_metadata:
|
|
163
|
-
graph.infer_metadata(
|
|
315
|
+
graph.infer_metadata(False)
|
|
164
316
|
|
|
165
317
|
if edges is None:
|
|
166
|
-
graph.infer_links(
|
|
318
|
+
graph.infer_links(False)
|
|
319
|
+
|
|
320
|
+
if verbose:
|
|
321
|
+
graph.print_metadata()
|
|
322
|
+
graph.print_links()
|
|
323
|
+
|
|
324
|
+
return graph
|
|
325
|
+
|
|
326
|
+
@classmethod
|
|
327
|
+
def from_snowflake_semantic_view(
|
|
328
|
+
cls,
|
|
329
|
+
semantic_view_name: str,
|
|
330
|
+
connection: Union['SnowflakeConnection', Dict[str, Any], None] = None,
|
|
331
|
+
verbose: bool = True,
|
|
332
|
+
) -> Self:
|
|
333
|
+
import yaml
|
|
334
|
+
|
|
335
|
+
from kumoai.experimental.rfm.backend.snow import (
|
|
336
|
+
Connection,
|
|
337
|
+
SnowTable,
|
|
338
|
+
connect,
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
if not isinstance(connection, Connection):
|
|
342
|
+
connection = connect(**(connection or {}))
|
|
343
|
+
assert isinstance(connection, Connection)
|
|
344
|
+
|
|
345
|
+
with connection.cursor() as cursor:
|
|
346
|
+
cursor.execute(f"SELECT SYSTEM$READ_YAML_FROM_SEMANTIC_VIEW("
|
|
347
|
+
f"'{semantic_view_name}')")
|
|
348
|
+
view = yaml.safe_load(cursor.fetchone()[0])
|
|
349
|
+
|
|
350
|
+
graph = cls(tables=[])
|
|
351
|
+
|
|
352
|
+
for table_desc in view['tables']:
|
|
353
|
+
primary_key: Optional[str] = None
|
|
354
|
+
if ('primary_key' in table_desc # NOTE No composite keys yet.
|
|
355
|
+
and len(table_desc['primary_key']['columns']) == 1):
|
|
356
|
+
primary_key = table_desc['primary_key']['columns'][0]
|
|
357
|
+
|
|
358
|
+
table = SnowTable(
|
|
359
|
+
connection,
|
|
360
|
+
name=table_desc['base_table']['table'],
|
|
361
|
+
database=table_desc['base_table']['database'],
|
|
362
|
+
schema=table_desc['base_table']['schema'],
|
|
363
|
+
primary_key=primary_key,
|
|
364
|
+
)
|
|
365
|
+
graph.add_table(table)
|
|
366
|
+
|
|
367
|
+
# TODO Find a solution to register time columns!
|
|
368
|
+
|
|
369
|
+
for relations in view['relationships']:
|
|
370
|
+
if len(relations['relationship_columns']) != 1:
|
|
371
|
+
continue # NOTE No composite keys yet.
|
|
372
|
+
graph.link(
|
|
373
|
+
src_table=relations['left_table'],
|
|
374
|
+
fkey=relations['relationship_columns'][0]['left_column'],
|
|
375
|
+
dst_table=relations['right_table'],
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
if verbose:
|
|
379
|
+
graph.print_metadata()
|
|
380
|
+
graph.print_links()
|
|
167
381
|
|
|
168
382
|
return graph
|
|
169
383
|
|
|
@@ -175,7 +389,7 @@ class LocalGraph:
|
|
|
175
389
|
"""
|
|
176
390
|
return name in self.tables
|
|
177
391
|
|
|
178
|
-
def table(self, name: str) ->
|
|
392
|
+
def table(self, name: str) -> Table:
|
|
179
393
|
r"""Returns the table with name ``name`` in the graph.
|
|
180
394
|
|
|
181
395
|
Raises:
|
|
@@ -186,11 +400,11 @@ class LocalGraph:
|
|
|
186
400
|
return self.tables[name]
|
|
187
401
|
|
|
188
402
|
@property
|
|
189
|
-
def tables(self) -> Dict[str,
|
|
403
|
+
def tables(self) -> Dict[str, Table]:
|
|
190
404
|
r"""Returns the dictionary of table objects."""
|
|
191
405
|
return self._tables
|
|
192
406
|
|
|
193
|
-
def add_table(self, table:
|
|
407
|
+
def add_table(self, table: Table) -> Self:
|
|
194
408
|
r"""Adds a table to the graph.
|
|
195
409
|
|
|
196
410
|
Args:
|
|
@@ -199,11 +413,21 @@ class LocalGraph:
|
|
|
199
413
|
Raises:
|
|
200
414
|
KeyError: If a table with the same name already exists in the
|
|
201
415
|
graph.
|
|
416
|
+
ValueError: If the table belongs to a different backend than the
|
|
417
|
+
rest of the tables in the graph.
|
|
202
418
|
"""
|
|
203
419
|
if table.name in self._tables:
|
|
204
420
|
raise KeyError(f"Cannot add table with name '{table.name}' to "
|
|
205
421
|
f"this graph; table names must be globally unique.")
|
|
206
422
|
|
|
423
|
+
if len(self._tables) > 0:
|
|
424
|
+
cls = next(iter(self._tables.values())).__class__
|
|
425
|
+
if table.__class__ != cls:
|
|
426
|
+
raise ValueError(f"Cannot register a "
|
|
427
|
+
f"'{table.__class__.__name__}' to this "
|
|
428
|
+
f"graph since other tables are of type "
|
|
429
|
+
f"'{cls.__name__}'.")
|
|
430
|
+
|
|
207
431
|
self._tables[table.name] = table
|
|
208
432
|
|
|
209
433
|
return self
|
|
@@ -241,7 +465,7 @@ class LocalGraph:
|
|
|
241
465
|
Example:
|
|
242
466
|
>>> # doctest: +SKIP
|
|
243
467
|
>>> import kumoai.experimental.rfm as rfm
|
|
244
|
-
>>> graph = rfm.
|
|
468
|
+
>>> graph = rfm.Graph(tables=...).infer_metadata()
|
|
245
469
|
>>> graph.metadata # doctest: +SKIP
|
|
246
470
|
name primary_key time_column end_time_column
|
|
247
471
|
0 users user_id - -
|
|
@@ -263,7 +487,7 @@ class LocalGraph:
|
|
|
263
487
|
})
|
|
264
488
|
|
|
265
489
|
def print_metadata(self) -> None:
|
|
266
|
-
r"""Prints the :meth:`~
|
|
490
|
+
r"""Prints the :meth:`~Graph.metadata` of the graph."""
|
|
267
491
|
if in_notebook():
|
|
268
492
|
from IPython.display import Markdown, display
|
|
269
493
|
display(Markdown('### 🗂️ Graph Metadata'))
|
|
@@ -287,7 +511,7 @@ class LocalGraph:
|
|
|
287
511
|
|
|
288
512
|
Note:
|
|
289
513
|
For more information, please see
|
|
290
|
-
:meth:`kumoai.experimental.rfm.
|
|
514
|
+
:meth:`kumoai.experimental.rfm.Table.infer_metadata`.
|
|
291
515
|
"""
|
|
292
516
|
for table in self.tables.values():
|
|
293
517
|
table.infer_metadata(verbose=False)
|
|
@@ -305,7 +529,7 @@ class LocalGraph:
|
|
|
305
529
|
return self._edges
|
|
306
530
|
|
|
307
531
|
def print_links(self) -> None:
|
|
308
|
-
r"""Prints the :meth:`~
|
|
532
|
+
r"""Prints the :meth:`~Graph.edges` of the graph."""
|
|
309
533
|
edges = [(edge.dst_table, self[edge.dst_table]._primary_key,
|
|
310
534
|
edge.src_table, edge.fkey) for edge in self.edges]
|
|
311
535
|
edges = sorted(edges)
|
|
@@ -333,9 +557,9 @@ class LocalGraph:
|
|
|
333
557
|
|
|
334
558
|
def link(
|
|
335
559
|
self,
|
|
336
|
-
src_table: Union[str,
|
|
560
|
+
src_table: Union[str, Table],
|
|
337
561
|
fkey: str,
|
|
338
|
-
dst_table: Union[str,
|
|
562
|
+
dst_table: Union[str, Table],
|
|
339
563
|
) -> Self:
|
|
340
564
|
r"""Links two tables (``src_table`` and ``dst_table``) from the foreign
|
|
341
565
|
key ``fkey`` in the source table to the primary key in the destination
|
|
@@ -358,11 +582,11 @@ class LocalGraph:
|
|
|
358
582
|
table does not exist in the graph, if the source key does not
|
|
359
583
|
exist in the source table.
|
|
360
584
|
"""
|
|
361
|
-
if isinstance(src_table,
|
|
585
|
+
if isinstance(src_table, Table):
|
|
362
586
|
src_table = src_table.name
|
|
363
587
|
assert isinstance(src_table, str)
|
|
364
588
|
|
|
365
|
-
if isinstance(dst_table,
|
|
589
|
+
if isinstance(dst_table, Table):
|
|
366
590
|
dst_table = dst_table.name
|
|
367
591
|
assert isinstance(dst_table, str)
|
|
368
592
|
|
|
@@ -396,9 +620,9 @@ class LocalGraph:
|
|
|
396
620
|
|
|
397
621
|
def unlink(
|
|
398
622
|
self,
|
|
399
|
-
src_table: Union[str,
|
|
623
|
+
src_table: Union[str, Table],
|
|
400
624
|
fkey: str,
|
|
401
|
-
dst_table: Union[str,
|
|
625
|
+
dst_table: Union[str, Table],
|
|
402
626
|
) -> Self:
|
|
403
627
|
r"""Removes an :class:`~kumoai.graph.Edge` from the graph.
|
|
404
628
|
|
|
@@ -410,11 +634,11 @@ class LocalGraph:
|
|
|
410
634
|
Raises:
|
|
411
635
|
ValueError: if the edge is not present in the graph.
|
|
412
636
|
"""
|
|
413
|
-
if isinstance(src_table,
|
|
637
|
+
if isinstance(src_table, Table):
|
|
414
638
|
src_table = src_table.name
|
|
415
639
|
assert isinstance(src_table, str)
|
|
416
640
|
|
|
417
|
-
if isinstance(dst_table,
|
|
641
|
+
if isinstance(dst_table, Table):
|
|
418
642
|
dst_table = dst_table.name
|
|
419
643
|
assert isinstance(dst_table, str)
|
|
420
644
|
|
|
@@ -428,17 +652,13 @@ class LocalGraph:
|
|
|
428
652
|
return self
|
|
429
653
|
|
|
430
654
|
def infer_links(self, verbose: bool = True) -> Self:
|
|
431
|
-
r"""Infers links for the tables and adds them as edges to the
|
|
655
|
+
r"""Infers missing links for the tables and adds them as edges to the
|
|
656
|
+
graph.
|
|
432
657
|
|
|
433
658
|
Args:
|
|
434
659
|
verbose: Whether to print verbose output.
|
|
435
|
-
|
|
436
|
-
Note:
|
|
437
|
-
This function expects graph edges to be undefined upfront.
|
|
438
660
|
"""
|
|
439
|
-
|
|
440
|
-
warnings.warn("Cannot infer links if graph edges already exist")
|
|
441
|
-
return self
|
|
661
|
+
known_edges = {(edge.src_table, edge.fkey) for edge in self.edges}
|
|
442
662
|
|
|
443
663
|
# A list of primary key candidates (+score) for every column:
|
|
444
664
|
candidate_dict: dict[
|
|
@@ -463,6 +683,9 @@ class LocalGraph:
|
|
|
463
683
|
src_table_name = src_table.name.lower()
|
|
464
684
|
|
|
465
685
|
for src_key in src_table.columns:
|
|
686
|
+
if (src_table.name, src_key.name) in known_edges:
|
|
687
|
+
continue
|
|
688
|
+
|
|
466
689
|
if src_key == src_table.primary_key:
|
|
467
690
|
continue # Cannot link to primary key.
|
|
468
691
|
|
|
@@ -528,7 +751,9 @@ class LocalGraph:
|
|
|
528
751
|
score += 1.0
|
|
529
752
|
|
|
530
753
|
# Cardinality ratio:
|
|
531
|
-
if
|
|
754
|
+
if (src_table._num_rows is not None
|
|
755
|
+
and dst_table._num_rows is not None
|
|
756
|
+
and src_table._num_rows > dst_table._num_rows):
|
|
532
757
|
score += 1.0
|
|
533
758
|
|
|
534
759
|
if score < 5.0:
|
|
@@ -790,7 +1015,7 @@ class LocalGraph:
|
|
|
790
1015
|
def __contains__(self, name: str) -> bool:
|
|
791
1016
|
return self.has_table(name)
|
|
792
1017
|
|
|
793
|
-
def __getitem__(self, name: str) ->
|
|
1018
|
+
def __getitem__(self, name: str) -> Table:
|
|
794
1019
|
return self.table(name)
|
|
795
1020
|
|
|
796
1021
|
def __delitem__(self, name: str) -> None:
|
|
@@ -1,9 +1,15 @@
|
|
|
1
|
+
from .dtype import infer_dtype
|
|
2
|
+
from .pkey import infer_primary_key
|
|
3
|
+
from .time_col import infer_time_column
|
|
1
4
|
from .id import contains_id
|
|
2
5
|
from .timestamp import contains_timestamp
|
|
3
6
|
from .categorical import contains_categorical
|
|
4
7
|
from .multicategorical import contains_multicategorical
|
|
5
8
|
|
|
6
9
|
__all__ = [
|
|
10
|
+
'infer_dtype',
|
|
11
|
+
'infer_primary_key',
|
|
12
|
+
'infer_time_column',
|
|
7
13
|
'contains_id',
|
|
8
14
|
'contains_timestamp',
|
|
9
15
|
'contains_categorical',
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from typing import Dict
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import pyarrow as pa
|
|
6
|
+
from kumoapi.typing import Dtype
|
|
7
|
+
|
|
8
|
+
PANDAS_TO_DTYPE: Dict[str, Dtype] = {
|
|
9
|
+
'bool': Dtype.bool,
|
|
10
|
+
'boolean': Dtype.bool,
|
|
11
|
+
'int8': Dtype.int,
|
|
12
|
+
'int16': Dtype.int,
|
|
13
|
+
'int32': Dtype.int,
|
|
14
|
+
'int64': Dtype.int,
|
|
15
|
+
'float16': Dtype.float,
|
|
16
|
+
'float32': Dtype.float,
|
|
17
|
+
'float64': Dtype.float,
|
|
18
|
+
'object': Dtype.string,
|
|
19
|
+
'string': Dtype.string,
|
|
20
|
+
'string[python]': Dtype.string,
|
|
21
|
+
'string[pyarrow]': Dtype.string,
|
|
22
|
+
'binary': Dtype.binary,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def infer_dtype(ser: pd.Series) -> Dtype:
|
|
27
|
+
"""Extracts the :class:`Dtype` from a :class:`pandas.Series`.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
ser: A :class:`pandas.Series` to analyze.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
The data type.
|
|
34
|
+
"""
|
|
35
|
+
if pd.api.types.is_datetime64_any_dtype(ser.dtype):
|
|
36
|
+
return Dtype.date
|
|
37
|
+
if pd.api.types.is_timedelta64_dtype(ser.dtype):
|
|
38
|
+
return Dtype.timedelta
|
|
39
|
+
if isinstance(ser.dtype, pd.CategoricalDtype):
|
|
40
|
+
return Dtype.string
|
|
41
|
+
|
|
42
|
+
if (pd.api.types.is_object_dtype(ser.dtype)
|
|
43
|
+
and not isinstance(ser.dtype, pd.ArrowDtype)):
|
|
44
|
+
index = ser.iloc[:1000].first_valid_index()
|
|
45
|
+
if index is not None and pd.api.types.is_list_like(ser[index]):
|
|
46
|
+
pos = ser.index.get_loc(index)
|
|
47
|
+
assert isinstance(pos, int)
|
|
48
|
+
ser = ser.iloc[pos:pos + 1000].dropna()
|
|
49
|
+
arr = pa.array(ser.tolist())
|
|
50
|
+
ser = pd.Series(arr, dtype=pd.ArrowDtype(arr.type))
|
|
51
|
+
|
|
52
|
+
if isinstance(ser.dtype, pd.ArrowDtype):
|
|
53
|
+
if pa.types.is_list(ser.dtype.pyarrow_dtype):
|
|
54
|
+
elem_dtype = ser.dtype.pyarrow_dtype.value_type
|
|
55
|
+
if pa.types.is_integer(elem_dtype):
|
|
56
|
+
return Dtype.intlist
|
|
57
|
+
if pa.types.is_floating(elem_dtype):
|
|
58
|
+
return Dtype.floatlist
|
|
59
|
+
if pa.types.is_decimal(elem_dtype):
|
|
60
|
+
return Dtype.floatlist
|
|
61
|
+
if pa.types.is_string(elem_dtype):
|
|
62
|
+
return Dtype.stringlist
|
|
63
|
+
if pa.types.is_null(elem_dtype):
|
|
64
|
+
return Dtype.floatlist
|
|
65
|
+
|
|
66
|
+
if isinstance(ser.dtype, np.dtype):
|
|
67
|
+
dtype_str = str(ser.dtype).lower()
|
|
68
|
+
elif isinstance(ser.dtype, pd.api.extensions.ExtensionDtype):
|
|
69
|
+
dtype_str = ser.dtype.name.lower()
|
|
70
|
+
dtype_str = dtype_str.split('[')[0] # Remove backend metadata
|
|
71
|
+
elif isinstance(ser.dtype, pa.DataType):
|
|
72
|
+
dtype_str = str(ser.dtype).lower()
|
|
73
|
+
else:
|
|
74
|
+
dtype_str = 'object'
|
|
75
|
+
|
|
76
|
+
if dtype_str not in PANDAS_TO_DTYPE:
|
|
77
|
+
raise ValueError(f"Unsupported data type '{ser.dtype}'")
|
|
78
|
+
|
|
79
|
+
return PANDAS_TO_DTYPE[dtype_str]
|