# Statistics - Nokken Documentation
Documentation for the Nokken medical tracking application
Author: Charlotte Croce

Skip to content

# Statistics

The statistics feature provides statistical analysis and visualization of user health data. It processes information from multiple sources (mood entries, medications, bloodwork, etc.) and uses the `HealthAnalyticsService` to generate insights, identify patterns, detect correlations, and predict trends.

## Architecture

    lib/src/features/stats/
    ├── charts/                  # Chart widgets for data visualization
    ├── models/                  # Data models for statistical analysis
    ├── providers/               # Riverpod providers for state management
    ├── screens/                 # UI screens for displaying analytics
    ├── tabs/                    # Tab components for the main stats screen
    ├── utils/                   # Utility functions for analysis and formatting
    └── widgets/                 # Reusable UI components

## Components

### Models

The analytics feature uses a large set of models to represent different types of statistical insights:

- `ComprehensiveAnalysis`: Container for all types of analytics data
- `StatisticalInsight`: Basic statistical findings
- `FactorRelationship`: Relationships between different health factors
- `HealthPattern`: Detected patterns in health data
- `HealthPrediction`: Forecasts of future health metrics
- `HealthAnomaly`: Unusual data points
- `FactorImpactRanking`: Impacts of factors on a target variable
- `WeekdayAnalysis`: Metrics across days of the week
- `HealthStreak`: Consistent periods for health metrics
- `HormoneAnalysis`: Hormone level analysis
- `MedicationImpact`: Effects of medications on health metrics

### Providers

    // Basic statistical insights
    final statisticsInsightsProvider = FutureProvider.autoDispose
        .family<List<StatisticalInsight>, String>((ref, timeframe) async { ... });

    // Comprehensive analysis (More detailed/resource extensive)
    final comprehensiveAnalysisProvider = FutureProvider.autoDispose
        .family<ComprehensiveAnalysis, String>((ref, timeframe) async { ... });

    // Factor-specific analysis
    final factorAnalysisProvider = FutureProvider.autoDispose
        .family<Map<String, dynamic>, FactorAnalysisParams>((ref, params) async { ... });

### Services

The analytics functionality relies on the `HealthAnalyticsService`

### Charts

- `CorrelationsChart`: Displays relationships between factors
- `ImpactChart`: Shows impact ranking of factors
- `WeekdayChart`: Visualizes metrics by day of week
- And other specialized charts

## UI Organization

The main Stats screen is organized into tabs: - `Overview`: Summary of health insights and key metrics - `Correlations`: Relationships between different health factors - `Patterns`: Detected trends and cyclical patterns - `Factors`: Analysis of what factors affect health metrics - `Predictions`: Forecasts of future health values

## Factor Analysis

The feature supports detailed analysis of specific factors with the `FactorAnalysisScreen`, which provides:

- Basic statistics (mean, median, min, max)
- Related factors and correlations
- Detected patterns
- Historical timeline
- Health impacts

## Data Sources

The Health Analytics feature consumes data from multiple sources: - Mood Tracker: Emotional state, energy levels, sleep quality, etc. - Medication Tracker: Medication adherence and effects - Bloodwork Tracker: Lab results and hormone levels

## Usage Examples

To access the comprehensive analysis:

    // Watch for analysis data with a specific timeframe
    final analysisAsync = ref.watch(comprehensiveAnalysisProvider('Last Month'));

    // Use the data when available
    analysisAsync.when(
      data: (analysis) {
        // Access insights, relationships, patterns, etc.
        final relationships = analysis.relationships;
        final patterns = analysis.patterns;
        final predictions = analysis.predictions;

        // Build UI with the data
        return ListView(
          children: [
            // Display insights
          ],
        );
      },
      loading: () => const LoadingView(),
      error: (error, stack) => ErrorView(error: error),
    );

To analyze a specific factor:

    // Watch for factor-specific analysis
    final factorAsync = ref.watch(
      factorAnalysisProvider(
        FactorAnalysisParams(
          factorName: 'Mood',
          timeframe: 'All Time',
        ),
      ),
    );

    // Use the data when available
    factorAsync.when(
      data: (factorAnalysis) {
        // Access factor-specific data
        final relationships = factorAnalysis['relationships'];
        final patterns = factorAnalysis['patterns'];

        // Build UI with the data
      },
      loading: () => const LoadingView(),
      error: (error, stack) => ErrorView(error: error),
    );

## Implementation Details

### Correlation Analysis

The service calculates Pearson correlation coefficients between different health factors to identify relationships. For example, it can detect correlations between:

- Sleep quality and mood
- Energy levels and exercise
- Hormone levels and emotions

### Pattern Detection

Patterns are identified through statistical analysis of time series data, including:

- Trends: Directional changes over time
- Cyclical Patterns: Repeating patterns (e.g., weekly sleep cycles)
- Clusters: Groupings of related factors
- Thresholds: Significant crossover points

### Anomaly Detection

The service identifies unusual data points using z-score analysis, which detects values that deviate significantly from normal patterns.

### Prediction Algorithm

Predictions are generated using a combination of:

- Linear trend extrapolation
- Moving averages
- Pattern-based forecasting