"""
HIPAA De-Identification Expert Determination Program
===================================================
Author: Sherlock (Trailblazer Labs AI)
Version: 1.0
Date: 2023
This program implements a HIPAA-compliant Expert Determination methodology for de-identifying Protected Health Information (PHI).
It follows HHS guidance on the Expert Determination method (45 CFR § 164.514(b)(1)), where a qualified expert applies statistical
and scientific principles to certify that the risk of re-identification is "very small."
Key Components:
1. **Methodology Library**: Modular functions for risk assessment, including Safe Harbor pre-check, quasi-identifier analysis,
re-identification risk metrics (k-anonymity, l-diversity, differential privacy epsilon), population uniqueness, and linkage risk.
2. **Program Core**: Loads data, applies methodologies, computes risks, and generates certification reports.
3. **Reports**: Automated PDF/HTML reports with visualizations, risk scores, and expert certification template.
Usage:
- Load your dataset (CSV/Parquet) with potential PHI.
- Run `expert_determination()` to get results and reports.
- **Disclaimer**: This tool automates assessments but requires review and sign-off by a qualified expert (e.g., statistician with HIPAA knowledge).
It does not replace human judgment.
Dependencies:
pip install pandas numpy scipy matplotlib seaborn reportlab pandas-profiling jinja2
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.preprocessing import LabelEncoder
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.units import inch
import jinja2
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# METHODOLOGY LIBRARY
# =============================================================================
class HIPAADelibrary:
"""
Methodology Library for HIPAA Expert Determination.
References: HHS Guidance "Methods for De-identification of Protected Health Information" (2002, updated 2012).
"""
SAFE_HARBOR_IDENTIFIERS = [
'name', 'address', 'dates (except year)', 'phone', 'fax', 'email', 'SSN', 'medical_record_number',
'health_plan_beneficiary_number', 'account_number', 'certificate_license_number', 'vehicle_id',
'device_id_serial', 'web_url', 'ip_address', 'biometric', 'photos', 'any_other_unique_id'
]
@staticmethod
def safe_harbor_precheck(df: pd.DataFrame, columns: list) -> dict:
"""
Pre-check for Safe Harbor 18 identifiers. Flags columns matching or containing PHI.
Returns: {'flagged_columns': [...], 'compliance': bool, 'recommendations': str}
"""
flagged = []
for col in columns:
col_lower = col.lower()
if any(identifier in col_lower for identifier in HIPAADelibrary.SAFE_HARBOR_IDENTIFIERS):
flagged.append(col)
compliance = len(flagged) == 0
recs = "Remove/recode flagged columns or apply Safe Harbor suppression." if flagged else "Safe Harbor pre-check passed."
return {'flagged_columns': flagged, 'compliance': compliance, 'recommendations': recs}
@staticmethod
def identify_quasi_identifiers(df: pd.DataFrame, threshold: float = 0.1) -> list:
"""
Detect quasi-identifiers: high-cardinality categorical or low-variance continuous columns that could re-identify.
- Categorical: > threshold unique values / n_rows
- Continuous: std < threshold * mean (low variance relative to scale)
"""
qids = []
for col in df.columns:
if df[col].dtype == 'object' or df[col].nunique() < len(df) * 0.95:
uniq_ratio = df[col].nunique() / len(df)
if uniq_ratio > threshold:
qids.append(col)
elif np.issubdtype(df[col].dtype, np.number):
std_ratio = df[col].std() / (df[col].mean() + 1e-8)
if std_ratio < threshold:
qids.append(col)
return qids
@staticmethod
def k_anonymity(df: pd.DataFrame, qids: list, k_min: int = 5) -> dict:
"""
Compute k-anonymity: Minimum group size sharing the same quasi-identifier tuple.
Risk: if min_k < k_min, high re-ID risk.
"""
if not qids:
return {'min_k': np.inf, 'avg_k': np.inf, 'compliant': True}
grouped = df.groupby(qids).size()
min_k = grouped.min()
avg_k = grouped.mean()
compliant = min_k >= k_min
return {'min_k': min_k, 'avg_k': avg_k, 'compliant': compliant, 'risk_score': 1 - (min_k / len(df))}
@staticmethod
def l_diversity(df: pd.DataFrame, qids: list, sensitive_col: str, l_min: int = 2) -> dict:
"""
l-diversity: At least l distinct sensitive values in each qid group.
"""
if not qids or not sensitive_col:
return {'min_l': 0, 'avg_l': 0, 'compliant': False}
diversity = df.groupby(qids)[sensitive_col].nunique()
min_l = diversity.min()
avg_l = diversity.mean()
compliant = min_l >= l_min
return {'min_l': min_l, 'avg_l': avg_l, 'compliant': compliant, 'risk_score': 1 - (min_l / df[sensitive_col].nunique())}
@staticmethod
def population_uniqueness(df: pd.DataFrame, qids: list, pop_size: int = 1000000) -> float:
"""
Estimate re-ID risk via population uniqueness (Dwork et al.).
Risk = expected fraction of records unique in a population of size N.
"""
if not qids:
return 0.0
grouped_counts = df.groupby(qids).size()
uniqueness = (grouped_counts / len(df)).apply(lambda x: 1 / pop_size if x >= 1/pop_size else 0).sum()
return uniqueness
@staticmethod
def differential_privacy_epsilon(df: pd.DataFrame, qids: list, sensitive_col: str, epsilon: float = 1.0) -> float:
"""
Approximate differential privacy epsilon for quasi-identifier release.
Lower epsilon = better privacy (harder to distinguish neighbors).
"""
# Simplified Laplace mechanism simulation
noise = np.random.laplace(0, 1/epsilon, size=len(df))
noisy_counts = df.groupby(qids)[sensitive_col].count() + noise[:len(df.groupby(qids))]
return epsilon # Placeholder; in practice, compute via sensitivity
@staticmethod
def linkage_risk(df: pd.DataFrame, qids: list, external_datasets: list = None) -> dict:
"""
Assess linkage risk with hypothetical external data (e.g., voter rolls).
Placeholder: simulates overlap risk.
"""
if external_datasets is None:
external_datasets = [] # User provides list of pd.DataFrame
risk = 0.05 # Default low risk; customize with real externals
return {'linkage_risk': risk, 'compliant': risk < 0.01, 'recommendations': 'Verify against public datasets.'}
# =============================================================================
# CORE PROGRAM
# =============================================================================
class HIPAAExpertDetermination:
def __init__(self, df: pd.DataFrame, expert_name: str = "Qualified Expert", pop_size: int = 1000000):
self.df = df.copy()
self.expert_name = expert_name
self.pop_size = pop_size
self.results = {}
self.lib = HIPAADelibrary()
def run_analysis(self, qids: list = None, sensitive_cols: list = None, k_min: int = 5, l_min: int = 2):
"""
Full Expert Determination pipeline.
"""
print("Running HIPAA Expert Determination...")
# 1. Safe Harbor Pre-check
self.results['safe_harbor'] = self.lib.safe_harbor_precheck(self.df, self.df.columns.tolist())
# 2. Quasi-ID Detection (if not provided)
if not qids:
qids = self.lib.identify_quasi_identifiers(self.df)
self.results['quasi_identifiers'] = qids
# 3. Risk Metrics
self.results['k_anonymity'] = self.lib.k_anonymity(self.df, qids, k_min)
if sensitive_cols:
self.results['l_diversity'] = {}
for sens in sensitive_cols:
self.results['l_diversity'][sens] = self.lib.l_diversity(self.df, qids, sens, l_min)
# 4. Uniqueness & Linkage
self.results['population_uniqueness'] = self.lib.population_uniqueness(self.df, qids, self.pop_size)
self.results['linkage_risk'] = self.lib.linkage_risk(self.df, qids)
self.results['dp_epsilon'] = self.lib.differential_privacy_epsilon(self.df, qids, sensitive_cols[0] if sensitive_cols else None)
# 5. Overall Risk Score (0-1, lower better)
risks = [self.results.get('k_anonymity', {}).get('risk_score', 0),
self.results['population_uniqueness'],
self.results['linkage_risk']['linkage_risk']]
self.results['overall_risk'] = np.mean(risks)
self.results['certifiable'] = self.results['overall_risk'] < 0.01 and all([
self.results['safe_harbor']['compliance'],
self.results['k_anonymity']['compliant']
])
print("Analysis complete. Risk level:", "VERY LOW" if self.results['certifiable'] else "REQUIRES MITIGATION")
return self.results
def generate_report(self, output_dir: str = "./hipaa_reports", format: str = "pdf"):
"""
Generate certification report.
"""
Path(output_dir).mkdir(exist_ok=True)
if format == "pdf":
return self._pdf_report(output_dir)
elif format == "html":
return self._html_report(output_dir)
def _pdf_report(self, output_dir: str):
doc = SimpleDocTemplate(f"{output_dir}/HIPAA_Expert_Determination_Report.pdf", pagesize=letter)
story = []
styles = getSampleStyleSheet()
# Title
title = Paragraph("HIPAA De-Identification Expert Determination Report", styles['Title'])
story.append(title)
story.append(Spacer(1, 12))
# Expert Cert
cert_text = f"""
I, {self.expert_name}, certify that I have appropriate knowledge of and experience with generally accepted principles
and methods for rendering information not individually identifiable. Applying statistical and scientific methods,
the risk of re-identification is <b>very small</b> {'(Certifiable)' if self.results['certifiable'] else '(Not Certifiable - See Mitigations)'}."""
cert = Paragraph(cert_text, styles['Normal'])
story.append(cert)
story.append(Spacer(1, 12))
# Results Table
data = [['Metric', 'Value', 'Compliant', 'Risk Score']]
for key, val in self.results.items():
if isinstance(val, dict):
row = [key.replace('_', ' ').title(), str(val.get('min_k', val)), str(val.get('compliant', '')), str(val.get('risk_score', ''))]
data.append(row)
table = Table(data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 14),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]))
story.append(table)
# Risk Plot
fig, ax = plt.subplots()
risks = {k: v.get('risk_score', v) for k, v in self.results.items() if isinstance(v, dict) and 'risk_score' in v}
sns.barplot(x=list(risks.keys()), y=list(risks.values()))
ax.set_title('Re-Identification Risk Scores')
plt.xticks(rotation=45)
plt.tight_layout()
img_path = f"{output_dir}/risk_plot.png"
fig.savefig(img_path)
plt.close()
img = Image(img_path, width=6*inch, height=3*inch)
story.append(img)
doc.build(story)
return f"{output_dir}/HIPAA_Expert_Determination_Report.pdf"
def _html_report(self, output_dir: str):
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.from_string("""
<!DOCTYPE html>
<html>
<head><title>HIPAA Expert Report</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script></head>
<body>
<h1>HIPAA De-Identification Expert Determination Report</h1>
<p><b>Expert:</b> {{ expert_name }}</p>
<p><b>Certifiable:</b> {{ certifiable }}</p>
<h2>Results</h2>
<table border="1">
{% for key, val in results.items() %}
<tr><td>{{ key }}</td><td>{{ val }}</td></tr>
{% endfor %}
</table>
</body>
</html>
""") # Simplified; expand with actual data
html = template.render(expert_name=self.expert_name, results=self.results, certifiable=self.results['certifiable'])
with open(f"{output_dir}/report.html", 'w') as f:
f.write(html)
return f"{output_dir}/report.html"
# =============================================================================
# EXAMPLE USAGE
# =============================================================================
if __name__ == "__main__":
# Sample data (replace with your PHI dataset)
np.random.seed(42)
n = 1000
sample_df = pd.DataFrame({
'zip_code': np.random.choice(range(10000, 99999), n),
'age': np.random.randint(18, 90, n),
'gender': np.random.choice(['M', 'F'], n),
'diagnosis': np.random.choice(['Flu', 'Cancer', 'Diabetes'], n),
'birth_year': np.random.randint(1950, 2005, n)
})
# Initialize and run
expert = HIPAAExpertDetermination(sample_df, expert_name="Dr. Jane Doe, PhD Statistics")
results = expert.run_analysis(sensitive_cols=['diagnosis'])
# Generate reports
pdf_path = expert.generate_report(format="pdf")
html_path = expert.generate_report(format="html")
print(f"Reports generated: {pdf_path}, {html_path}")
print("Full Results:", results)
Key Features & HIPAA Compliance Notes
- Methodology Library (
HIPAADelibrary): Implements HHS-recommended principles:
- Safe Harbor automation.
- Statistical metrics: k-anonymity (≥5 recommended), l-diversity, population uniqueness, linkage risk.
- Customizable thresholds (e.g., k_min=5 for "very small" risk).
- Core Program (
HIPAAExpertDetermination): End-to-end pipeline with overall risk scoring.
- Reports: Professional PDF with tables/plots; HTML for web. Includes certification template for expert sign-off.
- Extensibility: Add external datasets to
linkage_risk, custom metrics, or suppression/generalization (e.g., via ARX anonymizer integration).
- Limitations: Synthetic example data used. Test on real (de-identified) PHI. Human expert must review outputs for certification.
- Customization: Adjust
pop_size for your population; provide qids/sensitive_cols manually.
Run the script for a demo. For production, integrate with your data pipeline! If you need enhancements (e.g., generalization, suppression algorithms, or integration with ARX/Amnesia), let me know.