Skip to content

tdfs4ds.tutorial

tdfs4ds.tutorial

Synthetic data for the tutorial, in eight industry flavors of the same demo.

Every flavor has the same three tables and the same shapes; only the names, the category values and the amounts differ:

  • an entity table (customers, accounts, patients, ...) keyed by the entity id, with a region, a segment and a start date;
  • a partner table (merchants, counterparties, providers, ...) keyed by the partner id, with a category and a name made of codes (M0001 Grocery);
  • an events table (transactions, payments, claims, ...) with one row per event: event id, entity id, partner id, event date, amount and category.

The generator gives the tutorial something to show: about 15% of the entities stop before mid-year (churn), about 15% start in May or later (newcomers), each entity prefers one category, amounts depend on the category, events cover every day of the year, and about 1% of the events have no partner (a NULL partner id).

Three layers:

  • :func:tutorial_scenario -- pure: the names and descriptions of one flavor;
  • :func:tutorial_frames -- pure: the three pandas frames, deterministic per seed;
  • :func:create_tutorial_data / :func:drop_tutorial_data -- the only database writers (teradataml copy_to_sql and execute_sql).

ROLES module-attribute

ROLES = ('entities', 'partners', 'events')

REGIONS module-attribute

REGIONS = ('North', 'South', 'East', 'West', 'Central')

_SIZE_KEYS module-attribute

_SIZE_KEYS = ('n_entities', 'n_partners', 'n_events', 'year', 'seed')

SCENARIOS module-attribute

SCENARIOS: Dict[str, dict] = {'retail': dict(entity='CustomerID', entity_table='customers', entity_noun='customer', entity_start='Signup_Date', segments=('Standard', 'Premium', 'Business'), partner='MerchantID', partner_table='merchants', partner_noun='merchant', partner_name='Merchant_Name', partner_code='M', events_table='transactions', event_noun='card transaction', event_id='TransactionID', event_date='Date_transaction', amount='Transaction_Amount', amount_unit='euros', decimals=2, categories={'grocery': 45.0, 'fuel': 60.0, 'electronics': 320.0, 'clothing': 85.0, 'restaurants': 38.0, 'travel': 450.0}), 'banking': dict(entity='AccountID', entity_table='accounts', entity_noun='bank account', entity_start='Open_Date', segments=('Retail', 'Private', 'SME'), partner='CounterpartyID', partner_table='counterparties', partner_noun='counterparty', partner_name='Counterparty_Name', partner_code='C', events_table='payments', event_noun='payment', event_id='PaymentID', event_date='Payment_Date', amount='Payment_Amount', amount_unit='euros', decimals=2, categories={'transfer': 1200.0, 'card': 55.0, 'direct debit': 140.0, 'cash withdrawal': 120.0, 'standing order': 600.0, 'international transfer': 2500.0}), 'healthcare': dict(entity='PatientID', entity_table='patients', entity_noun='patient', entity_start='Enrollment_Date', segments=('Adult', 'Senior', 'Pediatric'), partner='ProviderID', partner_table='providers', partner_noun='care provider', partner_name='Provider_Name', partner_code='PRV', events_table='claims', event_noun='insurance claim', event_id='ClaimID', event_date='Claim_Date', amount='Claim_Amount', amount_unit='euros', decimals=2, categories={'consultation': 60.0, 'imaging': 420.0, 'surgery': 4800.0, 'laboratory': 95.0, 'pharmacy': 45.0, 'physiotherapy': 70.0}), 'pharma': dict(entity='PharmacyID', entity_table='pharmacies', entity_noun='pharmacy', entity_start='Opening_Date', segments=('Independent', 'Chain', 'Hospital'), partner='ProductID', partner_table='products', partner_noun='medicinal product', partner_name='Product_Name', partner_code='PRD', events_table='dispensings', event_noun='dispensing', event_id='DispensingID', event_date='Dispensing_Date', amount='Dispensed_Units', amount_unit='units (packs)', decimals=0, categories={'oncology': 12.0, 'cardiology': 90.0, 'diabetes': 120.0, 'respiratory': 60.0, 'dermatology': 35.0, 'vaccines': 25.0}), 'manufacturing': dict(entity='MachineID', entity_table='machines', entity_noun='machine', entity_start='Install_Date', segments=('Critical', 'Standard', 'Auxiliary'), partner='PlantID', partner_table='plants', partner_noun='plant', partner_name='Plant_Name', partner_code='PL', events_table='sensor_readings', event_noun='energy reading', event_id='ReadingID', event_date='Reading_Date', amount='Energy_kWh', amount_unit='kWh', decimals=2, categories={'pressing': 180.0, 'welding': 95.0, 'painting': 140.0, 'machining': 75.0, 'molding': 210.0, 'packaging': 30.0}), 'assembly': dict(entity='StationID', entity_table='stations', entity_noun='assembly station', entity_start='Commission_Date', segments=('Manual', 'Semi-automatic', 'Automatic'), partner='LineID', partner_table='lines', partner_noun='assembly line', partner_name='Line_Name', partner_code='L', events_table='steps', event_noun='assembly step', event_id='StepID', event_date='Step_Date', amount='Cycle_Time_s', amount_unit='seconds', decimals=1, categories={'fastening': 18.0, 'sub-assembly': 95.0, 'inspection': 40.0, 'wiring': 70.0, 'testing': 120.0, 'packing': 25.0}), 'energy': dict(entity='MeterID', entity_table='meters', entity_noun='electricity meter', entity_start='Install_Date', segments=('Low voltage', 'Medium voltage', 'High voltage'), partner='SubstationID', partner_table='substations', partner_noun='substation', partner_name='Substation_Name', partner_code='S', events_table='meter_readings', event_noun='meter reading', event_id='ReadingID', event_date='Reading_Date', amount='Consumption_kWh', amount_unit='kWh', decimals=2, categories={'residential': 9.0, 'commercial': 45.0, 'industrial': 380.0, 'EV charging': 28.0, 'street lighting': 15.0, 'agriculture': 60.0}), 'transportation': dict(entity='VehicleID', entity_table='vehicles', entity_noun='vehicle', entity_start='Service_Start_Date', segments=('Electric', 'Diesel', 'Hybrid'), partner='DepotID', partner_table='depots', partner_noun='depot', partner_name='Depot_Name', partner_code='D', events_table='trips', event_noun='trip', event_id='TripID', event_date='Trip_Date', amount='Distance_km', amount_unit='kilometres', decimals=1, categories={'bus': 120.0, 'tram': 70.0, 'rail': 340.0, 'on-demand': 25.0, 'coach': 450.0, 'ferry': 60.0})}

TutorialScenario dataclass

Names and descriptions of one flavor of the tutorial data.

tables holds the unqualified table names per role ('entities', 'partners', 'events'); :meth:table qualifies them once database is set (by :func:create_tutorial_data).

name instance-attribute

name: str

entity instance-attribute

entity: str

partner instance-attribute

partner: str

events instance-attribute

events: str

amount instance-attribute

amount: str

event_date instance-attribute

event_date: str

event_id instance-attribute

event_id: str

category instance-attribute

category: str

region instance-attribute

region: str

segment instance-attribute

segment: str

tables instance-attribute

tables: Dict[str, str]

database class-attribute instance-attribute

database: Optional[str] = None

descriptions class-attribute instance-attribute

descriptions: Dict[str, dict] = field(default_factory=dict)

entity_start class-attribute instance-attribute

entity_start: str = ''

partner_name class-attribute instance-attribute

partner_name: str = ''

categories class-attribute instance-attribute

categories: Tuple[str, ...] = ()

segments class-attribute instance-attribute

segments: Tuple[str, ...] = ()

regions class-attribute instance-attribute

regions: Tuple[str, ...] = REGIONS

amount_unit class-attribute instance-attribute

amount_unit: str = ''

__init__

__init__(name: str, entity: str, partner: str, events: str, amount: str, event_date: str, event_id: str, category: str, region: str, segment: str, tables: Dict[str, str], database: Optional[str] = None, descriptions: Dict[str, dict] = dict(), entity_start: str = '', partner_name: str = '', categories: Tuple[str, ...] = (), segments: Tuple[str, ...] = (), regions: Tuple[str, ...] = REGIONS, amount_unit: str = '') -> None

table

table(role: str) -> str

The table of role, db.table when the database is known, else bare.

key_column

key_column(role: str) -> str

describe

describe() -> pd.DataFrame

One row per table: role, table, key column, description.

_descriptions

_descriptions(name: str, s: dict) -> Dict[str, dict]

Plain-English descriptions of every table and column of a flavor.

tutorial_scenario

tutorial_scenario(scenario: str = 'retail') -> TutorialScenario

The names and descriptions of one flavor. Pure.

scenario is one of the keys of :data:SCENARIOS (case-insensitive).

tutorial_frames

tutorial_frames(scenario: str = 'retail', n_entities: int = 2000, n_partners: int = 200, n_events: int = 50000, year: int = 2023, seed: int = 42) -> Dict[str, pd.DataFrame]

The three frames ('entities', 'partners', 'events') of a flavor. Pure, deterministic.

Same seed, same sizes and same flavor give identical frames.

_weights

_weights(n: int) -> np.ndarray

Decreasing shares for n segments (the first segment is the most common).

_resolve_database

_resolve_database(database: Optional[str]) -> str

Explicit database, else tdfs4ds.SCHEMA, else the session's default database.

_staging_name

_staging_name(sc: TutorialScenario) -> str

_all_names

_all_names(sc: TutorialScenario) -> List[str]

_existing_tables

_existing_tables(database: str, names: List[str]) -> List[str]

Which of names exist in database (one DBC.TablesV read). Upper-case names.

_copy_types

_copy_types(sc: TutorialScenario) -> Dict[str, dict]

Explicit teradatasqlalchemy types of every column, per role (and the events staging).

_events_columns

_events_columns(sc: TutorialScenario) -> List[str]

events_ddl

events_ddl(sc: TutorialScenario, database: str, year: int = 2023, partitioned: bool = True) -> str

CREATE TABLE of the events table: MULTISET, PI on the entity id, one partition per day.

create_tutorial_data

create_tutorial_data(scenario: str = 'retail', database: Optional[str] = None, *, if_exists: str = 'fail', partitioned: bool = True, collect_stats: bool = True, **sizes) -> TutorialScenario

Write the three tables of a flavor in database; return the scenario with database set.

database None = tdfs4ds.SCHEMA, else the session's default database. if_exists='fail' refuses when one of the tables exists; 'replace' drops them first. sizes go to :func:tutorial_frames (n_entities, n_partners, n_events, year, seed).

drop_tutorial_data

drop_tutorial_data(scenario: str = 'retail', database: Optional[str] = None, dry_run: bool = False) -> List[str]

Drop the three tables of a flavor (and a leftover staging table) when they exist.

Returns the DROP statements; dry_run=True returns them without executing. When the existence read fails, a dry run lists all four statements.