Lab unit harmonization

From XuShuwenn/RedAct · View interactive version

Lab unit harmonization is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Harmonize clinical lab data from multiple sources with different units, handling scientific notation and decimal format issues.

How to use this skill

Skill file

Clinical Lab Unit Harmonization

When to Use

Task-Specific Protocol

Input Files

Before coding, inspect both files beyond the header. Read enough of ckd_lab_data.csv to see actual numeric encodings/issues, and read ckd_feature_descriptions.csv completely enough to cover every feature you will claim to harmonize. If any read is truncated, returns only headers, or errors, continue with smaller reads, targeted searches, chunked inspection, or column extraction until you confirm the relevant columns, feature presence, documented units, and ranges. Read representative rows from across the lab file for each feature you may convert. Do not invent dataset-wide conversion rules, unit mappings, or physiological ranges from partial reference information.

Truncation is a blocker for rule-setting. If any dataset preview or reference read shows only headers, partial rows, or truncated feature descriptions, keep reading by offsets/chunks/targeted extraction until you have enough coverage to support every feature-level rule you will implement. Do not make dataset-wide harmonization or conversion decisions from partial previews.

For large files, do not try to read the entire CSV at once just to satisfy inspection. Capture the full schema first, then inspect representative chunks/slices and targeted columns for candidate harmonized features until you have direct evidence for the rules you implement.

Inspection pattern to keep using: read the feature-description reference first, then inspect the lab CSV schema/column list and representative raw rows before writing conversion code. Use those raw rows to explicitly note decimal commas, scientific notation, whitespace, empty-like tokens, and mixed formatting that the parser must normalize.

Path discipline:

Writable-path precheck: Before creating any script, output, or helper file, list the exact absolute paths you intend to write and confirm each one is inside an explicitly allowed directory from the current task/runtime. If a sample output path in this skill conflicts with the environment, ignore the sample and use the task-authorized path.

Data Quality Issues

  1. Missing values → preserve rows by default; only remove patient rows if the current task explicitly requires or authorizes removal after parsing/normalization, and verify the row-count change against that requirement
  2. Scientific notation → convert 1.23e2 to 123.00
  3. Decimal commas → 12,34 → 12.34
  4. Mixed units → convert alternative units to standard (e.g., µmol/L → mg/dL)

Harmonization Steps

  1. Inspect the full schema, complete feature descriptions, and representative raw values before defining cleaning or conversion rules; if any metadata or data view is truncated, keep reading/searching until coverage is complete for every feature you will harmonize

1a. Do not write the harmonization script, assert dataset-wide rules, or state that scientific notation, decimal commas, mixed units, or specific conversion needs are present until you have direct evidence from representative raw data and metadata for the affected feature(s); headers, row counts, or generic expectations are not evidence.

1b. If an inspection command returns only head, a cut-off header, or partial rows, immediately issue narrower/chunked reads or targeted column extraction until the missing structure and representative values are confirmed.

1c. Treat header-only inspection as no inspection. Do not say you understand the dataset, define feature rules, or start the harmonization script until you have seen actual data rows for the relevant features.

1d. During initial inspection, explicitly check representative raw values for the numeric encodings that matter to parsing decisions: decimal commas, scientific notation, whitespace/empty-like tokens, and mixed formatting within the same feature. Base normalization rules on those observed raw strings, not on assumptions.

1e. Before finalizing any transformation logic, compare the full input column list against the feature-description/reference definitions and resolve any mismatch, omission, or unexpected extra lab column. Do not proceed as if all features are covered unless dataset schema and reference coverage are explicitly aligned.

1f. Do not state that scientific notation, decimal commas, mixed units, missingness patterns, or specific analyte conversions exist dataset-wide unless the log includes direct evidence from the affected columns/rows and corresponding metadata.

  1. Record the input header, feature count, and row count early so you can preserve schema and verify that final row-count changes come only from removed missing/unparsable rows

2d. Keep simple before/after row-count checkpoints through the pipeline (input rows, rows after parsing/drop-missing, rows after any unresolved-invalid removals, final saved rows) and use them to explain every row-count decrease from the saved output.

2a. Capture the full input column list exactly once at the start and compare the final saved CSV against that exact list; treat any added, dropped, reordered, truncated, or unexpectedly renamed columns as a blocker, not a harmless preview difference.

2a.i. When any preview is truncated or visually cuts off the header, obtain the full machine-readable input schema and exact column count before proceeding. Do not infer schema preservation from head output or a wrapped terminal preview.

2a.ii. If any later check shows a different visible header, different column count, or extra/missing columns, stop and reconcile the discrepancy on the actual saved CSV before claiming schema preservation.

2b. Before applying any destructive step from this skill, especially row deletion, confirm that the current task explicitly requires or permits it and that parsed-data evidence supports the deletion. If row removal is not clearly authorized, preserve row count and limit harmonization to value parsing/conversion/formatting.

2c. Keep observable evidence for each major claim: retain the actual script, conversion map, validation outputs, and inspected output rows so every reported transformation can be tied to code or file evidence.

2d.i. If the task only asks for harmonization/standardization and does not explicitly require dropping incomplete records, preserve rows by default and limit changes to parsing, normalization, and justified unit conversion. Escalate row deletion to a last resort only when the task/instructions or downstream validator clearly require complete-case output.

  1. Build the harmonization as one reusable script/pipeline for the whole table, and load lab columns as raw strings first so decimal commas, scientific notation, whitespace, and empty-like tokens are normalized intentionally before numeric coercion

3d. Prefer a rerunnable script for multi-step harmonization, and keep the core pipeline order stable: inspect schema + feature metadata → read lab fields as strings → normalize numeric text (decimal commas, scientific notation, whitespace) → coerce to numeric / mark unparsable as missing → assess mixed-unit candidates → apply analyte-specific conversions → remove rows still invalid after parsing/conversion as required → save → validate the saved CSV.

3e. Do not run physiological-range checks or mixed-unit detection on unnormalized raw text; perform those checks only after numeric normalization/parsing so the decisions are based on consistent numeric values.

3a. When you create the script file, write actual executable code with imports, parsing logic, conversion logic, save logic, and validation steps. Do not write a prose description, placeholder summary, TODO stub, or comments-only file instead of the implementation.

3b. After writing or updating the script, inspect the saved file contents enough to confirm the code actually contains the intended read, normalize, parse, convert, filter, save, and validate steps.

3c. Do not treat exit code 0, empty stdout, or lack of errors as evidence that harmonization succeeded; confirm that the expected output file was produced or updated and that downstream checks show the intended transformations actually occurred.

3f. Placeholder artifacts are a hard failure: do not create a script file containing only prose, comments, or TODOs. The saved script must contain executable read/normalize/parse/convert/save/validate code, and you must inspect the file text after writing it before relying on it.

3g. Minimum evidence before any success claim: inspect the saved script contents, run it, inspect actual saved output rows beyond the header, and capture whole-file validation results for schema/row counts, missingness after parsing, numeric-text formatting, and any feature-level unit conversions you claim.

3h. If any command fails because of shell syntax, unsupported options, bad quoting, placeholder text, or missing files, count that as no evidence. Fix the command and rerun it successfully before using its intended check in your reasoning.

  1. Extract or tabulate per-feature documented units and expected ranges from ckd_feature_descriptions.csv before finalizing conversion logic; maintain one authoritative per-feature conversion map (feature, source unit, target unit, factor, direction, evidence)

4a. Treat that per-feature reference table as the authoritative driver for cleaning decisions: explicitly pair each dataset column you may harmonize with its documented unit, target unit, expected range, and evidence from the reference file before coding the rule. Do not invent feature rules from names or generic lab knowledge when the reference file provides the needed specification.

4b. Keep conversion logic configurable in one small per-feature table/dict (feature, accepted source units or detection condition, target unit, factor, direction, range/evidence) so analyte-specific rules can be corrected or extended without rewriting the pipeline.

  1. Normalize raw numeric text first: scientific notation, decimal commas, whitespace, and other non-canonical numeric strings
  2. Convert normalized values to numeric and mark unparsable entries as missing
  3. Preserve rows by default. Only remove rows with missing values if the current task explicitly requires or authorizes row deletion after parsing/normalization has converted malformed numeric text into missing values; otherwise keep the rows and harmonize values without changing dataset length. Base any completeness checks on parsed numeric values, not the raw string dataframe.
  4. Detect mixed-unit candidates per feature using observed distributions plus fixed physiological/reference expectations after parsing: keep values already plausible in the target unit unchanged, and only consider supported alternate-unit conversions for values implausible in the target unit. Do not hard-code thresholds from feature names alone, use convert-only-extreme-outliers heuristics as the sole detector, or widen ranges just to silence warnings

8a. Profile parsed values feature-by-feature before adding a conversion rule: summarize out-of-range counts and inspect representative low/high sample values so mixed-unit rules are driven by observed residual patterns, not guesses. Use that profiling to decide which specific features need alternate-unit handling.

  1. Apply conversion factors only when supported by feature metadata, explicit units, or clear dataset-wide evidence; confirm the source→target direction and analyte-specific factor before bulk conversion, sanity-check multiply/divide direction with representative raw→converted examples, and do not reuse a guessed pattern across analytes

9a. If a feature has more than one plausible alternate source unit supported by metadata or observed site patterns, encode those candidates explicitly and test them against the same fixed target-unit acceptance range; keep the candidate that yields plausible target-unit values for the affected rows and leave already-plausible target-unit rows unchanged.

9b. When using multiple candidate factors for one feature, record representative raw→candidate-converted examples and the acceptance result for each candidate so the final choice is evidence-based rather than guessed.

  1. Re-check plausibility after conversion using the same fixed per-feature acceptance criteria and summarize remaining below-range/above-range counts by feature; if values remain implausible, trace representative raw→normalized→converted examples, refine only the justified analyte-specific rule, or treat unresolved values as missing and remove those rows per task requirements. Do not relax validation ranges, widen thresholds, clamp values, or otherwise change acceptance criteria merely to make warnings disappear.

10a. Preserve row identifiers or row positions through the pipeline so any remaining implausible or suspicious values can be traced back to their original raw strings.

10b. Use residual exceptions to drive the next iteration: after each validation pass, focus on the small set of still-failing or suspicious features, inspect representative examples, adjust only those feature-level rules, then rerun full validation. Preserve rules already passing instead of broadening the whole pipeline.

10c. For any suspected mixed-unit feature, inspect its parsed distribution (for example quantiles, value buckets, or clusters) plus representative raw→normalized→converted examples to identify distinct unit regimes and confirm the analyte-specific factor or direction before changing the rule.

10d. Treat near-universal conversion or multiple numeric regimes within one feature as a signal to inspect that feature's distribution directly; do not assume one broad rule is correct just because most rows changed.

10e. Do not accept a conversion rule solely because the converted value looks plausible in-range. For any heuristic or range-flagged mixed-unit rule, confirm it with at least one independent source of evidence such as feature-description metadata, explicit documented units, analyte-specific conventions from the task materials, or direct raw-value patterns that clearly separate target-unit values from alternate-unit values.

10f. If a feature still fails range/unit checks after justified conversion analysis, values outside the fixed accepted target-unit range remain unresolved invalids, not candidates for looser thresholds. Mark them missing and remove the affected rows only if row removal is required/allowed by the task; do not broaden the accepted range, clamp values, or force a pass.

  1. Round all values to 2 decimal places (X.XX) and write them with string-preserving formatting so trailing zeros are kept in the saved CSV

11a. Treat numeric value correctness and serialized text formatting as separate requirements: after numeric cleaning/conversion, explicitly format output fields to exactly two decimal places before writing, so values like 5 and 5.2 are saved as 5.00 and 5.20 rather than relying on default CSV serialization.

11b. If values are numerically correct but the saved CSV drops trailing zeros or rewrites number text unexpectedly, fix the output-writing step and regenerate the file rather than changing validated conversion logic.

11c. Do not assume dataframe display or a parsed round-trip proves formatting correctness; inspect the raw saved CSV text or use string-preserving reads to confirm trailing zeros were actually written.

  1. Validate the final saved CSV across the entire dataset before declaring success, and do not claim dataset-wide harmonization, conversion coverage, converted-row counts, supported units, or physiological compliance unless you explicitly computed or inspected evidence for each relevant feature from the final saved output
  2. Validate conversion logic explicitly, not just formatting: for each feature with any unit harmonization rule, produce evidence from the final saved output and representative raw→normalized→converted examples showing which rows were converted, which were left unchanged, the source→target direction, and why the result is plausible in the target unit.

13a. Do not claim that mixed units were detected or harmonized unless the run includes explicit feature-level evidence for the affected columns from the final saved CSV plus representative raw→normalized→converted row examples. Formatting checks, row counts, and a few output samples are not enough.

  1. If any validation output reports FAIL, warnings, contradictory examples, formatting/range/unit/schema failures, or conflicts with another check, stop and inspect the exact failing cases; determine the authoritative issue, fix the pipeline, regenerate the CSV, and rerun full validation before making any success claim.

14a. If a specific validator exposed the failure, rerun that same validator after the fix and clear the original failure condition before using any additional checker. Use alternate diagnostics to investigate, not to replace the acceptance test that just failed.

14b. Never explain away a reported FAIL as a display artifact, parser artifact, or harmless preview issue unless you verify the exact requirement directly on the saved file and rerun the original failing check to PASS.

14c. When a validator prints example failing rows or values, re-check those exact examples in the saved CSV before making any success claim.

14d. Do not delete scripts, verification helpers, or intermediate evidence after a failed or warning-producing validation run. Keep them available, inspect the named failing rows/features, repair the logic, and rerun the same checks until the blocker is resolved.

14e. Treat any remaining out-of-range, ambiguous-unit, or contradictory harmonization result as unresolved unless you corrected it or the task explicitly permits retaining it. Do not describe the dataset as fully harmonized while such cases remain.

  1. Treat incomplete or truncated validation output as not validated. If a command stops mid-check, returns only partial evidence, or does not show final pass/fail status for the requirement, rerun with concrete commands until the result is complete and inspectable.
  2. If a task uses an active validator or downstream checker, treat that checker as part of the acceptance criteria. Do not explain away a failing check or substitute a different interpretation; change the artifact, serialization, or validation method until the active check passes, or report that the requirement is still unmet.

16a. If one check fails and another check seems to pass, do not declare success from the more favorable interpretation. Reproduce the failing check, identify the exact mismatch between the artifact and the checker, fix it, and rerun that same check until it passes or remains a documented blocker.

Output

Use the task-specified output location only if it is explicitly allowed by the task/system instructions. Treat the /root/... path here as an example only, not proof that /root is writable in the current environment. If write permissions are not explicit, save inside an allowed workspace such as the provided data directory rather than creating files in a different top-level directory.

Use /root/ckd_lab_data_harmonized.csv only when /root is explicitly permitted. Otherwise save the harmonized CSV in an authorized workspace path, and keep the harmonization script plus any verification helpers in that same allowed location unless the task says otherwise.

/root/ckd_lab_data_harmonized.csv:

Verification requirements before finishing:

Output

Validation and Completion

Tips

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.