Traditional mental healthcare relies on periodic check-ins (weekly therapy sessions, monthly medication reviews). Digital therapeutics enable continuous monitoring, detecting concerning patterns immediately rather than waiting for the next appointment.
| Data Stream | Collection Method | Update Frequency | Risk Indicators |
|---|---|---|---|
| Symptom Self-Reports | Daily mood ratings, PHQ-2 quick checks | Daily or on-demand | Sudden worsening, persistent severity |
| Engagement Patterns | App usage logs, session attendance | Real-time | Sudden disengagement, pattern changes |
| Text Analysis | Journal entries, chat messages | Per entry | Crisis keywords, sentiment shift |
| Behavioral Data | Sleep, activity, social interaction logs | Hourly aggregation | Sleep disruption, social withdrawal |
| Physiological Signals | Wearables (heart rate, HRV, sleep) | Continuous | Elevated resting HR, poor HRV |
class RealTimeMonitoringEngine {
private streamProcessor: StreamProcessor;
private riskModels: Map;
private alertDispatcher: AlertDispatcher;
async processDataStream(
userId: string,
dataPoint: DataPoint
): Promise {
// 1. Validate and normalize data
const normalized = await this.normalize(dataPoint);
// 2. Update user's time series
await this.updateTimeSeries(userId, normalized);
// 3. Get recent history for context
const history = await this.getRecentHistory(userId, {
lookback: 14 // days
});
// 4. Calculate current risk scores
const risks = await this.assessRisks(userId, normalized, history);
// 5. Check for alert thresholds
const alerts = this.checkThresholds(risks);
// 6. Dispatch alerts if needed
if (alerts.length > 0) {
await this.dispatchAlerts(userId, alerts);
}
// 7. Update dashboards
await this.updateDashboards(userId, risks);
}
private async assessRisks(
userId: string,
current: DataPoint,
history: TimeSeriesData
): Promise {
// Parallel risk assessment across multiple models
const [
crisisRisk,
relapseRisk,
dropoutRisk,
deteriorationRisk
] = await Promise.all([
this.riskModels.get('crisis').predict(userId, current, history),
this.riskModels.get('relapse').predict(userId, current, history),
this.riskModels.get('dropout').predict(userId, current, history),
this.riskModels.get('deterioration').predict(userId, current, history)
]);
return {
crisis: {
probability: crisisRisk.probability,
confidence: crisisRisk.confidence,
timeframe: '24-72 hours',
factors: crisisRisk.contributingFactors
},
relapse: {
probability: relapseRisk.probability,
confidence: relapseRisk.confidence,
timeframe: '1-4 weeks',
factors: relapseRisk.contributingFactors
},
dropout: {
probability: dropoutRisk.probability,
confidence: dropoutRisk.confidence,
timeframe: '1-2 weeks',
factors: dropoutRisk.contributingFactors
},
deterioration: {
probability: deteriorationRisk.probability,
confidence: deteriorationRisk.confidence,
timeframe: '1 week',
factors: deteriorationRisk.contributingFactors
},
overallRiskLevel: this.calculateOverallRisk([
crisisRisk,
relapseRisk,
dropoutRisk,
deteriorationRisk
])
};
}
}
The most critical application of predictive analytics is identifying patients at imminent risk of suicide or self-harm. ML models trained on patterns preceding past crises can provide early warning, enabling life-saving interventions.
| Risk Factor Category | Specific Indicators | Detection Method | Relative Weight |
|---|---|---|---|
| Direct Statements | Suicidal ideation, plan, intent | NLP keyword/phrase detection | Very High (0.8-1.0) |
| Behavioral Changes | Social withdrawal, giving away possessions | Activity pattern analysis | High (0.6-0.8) |
| Mood Deterioration | Worsening depression/hopelessness | PHQ-9 trends, sentiment analysis | High (0.6-0.8) |
| Substance Use | Increased alcohol/drug use | Self-report, behavioral indicators | Medium (0.4-0.6) |
| Sleep Disruption | Insomnia, hypersomnia | Wearable data, self-report | Medium (0.4-0.6) |
| Recent Stressors | Loss, trauma, rejection | Timeline analysis, text mining | Medium (0.3-0.5) |
class CrisisPredictionModel {
private lstm: LSTMModel; // For time series patterns
private bert: BERTModel; // For text analysis
private ensemble: EnsembleModel;
async predictCrisisRisk(
userId: string,
timeframe: '24h' | '48h' | '72h'
): Promise {
// Gather multi-modal data
const data = await this.gatherData(userId);
// Time series analysis (14-day patterns)
const timeSeriesFeatures = await this.analyzeTimeSeries({
mood: data.moodRatings,
sleep: data.sleepData,
activity: data.activityData,
engagement: data.platformEngagement
});
// Text analysis (recent journal entries, messages)
const textFeatures = await this.analyzeText({
journalEntries: data.recentJournals,
messages: data.recentMessages,
thoughtRecords: data.thoughtRecords
});
// Clinical assessments
const clinicalFeatures = {
phq9Trend: this.calculateTrend(data.phq9Scores, 30),
gad7Trend: this.calculateTrend(data.gad7Scores, 30),
currentSeverity: data.latestPHQ9,
previousCrises: data.crisisHistory.length,
riskFactors: data.demographicRiskFactors
};
// Combine features
const combinedFeatures = {
...timeSeriesFeatures,
...textFeatures,
...clinicalFeatures
};
// Ensemble prediction
const prediction = await this.ensemble.predict(combinedFeatures);
// Risk stratification
let riskLevel: 'low' | 'moderate' | 'high' | 'severe';
if (prediction.probability >= 0.7) riskLevel = 'severe';
else if (prediction.probability >= 0.5) riskLevel = 'high';
else if (prediction.probability >= 0.3) riskLevel = 'moderate';
else riskLevel = 'low';
return {
riskLevel,
probability: prediction.probability,
confidence: prediction.confidence,
timeframe,
contributingFactors: this.explainPrediction(
combinedFeatures,
prediction
),
recommendedActions: this.getActions(riskLevel),
requiresImmediateAction: riskLevel === 'severe' || riskLevel === 'high',
predictedAt: new Date()
};
}
private getActions(riskLevel: string): Action[] {
const actions = {
severe: [
{
action: 'NOTIFY_EMERGENCY_CONTACTS',
priority: 'immediate',
description: 'Notify designated emergency contacts'
},
{
action: 'ALERT_THERAPIST',
priority: 'immediate',
description: 'Urgent notification to assigned therapist'
},
{
action: 'DISPLAY_CRISIS_RESOURCES',
priority: 'immediate',
description: '988 Suicide & Crisis Lifeline prominent display'
},
{
action: 'ACTIVATE_SAFETY_PLAN',
priority: 'immediate',
description: 'Guide through personalized safety plan'
},
{
action: 'SCHEDULE_URGENT_SESSION',
priority: 'high',
description: 'Offer same-day or next-day session'
}
],
high: [
{
action: 'ALERT_THERAPIST',
priority: 'high',
description: 'Notify therapist for follow-up within 24h'
},
{
action: 'OFFER_IMMEDIATE_SUPPORT',
priority: 'high',
description: 'Suggest crisis chat or helpline'
},
{
action: 'REVIEW_SAFETY_PLAN',
priority: 'medium',
description: 'Prompt to review and update safety plan'
}
],
moderate: [
{
action: 'THERAPIST_NOTIFICATION',
priority: 'medium',
description: 'Inform therapist for monitoring'
},
{
action: 'INCREASE_MONITORING',
priority: 'medium',
description: 'Suggest daily check-ins'
},
{
action: 'COPING_SKILLS_REMINDER',
priority: 'low',
description: 'Remind of learned coping strategies'
}
],
low: [
{
action: 'ROUTINE_MONITORING',
priority: 'low',
description: 'Continue standard monitoring'
}
]
};
return actions[riskLevel] || actions.low;
}
}
When risks are identified, automated systems can deliver appropriate interventions immediately rather than waiting for human clinicians to review alerts. These "just-in-time adaptive interventions" (JITAIs) provide support precisely when needed.
class JITAIEngine {
private interventionLibrary: InterventionRepository;
private userPreferences: Map;
private effectivenessTracker: EffectivenessTracker;
async selectIntervention(
userId: string,
context: Context,
risk: RiskAssessment
): Promise {
// Get user's intervention history and preferences
const history = await this.getUserHistory(userId);
const preferences = this.userPreferences.get(userId);
// Get candidate interventions for this risk level
const candidates = await this.interventionLibrary.search({
riskLevel: risk.level,
riskType: risk.type,
context: context.situation
});
// Score each intervention
const scored = candidates.map(intervention => {
let score = 0;
// Base effectiveness for this risk type
score += this.effectivenessTracker.getEffectiveness(
intervention.id,
risk.type
) * 40;
// Personal effectiveness history
const personalHistory = history.filter(
h => h.interventionId === intervention.id
);
if (personalHistory.length > 0) {
const avgRating = personalHistory.reduce(
(sum, h) => sum + h.helpfulnessRating,
0
) / personalHistory.length;
score += avgRating * 30;
}
// User preferences
if (preferences.preferredTypes.includes(intervention.type)) {
score += 20;
}
// Contextual appropriateness
if (this.isContextuallyAppropriate(intervention, context)) {
score += 10;
}
// Novelty (avoid overuse)
const recentUse = history.filter(
h => h.interventionId === intervention.id &&
h.timestamp > Date.now() - 7 * 24 * 60 * 60 * 1000
).length;
score -= recentUse * 5;
return { intervention, score };
});
// Select highest-scoring intervention
const selected = scored.sort((a, b) => b.score - a.score)[0];
// Log selection for learning
await this.logSelection({
userId,
intervention: selected.intervention,
context,
risk,
score: selected.score
});
return selected.intervention;
}
async deliverIntervention(
userId: string,
intervention: Intervention,
context: Context
): Promise {
// Choose delivery channel based on urgency and context
const channel = this.selectChannel(intervention.urgency, context);
// Personalize intervention content
const personalized = await this.personalizeContent(
intervention,
userId
);
// Deliver via selected channel
const result = await channel.send({
userId,
title: personalized.title,
content: personalized.content,
actions: personalized.actions,
priority: intervention.urgency
});
// Track delivery and response
await this.trackDelivery({
userId,
interventionId: intervention.id,
deliveredAt: new Date(),
channel: channel.name,
result
});
// Set up response monitoring
this.monitorResponse(userId, intervention, result);
return result;
}
}
For conditions like depression with high relapse rates (50-80% lifetime risk), early detection of warning signs enables timely intervention before full relapse occurs.
| Warning Sign Category | Early Indicators | Detection Window | Prevention Strategy |
|---|---|---|---|
| Mood Changes | Increased irritability, anhedonia returning | 1-2 weeks before | Increase monitoring, review coping skills |
| Thought Patterns | Negative automatic thoughts resurface | 2-3 weeks before | Cognitive restructuring exercises |
| Behavioral Activation | Withdrawal from activities, social isolation | 1-3 weeks before | Activity scheduling, social engagement prompts |
| Sleep Disruption | Insomnia or hypersomnia patterns | 1-2 weeks before | Sleep hygiene review, CBT-I modules |
| Stress Increase | Life stressors, reduced coping capacity | Variable | Stress management, problem-solving |