Recipes¶
Short, runnable patterns. Every python block runs in CI, in order, in one namespace.
Faker pools¶
Faker is slow per value; RandSpecs.faker_pool draws a pool once and returns a distincts spec.
Install the optional extra first: pip install "rand-engine[faker]". It accepts a Faker provider
such as name or email, a locale (default en_US), a positive pool_size (default 100), and
an optional seed. The seed fixes the materialized pool, then NumPy samples that pool for every row.
Invalid pool sizes, unavailable Faker, unsupported locales/providers, provider failures and
non-scalar provider values raise RandEngineError.
from rand_engine import DataGenerator, RandSpecs
name_spec = RandSpecs.faker_pool("name", locale="pt_BR", pool_size=500, seed=0)
people = DataGenerator({
"name": name_spec,
"email": RandSpecs.faker_pool("email", pool_size=500, seed=0),
}, seed=1).size(2_000).get_df()
assert people["name"].isin(name_spec["kwargs"]["distincts"]).all()
from rand_engine.validators.exceptions import RandEngineError
try:
RandSpecs.faker_pool("name", pool_size=0)
except RandEngineError:
pass
else:
raise AssertionError("expected positive pool_size")
Spec from an Arrow schema¶
RandSpecs.from_schema maps Arrow metadata to a validated RandSpec. Boolean fields become
booleans(true_prob=0.5); integer fields become integers(min=0, max=min(100, type maximum),
int_type=<Arrow type>); floating fields become floats(0..1, decimals=2); string and large-string
fields become uuid4; date fields become dates(2000-01-01..2030-12-31); timezone-naive timestamps
become second-resolution dates; string, large-string, date and timestamp fields generate string[pyarrow] columns; and null fields
become constant(None), an object column. Nullable fields retain
the same recipe: Arrow nullability does not add a RandSpec modifier.
For an override, kwargs merge into the default recipe. An override containing method replaces
the whole field recipe. The builder refuses non-schemas, unknown fields, duplicate schema names,
non-dict overrides, unsupported Arrow families without a complete method replacement, and any
resulting invalid RandSpec with SpecValidationError.
import pyarrow as pa
from rand_engine.validators.exceptions import SpecValidationError
schema = pa.schema([
("active", pa.bool_()), ("id", pa.int64()), ("score", pa.float64()),
("label", pa.string()), ("note", pa.large_string()), ("day", pa.date32()),
("at", pa.timestamp("s")), ("missing", pa.null()),
])
spec = RandSpecs.from_schema(schema, overrides={
"score": {"kwargs": {"min": 0, "max": 10}},
"label": {"method": "distincts", "kwargs": {"distincts": ["trial", "paid"]}},
})
df = DataGenerator(spec, seed=1).size(500).get_df()
assert list(spec) == list(schema.names) and df["score"].between(0, 10).all()
assert spec["label"] == {"method": "distincts", "kwargs": {"distincts": ["trial", "paid"]}}
try:
RandSpecs.from_schema(pa.schema([("amount", pa.decimal128(10, 2))]))
except SpecValidationError:
pass
else:
raise AssertionError("expected unsupported Arrow type")
try:
RandSpecs.from_schema(pa.schema([("id", pa.int32())]), overrides={"missing": {}})
except SpecValidationError:
pass
else:
raise AssertionError("expected unknown override")
Ready-made specifications¶
RandSpecs is the top-level alias for CommonRandSpecs: its ten factories work with both
DataGenerator and SparkGenerator. AdvancedRandSpecs has ten factories for DataGenerator
only; they demonstrate correlated and template methods. Use the factory pages as a compact inventory,
then run a returned spec with the generator that family supports.
Cross-compatible specification examples for DataGenerator and SparkGenerator.
All specs use the unified API with date_format parameter.
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> df = DataGenerator(RandSpecs.customers(), seed=42).size(100).get_df()
>>> list(df.columns)
['customer_id', 'age', 'city', 'total_spent', 'is_premium', 'registration_date']
>>> len(df)
100
Source code in rand_engine/examples/common_rand_specs.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
customers()
classmethod
¶
Return the customer profiles RandSpec (6 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 6 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.customers(), seed=1).size(5).get_df().columns)
['customer_id', 'age', 'city', 'total_spent', 'is_premium', 'registration_date']
Source code in rand_engine/examples/common_rand_specs.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
devices()
classmethod
¶
Return the device inventory RandSpec (7 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 7 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.devices(), seed=1).size(5).get_df().columns)
['device_id', 'serial_number', 'firmware_version', 'uptime_hours', 'status', 'is_critical', 'last_seen']
Source code in rand_engine/examples/common_rand_specs.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
employees()
classmethod
¶
Return the employee records RandSpec (8 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 8 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.employees(), seed=1).size(5).get_df().columns)
['employee_id', 'department', 'position', 'salary', 'hire_date', 'age', 'is_remote', 'performance_score']
Source code in rand_engine/examples/common_rand_specs.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |
events()
classmethod
¶
Return the system event logs RandSpec (6 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 6 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.events(), seed=1).size(5).get_df().columns)
['event_id', 'event_type', 'timestamp', 'duration_ms', 'is_error', 'severity']
Source code in rand_engine/examples/common_rand_specs.py
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | |
faker_pool(provider, locale='en_US', pool_size=100, seed=None)
classmethod
¶
Build one materialized distincts spec with a local Faker instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Faker provider method, such as |
required |
locale
|
str
|
Faker locale; an unsupported locale raises RandEngineError. |
"en_US"
|
pool_size
|
int
|
Number of values to materialize; a positive integer. |
100
|
seed
|
int
|
Seed of the Faker instance; the same seed gives the same pool. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
A |
Raises:
| Type | Description |
|---|---|
RandEngineError
|
If |
Examples:
>>> from rand_engine import RandSpecs
>>> spec = RandSpecs.faker_pool("city", pool_size=5, seed=1)
>>> spec["method"]
'distincts'
>>> len(spec["kwargs"]["distincts"])
5
Source code in rand_engine/examples/common_rand_specs.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
from_schema(schema, overrides=None)
classmethod
¶
Build a validated RandSpec from Arrow field metadata only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
Schema
|
Arrow schema; each field's type picks a default generation recipe. |
required |
overrides
|
dict
|
Per-field overrides keyed by field name. A |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec with one entry per schema field, validated before return. |
Raises:
| Type | Description |
|---|---|
SpecValidationError
|
If |
Examples:
>>> import pyarrow as pa
>>> from rand_engine import DataGenerator, RandSpecs
>>> schema = pa.schema([("id", pa.int32()), ("active", pa.bool_())])
>>> spec = RandSpecs.from_schema(schema, {"id": {"kwargs": {"max": 9}}})
>>> {name: column["method"] for name, column in spec.items()}
{'id': 'integers', 'active': 'booleans'}
>>> DataGenerator(spec, seed=1).size(5).get_df().shape
(5, 2)
Source code in rand_engine/examples/common_rand_specs.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
orders()
classmethod
¶
Return the e-commerce orders RandSpec (6 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 6 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.orders(), seed=1).size(5).get_df().columns)
['order_id', 'customer_id', 'amount', 'order_timestamp', 'status', 'payment_method']
Source code in rand_engine/examples/common_rand_specs.py
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
products()
classmethod
¶
Return the product catalog RandSpec (7 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 7 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.products(), seed=1).size(5).get_df().columns)
['product_id', 'sku', 'name', 'price', 'stock_quantity', 'category', 'is_active']
Source code in rand_engine/examples/common_rand_specs.py
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
sales()
classmethod
¶
Return the sales records RandSpec (8 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 8 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.sales(), seed=1).size(5).get_df().columns)
['transaction_id', 'sale_id', 'product_id', 'amount', 'quantity', 'sales_rep', 'sale_date', 'is_wholesale']
Source code in rand_engine/examples/common_rand_specs.py
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
sensors()
classmethod
¶
Return the IoT sensor readings RandSpec (7 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 7 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.sensors(), seed=1).size(5).get_df().columns)
['sensor_id', 'device_name', 'temperature', 'humidity', 'battery_level', 'timestamp', 'is_online']
Source code in rand_engine/examples/common_rand_specs.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
transactions()
classmethod
¶
Return the financial transactions RandSpec (7 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 7 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.transactions(), seed=1).size(5).get_df().columns)
['transaction_id', 'account_id', 'amount', 'transaction_type', 'timestamp', 'is_approved', 'fee']
Source code in rand_engine/examples/common_rand_specs.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 | |
users()
classmethod
¶
Return the application users RandSpec (7 Fields).
Returns:
| Type | Description |
|---|---|
dict
|
RandSpec mapping each of the 7 fields to its method and kwargs. |
Examples:
>>> from rand_engine import DataGenerator, RandSpecs
>>> list(DataGenerator(RandSpecs.users(), seed=1).size(5).get_df().columns)
['user_id', 'username', 'signup_date', 'login_count', 'subscription_plan', 'is_active', 'engagement_score']
Source code in rand_engine/examples/common_rand_specs.py
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
Advanced specification examples showcasing PyCore-exclusive methods for DataGenerator.
AdvancedRandSpecs demonstrates sophisticated data generation patterns using methods that are currently only available in DataGenerator (not yet in SparkGenerator). These specs focus on correlated data, complex patterns, and hierarchical relationships.
PyCore-Exclusive Methods:
- distincts_map: Generate correlated pairs (e.g., currency-country)
- distincts_multi_map: Generate hierarchical correlations (3+ levels)
- distincts_map_prop: Weighted correlated pairs with nested probabilities
- complex_distincts: Pattern-based generation with template replacement
Available Specs:
- products: Product catalog with complex SKU patterns
- orders: E-commerce orders with currency-country correlations
- employees: Employee hierarchy with department-level-role correlations
- devices: IoT devices with status-priority weighted correlations
- invoices: Invoice records with pattern-based numbering
- shipments: Shipping data with carrier-destination correlations
- network_devices: Network infrastructure with IP patterns
- vehicles: Vehicle fleet with make-model-year correlations
- real_estate: Property listings with location-type correlations
- healthcare: Patient records with diagnosis-treatment patterns
Usage Examples:
Basic usage¶
from rand_engine import DataGenerator from rand_engine.examples.advanced_rand_specs import AdvancedRandSpecs
df = DataGenerator(AdvancedRandSpecs.products(), seed=42).size(1000).get_df() print(df.head())
Exploring correlations¶
df = DataGenerator(AdvancedRandSpecs.employees(), seed=42).size(500).get_df() print(df[['department', 'level', 'role']].drop_duplicates())
Pattern-based generation¶
df = DataGenerator(AdvancedRandSpecs.network_devices(), seed=42).size(100).get_df() print(df['ip_address'].unique()[:5]) # Shows generated IPs like "192.168.1.45"
Notes:
- These specs work ONLY with DataGenerator (pandas)
- For cross-compatible specs, use CommonRandSpecs from common_rand_specs.py
- Static class - no instantiation required
- Each spec demonstrates 1-2 advanced patterns
- Specs range from 5-8 fields for realistic complexity
Source code in rand_engine/examples/advanced_rand_specs.py
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | |
devices()
classmethod
¶
IoT devices with status-priority weighted correlations.
Advanced Pattern: distincts_map_prop for weighted correlated pairs
Fields (7):
- device_id: UUID4 unique identifiers
- device_type: Device types (Sensor 50%, Gateway 30%, Controller 20%)
- status, priority: Weighted pairs via distincts_map_prop (splits into 2)
- temperature: Temperature readings 15-45°C
- battery_level: Battery percentage 0-100
- last_ping: Last communication timestamp
Key Learning:
- distincts_map_prop: Maps status to priority with nested weights
- Online→[(Low,70%), (Medium,20%), (High,10%)]
- Offline→[(Low,30%), (Medium,40%), (High,30%)]
- Allows realistic conditional distributions
Returns:
Dict[str, Any]: Specification for IoT devices with conditional priorities
Source code in rand_engine/examples/advanced_rand_specs.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
employees()
classmethod
¶
Employee records with department-level-role hierarchical correlations.
Advanced Pattern: distincts_multi_map for 3-level cartesian product
Fields (6):
- employee_id: Zero-padded IDs (6 digits)
- hire_date: Employment start dates
- salary: Normally distributed salaries (mean=6500, std=2000)
- department, level, role: 3-level hierarchy via distincts_multi_map
- is_remote: Remote work flag
- performance_score: Performance ratings 1-5
Key Learning:
- distincts_multi_map: Cartesian product of nested lists
- Engineering→[Junior,Senior]×[Developer,QA] = 4 combinations
- Sales→[Junior,Senior]×[Rep,Manager] = 4 combinations
- Generates all valid combinations respecting hierarchy
Returns:
Dict[str, Any]: Specification for employees with hierarchical roles
Source code in rand_engine/examples/advanced_rand_specs.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
healthcare()
classmethod
¶
Patient records with diagnosis-treatment patterns.
Advanced Pattern: distincts_map_prop for diagnosis-treatment correlations
Fields (7):
- patient_id: UUID4 unique identifiers
- age: Patient age 0-100
- diagnosis, treatment: Correlated via distincts_map_prop (weighted by diagnosis)
- admission_date: Hospital admission date
- discharge_date: Hospital discharge date
- bill_amount: Medical bill amount
- is_emergency: Emergency admission flag
Key Learning:
- distincts_map_prop: Diagnosis→Treatment with probabilities
- Flu→[(Medication,80%), (Hospitalization,20%)]
- Fracture→[(Surgery,60%), (Cast,40%)]
- Models medical decision patterns
Returns:
Dict[str, Any]: Specification for healthcare with realistic treatment paths
Source code in rand_engine/examples/advanced_rand_specs.py
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | |
invoices()
classmethod
¶
Invoice records with pattern-based invoice numbering.
Advanced Pattern: complex_distincts with multiple templates (INV-YYYY-XXXXX)
Fields (6):
- invoice_number: Pattern "INV-2023-00001" using 2 templates
- issue_date: Invoice issue date
- due_date: Payment due date
- amount: Invoice amount 100-50000
- status: Payment status (Paid 60%, Pending 30%, Overdue 10%)
- tax_rate: Tax percentage 0-25%
Key Learning:
- complex_distincts: Pattern "INV-x-x" with 2 replacements
- First x→year (2023 or 2024)
- Second x→5-digit zero-filled number
- Templates processed left-to-right in order
Returns:
Dict[str, Any]: Specification for invoices with structured numbering
Source code in rand_engine/examples/advanced_rand_specs.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
network_devices()
classmethod
¶
Network infrastructure devices with IP address patterns.
Advanced Pattern: complex_distincts for IP address generation (x.x.x.x)
Fields (7):
- device_id: UUID4 unique identifiers
- hostname: Zero-padded hostname IDs
- ip_address: Pattern "192.168.x.x" using 4 templates
- subnet: Network subnet addresses
- device_type: Network device types (Router, Switch, Firewall, AP)
- uptime_hours: Hours since last reboot
- is_active: Device active status
Key Learning:
- complex_distincts: Pattern "x.x.x.x" with 4 replacements
- First two octets: Fixed (192, 168)
- Last two octets: Random integers 0-255
- Generates realistic private IP addresses
Returns:
Dict[str, Any]: Specification for network devices with IP patterns
Source code in rand_engine/examples/advanced_rand_specs.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
orders()
classmethod
¶
E-commerce orders with currency-country correlations.
Advanced Pattern: distincts_map for currency-country pairs
Fields (7):
- order_id: UUID4 unique identifiers
- order_date: Unix timestamps from 2023
- amount: Order amounts 10-5000
- status: Order status (Pending 20%, Completed 70%, Cancelled 10%)
- payment_method: Payment types
- currency, country: Correlated pairs via distincts_map (splits into 2 columns)
Key Learning:
- distincts_map: Maps countries to currencies (US→USD, DE→EUR, BR→BRL, JP→JPY)
- splitable=True: Generates single column then splits into multiple
- sep=";": Delimiter for splitting
- cols=[]: Resulting column names after split
Returns:
Dict[str, Any]: Specification for orders with currency-country correlation
Source code in rand_engine/examples/advanced_rand_specs.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
products()
classmethod
¶
Product catalog with complex SKU patterns.
Advanced Pattern: complex_distincts for SKU generation (PRD-XXXX format)
Fields (6):
- sku: Pattern-based SKU "PRD-1234" using complex_distincts
- product_name: Random product names
- category: Weighted categories (Electronics 50%, Clothing 30%, Food 20%)
- price: Product prices 5-500
- stock: Inventory levels 0-1000
- rating: Normally distributed ratings (mean=4.0, std=0.8)
Key Learning:
- complex_distincts: Pattern "PRD-x" where x is replaced by template (integers 1000-9999)
- Templates use "kwargs" dict for parameters
- Useful for generating codes, IDs, serial numbers
Returns:
Dict[str, Any]: Specification for advanced product catalog
Source code in rand_engine/examples/advanced_rand_specs.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
real_estate()
classmethod
¶
Property listings with location-type correlations.
Advanced Pattern: distincts_map_prop for location-based pricing
Fields (8):
- property_id: UUID4 unique identifiers
- address: Property street addresses
- city, type: Correlated via distincts_map (city determines available types)
- bedrooms: Number of bedrooms 1-5
- bathrooms: Number of bathrooms 1-4
- price: Property price (normal distribution by type)
- is_available: Availability status
Key Learning:
- distincts_map: City→PropertyTypes mapping
- Manhattan→[Apartment,Condo], Brooklyn→[Apartment,Townhouse]
- Models geographic constraints on property types
Returns:
Dict[str, Any]: Specification for real estate with location constraints
Source code in rand_engine/examples/advanced_rand_specs.py
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 | |
shipments()
classmethod
¶
Shipping records with carrier-destination correlations.
Advanced Pattern: distincts_map for carrier routing rules
Fields (7):
- tracking_number: Pattern "TRK-XXXXXXXXXX" (10 digits)
- carrier, destination: Correlated via distincts_map (FedEx→US/CA only)
- weight: Package weight 0.1-50 kg
- status: Shipping status (In Transit 40%, Delivered 50%, Exception 10%)
- ship_date: Shipment date
- estimated_delivery: Expected delivery date
Key Learning:
- distincts_map: Models real-world constraints (carriers serve specific regions)
- FedEx→[US,CA], DHL→[EU,UK], USPS→[US], UPS→[US,MX]
- Ensures generated data respects business rules
Returns:
Dict[str, Any]: Specification for shipments with routing rules
Source code in rand_engine/examples/advanced_rand_specs.py
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | |
vehicles()
classmethod
¶
Vehicle fleet with make-model-year correlations.
Advanced Pattern: distincts_multi_map for vehicle hierarchy
Fields (8):
- vehicle_id: UUID4 unique identifiers
- license_plate: Pattern "XXX-XXXX" (letters-numbers)
- make, model, year: Correlated hierarchy via distincts_multi_map
- mileage: Odometer reading
- fuel_type: Fuel types (Gasoline 60%, Diesel 30%, Electric 10%)
- is_active: Fleet active status
Key Learning:
- distincts_multi_map: Make→Model→Year hierarchy
- Toyota→[Corolla,Camry]×[2020,2021,2022]
- Ford→[F150,Mustang]×[2019,2020,2021]
- Ensures only valid make-model-year combinations
Returns:
Dict[str, Any]: Specification for vehicle fleet with valid combinations
Source code in rand_engine/examples/advanced_rand_specs.py
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
Kafka or any queue¶
stream_dict yields Python record dicts at a bounded rate; send them with your client.
After normalization, every microbatch uses pandas records so its public Python representation is
retained.
import json
from itertools import islice
events = DataGenerator({
"event_id": {"method": "pk", "kwargs": {"start": 1}},
"kind": {"method": "distincts", "kwargs": {"distincts": ["click", "view"]}},
}, seed=1).size(100)
records = [json.dumps(r).encode() for r in islice(events.stream_dict(min_throughput=500, max_throughput=1000), 20)]
assert json.loads(records[0])["event_id"] == 1
With kafka-python (not a test dependency, so this block is not executed):
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers="localhost:9092")
for record in events.stream_dict(min_throughput=10, max_throughput=50):
producer.send("events", json.dumps(record).encode())
Parquet lake¶
One folder per partition value, several files each.
import pandas as pd
for day in ["2024-01-01", "2024-01-02"]:
sales = DataGenerator({
"sale_id": {"method": "pk", "kwargs": {"start": 1, "format": day.replace("-", "") + "{:06d}"}},
"amount": {"method": "floats", "kwargs": {"min": 1, "max": 500}},
}, seed=int(day[-2:])).size(1_000)
sales.write.format("parquet").options(numFiles=2, compression="zstd").save(f"lake/sales/day={day}")
lake = pd.read_parquet("lake/sales")
assert len(lake) == 2_000 and lake["sale_id"].is_unique
Related tables¶
Share the parent's pk spec with the child's fk; see 4_CONSTRAINTS.md.
customer_pk = {"method": "pk", "kwargs": {"start": 1, "format": "C{:05d}"}}
order_pk = {"method": "pk", "kwargs": {"start": 1}}
customers = DataGenerator({"customer_id": customer_pk}, seed=1).size(500).get_df()
orders = DataGenerator({
"order_id": order_pk,
"customer_id": {"method": "fk", "kwargs": {"parent": customer_pk, "parent_size": 500, "skew": 1.0}},
}, seed=2).size(2_000).get_df()
items = DataGenerator({
"order_id": {"method": "fk", "kwargs": {"parent": order_pk, "parent_size": 2_000}},
"qty": {"method": "integers", "kwargs": {"min": 1, "max": 5}},
}, seed=3).size(3_000).get_df()
assert orders.merge(customers, on="customer_id").shape[0] == 2_000
assert items.merge(orders, on="order_id").shape[0] == 3_000