Loading...
Loading...
Analyze sleep data, identify sleep patterns, evaluate sleep quality, and provide personalized sleep improvement recommendations. Supports correlation analysis with other health data.
npx skill4agent add huifer/wellally-health sleep-analyzerdata-example/sleep-tracker.jsondata-example/sleep-logs/YYYY-MM/YYYY-MM-DD.jsondata-example/fitness-tracker.jsondata-example/hypertension-tracker.jsondata-example/diabetes-tracker.jsondata-example/diet-records/data-example/mood-tracker.json# Sleep Quality Analysis Report
## Analysis Period
March 20, 2025 to June 20, 2025 (3 months)
---
## Sleep Duration Trend
- **Trend**: ⬆️ Improving
- **Start**: Average 6.2 hours/night
- **Current**: Average 7.1 hours/night
- **Change**: +0.9 hours (+14.5%)
- **Interpretation**: Sleep duration has increased significantly, approaching the ideal target (7.5 hours)
**Trend Line**:
---
## Sleep Efficiency
- **Average Sleep Efficiency**: 85.3%
- **Efficiency Range**: 78%-92%
- **Compliance Rate**: 63% (>85% is compliant)
- **Interpretation**: Sleep efficiency is normal, with room for improvement
**Efficiency Distribution**:
- Excellent (>90%): 15 nights
- Good (85-90%): 28 nights
- Needs Improvement (<85%): 47 nights
---
## Sleep Schedule Regularity
- **Average Bedtime**: 23:15 (range: 22:30-01:00)
- **Average Wake-up Time**: 07:05 (range: 06:30-08:30)
- **Sleep Consistency Score**: 72/100
- **Social Jetlag**: 45 minutes (later bedtime and wake-up time on weekends than workdays)
- **Interpretation**: Sleep schedule is generally regular, but with significant fluctuations on weekends
**Recommendations**:
- 🎯 Maintain a consistent wake-up time, including weekends
- 🎯 Gradually adjust bedtime to avoid excessive delays on weekends
---
## Sleep Quality Distribution
| Quality Level | Days | Percentage | Trend |
|---------|------|------|------|
| Excellent | 8 | 9% | ⬆️ |
| Very Good | 12 | 13% | ➡️ |
| Good | 15 | 17% | ⬆️ |
| Fair | 42 | 47% | ⬇️ |
| Poor | 10 | 11% | ⬇️ |
| Very Poor | 3 | 3% | ➡️ |
**Interpretation**: Sleep quality is mainly "fair", but the number of days with "good" or higher quality is increasing
---
## Nighttime Awakening Analysis
- **Average Awakening Frequency**: 1.8 times/night
- **Average Awakening Duration**: 18 minutes
- **Main Causes**:
1. Urination (45%)
2. Noise (25%)
3. Overheating (15%)
4. Other (15%)
**Recommendations**:
- 🎯 Limit fluid intake 2 hours before bedtime
- 🎯 Optimize bedroom temperature (18-22℃)
- 🎯 Use a white noise machine to mask background noise
---
## PSQI Evaluation Trend
- **Latest Score**: 8 points (fair sleep quality)
- **Previous Score**: 10 points (March 20, 2025)
- **Change**: -2 points (improving)
- **Trend**: ⬆️ Continuous improvement
**Historical Trend**:
**Component Changes**:
- Subjective Sleep Quality: 2→2 (stable)
- Sleep Onset Time: 2→2 (stable)
- Sleep Duration: 2→1 (improving)
- Sleep Efficiency: 2→1 (improving)
- Sleep Disorders: 2→1 (improving)
---
## Sleep Problem Identification
### Insomnia Assessment
- **Type**: Mixed Insomnia
- **Frequency**: 4-5 nights/week
- **Duration**: 18 months
- **Main Symptoms**:
- ✗ Difficulty Falling Asleep (latency >30 minutes)
- ✗ Difficulty Maintaining Sleep (nighttime awakenings >2 times)
- ✓ No early awakening issue
- **Impacts**:
- Daytime Fatigue: Moderate
- Mood Irritability: Yes
- Attention Difficulty: Yes
- Work Performance: Mild impact
- **Recommendation**: 🏥 Persists for >3 months, consult a sleep specialist
### Sleep Apnea Screening (STOP-BANG)
- **Score**: 3/8
- **Risk Level**: Medium Risk
- **Positive Items**:
- ✗ Snoring
- ✗ Tired
- ✓ Observed apnea (not observed)
- ✗ Pressure (hypertension)
- ✓ BMI > 28
- ✓ Age > 50
- ✗ Neck size > 40cm
- ✓ Gender = male
- **Recommendation**: ⚠️ Recommend sleep study (PSG)
---
## Correlation Analysis
### Sleep ↔ Exercise
**Exercise Days vs. Rest Days**:
- Average sleep on exercise days: 7.3 hours
- Average sleep on rest days: 6.8 hours
- Difference: +0.5 hours (+7.4%)
**Impact of Exercise Timing on Sleep**:
- Morning Exercise: 7.5 hours sleep duration, quality score 7.8/10
- Afternoon Exercise: 7.2 hours sleep duration, quality score 7.5/10
- Evening Exercise: 6.8 hours sleep duration, quality score 6.8/10
**Correlation**: Moderate positive correlation (r = 0.42)
**Conclusion**: Regular exercise helps improve sleep, but avoid intense exercise 2-3 hours before bedtime
**Recommendations**:
- 🎯 Maintain regular exercise habits
- 🎯 Shift exercise time to morning or afternoon
- 🎯 Avoid intense exercise 2-3 hours before bedtime
---
### Sleep ↔ Caffeine
**Caffeine Intake Time Analysis**:
- Intake before 2 PM: Average sleep 7.2 hours, sleep onset latency 25 minutes
- Intake after 2 PM: Average sleep 6.7 hours, sleep onset latency 40 minutes
- Difference: -0.5 hours duration, +15 minutes latency
**Correlation**: Moderate negative correlation (r = -0.38)
**Conclusion**: Caffeine intake after 2 PM significantly affects sleep
**Recommendations**:
- 🎯 Avoid caffeine intake after 2 PM
- 🎯 Completely avoid caffeine 6 hours before bedtime
---
### Sleep ↔ Mood
**Impact of Sleep Quality on Next Day's Mood**:
- Good Sleep: 82% probability of positive mood next day
- Fair Sleep: 45% probability of positive mood next day
- Poor Sleep: 18% probability of positive mood next day
**Impact of Pre-sleep Mood on Sleep Onset**:
- High pre-sleep stress: 45 minutes sleep onset latency
- Low pre-sleep stress: 20 minutes sleep onset latency
- Difference: +25 minutes
**Correlation**: Strong bidirectional correlation (r = 0.65)
**Conclusion**: Sleep and mood have significant mutual influence
**Recommendations**:
- 🎯 Practice stress management before bedtime (meditation, deep breathing)
- 🎯 Establish a relaxing pre-sleep routine
- 🎯 Keep a mood journal to identify stress patterns
---
## Insights and Recommendations
### Key Insights
1. **Inconsistent Sleep Schedule is the Main Issue**
- 45 minutes of social jetlag
- Significant deviation of weekend schedule from workdays
- Impact: Circadian rhythm disruption, Monday "jetlag effect"
2. **Evening Exercise Affects Sleep Onset**
- 15 minutes longer sleep onset latency on evenings with exercise
- Recommendation: Adjust exercise time
3. **Sleep Environment Can Be Optimized**
- Noise-related awakenings account for 25%
- Overheating accounts for 15%
- Recommendation: Targeted improvements
---
### Priority Action Plan
#### Priority 1: Establish Consistent Sleep Schedule (2 Weeks)
**Goal**: Increase sleep consistency score to 85
**Specific Actions**:
1. Fix wake-up time at 07:00 (including weekends)
2. Fix bedtime at 23:00
3. Limit naps to <30 minutes, and before 3 PM
4. Gradually adjust weekend schedule (15 minutes earlier each time)
**Expected Effects**:
- Sleep Consistency Score: 72 → 85
- Sleep Efficiency Improvement: +3-5%
- Reduced Monday fatigue
---
#### Priority 2: Create Pre-sleep Routine (3 Weeks)
**Goal**: Establish a stable pre-sleep routine
**Specific Actions**:
1. Start routine 1 hour before bedtime (22:00)
2. Turn off electronic devices (22:30)
3. Dim bedroom lights
4. Engage in relaxing activities (reading, meditation, warm bath)
5. Keep bedroom quiet, dark, and cool (18-22℃)
**Expected Effects**:
- Sleep Onset Latency Reduction: 30 → 20 minutes
- Sleep Quality Improvement: Fair → Good
- Reduced pre-sleep stress
---
#### Priority 3: Optimize Sleep Environment (1 Week)
**Goal**: Eliminate environmental disturbances to sleep
**Specific Actions**:
1. Install blackout curtains
2. Use a white noise machine to mask background noise
3. Optimize temperature to 18-22℃
4. Remove bedroom clock
5. Replace with comfortable pillows and mattress
**Expected Effects**:
- Reduction in Nighttime Awakenings: 1.8 → 1.2 times/night
- Improved sleep continuity
- Better morning state
---
#### Priority 4: Lifestyle Adjustment (4 Weeks)
**Goal**: Eliminate lifestyle habits affecting sleep
**Specific Actions**:
1. Shift exercise to morning or afternoon
2. Stop caffeine intake after 2 PM
3. Avoid alcohol 3 hours before bedtime
4. Avoid heavy meals 2 hours before bedtime
5. Avoid work-related discussions 1 hour before bedtime
**Expected Effects**:
- Increase in Sleep Duration: +0.3 hours
- Sleep Quality Score Improvement: +1 point
- PSQI Score Improvement: 8 → 6
---
## Long-term Goals
- **Sleep Duration**: Reach 7.5 hours/night (current 7.1 hours)
- **Sleep Efficiency**: Improve to >90% (current 85%)
- **PSQI Score**: Reduce to ≤5 points (current 8 points)
- **Sleep Consistency**: Increase to ≥85 points (current 72 points)
- **Sleep Onset Latency**: Reduce to <20 minutes (current 28 minutes)
---
## Medical Safety Reminder
⚠️ **Medical Consultation Recommendations**:
- 🏥 Insomnia persists for >3 months, consult a sleep specialist
- 🏥 STOP-BANG ≥3, recommend sleep study (PSG)
- 🏥 Severe sleepiness affecting driving safety, seek immediate medical attention
- 🏥 Sudden severe sleep problems
---
**Report Generation Time**: June 20, 2025
**Analysis Period**: March 20, 2025 to June 20, 2025 (90 days)
**Number of Data Records**: 90 nights
**Sleep Analyzer Version**: v1.0{
"sleep_records": [
{
"id": "sleep_20250620001",
"date": "2025-06-20",
"sleep_times": {
"bedtime": "23:00",
"sleep_onset_time": "23:30",
"wake_time": "07:00",
"out_of_bed_time": "07:15"
},
"sleep_metrics": {
"sleep_duration_hours": 7.0,
"time_in_bed_hours": 8.25,
"sleep_latency_minutes": 30,
"sleep_efficiency": 84.8
},
"sleep_quality": {
"subjective_quality": "fair",
"quality_score": 5,
"rested_feeling": "somewhat"
},
"factors": {
"exercise": true,
"exercise_time": "evening",
"caffeine_after_2pm": false,
"screen_time_before_bed_minutes": 60
}
}
]
}def calculate_sleep_quality_score(record):
"""
Calculate sleep quality score (0-10 points)
Factor Weights:
- Sleep Duration: 30%
- Sleep Efficiency: 25%
- Sleep Onset Latency: 20%
- Nighttime Awakenings: 15%
- Subjective Quality: 10%
"""
score = 0
# Sleep Duration Score (ideal 7-9 hours)
duration = record['sleep_duration_hours']
if 7 <= duration <= 9:
duration_score = 10
elif 6 <= duration < 7 or 9 < duration <= 10:
duration_score = 7
else:
duration_score = 4
score += duration_score * 0.30
# Sleep Efficiency Score (>90% excellent)
efficiency = record['sleep_efficiency']
efficiency_score = min(efficiency / 90 * 10, 10)
score += efficiency_score * 0.25
# Sleep Onset Latency Score (<15 minutes excellent)
latency = record['sleep_latency_minutes']
if latency <= 15:
latency_score = 10
elif latency <= 30:
latency_score = 7
elif latency <= 45:
latency_score = 4
else:
latency_score = 1
score += latency_score * 0.20
# Nighttime Awakening Score (0 times excellent)
awakenings = record['awakenings']['count']
awakening_score = max(10 - awakenings * 2, 0)
score += awakening_score * 0.15
# Subjective Quality Score
quality_map = {
'excellent': 10,
'very_good': 8,
'good': 7,
'fair': 5,
'poor': 3,
'very_poor': 1
}
subjective_score = quality_map.get(
record['sleep_quality']['subjective_quality'],
5
)
score += subjective_score * 0.10
return round(score, 1)def calculate_sleep_consistency_score(records):
"""
Calculate sleep consistency score (0-100 points)
Factors:
- Bedtime standard deviation
- Wake-up time standard deviation
- Sleep duration standard deviation
- Weekday vs. weekend difference
"""
# Extract time data
bedtimes = [r['bedtime'] for r in records]
wake_times = [r['wake_time'] for r in records]
durations = [r['sleep_duration_hours'] for r in records]
# Calculate standard deviation (minutes)
bedtime_std = time_to_minutes_std(bedtimes)
wake_std = time_to_minutes_std(wake_times)
duration_std = statistics.stdev(durations)
# Calculate weekday vs. weekend difference
weekday_avg = avg([r['sleep_duration_hours']
for r in records if is_weekday(r)])
weekend_avg = avg([r['sleep_duration_hours']
for r in records if is_weekend(r)])
diff = abs(weekday_avg - weekend_avg)
# Comprehensive score
score = 100
score -= bedtime_std * 0.5 # Impact of bedtime standard deviation
score -= wake_std * 0.5 # Impact of wake-up time standard deviation
score -= duration_std * 2 # Impact of sleep duration standard deviation
score -= diff * 10 # Impact of weekday-weekend difference
return max(0, min(100, round(score)))def calculate_correlation(sleep_data, other_data, lag_days=0):
"""
Calculate correlation between sleep and other indicators
Parameters:
- sleep_data: List of sleep data
- other_data: List of other indicator data
- lag_days: Number of lag days (considering delay effects)
Returns:
- correlation_coefficient: Correlation coefficient
- p_value: Statistical significance
- interpretation: Correlation explanation
"""
# Align data (considering lag)
aligned = align_data_with_lag(sleep_data, other_data, lag_days)
# Calculate Pearson correlation coefficient
from scipy import stats
corr, p_value = stats.pearsonr(
aligned['sleep_values'],
aligned['other_values']
)
# Interpret correlation
if abs(corr) < 0.3:
strength = "Weak"
elif abs(corr) < 0.7:
strength = "Moderate"
else:
strength = "Strong"
direction = "Positive Correlation" if corr > 0 else "Negative Correlation"
significant = p_value < 0.05
interpretation = f"{strength} {direction}"
if significant:
interpretation += " (Statistically Significant)"
return {
'correlation_coefficient': round(corr, 3),
'p_value': round(p_value, 4),
'interpretation': interpretation,
'significant': significant
}