Record Mapping Process¶
RecordMapper (registered under the
record_mapper entry point on sdk.workflows.record_mapper) turns raw
Record payloads into a pandas.DataFrame. It loads Variable metadata
from the Data Dictionary, builds a dynamic model, parses the Records, and
assembles the final table.
Explicit normalization¶
General RecordMapper exports retain source field strings and analytical types.
Use CategoricalNormalizer(date_fields={"assessmentDate"}, date_order="MDY")
for an explicit normalization step. Only the named date fields are converted;
ambiguous slash dates require MDY or DMY, and invalid/partial/unknown dates remain
unchanged. Timezone offsets and string fractional precision are retained.
Pass a study-approved vocabulary to CategoricalNormalizer(cdisc_ct=...) to
opt into case-insensitive term matching. The normalizer snapshots the vocabulary
and rejects ambiguous case collisions. Explicit terminology lookups take
precedence, including in readiness scoring. Out-of-set values are preserved and
reported without echoing their contents in new terminology diagnostics.
NORMALIZATION_TERMINOLOGY is a project reporting vocabulary, not a dated
CDISC Controlled Terminology release. The compatibility name
CDISC_CONTROLLED_TERMINOLOGY refers to that same project vocabulary. Neither
is enabled by default. Callers own the selected terminology version and its
extensibility policy; full versioned conformance remains tracked in issue #1592.
Existing USUBJID values are preserved. An explicit study_key argument may
fill an existing empty USUBJID placeholder from study/subject keys, preserving
case. This convenience does not allocate a globally unique subject identity;
use the study’s identity mapping for pooled data and repeat participants.
MappingRule/StudyConfiguration strictCdash (also local strict or
strictMode) and IMEDNET_STRICT_CDASH enable a local naming/prefix
heuristic. SDK IMEDNET_STRICT_MODE retains its separate response-drift
meaning. The heuristic accepts reporting aliases and does not certify membership
in any official CDASH/SDTM version.
Evidence and limits: CDISC CDASHIG v2.1 permits partial-date collection; CDISC SDTM v1.7 defines USUBJID across studies; CDISC terminology publications are versioned and some codelists are extensible. Source references:
https://www.cdisc.org/standards/foundational/cdashig-v2-1https://www.cdisc.org/standards/foundational/sdtm/sdtm-v1-7/htmlhttps://www.cdisc.org/kb/articles/controlled-terminology-faqs
Sandboxed MappingRule.business_logic expressions¶
When enriching Study, Subject, Site, Form, Record, Visit,
Interval, Variable, Query, Data Dictionary, or Job outputs via
StudyConfiguration, each
MappingRule can supply an optional
business_logic expression. Rather than invoking Python eval, expressions are
parsed with parse_expression() and executed inside
RestrictedAstEvaluator (via
evaluate_expression()):
Safe function and method allowlists: Calls are restricted to
DEFAULT_SAFE_FUNCTIONS(float,int,str,bool,len) andDEFAULT_SAFE_METHODS(pure inspection methods onstr,dict,list/tuple, andset).Blocked escape and mutation vectors: Disallowed syntax and calls raise
RestrictedEvaluationError(while runtime arithmetic or type failures raiseEvaluationError). In particular,.format,.format_map, and f-strings (JoinedStr/FormattedValue) are blocked so format-string attribute traversal (such as"{0.__class__}".format(value)) cannot inspect internal Python objects, private_attributes are rejected, and mutating container methods (such asclear,pop,update, andappend) are excluded.Authoring-time validation via ``parse_expression`` and ``validate_ast``:
MappingRuledeserializesbusiness_logicas a plainstr | Nonewithout compiling ASTs at model load time. Callparse_expression()(orvalidate_ast()on a parsedast.AST) when authoring or reviewing rules to catch syntax or sandbox violations early.Raw-value fallback in enrichment and SDTM pipelines:
EnrichmentPipelinebinds{"value": value}when evaluatingMappingRule.business_logic; ifRestrictedEvaluationErrororEvaluationErroroccurs, it logs a warning and preserves the originalVariablevalue. Becausetransform_records_to_sdtm_rows()appliesEnrichmentPipelineprior to CDISC SDTM domain projection, blocked or failing expressions likewise retain the rawRecordVariablevalue instead of aborting the batch.Scoped
(domain, source_form_key, source_variable_name)resolution and collision skips:EnrichmentPipelineindexes eachMappingRuleby(domain, source_form_key, source_variable_name). Passdomainandform_keytoprocess()(or includeDOMAIN/domainandformKey/form_keykeys on a Record dictionary) when a Study defines multiple Forms. Ifdomainandform_keyare omitted and more than oneMappingRuleshares the samesource_variable_name(orsnake_casealias), unscoped lookup returnsNoneand skips conflicting rules rather than applying the wrong Form’s transformation.Scoped
fallback_valuedefaults: Missing,None, or whitespace-only Variable values receiveMappingRule.fallback_valuedefaults whenprocessruns with matchingdomain/form_keycontext (populating nestedrecordData/record_datadictionaries when enriching full Record envelopes). Unscopedprocesscalls skipfallback_valuerules that declare asource_form_keyor collide across multiple rules.domain.variableterminology lookup precedence: When mapping coded values throughStudyConfiguration.terminology_lookups,EnrichmentPipelinechecks domain-qualifieddomain.variablekeys first (for example,"AE.aeSeverity"whendomain="AE"), then the exactVariablekey ("aeSeverity"), and finally its normalizedsnake_casekey ("ae_severity").
from imednet.errors import EvaluationError, RestrictedEvaluationError
from imednet.integrations.enrichment import EnrichmentPipeline
from imednet.models.sdtm import transform_records_to_sdtm_rows
from imednet.models.study_config import MappingRule, StudyConfiguration
from imednet.utils import (
RestrictedAstEvaluator,
evaluate_expression,
parse_expression,
)
from imednet.utils.evaluator import (
DEFAULT_SAFE_FUNCTIONS,
DEFAULT_SAFE_METHODS,
validate_ast,
)
assert set(DEFAULT_SAFE_FUNCTIONS) == {"float", "int", "str", "bool", "len"}
assert {"strip", "upper", "lower", "get"}.issubset(DEFAULT_SAFE_METHODS)
assert {"format", "format_map", "clear", "update"}.isdisjoint(DEFAULT_SAFE_METHODS)
# Pre-check candidate AST syntax before saving StudyConfiguration rules
compiled_rule = parse_expression("value.strip().upper()")
validate_ast(compiled_rule)
rule_evaluator = RestrictedAstEvaluator("value.strip().upper()")
assert rule_evaluator.evaluate({"value": " mild "}) == "MILD"
fstring_rejected = False
try:
parse_expression("f'{value}'")
except RestrictedEvaluationError:
fstring_rejected = True
assert fstring_rejected
for unsafe_expr in ("'{0.__class__}'.format(value)", "'{}'.format_map({'a': 1})"):
rejected = False
try:
evaluate_expression(unsafe_expr, {"value": "Headache"}, raise_on_error=True)
except RestrictedEvaluationError:
rejected = True
assert rejected
coercion_failed = False
try:
evaluate_expression("int(value)", {"value": "not-an-int"}, raise_on_error=True)
except EvaluationError:
coercion_failed = True
assert coercion_failed
mapping_cfg = StudyConfiguration(
study_key="STUDY",
terminology_lookups={
"AE.aeSeverity": {"2": " moderate "},
"aeSeverity": {"2": " grade 2 "},
"ae_outcome": {"1": "RECOVERED/RESOLVED"},
},
mappings=[
MappingRule(
domain="AE",
target_field="aeSeverity",
source_form_key="F_AE",
source_variable_name="aeSeverity",
business_logic="value.strip().upper()",
),
MappingRule(
domain="CM",
target_field="cmSeverity",
source_form_key="F_CM",
source_variable_name="aeSeverity",
business_logic="value.strip().lower()",
),
MappingRule(
domain="AE",
target_field="aeTerm",
source_form_key="F_AE",
source_variable_name="aeTerm",
business_logic="'{0.__class__}'.format(value)",
),
MappingRule(
domain="AE",
target_field="aeOutcome",
source_form_key="F_AE",
source_variable_name="aeOutcome",
fallback_value="UNKNOWN",
),
],
)
enrichment = EnrichmentPipeline(mapping_cfg)
# Unscoped call skips colliding multi-Form 'aeSeverity' rules and Form-scoped 'fallback_value'
unscoped_payload = enrichment.process(
{"aeSeverity": " moderate ", "aeTerm": "Headache"},
mask_phi=False,
)
assert unscoped_payload["aeSeverity"] == " moderate "
assert "aeOutcome" not in unscoped_payload
# Scoped call resolves (AE, F_AE, *), applies AE.aeSeverity terminology + snake_case lookup, and fills fallback_value
enriched_payload = enrichment.process(
{"aeSeverity": "2", "aeTerm": "Headache", "aeOutcome": ""},
mask_phi=False,
domain="AE",
form_key="F_AE",
)
assert enriched_payload["aeSeverity"] == "MODERATE"
# Blocked .format() expression falls back to the raw Variable value
assert enriched_payload["aeTerm"] == "Headache"
assert enriched_payload["aeOutcome"] == "UNKNOWN"
mapped_outcome = enrichment.process(
{"aeSeverity": "2", "aeTerm": "Headache", "aeOutcome": "1"},
mask_phi=False,
domain="AE",
form_key="F_AE",
)
assert mapped_outcome["aeOutcome"] == "RECOVERED/RESOLVED"
sdtm_rows = transform_records_to_sdtm_rows(
[
{
"subjectKey": "SUBJ-001",
"recordId": 101,
"formKey": "F_AE",
"record_data": {"aeSeverity": "2", "aeTerm": "Headache"},
}
],
"AE",
"STUDY",
mask_phi=False,
pipeline=enrichment,
)
assert sdtm_rows[0]["AESEV"] == "MODERATE"
assert sdtm_rows[0]["AETERM"] == "Headache"
Default PHI Masking & SensitivityRegistry¶
Export mappers, SDTM transformers, and ExportSink implementations enforce
mask_phi=True by default via SensitivityRegistry
and mask_clinical_phi(). Key matching normalizes
camelCase, PascalCase, hyphenated, and upper/lower snake_case Variable names
before comparison, replacing matching non-null values with ***MASKED***.
14 Default Sensitive PHI Keys (redacted to
***MASKED***across case and delimiter variants):patient_name,patname,patient_initials,dob,date_of_birth,ssn,phone,email,address,birth_date,brthdtc,brthdat,brthyr, andsubjinit.6 Exempt Structural Keys (preserved so
Study,Subject, andRecordjoins, partitions, and graph edges remain intact even if passed in custom key lists):subject_key,study_key,record_id,usubjid,subjid, andstudyid.Study-Specific PHI Extensions: Additional
Study-levelVariablekeys declared inStudyConfiguration(phiFields=[...])(and governed viaConfigVersionStore; see Governance — Trust, Traceability & Audit Trail) are merged into the activeSensitivityRegistryautomatically.SDTM ``BRTHDTC`` Year Redaction: During CDISC SDTM transformation with
mask_phi=True,BRTHDTCvalues are redacted to 4-digit ISO 8601 birth years (YYYY) — orNonewhen no 4-digit year can be parsed — rather than***MASKED***literal text so downstream SDTMDMdate typing remains valid without exposing full birth dates.
CDISC SDTM Domain Transformations¶
Use transform_records_to_sdtm_rows() (or
transform_records_to_sdtm()) to project clinical
Record payloads into standardized CDISC SDTM domain rows across all 9
domains defined in SDTM_DOMAIN_SPECS:
Domain |
Label |
Core Standardized Variables & Notes |
|---|---|---|
|
Adverse Events |
|
|
Protocol Deviations |
|
|
Device Deficiencies |
|
|
Concomitant Medications |
|
|
Demographics |
|
|
Vital Signs |
|
|
Laboratory Test Results |
|
|
Exposure |
|
|
Medical History |
|
Standards Readiness Validation & SinkConfig Controls¶
Before writing to downstream analytical or regulatory destinations
(Export Destinations), StandardsReadinessValidator
and evaluate_standards_readiness() evaluate
required SDTM identifiers, ISO 8601 --DTC date formatting, and controlled
terminology conformance across "general", "drug", and "device"
StandardsProfile presets.
All export sinks share five SinkConfig controls
for SDTM projection, readiness gating, and field naming:
as_sdtm— transform exportedRecorditems into CDISC SDTM domain rows viatransform_records_to_sdtm_rows()(automatically enabled whensdtm_domainis set).sdtm_domain— target 2-character SDTM domain code ("AE","DV","DD","CM","DM","VS","LB","EX", or"MH").standards_profile—"general","drug","device", or a customStandardsProfileevaluated before sink writes.min_standards_score— minimum readiness score (0.0–100.0) enforced viaevaluate_standards_readiness()(raisingStandardsValidationErrorwhenreport.score < min_standards_score).naming_convention— rawVariableand metadata key naming convention ("snake_case","camelCase", or"sdtm") applied across tabular, document, graph, and warehouse mappers.
from imednet.models.records import Record
from imednet.models.standards import StandardsReadinessValidator
from imednet.spi.models import transform_records_to_sdtm_rows
from imednet.spi.sink_base import SinkConfig, evaluate_standards_readiness
from imednet.utils.security import mask_clinical_phi
raw_payload = {
"subject_key": "SUB-101",
"patient_name": "Jane Doe",
"brthdtc": "1985-07-19",
}
masked_payload = mask_clinical_phi(raw_payload)
assert masked_payload["subject_key"] == "SUB-101"
assert masked_payload["patient_name"] == "***MASKED***"
dm_record = Record.model_validate(
{
"studyKey": "STUDY",
"recordId": 1001,
"subjectKey": "SUB-101",
"siteName": "SITE-01",
"formKey": "DM",
"deleted": False,
"recordData": {
"birthDate": "1985-07-19",
"sex": "F",
"age": 41,
"race": "WHITE",
"ethnicity": "NOT HISPANIC OR LATINO",
"ARM": "Treatment A",
"COUNTRY": "USA",
"patient_initials": "JD",
},
}
)
dm_rows = transform_records_to_sdtm_rows([dm_record], domain="DM", study_key="STUDY")
assert len(dm_rows) == 1
assert dm_rows[0]["USUBJID"] == "SUB-101"
assert dm_rows[0]["BRTHDTC"] == "1985"
assert dm_rows[0]["patient_initials"] == "***MASKED***"
assert "DMSEQ" not in dm_rows[0]
validator = StandardsReadinessValidator("drug")
sex_lookup = {"sex": {"F": "F"}}
report = validator.score_records(
records_by_domain={
"DM": [{"subjectKey": dm_record.subject_key, **dm_record.record_data}]
},
terminology_lookups=sex_lookup,
)
assert report.score == 100.0 and report.is_ready
sink_cfg = SinkConfig(
study_key="STUDY",
as_sdtm=True,
sdtm_domain="DM",
standards_profile="drug",
min_standards_score=95.0,
naming_convention="sdtm",
)
gate_report = evaluate_standards_readiness(
[dm_record],
study_key="STUDY",
config=sink_cfg,
terminology_lookups=sex_lookup,
)
assert gate_report.score == 100.0 and gate_report.is_ready