cupami 0.1.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.
- cupami/__init__.py +22 -0
- cupami/extras/__init__.py +1 -0
- cupami/extras/_quantitative_io.py +175 -0
- cupami/extras/_temporal_io.py +118 -0
- cupami/extras/datasetConverter.py +39 -0
- cupami/extras/fileConverter.py +148 -0
- cupami/extras/syntheticDataGenerator/BinaryTransactionalDatabase.py +14 -0
- cupami/extras/syntheticDataGenerator/QuantitativeTransactionalDatabase.py +41 -0
- cupami/extras/syntheticDataGenerator/TemporalDatabase.py +83 -0
- cupami/extras/syntheticDataGenerator/TransactionalDatabase.py +172 -0
- cupami/extras/syntheticDataGenerator/__init__.py +8 -0
- cupami/frequentPattern/__init__.py +7 -0
- cupami/frequentPattern/_bitsets.py +125 -0
- cupami/frequentPattern/_fptree.py +231 -0
- cupami/frequentPattern/_gpu_io.py +65 -0
- cupami/frequentPattern/cuApriori.py +490 -0
- cupami/frequentPattern/cuEclat.py +142 -0
- cupami/frequentPattern/cuFPGrowth.py +110 -0
- cupami/fuzzyFrequentPattern/__init__.py +7 -0
- cupami/fuzzyFrequentPattern/_fuzzy.py +77 -0
- cupami/fuzzyFrequentPattern/_multi.py +2213 -0
- cupami/fuzzyFrequentPattern/_multi_api.py +148 -0
- cupami/fuzzyFrequentPattern/cuFFIMiner.py +213 -0
- cupami/fuzzyFrequentPattern/cuFlatMulti.py +16 -0
- cupami/fuzzyFrequentPattern/cuGPUMulti.py +16 -0
- cupami/fuzzyFrequentPattern/cuMFFIMiner.py +51 -0
- cupami/georeferencedFrequentPattern/__init__.py +4 -0
- cupami/georeferencedFrequentPattern/cuSpatialEclat.py +90 -0
- cupami/partialPeriodicPattern/__init__.py +5 -0
- cupami/partialPeriodicPattern/_partial.py +126 -0
- cupami/partialPeriodicPattern/cuPPPApriori.py +15 -0
- cupami/partialPeriodicPattern/cuPPPEclat.py +16 -0
- cupami/periodicFrequentPattern/__init__.py +6 -0
- cupami/periodicFrequentPattern/_temporal.py +181 -0
- cupami/periodicFrequentPattern/cuPFApriori.py +34 -0
- cupami/periodicFrequentPattern/cuPFEclat.py +52 -0
- cupami/periodicFrequentPattern/cuPFGrowth.py +38 -0
- cupami-0.1.0.dist-info/METADATA +353 -0
- cupami-0.1.0.dist-info/RECORD +42 -0
- cupami-0.1.0.dist-info/WHEEL +5 -0
- cupami-0.1.0.dist-info/licenses/LICENSE +674 -0
- cupami-0.1.0.dist-info/top_level.txt +1 -0
cupami/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""CUDA pattern-mining utilities."""
|
|
2
|
+
|
|
3
|
+
from .extras.syntheticDataGenerator import (
|
|
4
|
+
BinaryTransactionalDatabase, QuantitativeTransactionalDatabase,
|
|
5
|
+
TemporalDatabase, TransactionalDatabase,
|
|
6
|
+
)
|
|
7
|
+
from .frequentPattern import cuApriori, cuEclat, cuFPGrowth
|
|
8
|
+
from .fuzzyFrequentPattern import cuFFIMiner, cuMFFIMiner, cuFlatMulti, cuGPUMulti
|
|
9
|
+
from .georeferencedFrequentPattern import cuSpatialEclat
|
|
10
|
+
from .periodicFrequentPattern import cuPFApriori, cuPFEclat, cuPFGrowth
|
|
11
|
+
from .partialPeriodicPattern import cuPPPApriori, cuPPPEclat
|
|
12
|
+
from .extras.fileConverter import convertFile, convertTransactions
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"TransactionalDatabase", "TemporalDatabase",
|
|
16
|
+
"BinaryTransactionalDatabase", "QuantitativeTransactionalDatabase",
|
|
17
|
+
"cuApriori", "cuEclat", "cuFPGrowth",
|
|
18
|
+
"cuPFApriori", "cuPFEclat", "cuPFGrowth",
|
|
19
|
+
"cuFFIMiner", "cuMFFIMiner", "cuFlatMulti", "cuGPUMulti", "cuSpatialEclat",
|
|
20
|
+
"cuPPPApriori", "cuPPPEclat",
|
|
21
|
+
"convertFile", "convertTransactions",
|
|
22
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""cuPAMI quantitative schemas: aligned uint32 IDs and float64 quantities.
|
|
2
|
+
|
|
3
|
+
BIN is a local versioned CSR format, not PAMI's binary format. Text follows
|
|
4
|
+
PAMI's items:quantities convention; Parquet uses Apache Arrow list columns.
|
|
5
|
+
https://arrow.apache.org/docs/python/parquet.html
|
|
6
|
+
"""
|
|
7
|
+
import csv
|
|
8
|
+
import math
|
|
9
|
+
import shutil
|
|
10
|
+
import struct
|
|
11
|
+
import tempfile
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from itertools import islice
|
|
14
|
+
from numbers import Integral, Real
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
_HEADER = struct.Struct('<8sQQQ')
|
|
20
|
+
_MAGIC = b'CUPAMIQ1'
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def normalize(row):
|
|
24
|
+
if not isinstance(row, Mapping):
|
|
25
|
+
raise ValueError('Quantitative rows must be mappings of item IDs to quantities')
|
|
26
|
+
result = {}
|
|
27
|
+
for label, quantity in row.items():
|
|
28
|
+
if isinstance(label, bool) or not isinstance(label, (str, Integral)):
|
|
29
|
+
raise ValueError('Quantitative item IDs must be uint32 integers')
|
|
30
|
+
try:
|
|
31
|
+
item = int(label)
|
|
32
|
+
except ValueError:
|
|
33
|
+
raise ValueError(f'Invalid item ID {label!r}') from None
|
|
34
|
+
if not 0 <= item <= 0xFFFFFFFF or item in result:
|
|
35
|
+
raise ValueError('Quantitative IDs must be unique uint32 integers')
|
|
36
|
+
if isinstance(quantity, bool) or not isinstance(quantity, Real) or not math.isfinite(quantity) or quantity <= 0:
|
|
37
|
+
raise ValueError('Quantities must be positive finite numbers')
|
|
38
|
+
if isinstance(quantity, Integral) and quantity > 2**53:
|
|
39
|
+
raise ValueError('Integer quantities must be at most 2**53 for exact float64 storage')
|
|
40
|
+
result[item] = float(quantity)
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _arrow():
|
|
45
|
+
try:
|
|
46
|
+
import pyarrow as pa
|
|
47
|
+
import pyarrow.parquet as pq
|
|
48
|
+
except ImportError as error:
|
|
49
|
+
raise ImportError('Parquet conversion requires pyarrow: pip install pyarrow') from error
|
|
50
|
+
return pa, pq
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def write(path, rows, sep=','):
|
|
54
|
+
suffix = Path(path).suffix.lower()
|
|
55
|
+
rows = (normalize(row) for row in rows)
|
|
56
|
+
if suffix == '.bin':
|
|
57
|
+
_write_binary(path, rows)
|
|
58
|
+
elif suffix == '.parquet':
|
|
59
|
+
pa, pq = _arrow()
|
|
60
|
+
schema = pa.schema([
|
|
61
|
+
pa.field('items', pa.list_(pa.field('item', pa.uint32(), nullable=False)), nullable=False),
|
|
62
|
+
pa.field('quantities', pa.list_(pa.field('quantity', pa.float64(), nullable=False)), nullable=False),
|
|
63
|
+
])
|
|
64
|
+
with pq.ParquetWriter(path, schema, compression='snappy') as writer:
|
|
65
|
+
while batch := list(islice(rows, 8192)):
|
|
66
|
+
writer.write_table(pa.Table.from_arrays([
|
|
67
|
+
pa.array([list(row) for row in batch], type=schema.field('items').type),
|
|
68
|
+
pa.array([list(row.values()) for row in batch], type=schema.field('quantities').type),
|
|
69
|
+
], schema=schema))
|
|
70
|
+
elif suffix in ('', '.csv', '.tsv', '.txt', '.dat'):
|
|
71
|
+
sep = '\t' if suffix == '.tsv' else sep
|
|
72
|
+
with Path(path).open('w', encoding='utf-8', newline='') as output:
|
|
73
|
+
for row in rows:
|
|
74
|
+
ids = sep.join(map(str, row))
|
|
75
|
+
values = sep.join(format(q, '.17g') for q in row.values())
|
|
76
|
+
output.write(f'{ids}:{values}\n')
|
|
77
|
+
else:
|
|
78
|
+
raise ValueError('Use .csv, .tsv, .txt, .dat, .bin, or .parquet')
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _write_binary(path, rows):
|
|
82
|
+
with tempfile.TemporaryFile() as offsets, tempfile.TemporaryFile() as ids, tempfile.TemporaryFile() as quantities:
|
|
83
|
+
count = total = universe = 0
|
|
84
|
+
offsets.write(struct.pack('<Q', 0))
|
|
85
|
+
for row in rows:
|
|
86
|
+
ids.write(struct.pack(f'<{len(row)}I', *row))
|
|
87
|
+
quantities.write(struct.pack(f'<{len(row)}d', *row.values()))
|
|
88
|
+
count += 1
|
|
89
|
+
total += len(row)
|
|
90
|
+
universe = max(universe, max(row, default=0))
|
|
91
|
+
offsets.write(struct.pack('<Q', total))
|
|
92
|
+
with Path(path).open('wb') as output:
|
|
93
|
+
output.write(_HEADER.pack(_MAGIC, count, total, universe))
|
|
94
|
+
for stream in (offsets, ids, quantities):
|
|
95
|
+
stream.seek(0)
|
|
96
|
+
shutil.copyfileobj(stream, output)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _quantity(text):
|
|
100
|
+
# Parse integer text before float conversion to detect inexact large ints.
|
|
101
|
+
try:
|
|
102
|
+
return int(text)
|
|
103
|
+
except ValueError:
|
|
104
|
+
return float(text)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def read(path, sep=None):
|
|
108
|
+
suffix = Path(path).suffix.lower()
|
|
109
|
+
if suffix == '.bin':
|
|
110
|
+
return _read_binary(path)
|
|
111
|
+
if suffix == '.parquet':
|
|
112
|
+
pa, pq = _arrow()
|
|
113
|
+
table = pq.read_table(path)
|
|
114
|
+
if set(table.column_names) != {'items', 'quantities'}:
|
|
115
|
+
raise ValueError('Quantitative Parquet requires items and quantities columns')
|
|
116
|
+
ids, quantities = table['items'], table['quantities']
|
|
117
|
+
if not pa.types.is_list(ids.type) or ids.type.value_type != pa.uint32() or not pa.types.is_list(quantities.type) or quantities.type.value_type != pa.float64():
|
|
118
|
+
raise ValueError('Expected items: list<uint32> and quantities: list<float64>')
|
|
119
|
+
if ids.null_count or quantities.null_count or ids.combine_chunks().flatten().null_count or quantities.combine_chunks().flatten().null_count:
|
|
120
|
+
raise ValueError('Quantitative Parquet cannot contain nulls')
|
|
121
|
+
return [_paired(items, values) for items, values in zip(ids.to_pylist(), quantities.to_pylist())]
|
|
122
|
+
with Path(path).open(encoding='utf-8-sig') as source:
|
|
123
|
+
rows = []
|
|
124
|
+
for number, line in enumerate(source, 1):
|
|
125
|
+
if not line.strip():
|
|
126
|
+
continue
|
|
127
|
+
parts = line.strip().split(':')
|
|
128
|
+
if len(parts) != 2:
|
|
129
|
+
raise ValueError(f'Line {number}: expected items:quantities')
|
|
130
|
+
delimiter = sep or ('\t' if '\t' in line else ',' if ',' in line else None)
|
|
131
|
+
if delimiter:
|
|
132
|
+
items, values = (next(csv.reader([part], delimiter=delimiter)) if part else [] for part in parts)
|
|
133
|
+
else:
|
|
134
|
+
items, values = (part.split() for part in parts)
|
|
135
|
+
try:
|
|
136
|
+
rows.append(_paired(items, [_quantity(q) for q in values]))
|
|
137
|
+
except ValueError as error:
|
|
138
|
+
raise ValueError(f'Line {number}: {error}') from error
|
|
139
|
+
return rows
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _paired(items, quantities):
|
|
143
|
+
if len(items) != len(quantities) or len(set(items)) != len(items):
|
|
144
|
+
raise ValueError('Item and quantity lists must align and contain unique IDs')
|
|
145
|
+
# Normalize before constructing the result to detect aliases such as 01/1.
|
|
146
|
+
result = {}
|
|
147
|
+
for label, quantity in zip(items, quantities):
|
|
148
|
+
row = normalize({label: quantity})
|
|
149
|
+
if next(iter(row)) in result:
|
|
150
|
+
raise ValueError('Duplicate quantitative item ID')
|
|
151
|
+
result.update(row)
|
|
152
|
+
return result
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _read_binary(path):
|
|
156
|
+
with Path(path).open('rb') as source:
|
|
157
|
+
header = source.read(_HEADER.size)
|
|
158
|
+
if len(header) != _HEADER.size:
|
|
159
|
+
raise ValueError('Invalid quantitative BIN header')
|
|
160
|
+
magic, count, total, universe = _HEADER.unpack(header)
|
|
161
|
+
if magic != _MAGIC or universe > 0xFFFFFFFF:
|
|
162
|
+
raise ValueError('Expected a quantitative BIN file (CUPAMIQ1)')
|
|
163
|
+
if Path(path).stat().st_size != _HEADER.size + 8 * (count + 1) + 12 * total:
|
|
164
|
+
raise ValueError('Invalid quantitative BIN size')
|
|
165
|
+
offsets = np.fromfile(source, dtype='<u8', count=count + 1)
|
|
166
|
+
items = np.fromfile(source, dtype='<u4', count=total)
|
|
167
|
+
quantities = np.fromfile(source, dtype='<f8', count=total)
|
|
168
|
+
if len(offsets) != count + 1 or len(items) != total or len(quantities) != total:
|
|
169
|
+
raise ValueError('Truncated quantitative BIN arrays')
|
|
170
|
+
if offsets[0] != 0 or offsets[-1] != total or np.any(offsets[1:] < offsets[:-1]):
|
|
171
|
+
raise ValueError('Invalid quantitative BIN offsets')
|
|
172
|
+
if np.any(items > universe):
|
|
173
|
+
raise ValueError('Quantitative item ID exceeds header bound')
|
|
174
|
+
return [_paired(items[int(a):int(b)].tolist(), quantities[int(a):int(b)].tolist())
|
|
175
|
+
for a, b in zip(offsets, offsets[1:])]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Temporal BIN and Parquet storage with timestamps separate from item IDs.
|
|
2
|
+
Local CUPAMIT1 schema; Apache Arrow list-column reference:
|
|
3
|
+
https://arrow.apache.org/docs/python/parquet.html
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import shutil
|
|
7
|
+
import struct
|
|
8
|
+
import tempfile
|
|
9
|
+
from itertools import islice
|
|
10
|
+
from numbers import Integral
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
_MAGIC = b"CUPAMIT1"
|
|
16
|
+
_HEADER = struct.Struct("<8sQQQ")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _row(row, universe):
|
|
20
|
+
timestamp, *items = row
|
|
21
|
+
if isinstance(timestamp, bool) or not isinstance(timestamp, Integral) or not 0 <= timestamp <= 0x7FFFFFFFFFFFFFFF:
|
|
22
|
+
raise ValueError("Temporal timestamps must be nonnegative int64 integers")
|
|
23
|
+
if any(isinstance(item, bool) or not isinstance(item, Integral) or not 0 <= item <= universe for item in items):
|
|
24
|
+
raise ValueError("Temporal item IDs must be integers within the configured item range")
|
|
25
|
+
return int(timestamp), list(map(int, items))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_binary(path, rows, universe):
|
|
29
|
+
if not 1 <= universe <= 0xFFFFFFFF:
|
|
30
|
+
raise ValueError("BIN item IDs must fit in uint32")
|
|
31
|
+
with tempfile.TemporaryFile() as timestamps, tempfile.TemporaryFile() as offsets, tempfile.TemporaryFile() as items:
|
|
32
|
+
count = total = 0
|
|
33
|
+
offsets.write(struct.pack("<Q", 0))
|
|
34
|
+
for row in rows:
|
|
35
|
+
timestamp, basket = _row(row, universe)
|
|
36
|
+
timestamps.write(struct.pack("<q", timestamp))
|
|
37
|
+
items.write(struct.pack(f"<{len(basket)}I", *basket))
|
|
38
|
+
count += 1
|
|
39
|
+
total += len(basket)
|
|
40
|
+
offsets.write(struct.pack("<Q", total))
|
|
41
|
+
with Path(path).open("wb") as output:
|
|
42
|
+
output.write(_HEADER.pack(_MAGIC, count, total, universe))
|
|
43
|
+
for stream in (timestamps, offsets, items):
|
|
44
|
+
stream.seek(0)
|
|
45
|
+
shutil.copyfileobj(stream, output)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_binary(path):
|
|
49
|
+
with Path(path).open("rb") as source:
|
|
50
|
+
header = source.read(_HEADER.size)
|
|
51
|
+
if len(header) != _HEADER.size:
|
|
52
|
+
raise ValueError("Invalid temporal BIN header")
|
|
53
|
+
magic, count, total, universe = _HEADER.unpack(header)
|
|
54
|
+
if magic != _MAGIC:
|
|
55
|
+
raise ValueError("Expected a temporal BIN file with timestamp data")
|
|
56
|
+
if not 1 <= universe <= 0xFFFFFFFF:
|
|
57
|
+
raise ValueError("Invalid temporal BIN item range")
|
|
58
|
+
if Path(path).stat().st_size != _HEADER.size + 8 * count + 8 * (count + 1) + 4 * total:
|
|
59
|
+
raise ValueError("Invalid temporal BIN file size")
|
|
60
|
+
timestamps = np.fromfile(source, dtype="<i8", count=count)
|
|
61
|
+
offsets = np.fromfile(source, dtype="<u8", count=count + 1)
|
|
62
|
+
items = np.fromfile(source, dtype="<u4", count=total)
|
|
63
|
+
if len(timestamps) != count or len(offsets) != count + 1 or len(items) != total:
|
|
64
|
+
raise ValueError("Truncated temporal BIN arrays")
|
|
65
|
+
if np.any(timestamps < 0):
|
|
66
|
+
raise ValueError("Temporal timestamps must be nonnegative")
|
|
67
|
+
if offsets[0] != 0 or offsets[-1] != total or np.any(offsets[1:] < offsets[:-1]):
|
|
68
|
+
raise ValueError("Invalid temporal BIN offsets")
|
|
69
|
+
if np.any(items > universe):
|
|
70
|
+
raise ValueError("Temporal BIN item ID exceeds header range")
|
|
71
|
+
return [[int(timestamp), *items[int(offsets[i]):int(offsets[i + 1])].tolist()]
|
|
72
|
+
for i, timestamp in enumerate(timestamps)]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _arrow():
|
|
76
|
+
try:
|
|
77
|
+
import pyarrow as pa
|
|
78
|
+
import pyarrow.parquet as pq
|
|
79
|
+
except ImportError as error:
|
|
80
|
+
raise ImportError("Temporal Parquet requires pyarrow: pip install pyarrow") from error
|
|
81
|
+
return pa, pq
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write_parquet(path, rows, universe):
|
|
85
|
+
if not 1 <= universe <= 0xFFFFFFFF:
|
|
86
|
+
raise ValueError("Parquet item IDs must fit in uint32")
|
|
87
|
+
pa, pq = _arrow()
|
|
88
|
+
schema = pa.schema([
|
|
89
|
+
pa.field("timestamp", pa.int64(), nullable=False),
|
|
90
|
+
pa.field("items", pa.list_(pa.field("item", pa.uint32(), nullable=False)), nullable=False),
|
|
91
|
+
])
|
|
92
|
+
rows = iter(rows)
|
|
93
|
+
with pq.ParquetWriter(path, schema, compression="snappy") as writer:
|
|
94
|
+
while True:
|
|
95
|
+
batch = [_row(row, universe) for row in islice(rows, 8192)]
|
|
96
|
+
if not batch:
|
|
97
|
+
break
|
|
98
|
+
table = pa.Table.from_arrays([
|
|
99
|
+
pa.array([row[0] for row in batch], type=pa.int64()),
|
|
100
|
+
pa.array([row[1] for row in batch], type=schema.field("items").type),
|
|
101
|
+
], schema=schema)
|
|
102
|
+
writer.write_table(table)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def read_parquet(path):
|
|
106
|
+
pa, pq = _arrow()
|
|
107
|
+
table = pq.read_table(path)
|
|
108
|
+
if "timestamp" not in table.column_names or "items" not in table.column_names:
|
|
109
|
+
raise ValueError("Temporal Parquet requires timestamp and items columns")
|
|
110
|
+
timestamp, items = table["timestamp"].combine_chunks(), table["items"].combine_chunks()
|
|
111
|
+
if timestamp.type != pa.int64() or not pa.types.is_list(items.type) or items.type.value_type != pa.uint32():
|
|
112
|
+
raise ValueError("Temporal Parquet requires timestamp: int64 and items: list<uint32>")
|
|
113
|
+
if timestamp.null_count or items.null_count or items.flatten().null_count:
|
|
114
|
+
raise ValueError("Temporal Parquet cannot contain null timestamps, baskets, or items")
|
|
115
|
+
timestamps = timestamp.to_pylist()
|
|
116
|
+
if any(value < 0 for value in timestamps):
|
|
117
|
+
raise ValueError("Temporal timestamps must be nonnegative")
|
|
118
|
+
return [[ts, *basket] for ts, basket in zip(timestamps, items.to_pylist())]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Convert binary, temporal, and quantitative datasets without CUDA.
|
|
2
|
+
|
|
3
|
+
Examples:
|
|
4
|
+
python -m cupami.extras.datasetConverter baskets.csv baskets.bin
|
|
5
|
+
python -m cupami.extras.datasetConverter baskets.bin baskets.parquet
|
|
6
|
+
python -m cupami.extras.datasetConverter baskets.parquet baskets.tsv
|
|
7
|
+
python -m cupami.extras.datasetConverter quantities.csv quantities.bin --data-type quantitative
|
|
8
|
+
|
|
9
|
+
Uses cuPAMI's versioned BIN schemas and Apache Parquet list columns:
|
|
10
|
+
https://arrow.apache.org/docs/python/parquet.html
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
|
|
15
|
+
from .fileConverter import convertFile, convertTransactions
|
|
16
|
+
|
|
17
|
+
__all__ = ['convertFile', 'convertTransactions']
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv=None):
|
|
21
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
22
|
+
parser.add_argument('source', help='Input CSV, TSV, text, BIN, or Parquet file')
|
|
23
|
+
parser.add_argument('output', help='Output file; extension selects its format')
|
|
24
|
+
parser.add_argument('--data-type', choices=['binary', 'transactional', 'temporal', 'quantitative'], default='binary')
|
|
25
|
+
parser.add_argument('--sep', help=r'Input text delimiter, e.g. "," or "\t"; default: detect')
|
|
26
|
+
parser.add_argument('--output-sep', help=r'Output text delimiter; default: comma (tab for .tsv)')
|
|
27
|
+
args = parser.parse_args(argv)
|
|
28
|
+
def delimiter(value):
|
|
29
|
+
return '\t' if value == r'\t' else value
|
|
30
|
+
try:
|
|
31
|
+
summary = convertFile(args.source, args.output, dataType=args.data_type,
|
|
32
|
+
sep=delimiter(args.sep), outputSep=delimiter(args.output_sep))
|
|
33
|
+
except (ValueError, OSError, ImportError) as error:
|
|
34
|
+
parser.exit(2, f'Conversion failed: {error}\n')
|
|
35
|
+
print(json.dumps(summary, indent=2))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == '__main__':
|
|
39
|
+
main()
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Convert database files through one interface selected by data type.
|
|
2
|
+
|
|
3
|
+
Local cuPAMI conversion routines; schemas: docs/transaction-formats.md.
|
|
4
|
+
Parquet list-column reference: https://arrow.apache.org/docs/python/parquet.html
|
|
5
|
+
CLI: python -m cupami.extras.datasetConverter --help
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def convertFile(source, outputFile, dataType="transactional", sep=None, *, outputSep=None):
|
|
12
|
+
"""Convert CSV/TSV/text, BIN, or Parquet in either direction without CUDA.
|
|
13
|
+
|
|
14
|
+
dataType is binary (or transactional), temporal, or quantitative. sep is
|
|
15
|
+
the input text delimiter; outputSep overrides the output text delimiter.
|
|
16
|
+
Output is written atomically so validation errors preserve existing files.
|
|
17
|
+
Quantitative input rows are mappings; file rows use items:quantities.
|
|
18
|
+
"""
|
|
19
|
+
handlers = {"transactional": _convertTransactional, "binary": _convertTransactional,
|
|
20
|
+
"temporal": _convertTemporal, "quantitative": _convertQuantitative}
|
|
21
|
+
if not isinstance(dataType, str) or dataType.lower() not in handlers:
|
|
22
|
+
raise ValueError(f"Unsupported data type {dataType!r}; supported: binary, transactional, temporal, quantitative")
|
|
23
|
+
path = Path(outputFile)
|
|
24
|
+
suffix = path.suffix.lower()
|
|
25
|
+
if suffix not in (".csv", ".tsv", ".txt", ".dat", "", ".bin", ".parquet"):
|
|
26
|
+
raise ValueError("Use .csv, .tsv, .txt, .dat, .bin, or .parquet output")
|
|
27
|
+
if outputSep is not None and (not isinstance(outputSep, str) or len(outputSep) != 1 or outputSep in '\r\n:"'):
|
|
28
|
+
raise ValueError('outputSep must be one character other than newline, colon, or quote')
|
|
29
|
+
if outputSep is not None and suffix in ('.bin', '.parquet'):
|
|
30
|
+
raise ValueError('outputSep applies only to text output')
|
|
31
|
+
import os
|
|
32
|
+
import tempfile
|
|
33
|
+
descriptor, temporary = tempfile.mkstemp(prefix='.' + path.stem + '-', suffix=suffix, dir=path.parent)
|
|
34
|
+
os.close(descriptor)
|
|
35
|
+
try:
|
|
36
|
+
summary = handlers[dataType.lower()](source, temporary, sep=sep)
|
|
37
|
+
if outputSep is not None:
|
|
38
|
+
import csv
|
|
39
|
+
delimiter = '\t' if suffix == '.tsv' else ','
|
|
40
|
+
temp_path = Path(temporary)
|
|
41
|
+
if dataType.lower() == 'quantitative':
|
|
42
|
+
from . import _quantitative_io
|
|
43
|
+
rows = _quantitative_io.read(temp_path, sep=delimiter)
|
|
44
|
+
# Use the selected delimiter even when the extension is TSV.
|
|
45
|
+
text = ''.join(outputSep.join(map(str, row)) + ':' +
|
|
46
|
+
outputSep.join(format(q, '.17g') for q in row.values()) + '\n' for row in rows)
|
|
47
|
+
temp_path.write_text(text, encoding='utf-8')
|
|
48
|
+
else:
|
|
49
|
+
with temp_path.open(newline='', encoding='utf-8') as stream:
|
|
50
|
+
rows = list(csv.reader(stream, delimiter=delimiter))
|
|
51
|
+
with temp_path.open('w', newline='', encoding='utf-8') as stream:
|
|
52
|
+
csv.writer(stream, delimiter=outputSep).writerows(rows)
|
|
53
|
+
os.replace(temporary, path)
|
|
54
|
+
return summary
|
|
55
|
+
finally:
|
|
56
|
+
Path(temporary).unlink(missing_ok=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def convertTransactions(source, outputFile, sep=None):
|
|
60
|
+
"""Compatibility shorthand for convertFile(..., dataType='transactional')."""
|
|
61
|
+
return convertFile(source, outputFile, dataType="transactional", sep=sep)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _convertTransactional(source, outputFile, sep=None):
|
|
65
|
+
"""Convert local CSV/BIN/Parquet, delimited text URLs, or transaction rows.
|
|
66
|
+
|
|
67
|
+
Output format is selected by extension. Item IDs must be integers in
|
|
68
|
+
0..2**32-1. Repeated items are removed and empty baskets are omitted,
|
|
69
|
+
matching cuApriori's input semantics. This utility does not require CUDA;
|
|
70
|
+
Parquet requires PyArrow. The database is retained in CPU memory.
|
|
71
|
+
"""
|
|
72
|
+
from cupami.frequentPattern import cuApriori
|
|
73
|
+
from .syntheticDataGenerator import TransactionalDatabase
|
|
74
|
+
|
|
75
|
+
suffix = Path(outputFile).suffix.lower()
|
|
76
|
+
if suffix not in (".csv", ".bin", ".parquet", ".tsv", ".txt", ".dat", ""):
|
|
77
|
+
raise ValueError("Use a .csv, .bin, or .parquet output file")
|
|
78
|
+
reader = cuApriori(source, 1, sep=sep, use_gds=False, use_gpu_io=False)
|
|
79
|
+
transactions = []
|
|
80
|
+
universe = 0
|
|
81
|
+
occurrences = 0
|
|
82
|
+
for rowIndex, row in enumerate(reader._Database, start=1):
|
|
83
|
+
transaction = []
|
|
84
|
+
for label in row:
|
|
85
|
+
try:
|
|
86
|
+
item = int(label)
|
|
87
|
+
except ValueError as error:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
f"Transaction {rowIndex}: item {label!r} is not an integer ID"
|
|
90
|
+
) from error
|
|
91
|
+
if not 0 <= item <= 0xFFFFFFFF:
|
|
92
|
+
raise ValueError(f"Transaction {rowIndex}: item IDs must be in 0..2**32-1")
|
|
93
|
+
if item not in transaction:
|
|
94
|
+
transaction.append(item)
|
|
95
|
+
universe = max(universe, max(transaction))
|
|
96
|
+
occurrences += len(transaction)
|
|
97
|
+
transactions.append(transaction)
|
|
98
|
+
|
|
99
|
+
# Reuse the generator's format writer so the schemas cannot drift.
|
|
100
|
+
writer = TransactionalDatabase(len(transactions), max(1, universe))
|
|
101
|
+
writer._writeDatabase(outputFile, iter(transactions))
|
|
102
|
+
return {"transactions": len(transactions), "item_occurrences": occurrences,
|
|
103
|
+
"max_item_id": universe if transactions else None,
|
|
104
|
+
"format": suffix.lstrip(".") if suffix in (".bin", ".parquet") else "tsv" if suffix == ".tsv" else "csv"}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _convertTemporal(source, outputFile, sep=None):
|
|
108
|
+
"""Convert temporal files while preserving timestamps and separate rows."""
|
|
109
|
+
from ..periodicFrequentPattern._temporal import TemporalInput
|
|
110
|
+
from .syntheticDataGenerator import TemporalDatabase
|
|
111
|
+
|
|
112
|
+
suffix = Path(outputFile).suffix.lower()
|
|
113
|
+
if suffix not in (".csv", ".bin", ".parquet", ".tsv", ".txt", ".dat", ""):
|
|
114
|
+
raise ValueError("Use a .csv, .bin, or .parquet output file")
|
|
115
|
+
reader = TemporalInput(source, minSup=1, maxPer=0, sep=sep)
|
|
116
|
+
rows = []
|
|
117
|
+
universe = occurrences = 0
|
|
118
|
+
for row_index, (timestamp, basket) in enumerate(zip(reader._timestamps, reader._Database), start=1):
|
|
119
|
+
items = []
|
|
120
|
+
for label in basket:
|
|
121
|
+
try:
|
|
122
|
+
item = int(label)
|
|
123
|
+
except ValueError as error:
|
|
124
|
+
raise ValueError(f"Transaction {row_index}: item {label!r} is not an integer ID") from error
|
|
125
|
+
if not 0 <= item <= 0xFFFFFFFF:
|
|
126
|
+
raise ValueError(f"Transaction {row_index}: item IDs must be in 0..2**32-1")
|
|
127
|
+
if item not in items:
|
|
128
|
+
items.append(item)
|
|
129
|
+
universe = max(universe, max(items, default=0))
|
|
130
|
+
occurrences += len(items)
|
|
131
|
+
rows.append([timestamp, *items])
|
|
132
|
+
writer = TemporalDatabase(transactions=len(rows), items=max(1, universe))
|
|
133
|
+
writer._writeDatabase(outputFile, iter(rows))
|
|
134
|
+
return {"transactions": len(rows), "item_occurrences": occurrences,
|
|
135
|
+
"max_item_id": universe if occurrences else None,
|
|
136
|
+
"format": suffix.lstrip(".") if suffix in (".bin", ".parquet") else "tsv" if suffix == ".tsv" else "csv"}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _convertQuantitative(source, outputFile, sep=None):
|
|
140
|
+
"""Preserve aligned item quantities through all supported formats."""
|
|
141
|
+
from . import _quantitative_io
|
|
142
|
+
rows = (_quantitative_io.read(source, sep=sep) if isinstance(source, (str, Path))
|
|
143
|
+
else [_quantitative_io.normalize(row) for row in source])
|
|
144
|
+
_quantitative_io.write(outputFile, rows)
|
|
145
|
+
suffix = Path(outputFile).suffix.lower()
|
|
146
|
+
return {"transactions": len(rows), "item_occurrences": sum(map(len, rows)),
|
|
147
|
+
"max_item_id": max((item for row in rows for item in row), default=None),
|
|
148
|
+
"format": suffix.lstrip('.') if suffix in ('.bin', '.parquet', '.tsv') else 'csv'}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Generate item-presence transactions, independently of storage format.
|
|
2
|
+
|
|
3
|
+
Uses cuPAMI's uniform basket sampler in TransactionalDatabase; this is not
|
|
4
|
+
an implementation of IBM's association-rule workload generator.
|
|
5
|
+
"""
|
|
6
|
+
from .TransactionalDatabase import TransactionalDatabase
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BinaryTransactionalDatabase(TransactionalDatabase):
|
|
10
|
+
"""Binary (presence/absence) baskets; export as CSV, BIN, or Parquet.
|
|
11
|
+
|
|
12
|
+
Arguments: transactions, items, avg_length=None, seed=None.
|
|
13
|
+
Each returned row is a sorted list of unique integer item IDs.
|
|
14
|
+
"""
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Generate item/quantity baskets with cuPAMI's uniform basket sampler.
|
|
2
|
+
|
|
3
|
+
Quantities are independent uniform integer draws, not utility values or
|
|
4
|
+
fuzzy memberships. File schemas are defined in extras._quantitative_io.
|
|
5
|
+
"""
|
|
6
|
+
from numbers import Integral
|
|
7
|
+
|
|
8
|
+
from .TransactionalDatabase import TransactionalDatabase
|
|
9
|
+
from .. import _quantitative_io
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class QuantitativeTransactionalDatabase(TransactionalDatabase):
|
|
13
|
+
"""Return rows of {item_id: quantity}, with unique items per basket.
|
|
14
|
+
|
|
15
|
+
min_quantity and max_quantity are inclusive positive integer bounds.
|
|
16
|
+
CSV uses aligned items:quantities lists; BIN and Parquet preserve both.
|
|
17
|
+
"""
|
|
18
|
+
def __init__(self, transactions, items, avg_length=None, seed=None, *,
|
|
19
|
+
min_quantity=1, max_quantity=10):
|
|
20
|
+
for name, value in (('min_quantity', min_quantity), ('max_quantity', max_quantity)):
|
|
21
|
+
if isinstance(value, bool) or not isinstance(value, Integral):
|
|
22
|
+
raise TypeError(f'{name} must be an integer')
|
|
23
|
+
if not 1 <= value <= 2**53:
|
|
24
|
+
raise ValueError(f'{name} must be in 1..2**53')
|
|
25
|
+
if min_quantity > max_quantity:
|
|
26
|
+
raise ValueError('min_quantity must not exceed max_quantity')
|
|
27
|
+
super().__init__(transactions, items, avg_length, seed)
|
|
28
|
+
self.min_quantity = int(min_quantity)
|
|
29
|
+
self.max_quantity = int(max_quantity)
|
|
30
|
+
|
|
31
|
+
def _generateTransactions(self):
|
|
32
|
+
for basket in super()._generateTransactions():
|
|
33
|
+
yield {item: self._random.randint(self.min_quantity, self.max_quantity)
|
|
34
|
+
for item in basket}
|
|
35
|
+
|
|
36
|
+
def createQuantitativeDatabase(self, outputFile):
|
|
37
|
+
"""Generate directly to a file without retaining all transactions."""
|
|
38
|
+
self.createTransactionalDatabase(outputFile)
|
|
39
|
+
|
|
40
|
+
def _writeDatabase(self, outputFile, transactions):
|
|
41
|
+
_quantitative_io.write(outputFile, transactions)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Local temporal workload generator built on the binary basket sampler.
|
|
2
|
+
|
|
3
|
+
Timestamp-step sampling is a cuPAMI convention, not an implementation of
|
|
4
|
+
a published temporal workload model. Format references: docs/transaction-formats.md.
|
|
5
|
+
"""
|
|
6
|
+
from .TransactionalDatabase import TransactionalDatabase
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TemporalDatabase(TransactionalDatabase):
|
|
10
|
+
"""Generate timestamped baskets with optional random repeats and gaps.
|
|
11
|
+
|
|
12
|
+
Allowed timestamp steps are 0 (repeat), 1 (next), and 2 (skip one).
|
|
13
|
+
All flags default to False. Merging unions items at each repeated timestamp.
|
|
14
|
+
"""
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
transactions,
|
|
18
|
+
items,
|
|
19
|
+
avg_length=None,
|
|
20
|
+
seed=None,
|
|
21
|
+
*,
|
|
22
|
+
repeatAllowed=False,
|
|
23
|
+
missingAllowed=False,
|
|
24
|
+
mergeTimestamps=False,
|
|
25
|
+
):
|
|
26
|
+
for name, value in (
|
|
27
|
+
("repeatAllowed", repeatAllowed),
|
|
28
|
+
("missingAllowed", missingAllowed),
|
|
29
|
+
("mergeTimestamps", mergeTimestamps),
|
|
30
|
+
):
|
|
31
|
+
if not isinstance(value, bool):
|
|
32
|
+
raise TypeError(f"{name} must be a boolean")
|
|
33
|
+
if mergeTimestamps and not repeatAllowed:
|
|
34
|
+
raise ValueError("mergeTimestamps=True requires repeatAllowed=True")
|
|
35
|
+
super().__init__(transactions, items, avg_length, seed)
|
|
36
|
+
self.repeatAllowed = repeatAllowed
|
|
37
|
+
self.missingAllowed = missingAllowed
|
|
38
|
+
self.mergeTimestamps = mergeTimestamps
|
|
39
|
+
|
|
40
|
+
def _generateTransactions(self):
|
|
41
|
+
timestamp = 1
|
|
42
|
+
pendingTimestamp = None
|
|
43
|
+
pendingItems = set()
|
|
44
|
+
|
|
45
|
+
for index, transaction in enumerate(super()._generateTransactions()):
|
|
46
|
+
if index:
|
|
47
|
+
step = 1
|
|
48
|
+
if self.repeatAllowed or self.missingAllowed:
|
|
49
|
+
step = self._random.randint(
|
|
50
|
+
0 if self.repeatAllowed else 1,
|
|
51
|
+
2 if self.missingAllowed else 1,
|
|
52
|
+
)
|
|
53
|
+
timestamp += step
|
|
54
|
+
|
|
55
|
+
if not self.mergeTimestamps:
|
|
56
|
+
yield [timestamp, *transaction]
|
|
57
|
+
continue
|
|
58
|
+
|
|
59
|
+
if pendingTimestamp is not None and pendingTimestamp != timestamp:
|
|
60
|
+
yield [pendingTimestamp, *sorted(pendingItems)]
|
|
61
|
+
pendingItems.clear()
|
|
62
|
+
|
|
63
|
+
pendingTimestamp = timestamp
|
|
64
|
+
pendingItems.update(transaction)
|
|
65
|
+
|
|
66
|
+
if pendingTimestamp is not None:
|
|
67
|
+
yield [pendingTimestamp, *sorted(pendingItems)]
|
|
68
|
+
|
|
69
|
+
def createTemporalDatabase(self, outputFile):
|
|
70
|
+
self.createTransactionalDatabase(outputFile)
|
|
71
|
+
|
|
72
|
+
def _writeDatabase(self, outputFile, transactions):
|
|
73
|
+
from pathlib import Path
|
|
74
|
+
|
|
75
|
+
from .. import _temporal_io
|
|
76
|
+
|
|
77
|
+
suffix = Path(outputFile).suffix.lower()
|
|
78
|
+
if suffix == ".bin":
|
|
79
|
+
_temporal_io.write_binary(outputFile, transactions, self.items)
|
|
80
|
+
elif suffix == ".parquet":
|
|
81
|
+
_temporal_io.write_parquet(outputFile, transactions, self.items)
|
|
82
|
+
else:
|
|
83
|
+
super()._writeDatabase(outputFile, transactions)
|