imednet.integrations package¶
Integration helpers for exporting study data.
Submodules¶
imednet.integrations.cdisc_export module¶
CDISC ODM 1.3.2 and Dataset-JSON v1.1 streaming export sinks and helpers.
- imednet.integrations.cdisc_export.export_to_dataset_json(sdk, study_key, path=None, *, config=None, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, form_key=None, as_sdtm=None, sdtm_domain=None, naming_convention=None, preserve_record_id=None, metadata_version_oid='MDV.001', file_oid=None, creation_datetime=None, indent=2, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export study clinical datasets to CDISC Dataset-JSON v1.1 for CDASH Forms or SDTM domains.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str] | None) –
config (SinkConfig | None) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
form_key (str | None) –
as_sdtm (bool | None) –
sdtm_domain (str | None) –
naming_convention (str | None) –
preserve_record_id (bool | None) –
metadata_version_oid (str) –
file_oid (str | None) –
creation_datetime (str | None) –
indent (int) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.cdisc_export.export_to_odm(sdk, study_key, path=None, *, config=None, data_dictionary=None, reference_data=(), include_audit_trail=True, include_annotations=True, variable_whitelist=None, form_whitelist=None, metadata_version_oid='MDV.001', file_oid=None, creation_datetime=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export a study snapshot to CDISC ODM 1.3.2 XML with incremental checkpointing and PHI redaction.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str] | None) –
config (SinkConfig | None) –
data_dictionary (DataDictionary | None) –
reference_data (Sequence[OdmReferenceData]) –
include_audit_trail (bool) –
include_annotations (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
metadata_version_oid (str) –
file_oid (str | None) –
creation_datetime (str | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
imednet.integrations.dispatcher module¶
Unified functional facade for synchronous and asynchronous data export.
This module provides export() and async_export() entry points for data
persistence tasks, supporting both tabular procedural functions and object-oriented
streaming sink classes.
- class imednet.integrations.dispatcher.ExportRegistry[source]¶
Bases:
objectCentral registry mapping target types to sync and async implementations.
- get_async_sink(target_type)[source]¶
Retrieve a registered asynchronous sink class, or None if not found.
- Parameters:
target_type (str) –
- Return type:
type[AsyncExportSink] | None
- get_async_tabular(target_type)[source]¶
Retrieve a registered async tabular function, or None if not found.
- Parameters:
target_type (str) –
- Return type:
Callable[…, Any] | None
- get_config_class(target_type)[source]¶
Retrieve a registered config class, or SinkConfig as default.
- Parameters:
target_type (str) –
- Return type:
type[SinkConfig]
- get_sink(target_type)[source]¶
Retrieve a registered synchronous sink class, or None if not found.
- Parameters:
target_type (str) –
- Return type:
type[ExportSink] | None
- get_tabular(target_type)[source]¶
Retrieve a registered tabular function, or None if not found.
- Parameters:
target_type (str) –
- Return type:
Callable[…, Any] | None
- register_async_sink(target_type, sink_class)[source]¶
Register an asynchronous object-oriented sink class for a target type.
- Parameters:
target_type (str) –
sink_class (type[AsyncExportSink]) –
- Return type:
None
- register_async_tabular(target_type, func)[source]¶
Register an async tabular procedural function for a target type.
- Parameters:
target_type (str) –
func (Callable[..., Any]) –
- Return type:
None
- register_config(target_type, config_class)[source]¶
Register a configuration class for a target type.
- Parameters:
target_type (str) –
config_class (type[SinkConfig]) –
- Return type:
None
- register_sink(target_type, sink_class)[source]¶
Register a synchronous object-oriented sink class for a target type.
- Parameters:
target_type (str) –
sink_class (type[ExportSink]) –
- Return type:
None
- async imednet.integrations.dispatcher.async_export(target, sdk, study_key, *, config=None, **kwargs)[source]¶
Unified asynchronous entry point for data export.
Routes the export request to an async tabular function, a native
AsyncExportSinkclass, or an async-prefetched local tabular target.- Raises:
TypeError – If
sdkis a synchronousImednetSDK.ValueError – If the target type is not registered or unsupported.
- Parameters:
target (str) –
sdk (AsyncImednetFacade) –
study_key (str) –
config (SinkConfig | None) –
kwargs (Any) –
- Return type:
Any
- imednet.integrations.dispatcher.export(target, sdk, study_key, *, config=None, **kwargs)[source]¶
Unified synchronous entry point for data export.
Routes the export request to either a tabular function or a sink class based on the target identifier.
- Raises:
TypeError – If
sdkis anAsyncImednetSDK.ValueError – If the target type is not registered or unsupported.
- Parameters:
target (str) –
sdk (ImednetFacade) –
study_key (str) –
config (SinkConfig | None) –
kwargs (Any) –
- Return type:
Any
- imednet.integrations.dispatcher.register_async_sink_target(target_type, sink_class)[source]¶
Register an asynchronous object-oriented sink class for a target type.
- Parameters:
target_type (str) –
sink_class (type[AsyncExportSink]) –
- Return type:
None
- imednet.integrations.dispatcher.register_async_tabular_target(target_type, func)[source]¶
Register an async tabular procedural function for a target type.
- Parameters:
target_type (str) –
func (Callable[..., Any]) –
- Return type:
None
- imednet.integrations.dispatcher.register_config_target(target_type, config_class)[source]¶
Register a configuration class for a target type.
- Parameters:
target_type (str) –
config_class (type[SinkConfig]) –
- Return type:
None
- imednet.integrations.dispatcher.register_sink_target(target_type, sink_class)[source]¶
Register a synchronous object-oriented sink class for a target type.
- Parameters:
target_type (str) –
sink_class (type[ExportSink]) –
- Return type:
None
imednet.integrations.enrichment module¶
Data enrichment and transformation pipeline.
This module provides the EnrichmentPipeline for transforming raw API
data using configured mappings, terminology lookups, and PHI masking rules.
- class imednet.integrations.enrichment.CentralizedMapper[source]¶
Bases:
objectUnified Mapper with Enrichment Engine for data sinks.
- __init__(mode='document', post_processor=None, *, mask_phi=True, study_config=None, naming_convention=None, as_sdtm=None, sdtm_domain=None, seq_counters=None, domain_seq_counters=None, form_domain_map=None, seq_overrides=None, lineage_out=None, record_seqs=None, preserve_record_id=False)[source]¶
Initialize the mapper.
- Parameters:
mode (str) – “tabular” for flattened structures, “document” for nested structures.
post_processor (Callable[[dict[str, Any]], dict[str, Any]] | None) – Optional function to apply destination-specific formatting.
mask_phi (bool) – Whether to mask sensitive PHI fields by default.
study_config (StudyConfiguration | None) – Optional study configuration containing custom enrichment rules.
naming_convention (str | None) – Optional key convention (‘snake_case’, ‘camelCase’, ‘sdtm’).
as_sdtm (bool | None) – When True, transform records directly into CDISC SDTM domain rows.
sdtm_domain (str | None) – Optional SDTM domain code (e.g. ‘AE’, ‘VS’, ‘DM’).
seq_counters (dict[str, int] | None) – Optional per-USUBJID sequence counter map shared across batches.
domain_seq_counters (dict[str, dict[str, int]] | None) – Optional per-domain sequence counter map for multi-Form SDTM.
form_domain_map (Mapping[Any, str] | None) – Optional lookup from form_id / form_key to SDTM domain code.
seq_overrides (Mapping[str, int] | None) – Optional rehydrated record_id -> <DOM>SEQ overrides.
lineage_out (dict[str, dict[str, Any]] | None) – Optional dictionary populated with record_id -> SDTM lineage metadata.
record_seqs (dict[str, int] | None) – Optional per-Record sequence map for idempotent incremental reruns.
preserve_record_id (bool) – When True, retain RECORD_ID in transformed SDTM rows.
- bind_sdtm_lineage(*, domain_seq_counters=None, seq_overrides=None, seq_counters=None)[source]¶
Bind live SDTM sequence counters and overrides without rebuilding the mapper.
- Parameters:
domain_seq_counters (dict[str, dict[str, int]] | None) –
seq_overrides (Mapping[str, int] | None) –
seq_counters (dict[str, int] | None) –
- Return type:
None
- map_batch(records, study_key=None)[source]¶
Map a batch of records, sorting and sequencing SDTM batches per domain and USUBJID.
- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
- Return type:
list[dict[str, Any]]
- map_batch_with_sources(records, study_key=None)[source]¶
Map an SDTM batch returning
(source_record, sdtm_row)pairs in finalized order.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
- Return type:
list[tuple[Any, dict[str, Any]]]
- class imednet.integrations.enrichment.EnrichmentPipeline[source]¶
Bases:
objectPipeline for transforming and enriching study data.
Applies a set of rules defined in a
StudyConfigurationto data objects, including PHI masking, terminology mapping, and custom business logic.- __init__(config)[source]¶
Initialize the enrichment pipeline.
- Parameters:
config (StudyConfiguration) – The study configuration containing enrichment rules.
- process(data, *, mask_phi=True, _skip_default_phi=False, domain=None, form_key=None)[source]¶
Process the input data through the enrichment pipeline.
- Parameters:
data (Any) – The raw data to be enriched.
mask_phi (bool) – Whether default and configured PHI rules should be applied.
domain (str | None) – Optional SDTM domain scoping
MappingRuleresolution.form_key (str | None) – Optional EDC Form key scoping
MappingRuleresolution._skip_default_phi (bool) –
- Returns:
The enriched and transformed data.
- Return type:
Any
- imednet.integrations.enrichment.mask_custom_phi_recursive(value, phi_keys)¶
Recursively mask custom normalized study PHI keys prior to flattening.
- Parameters:
value (Any) –
phi_keys (set[str]) –
- Return type:
Any
- imednet.integrations.enrichment.resolve_enrichment_pipeline(study_key)[source]¶
Return an
EnrichmentPipelinefor study_key when committed rules exist.- Parameters:
study_key (str | None) –
- Return type:
EnrichmentPipeline | None
- imednet.integrations.enrichment.resolve_sink_enrichment_pipeline(study_key=None, *, config=None, records=None)[source]¶
Resolve an enrichment pipeline from
SinkConfig.extra,study_key, or Recordstudy_keyvalues.- Parameters:
study_key (str | None) –
config (Any | None) –
records (Any) –
- Return type:
Any | None
- imednet.integrations.enrichment.resolve_sink_phi_keys(study_key=None, *, config=None, records=None, phi_keys=None)[source]¶
Resolve normalized custom PHI Variable keys from
SinkConfig.extra, store, and Records.- Parameters:
study_key (str | None) –
config (Any | None) –
records (Any) –
phi_keys (Iterable[str] | None) –
- Return type:
set[str] | None
- imednet.integrations.enrichment.resolve_study_configuration(study_key)[source]¶
Resolve the latest committed
StudyConfigurationfor study_key via entry points.Fails closed by returning
Nonewhenever no store plugin is installed, the study has no committed configuration history, or decryption/storage errors occur so callers still enforce defaultglobal_sensitivity_registryPHI masking.- Parameters:
study_key (str | None) –
- Return type:
StudyConfiguration | None
imednet.integrations.export module¶
Export helpers built on top of RecordMapper.
- class imednet.integrations.export.TabularCSVSink[source]¶
Bases:
ExportSinkSink for exporting data to CSV format.
- __init__(path, config)[source]¶
Initialize the CSV sink.
- Parameters:
path (str | PathLike[str]) –
config (TabularSinkConfig) –
- bind_stream_metadata(metadata)¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- flush()[source]¶
Finalize staged incremental CSV updates and voided deletions atomically.
- Return type:
None
- reconcile_deleted(records, *, batch_id)[source]¶
Stage newly voided record IDs or SDTM keys for atomic CSV reconciliation on flush.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- class imednet.integrations.export.TabularDuckDBSink[source]¶
Bases:
ExportSinkStreaming sink for exporting DataFrame batches into a DuckDB table.
- __init__(db_path, table_name, config, *, contract_types=None, conn=None)[source]¶
Initialize the DuckDB sink.
- Parameters:
db_path (str | PathLike[str]) –
table_name (str) –
config (TabularSinkConfig) –
contract_types (Mapping[str, str | None] | None) –
conn (Any | None) –
- Return type:
None
- bind_stream_metadata(metadata)¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- flush()[source]¶
Replace target with empty snapshot on full zero-row export; keep intact on incremental.
- Return type:
None
- reconcile_deleted(records, *, batch_id)[source]¶
Delete newly voided rows from DuckDB when running idempotently.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- class imednet.integrations.export.TabularParquetSink[source]¶
Bases:
ExportSinkStreaming Parquet sink backed by
pyarrow.parquet.ParquetWriter.- __init__(path, config, *, contract_types=None)[source]¶
Initialize the Parquet sink.
- Parameters:
path (str | PathLike[str]) –
config (TabularSinkConfig) –
contract_types (Mapping[str, str | None] | None) –
- Return type:
None
- bind_stream_metadata(metadata)¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- close()[source]¶
Ensure underlying ParquetWriter is closed and any staging file is removed.
- Return type:
None
- flush()[source]¶
Flush and finalize Parquet footer or reconcile incremental deltas before checkpoint commit.
- Return type:
None
- reconcile_deleted(records, *, batch_id)[source]¶
Stage newly voided record IDs or SDTM keys for atomic Parquet reconciliation on flush.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- class imednet.integrations.export.TabularSQLSink[source]¶
Bases:
ExportSinkSink for exporting data to SQL databases.
- __init__(table, engine, config)[source]¶
Initialize the SQL sink.
- Parameters:
table (str) –
engine (Any) –
config (TabularSinkConfig) –
- bind_stream_metadata(metadata)¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- flush()[source]¶
Flush the sink, writing an empty SDTM schema snapshot on full zero-row export.
- Return type:
None
- reconcile_deleted(records, *, batch_id)[source]¶
Delete newly voided rows from the SQL table when running idempotently.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- class imednet.integrations.export.TabularSinkConfig[source]¶
Bases:
SinkConfigConfiguration for tabular sinks.
- study_key: str¶
Required.
- batch_size: int = 500¶
- max_retries: int = 3¶
- retry_backoff: float = 1.0¶
- idempotent: bool = True¶
- mask_phi: bool = True¶
- extra: dict[str, Any] = dict()¶
- quality_gate_enabled: bool = False¶
- min_schema_readiness_score: float = 100.0¶
- tracer: Any | None = ...¶
- modified_since: datetime | str | None = None¶
- record_filter: dict[str, Any] | str | None = None¶
- record_data_filter: str | None = None¶
- include_deleted: bool = False¶
- incremental: bool = False¶
- stream_name: str | None = None¶
- ledger_path: str | Path | None = None¶
- state_provider: Any | None = ...¶
- max_buffered_records: int | None = None¶
- as_sdtm: bool = None¶
- sdtm_domain: str | None = None¶
- standards_profile: str | Any | None = None¶
- min_standards_score: float | None = None¶
- naming_convention: str | None = None¶
- preserve_record_id: bool | None = None¶
- manifest_path: str | None = None¶
- use_labels_as_columns: bool = False¶
- sanitize: bool = False¶
- variable_whitelist: list[str] | None = None¶
- form_whitelist: list[int] | None = None¶
- pandas_kwargs: dict[str, Any] = dict()¶
- __init__(study_key, batch_size=500, max_retries=3, retry_backoff=1.0, idempotent=True, mask_phi=True, extra=dict(), quality_gate_enabled=False, min_schema_readiness_score=100.0, tracer=..., modified_since=None, record_filter=None, record_data_filter=None, include_deleted=False, incremental=False, stream_name=None, ledger_path=None, state_provider=..., max_buffered_records=None, as_sdtm=None, sdtm_domain=None, standards_profile=None, min_standards_score=None, naming_convention=None, preserve_record_id=None, manifest_path=None, use_labels_as_columns=False, sanitize=False, variable_whitelist=None, form_whitelist=None, pandas_kwargs=dict())¶
- Parameters:
study_key (str) –
batch_size (int) –
max_retries (int) –
retry_backoff (float) –
idempotent (bool) –
mask_phi (bool) –
extra (dict[str, Any]) –
quality_gate_enabled (bool) –
min_schema_readiness_score (float) –
tracer (Any | None) –
modified_since (datetime | str | None) –
record_filter (dict[str, Any] | str | None) –
record_data_filter (str | None) –
include_deleted (bool) –
incremental (bool) –
stream_name (str | None) –
ledger_path (str | Path | None) –
state_provider (Any | None) –
max_buffered_records (int | None) –
as_sdtm (bool) –
sdtm_domain (str | None) –
standards_profile (str | Any | None) –
min_standards_score (float | None) –
naming_convention (str | None) –
preserve_record_id (bool | None) –
manifest_path (str | None) –
use_labels_as_columns (bool) –
sanitize (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
pandas_kwargs (dict[str, Any]) –
- Return type:
None
- imednet.integrations.export.export_to_csv(sdk, study_key, path, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, manifest_path=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export Study Records to a CSV file.
All exports inherit StudyConfiguration rules by default.
Parameters¶
- use_labels_as_columns:
When
True, Variable labels are used for column names instead of Variable names.- quality_gate_enabled:
When
True, filters Study Records throughapply_quality_gate()before writing. Defaults toFalse.- mask_phi:
When
True(default), sensitive Subject PHI values are replaced with***MASKED***.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str]) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
manifest_path (str | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_dataset_json(*args, **kwargs)[source]¶
Export study clinical datasets to CDISC Dataset-JSON v1.1.
- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_duckdb(sdk, study_key, db_path, table_name, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export study records to a DuckDB table using native DataFrame registration.
All exports now inherit StudyConfiguration rules by default.
Parameters¶
- sdk:
Authenticated SDK instance used to fetch study records.
- study_key:
Study identifier to export.
- db_path:
Path to the target
.duckdbdatabase file.- table_name:
Name of the destination DuckDB table.
- use_labels_as_columns:
When
True, variable labels are used for DataFrame column names.- variable_whitelist:
Optional list of variable names to include.
- form_whitelist:
Optional list of form IDs to include.
- mask_phi:
When
True(default), sensitive PHI values are replaced with***MASKED***.
Raises:¶
- ImportError
If the optional
duckdbdependency is not installed.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
db_path (str | PathLike[str]) –
table_name (str) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_duckdb_by_form(sdk, study_key, db_path, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export Study Records to separate DuckDB tables for each Form.
Each Form is exported to a table named after
form.form_key.Parameters¶
- sdk:
Authenticated SDK instance used to fetch Study Records.
- study_key:
Study identifier to export.
- db_path:
Path to the target
.duckdbdatabase file.- use_labels_as_columns:
When
True, Variable labels are used for DataFrame column names.- variable_whitelist:
Optional list of Variable names to include.
- form_whitelist:
Optional list of Form IDs to include.
- quality_gate_enabled:
When
True, filters Study Records throughapply_quality_gate()before writing. Defaults toFalse.- mask_phi:
When
True(default), sensitive Subject PHI values are replaced with***MASKED***.
Raises:¶
- ImportError
If the optional
duckdbdependency is not installed.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
db_path (str | PathLike[str]) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_excel(sdk, study_key, path, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export study records to an Excel workbook.
All exports now inherit StudyConfiguration rules by default.
Parameters¶
- use_labels_as_columns:
When
True, variable labels are used for column names instead of variable names.- mask_phi:
When
True(default), sensitive PHI values are replaced with***MASKED***.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str]) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_hive_parquet(*args, **kwargs)[source]¶
Export study records to a Hive-partitioned Parquet directory layout.
- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_json(sdk, study_key, path, *, use_labels_as_columns=False, hierarchical=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export study records to a JSON file.
All exports now inherit StudyConfiguration rules by default.
Parameters¶
- use_labels_as_columns:
When
True, variable labels are used for column names instead of variable names.- hierarchical:
When
True, generates a nested tree (Subject > Visit > Form) suitable for Veeva Vault integrations instead of a flat tabular layout.- mask_phi:
When
True(default), sensitive PHI values are replaced with***MASKED***.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str]) –
use_labels_as_columns (bool) –
hierarchical (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_long_sql(sdk, study_key, table_name, conn_str, *, variable_whitelist=None, form_whitelist=None, chunk_size=1000, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export Study Records to a normalized long-format SQL table.
Parameters¶
- variable_whitelist:
Optional collection of Variable names (or formatted column names) to retain when unpacking record payloads.
- form_whitelist:
Optional collection of integer Form IDs to include in the export.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
table_name (str) –
conn_str (str) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
chunk_size (int) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_odm(*args, **kwargs)[source]¶
Export study snapshot to CDISC ODM 1.3.2 XML.
- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_parquet(sdk, study_key, path, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export study records to a Parquet file.
All exports now inherit StudyConfiguration rules by default.
Parameters¶
- use_labels_as_columns:
When
True, variable labels are used for column names instead of variable names.- mask_phi:
When
True(default), sensitive PHI values are replaced with***MASKED***.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
path (str | PathLike[str]) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_sql(sdk, study_key, table, conn_str, if_exists=None, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, manifest_path=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export Study Records to a SQL table.
All exports inherit StudyConfiguration rules by default.
Parameters¶
- use_labels_as_columns:
When
True, Variable labels are used for column names instead of Variable names.- manifest_path:
Optional path to a file where manifest entries should be logged. Defaults to
None.- quality_gate_enabled:
When
True, filters Study Records throughapply_quality_gate()before writing. Defaults toFalse.- mask_phi:
When
True(default), sensitive Subject PHI values are replaced with***MASKED***.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
table (str) –
conn_str (str) –
if_exists (Literal['fail', 'replace', 'append', 'delete_rows'] | None) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
manifest_path (str | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
- imednet.integrations.export.export_to_sql_by_form(sdk, study_key, conn_str, if_exists=None, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, quality_gate_enabled=False, mask_phi=True, **kwargs)[source]¶
Export Study Records to separate SQL tables for each Form.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
conn_str (str) –
if_exists (Literal['fail', 'replace', 'append', 'delete_rows'] | None) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
quality_gate_enabled (bool) –
mask_phi (bool) –
kwargs (Any) –
- Return type:
None
imednet.integrations.parquet module¶
Hive-partitioned Parquet integration helpers.
- imednet.integrations.parquet.export_to_hive_parquet(sdk, study_key, base_dir, *, use_labels_as_columns=False, variable_whitelist=None, form_whitelist=None, chunk_size=5000, quality_gate_enabled=False, mask_phi=True, max_buffered_records=None, **kwargs)[source]¶
Export Study Records to a Hive-partitioned Parquet directory layout.
- Parameters:
sdk (ImednetSDK) –
study_key (str) –
base_dir (str) –
use_labels_as_columns (bool) –
variable_whitelist (list[str] | None) –
form_whitelist (list[int] | None) –
chunk_size (int) –
quality_gate_enabled (bool) –
mask_phi (bool) –
max_buffered_records (int | None) –
kwargs (Any) –
- Return type:
None
imednet.integrations.parquet_engine module¶
Partitioned Parquet storage engines.
- class imednet.integrations.parquet_engine.PartitionedStorageEngine[source]¶
Bases:
ProtocolInterface for writing tables into a partitioned dataset.
- class imednet.integrations.parquet_engine.PyArrowDatasetPartitionedStorageEngine[source]¶
Bases:
PartitionedStorageEnginePartitioned storage engine powered by
pyarrow.dataset.write_dataset.- compression: str = 'snappy'¶
- use_dictionary: bool = True¶
- existing_data_behavior: str = 'overwrite_or_ignore'¶
- staging_dir_name: str = '.imednet_staging'¶
- __init__(compression='snappy', use_dictionary=True, existing_data_behavior='overwrite_or_ignore', staging_dir_name='.imednet_staging')¶
- Parameters:
compression (str) –
use_dictionary (bool) –
existing_data_behavior (str) –
staging_dir_name (str) –
- Return type:
None
- write_form_table(table, *, base_dir, study_key, form_key)[source]¶
Persist a form table into a partitioned dataset layout using PyArrow.
This implementation uses a staging directory and atomic renames to ensure that data is written consistently.
- Parameters:
table (Any) – The pyarrow table to write.
base_dir (str) – The base directory for the Hive dataset.
study_key (str) – The iMednet study key (used for partitioning).
form_key (str) – The iMednet form key (used for partitioning).
- Raises:
RuntimeError – If the write operation fails or produces unexpected output.
- Return type:
None
imednet.integrations.sink_base module¶
Shared base classes and helpers for all export sinks.
Architecture decision¶
The SDK provides three export paths:
- Tabular path (
RecordMapper+pandas.DataFrame) Flattens record data into a wide DataFrame and writes it to CSV, Excel, JSON, SQL, DuckDB, or Parquet. All functions in
imednet.integrations.exportfollow this path.- Structure-preserving path (
DataExtractionWorkflow+ typed records) Traverses the clinical data hierarchy Study → Subject → Visit → Record and materialises the relationships into a destination that can represent them natively — a property graph (Neo4j) or a nested document store (MongoDB).
- Warehouse path (staged Parquet + native bulk loader)
Writes one Parquet file per form to an intermediate staging area and then invokes the destination’s native bulk-loading command (e.g. Snowflake
COPY INTO).
All three paths share the contracts defined in this module: SinkConfig,
the ExportSink ABC, the import-guard helper _require_optional_dep(),
and the credential-redaction helper _redact_uri().
Optional dependency conventions¶
Each sink module calls
_require_optional_dep()at connection time (not at import time) so that importing the module never fails due to a missing optional library.Extras keys follow the pattern
imednet[<key>]:pip install 'imednet[neo4j]' pip install 'imednet[mongodb]' pip install 'imednet[snowflake]'
Public-API exposure rules¶
imednet.integrationsexports tabular helpers and shared sink contracts (SinkConfigandExportSink).Document, graph, and warehouse sinks (
MongoDbExportSink,Neo4jExportSink,SnowflakeExportSink) and their configuration classes andexport_to_*helpers live inimednet_sinks(imednet_sinks.document,imednet_sinks.graph,imednet_sinks.warehouse) and are exposed dynamically viasdk.sinks.Airflow helpers in
apache_airflow_providers_imednet.exportwrap only the tabular path, whileImednetExportOperatorresolvesmongodb,neo4j, andsnowflakedestinations dynamically viasdk.sinks.
- class imednet.integrations.sink_base.AsyncBoundedFormBufferRouter[source]¶
Bases:
objectAsynchronously buffer per-form records and flush on batch size or memory ceiling.
- __init__(form_keys, *, batch_size, max_buffered_records=None, on_flush_active, on_flush_voided=None)[source]¶
Initialize per-form async buffers and global ceiling tracking.
- Parameters:
form_keys (Sequence[str]) –
batch_size (int) –
max_buffered_records (int | None) –
on_flush_active (Callable[[str, list[Any], int], Awaitable[None]]) –
on_flush_voided (Callable[[str, list[Any], int], Awaitable[None]] | None) –
- Return type:
None
- async add_active(form_key, record)[source]¶
Append an active record to
form_keyand flush if thresholds are met.- Parameters:
form_key (str) –
record (Any) –
- Return type:
None
- class imednet.integrations.sink_base.AsyncExportSink[source]¶
Bases:
ABCAbstract base class for native asynchronous export sinks.
Subclasses must implement
write_batch(),flush(), andclose()as coroutines. The async context-manager protocol and automatic PHI redaction wrapper are provided by this class.- __init__(config)[source]¶
Initialize the asynchronous export sink with a configuration.
- Parameters:
config (SinkConfig) –
- Return type:
None
- bind_stream_metadata(metadata)[source]¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- abstract async close()[source]¶
Asynchronously release all resources held by this sink.
- Return type:
None
- abstract async flush()[source]¶
Asynchronously flush any internal buffers to the destination.
- Return type:
None
- async reconcile_deleted(records, *, batch_id)[source]¶
Asynchronously reconcile newly voided records in idempotent targets.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)[source]¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- class imednet.integrations.sink_base.BoundedFormBufferRouter[source]¶
Bases:
objectBuffer per-form records and flush on per-form batch size or global memory ceiling.
- __init__(form_keys, *, batch_size, max_buffered_records=None, on_flush_active, on_flush_voided=None)[source]¶
Initialize per-form buffers and global ceiling tracking.
- Parameters:
form_keys (Sequence[str]) –
batch_size (int) –
max_buffered_records (int | None) –
on_flush_active (Callable[[str, list[Any], int], None]) –
on_flush_voided (Callable[[str, list[Any], int], None] | None) –
- Return type:
None
- add_active(form_key, record)[source]¶
Append an active record to
form_keyand flush if thresholds are met.- Parameters:
form_key (str) –
record (Any) –
- Return type:
None
- class imednet.integrations.sink_base.ExportSink[source]¶
Bases:
ABCAbstract base class for all export sinks.
Subclasses must implement
write_batch(),flush(), andclose(). The context-manager protocol is provided by this class.Parameters¶
- config:
Shared sink configuration. Defaults to
SinkConfigwith all values at their defaults.
- __init__(config)[source]¶
Initialize the export sink with a configuration.
- Parameters:
config (SinkConfig) –
- Return type:
None
- bind_stream_metadata(metadata)[source]¶
Bind mutable checkpoint metadata for the active streaming run.
- Parameters:
metadata (dict[str, Any]) –
- Return type:
None
- abstract close()[source]¶
Release all resources held by this sink (connections, file handles).
Implementations must be idempotent — calling
close()on an already closed sink must not raise.- Return type:
None
- abstract flush()[source]¶
Flush any internal buffers to the destination.
Raises:¶
- ~imednet.errors.ExportError
On flush failure.
- Return type:
None
- reconcile_deleted(records, *, batch_id)[source]¶
Reconcile newly voided records in idempotent downstream targets.
Parameters¶
- records:
Sequence of newly voided (
deleted=True) records observed during an incremental or watermarked export.- batch_id:
Idempotency key for error reporting and telemetry.
Returns:¶
- int
Number of voided records reconciled in the destination.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- redact_batch(records, *, study_key=None, config=None, phi_keys=None)[source]¶
Redact sensitive clinical PHI across
recordswhenconfig.mask_phiis enabled.- Parameters:
records (Sequence[Any]) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- abstract write_batch(records, *, batch_id)[source]¶
Write one batch of records to the destination.
Parameters¶
- records:
Sequence of records to write. The concrete type depends on the export path:
Tabular path –
pandas.DataFramerows or plain dicts produced byRecordMapper.Structure-preserving path – typed
Recordinstances fromDataExtractionWorkflow.Warehouse path –
pyarrow.RecordBatchor dicts destined for a staged Parquet file.
- batch_id:
Caller-supplied idempotency key. Recommended format:
"<study_key>/<form_key>/<batch_number>".
Returns:¶
- int
Number of records successfully written.
Raises:¶
- ~imednet.errors.ExportBatchError
When the batch cannot be written after all retries.
- Parameters:
records (Sequence[Any]) –
batch_id (str) –
- Return type:
int
- class imednet.integrations.sink_base.SdtmLineageSession[source]¶
Bases:
objectStream-scoped in-memory cache of SDTM record lineage, watermarks, and sequence maps.
- study_key: str¶
Required.
- stream_name: str¶
Required.
- full_lineage: dict[str, dict[str, Any]] = dict()¶
- watermarks: dict[str, int] = dict()¶
- domain_seq_counters: dict[str, dict[str, int]] = dict()¶
- seq_overrides: dict[str, int] = _ScopedSeqOverrides()¶
- apply_updates(lineage_updates, watermark_updates=None)[source]¶
Incrementally merge lineage_updates in
O(len(lineage_updates)).- Parameters:
lineage_updates (Mapping[str, Any]) –
watermark_updates (Mapping[str, int] | None) –
- Return type:
tuple[dict[str, dict[str, Any]], dict[str, int]]
- classmethod from_payload(study_key, stream_name, *, lineage=None, watermarks=None)[source]¶
Construct a hydrated
SdtmLineageSessionfrom lineage and watermark mappings.- Parameters:
study_key (str) –
stream_name (str) –
lineage (Mapping[str, Any] | None) –
watermarks (Mapping[str, Any] | None) –
- Return type:
- class imednet.integrations.sink_base.SinkConfig[source]¶
Bases:
objectShared configuration for all export sinks.
Parameters¶
- study_key:
Mandatory study key for the export.
- batch_size:
Number of records per
ExportSink.write_batch()call.- max_retries:
Maximum number of retry attempts on transient errors.
- retry_backoff:
Base delay in seconds between retry attempts. The actual delay grows exponentially:
retry_backoff * 2 ** attempt.- idempotent:
When
True, sinks use upsert / replace semantics so that replaying a batch with the samebatch_idproduces no duplicate data.- mask_phi:
When
True(default), sensitive clinical PHI fields inrecord_dataare replaced with***MASKED***before writing to the destination.- modified_since:
Optional lower-bound modification timestamp watermark (
dateModified >= ...).- record_filter:
Optional record attribute filter dictionary or filter string.
- record_data_filter:
Optional clinical variable payload filter (
recordDataFilter).- include_deleted:
When
True, voided (deleted=True) records are included in exports.- incremental:
When
True, reads and commits checkpoints via a state ledger provider.- stream_name:
Optional stream identifier used in the checkpoint state ledger.
- ledger_path:
Optional file path for file-backed checkpoint state providers.
- state_provider:
Optional pre-configured checkpoint state provider instance.
- max_buffered_records:
Optional global upper bound on records buffered across per-form streams.
- as_sdtm:
When
True, transforms exported records into CDISC SDTM domain rows.- sdtm_domain:
Optional target 2-character CDISC SDTM domain code (e.g.
"AE","VS").- standards_profile:
Optional standards validation profile name (e.g.
"drug","device", or"general") orStandardsProfile.- min_standards_score:
Optional minimum CDISC standards readiness score
[0.0, 100.0]required for exports to proceed.- naming_convention:
Optional raw variable/metadata naming convention (
"snake_case","camelCase", or"sdtm").
- study_key: str¶
Required.
- batch_size: int = 500¶
- max_retries: int = 3¶
- retry_backoff: float = 1.0¶
- idempotent: bool = True¶
- mask_phi: bool = True¶
- extra: dict[str, Any] = dict()¶
- quality_gate_enabled: bool = False¶
- min_schema_readiness_score: float = 100.0¶
- tracer: Any | None = ...¶
- modified_since: datetime | str | None = None¶
- record_filter: dict[str, Any] | str | None = None¶
- record_data_filter: str | None = None¶
- include_deleted: bool = False¶
- incremental: bool = False¶
- stream_name: str | None = None¶
- ledger_path: str | Path | None = None¶
- state_provider: Any | None = ...¶
- max_buffered_records: int | None = None¶
- as_sdtm: bool = None¶
- sdtm_domain: str | None = None¶
- standards_profile: str | Any | None = None¶
- min_standards_score: float | None = None¶
- naming_convention: str | None = None¶
- preserve_record_id: bool | None = None¶
- class imednet.integrations.sink_base.StateProviderProtocol[source]¶
Bases:
ProtocolRuntime-discoverable protocol for incremental export checkpoint ledgers.
- batch_transaction(study_key, stream_names, fallback_timestamp=None)[source]¶
Execute a batched checkpoint transaction across multiple streams in one study.
- Parameters:
study_key (str) –
stream_names (Sequence[str]) –
fallback_timestamp (datetime | None) –
- Return type:
AbstractContextManager[dict[str, dict[str, Any]]]
- delete_entry(study_key, stream_name=None)[source]¶
Delete ledger state entry.
- Parameters:
study_key (str) –
stream_name (str | None) –
- Return type:
bool
- get_last_timestamp(study_key, stream_name)[source]¶
Retrieve high-water mark timestamp for a study stream.
- Parameters:
study_key (str) –
stream_name (str) –
- Return type:
datetime | None
- get_sdtm_lineage(study_key, stream_name)[source]¶
Retrieve persisted SDTM sidecar lineage and monotonic sequence watermarks.
- Parameters:
study_key (str) –
stream_name (str) –
- Return type:
dict[str, Any]
- record_sdtm_lineage(study_key, stream_name, lineage_updates=None, seq_watermarks=None)[source]¶
Persist SDTM sidecar lineage and monotonic sequence watermarks.
- Parameters:
study_key (str) –
stream_name (str) –
lineage_updates (Mapping[str, dict[str, Any] | None] | None) –
seq_watermarks (Mapping[str, int] | None) –
- Return type:
None
- set_last_timestamp(study_key, stream_name, timestamp, records_processed=0, metadata=None, status='success', error_message=None)[source]¶
Persist high-water mark timestamp and execution metadata.
- Parameters:
study_key (str) –
stream_name (str) –
timestamp (datetime | None) –
records_processed (int) –
metadata (dict[str, Any] | None) –
status (Any) –
error_message (str | None) –
- Return type:
None
- class imednet.integrations.sink_base.TabularBatchStamp[source]¶
Bases:
objectImmutable preparation stamp bound to a prepared pandas DataFrame batch.
- mask_phi: bool¶
Required.
- registry_snapshot: tuple[frozenset[str], frozenset[str]]¶
Required.
- phi_keys: frozenset[str]¶
Required.
- columns: tuple[Any, ...]¶
Required.
- sanitized: bool = False¶
- imednet.integrations.sink_base.apply_quality_gate(sdk, study_key, records, config, *, variables=None, forms=None)[source]¶
Filter records based on schema readiness and optional CDASH naming checks.
- Parameters:
sdk (Any) –
study_key (str) –
records (Iterable[Any]) –
config (SinkConfig) –
variables (Iterable[Any] | None) –
forms (Iterable[Any] | None) –
- Return type:
Iterator[Any]
- async imednet.integrations.sink_base.async_apply_quality_gate(sdk, study_key, records, config, *, variables=None, forms=None)[source]¶
Asynchronously filter records based on schema readiness and optional CDASH checks.
- Parameters:
sdk (AsyncImednetFacade) –
study_key (str) –
records (AsyncIterable[Any] | Iterable[Any]) –
config (SinkConfig) –
variables (Iterable[Any] | None) –
forms (Iterable[Any] | None) –
- Return type:
AsyncIterator[Any]
- imednet.integrations.sink_base.async_iter_batches(records, batch_size)[source]¶
Asynchronously yield
recordslazily in fixed-size batches ofbatch_size.- Parameters:
records (AsyncIterable[Any] | Iterable[Any]) –
batch_size (int) –
- Return type:
AsyncIterator[list[Any]]
- async imednet.integrations.sink_base.async_iter_filtered_sdk_records(sdk, study_key, *, watermark=None, record_filter=None, record_data_filter=None, exclude_deleted_upstream=True, sort=None)[source]¶
Asynchronously yield records from
sdk.records.listorsdk.get_records.- Parameters:
sdk (Any) –
study_key (str) –
watermark (datetime | str | None) –
record_filter (dict[str, Any] | str | Sequence[str] | None) –
record_data_filter (str | None) –
exclude_deleted_upstream (bool) –
sort (str | None) –
- Return type:
AsyncIterator[Any]
- async imednet.integrations.sink_base.async_run_streaming_export(sdk, study_key, sink, config, *, stream_name=None, batch_id_prefix=None, default_provider_name=None, records_source=None, quality_gate_fn=None, iter_batches_fn=None, _caller_sdk=None)[source]¶
Asynchronously stream paginated records into
sinkwith checkpointing and audit gates.Commits ledger checkpoints strictly after all batches and
await sink.flush()succeed.- Parameters:
sdk (AsyncImednetFacade) –
study_key (str) –
sink (AsyncExportSink | Callable[[], AsyncExportSink]) –
config (SinkConfig) –
stream_name (str | None) –
batch_id_prefix (str | None) –
default_provider_name (str | None) –
records_source (Callable[[datetime | None, bool], AsyncIterable[Any] | Iterable[Any] | Awaitable[Iterable[Any]]] | None) –
quality_gate_fn (Callable[..., Any] | None) –
iter_batches_fn (Callable[..., Any] | None) –
_caller_sdk (Any) –
- Return type:
int
- imednet.integrations.sink_base.bind_sdtm_stream_metadata(metadata, seq_counters, record_seqs=None)[source]¶
Hydrate and bind mutable SDTM sequence counters into
StreamState.metadata.- Parameters:
metadata (dict[str, Any]) –
seq_counters (dict[str, int]) –
record_seqs (dict[str, int] | None) –
- Return type:
None
- imednet.integrations.sink_base.build_record_query_branches(*, record_filter=None, watermark=None, exclude_deleted_upstream=True)[source]¶
Build AND-only filter dictionaries for
sdk.records.list.Ensures OR filter clauses (comma-separated strings or scalar lists) are split into separate query branches so
;(AND) and,(OR) connectors are never mixed in a single upstreamfilterparameter, and mergeswatermarkintodateModifiedwithout emitting duplicatedateModifiedattributes in one request.- Parameters:
record_filter (dict[str, Any] | str | Sequence[str] | None) –
watermark (datetime | str | None) –
exclude_deleted_upstream (bool) –
- Return type:
list[dict[str, Any]]
- imednet.integrations.sink_base.commit_sdtm_lineage(sink_or_config, lineage_updates, *, study_key=None, stream_name=None)[source]¶
Record new/updated SDTM lineage entries and monotonic sequence watermarks.
- Parameters:
sink_or_config (Any) –
lineage_updates (Mapping[str, dict[str, Any]]) –
study_key (str | None) –
stream_name (str | None) –
- Return type:
None
- imednet.integrations.sink_base.evaluate_standards_readiness(records, *, study_key, config=None, standards_profile=None, sdtm_domain=None, terminology_lookups=None, form_domain_map=None)[source]¶
Validate and score records against CDASH naming rules and a StandardsProfile.
- Parameters:
records (Iterable[Any]) –
study_key (str) –
config (SinkConfig | None) –
standards_profile (str | StandardsProfile | None) –
sdtm_domain (str | None) –
terminology_lookups (dict[str, dict[str, str]] | None) –
form_domain_map (Mapping[Any, str] | None) –
- Return type:
- imednet.integrations.sink_base.extract_record_id(record)[source]¶
Extract
record_id/recordIdfrom a record object or mapping.- Parameters:
record (Any) –
- Return type:
Any | None
- imednet.integrations.sink_base.extract_record_timestamp(record)[source]¶
Extract a normalized UTC modification timestamp from a record.
- Parameters:
record (Any) –
- Return type:
datetime | None
- imednet.integrations.sink_base.get_state_provider(ledger_path=None, *, provider_name=None)[source]¶
Discover and instantiate a pluggable checkpoint state provider at runtime.
- Parameters:
ledger_path (str | Path | None) –
provider_name (str | None) –
- Return type:
- imednet.integrations.sink_base.get_tabular_batch_stamp(df)[source]¶
Return
df’sTabularBatchStampwhen present and matchingdf.columns.- Parameters:
df (Any) –
- Return type:
TabularBatchStamp | None
- imednet.integrations.sink_base.has_valid_tabular_batch_stamp(df, *, mask_phi=True, phi_keys=None, require_sanitized=False, registry=None)[source]¶
Verify whether
dfcarries a valid preparation stamp for the requested requirements.- Parameters:
df (Any) –
mask_phi (bool) –
phi_keys (Iterable[str] | None) –
require_sanitized (bool) –
registry (SensitivityRegistry | None) –
- Return type:
bool
- imednet.integrations.sink_base.is_incremental_sink_config(config)[source]¶
Return True when
configactivates incremental, watermark, or stateful sync.- Parameters:
config (Any) –
- Return type:
bool
- imednet.integrations.sink_base.is_record_deleted(record)[source]¶
Return True strictly when a record carries an explicit
deleted=Trueflag.- Parameters:
record (Any) –
- Return type:
bool
- imednet.integrations.sink_base.iter_batches(records, batch_size)[source]¶
Yield
recordslazily in fixed-size batches ofbatch_size.- Parameters:
records (Iterable[Any]) –
batch_size (int) –
- Return type:
Iterator[list[Any]]
- imednet.integrations.sink_base.iter_filtered_sdk_records(sdk, study_key, *, watermark=None, record_filter=None, record_data_filter=None, exclude_deleted_upstream=True, sort=None)[source]¶
Lazily yield records from
sdk.records.listacross one or more AND-safe branches.- Parameters:
sdk (Any) –
study_key (str) –
watermark (datetime | str | None) –
record_filter (dict[str, Any] | str | Sequence[str] | None) –
record_data_filter (str | None) –
exclude_deleted_upstream (bool) –
sort (str | None) –
- Return type:
Iterator[Any]
- imednet.integrations.sink_base.normalize_phi_keys_snapshot(phi_keys, *, registry=None)[source]¶
Normalize custom StudyConfiguration PHI keys into a canonical collapsed frozenset.
- Parameters:
phi_keys (Iterable[str] | None) –
registry (SensitivityRegistry | None) –
- Return type:
frozenset[str]
- imednet.integrations.sink_base.normalize_sink_value(value, *, by_alias=False)[source]¶
Dump Pydantic models,
Enumvalues, and tuples into plain containers.Leaves scalar
Decimal,datetime, anddateinstances intact so each destination sink can encode them without lossy float conversion.- Parameters:
value (Any) –
by_alias (bool) –
- Return type:
Any
- imednet.integrations.sink_base.normalize_watermark_datetime(value)[source]¶
Normalize a datetime or ISO-8601 date/timestamp string into UTC.
- Parameters:
value (datetime | str | None) –
- Return type:
datetime | None
- imednet.integrations.sink_base.redact_batch_records(records, *, mask_phi=True, as_sdtm=False, study_key=None, config=None, phi_keys=None)[source]¶
Apply Study-scoped SensitivityRegistry PHI redaction across a batch of records or DataFrame.
- Parameters:
records (Any) –
mask_phi (bool) –
as_sdtm (bool) –
study_key (str | None) –
config (SinkConfig | None) –
phi_keys (Collection[str] | None) –
- Return type:
Any
- imednet.integrations.sink_base.rehydrate_sdtm_lineage(sink_or_config, *, study_key=None, stream_name=None)[source]¶
Rehydrate
(domain_seq_counters, seq_overrides, full_lineage)from session or ledger.- Parameters:
sink_or_config (Any) –
study_key (str | None) –
stream_name (str | None) –
- Return type:
tuple[dict[str, dict[str, int]], dict[str, int], dict[str, dict[str, Any]]]
- imednet.integrations.sink_base.resolve_effective_as_sdtm(config, *, as_sdtm=None, sdtm_domain=None)[source]¶
Resolve effective
as_sdtmmode while honoring explicitas_sdtm=False.- Parameters:
config (Any) –
as_sdtm (bool | None) –
sdtm_domain (str | None) –
- Return type:
bool
- imednet.integrations.sink_base.resolve_max_buffered_records(batch_size, max_buffered_records)[source]¶
Resolve the effective global buffered-record ceiling across per-form buffers.
- Parameters:
batch_size (int) –
max_buffered_records (int | None) –
- Return type:
int
- imednet.integrations.sink_base.resolve_voided_sdtm_keys(records, sink_or_config, *, study_key=None, stream_name=None, sdtm_domain=None, form_domain_map=None)[source]¶
Resolve voided records to composite SDTM keys
(study_id, domain, usubjid, seq_col, seq_val).- Parameters:
records (Sequence[Any]) –
sink_or_config (Any) –
study_key (str | None) –
stream_name (str | None) –
sdtm_domain (str | None) –
form_domain_map (Mapping[Any, str] | None) –
- Return type:
list[dict[str, Any]]
- imednet.integrations.sink_base.run_streaming_export(sdk, study_key, sink, config, *, stream_name=None, batch_id_prefix=None, default_provider_name=None, records_source=None, quality_gate_fn=None, iter_batches_fn=None)[source]¶
Stream paginated records into
sinkin fixed-size batches with checkpointing.Commits ledger checkpoints only after all batches and
sink.flush()succeed.- Parameters:
sdk (ImednetFacade) –
study_key (str) –
sink (ExportSink | Callable[[], ExportSink]) –
config (SinkConfig) –
stream_name (str | None) –
batch_id_prefix (str | None) –
default_provider_name (str | None) –
records_source (Callable[[datetime | None, bool], Iterable[Any]] | None) –
quality_gate_fn (Callable[[Any, str, Iterable[Any], SinkConfig], Iterable[Any]] | None) –
iter_batches_fn (Callable[[Iterable[Any], int], Iterable[Sequence[Any]]] | None) –
- Return type:
int
- imednet.integrations.sink_base.should_preserve_sdtm_record_id(config, preserve_record_id=None)[source]¶
Return True when SDTM sink projections should retain
RECORD_IDfor lineage/upserts.- Parameters:
config (Any) –
preserve_record_id (bool | None) –
- Return type:
bool
- imednet.integrations.sink_base.stamp_tabular_batch(df, *, mask_phi, phi_keys=None, sanitized=False, registry=None)[source]¶
Attach a
TabularBatchStamptodfbinding active PHI and header state.- Parameters:
df (Any) –
mask_phi (bool) –
phi_keys (Iterable[str] | None) –
sanitized (bool) –
registry (SensitivityRegistry | None) –
- Return type:
Any