mirror of
https://github.com/sstent/GarminSync.git
synced 2026-01-27 17:41:53 +00:00
working - moved to compose
This commit is contained in:
73
garminsync/fit_processor/gear_analyzer.py
Normal file
73
garminsync/fit_processor/gear_analyzer.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import numpy as np
|
||||
|
||||
class SinglespeedAnalyzer:
|
||||
def __init__(self):
|
||||
self.chainring_options = [38, 46] # teeth
|
||||
self.common_cogs = list(range(11, 28)) # 11t to 27t rear cogs
|
||||
self.wheel_circumference_m = 2.096 # 700x25c tire
|
||||
|
||||
def analyze_gear_ratio(self, speed_data, cadence_data, gradient_data):
|
||||
"""Determine most likely singlespeed gear ratio"""
|
||||
# Validate input parameters
|
||||
if not speed_data or not cadence_data or not gradient_data:
|
||||
raise ValueError("Input data cannot be empty")
|
||||
if len(speed_data) != len(cadence_data) or len(speed_data) != len(gradient_data):
|
||||
raise ValueError("Input data arrays must be of equal length")
|
||||
|
||||
# Filter for flat terrain segments (gradient < 3%)
|
||||
flat_indices = [i for i, grad in enumerate(gradient_data) if abs(grad) < 3.0]
|
||||
flat_speeds = [speed_data[i] for i in flat_indices]
|
||||
flat_cadences = [cadence_data[i] for i in flat_indices]
|
||||
|
||||
# Only consider data points with sufficient speed (15 km/h) and cadence
|
||||
valid_indices = [i for i in range(len(flat_speeds))
|
||||
if flat_speeds[i] > 4.17 and flat_cadences[i] > 0] # 15 km/h threshold
|
||||
|
||||
if not valid_indices:
|
||||
return None # Not enough data
|
||||
|
||||
valid_speeds = [flat_speeds[i] for i in valid_indices]
|
||||
valid_cadences = [flat_cadences[i] for i in valid_indices]
|
||||
|
||||
# Calculate gear ratios from speed and cadence
|
||||
gear_ratios = []
|
||||
for speed, cadence in zip(valid_speeds, valid_cadences):
|
||||
# Gear ratio = (speed in m/s * 60 seconds/minute) / (cadence in rpm * wheel circumference in meters)
|
||||
gr = (speed * 60) / (cadence * self.wheel_circumference_m)
|
||||
gear_ratios.append(gr)
|
||||
|
||||
# Calculate average gear ratio
|
||||
avg_gear_ratio = sum(gear_ratios) / len(gear_ratios)
|
||||
|
||||
# Find best matching chainring and cog combination
|
||||
best_fit = None
|
||||
min_diff = float('inf')
|
||||
for chainring in self.chainring_options:
|
||||
for cog in self.common_cogs:
|
||||
theoretical_ratio = chainring / cog
|
||||
diff = abs(theoretical_ratio - avg_gear_ratio)
|
||||
if diff < min_diff:
|
||||
min_diff = diff
|
||||
best_fit = (chainring, cog, theoretical_ratio)
|
||||
|
||||
if not best_fit:
|
||||
return None
|
||||
|
||||
chainring, cog, ratio = best_fit
|
||||
|
||||
# Calculate gear metrics
|
||||
wheel_diameter_inches = 27.0 # 700c wheel diameter
|
||||
gear_inches = ratio * wheel_diameter_inches
|
||||
development_meters = ratio * self.wheel_circumference_m
|
||||
|
||||
# Calculate confidence score (1 - relative error)
|
||||
confidence = max(0, 1 - (min_diff / ratio)) if ratio > 0 else 0
|
||||
|
||||
return {
|
||||
'estimated_chainring_teeth': chainring,
|
||||
'estimated_cassette_teeth': cog,
|
||||
'gear_ratio': ratio,
|
||||
'gear_inches': gear_inches,
|
||||
'development_meters': development_meters,
|
||||
'confidence_score': confidence
|
||||
}
|
||||
44
garminsync/fit_processor/power_estimator.py
Normal file
44
garminsync/fit_processor/power_estimator.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import numpy as np
|
||||
|
||||
class PowerEstimator:
|
||||
def __init__(self):
|
||||
self.bike_weight_kg = 10.0 # 22 lbs
|
||||
self.rider_weight_kg = 75.0 # Default assumption
|
||||
self.drag_coefficient = 0.88 # Road bike
|
||||
self.frontal_area_m2 = 0.4 # Typical road cycling position
|
||||
self.rolling_resistance = 0.004 # Road tires
|
||||
self.drivetrain_efficiency = 0.97
|
||||
self.air_density = 1.225 # kg/m³ at sea level, 20°C
|
||||
|
||||
def calculate_power(self, speed_ms, gradient_percent,
|
||||
air_temp_c=20, altitude_m=0):
|
||||
"""Calculate estimated power using physics model"""
|
||||
# Validate input parameters
|
||||
if not isinstance(speed_ms, (int, float)) or speed_ms < 0:
|
||||
raise ValueError("Speed must be a non-negative number")
|
||||
if not isinstance(gradient_percent, (int, float)):
|
||||
raise ValueError("Gradient must be a number")
|
||||
|
||||
# Calculate air density based on temperature and altitude
|
||||
temp_k = air_temp_c + 273.15
|
||||
pressure = 101325 * (1 - 0.0000225577 * altitude_m) ** 5.25588
|
||||
air_density = pressure / (287.05 * temp_k)
|
||||
|
||||
# Convert gradient to angle
|
||||
gradient_rad = np.arctan(gradient_percent / 100.0)
|
||||
|
||||
# Total mass
|
||||
total_mass = self.bike_weight_kg + self.rider_weight_kg
|
||||
|
||||
# Power components
|
||||
P_roll = self.rolling_resistance * total_mass * 9.81 * np.cos(gradient_rad) * speed_ms
|
||||
P_grav = total_mass * 9.81 * np.sin(gradient_rad) * speed_ms
|
||||
P_aero = 0.5 * air_density * self.drag_coefficient * self.frontal_area_m2 * speed_ms ** 3
|
||||
|
||||
# Power = (Rolling + Gravity + Aerodynamic) / Drivetrain efficiency
|
||||
return (P_roll + P_grav + P_aero) / self.drivetrain_efficiency
|
||||
|
||||
def estimate_peak_power(self, power_values, durations):
|
||||
"""Calculate peak power for various durations"""
|
||||
# This will be implemented in Phase 3
|
||||
return {}
|
||||
154
garminsync/web/templates/activity.html
Normal file
154
garminsync/web/templates/activity.html
Normal file
@@ -0,0 +1,154 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Activity Details - GarminSync</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="/static/styles.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-4">
|
||||
<h1 class="mb-4">Activity Details</h1>
|
||||
|
||||
<div id="activity-details">
|
||||
<!-- Activity details will be populated by JavaScript -->
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<h2>Analysis Metrics</h2>
|
||||
<table class="table table-striped" id="metrics-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Metric</th>
|
||||
<th>Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<!-- Metrics will be populated by JavaScript -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<button id="reprocess-btn" class="btn btn-warning">
|
||||
<span id="spinner" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
|
||||
Reprocess Activity
|
||||
</button>
|
||||
<div id="reprocess-result" class="mt-2"></div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<a href="/activities" class="btn btn-secondary">Back to Activities</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/utils.js"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', async function() {
|
||||
const activityId = new URLSearchParams(window.location.search).get('id');
|
||||
if (!activityId) {
|
||||
showError('Activity ID not provided');
|
||||
return;
|
||||
}
|
||||
|
||||
// Load activity details
|
||||
await loadActivity(activityId);
|
||||
|
||||
// Setup reprocess button
|
||||
document.getElementById('reprocess-btn').addEventListener('click', () => {
|
||||
reprocessActivity(activityId);
|
||||
});
|
||||
});
|
||||
|
||||
async function loadActivity(activityId) {
|
||||
try {
|
||||
const response = await fetch(`/api/activities/${activityId}`);
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load activity details');
|
||||
}
|
||||
|
||||
const activity = await response.json();
|
||||
renderActivity(activity);
|
||||
} catch (error) {
|
||||
showError(`Error loading activity: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function renderActivity(activity) {
|
||||
const detailsEl = document.getElementById('activity-details');
|
||||
detailsEl.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">${activity.name}</h5>
|
||||
<p class="card-text">
|
||||
<strong>Date:</strong> ${formatDateTime(activity.start_time)}<br>
|
||||
<strong>Type:</strong> ${activity.activity_type}<br>
|
||||
<strong>Duration:</strong> ${formatDuration(activity.duration)}<br>
|
||||
<strong>Distance:</strong> ${formatDistance(activity.distance)}<br>
|
||||
<strong>Status:</strong>
|
||||
<span class="badge ${activity.reprocessed ? 'bg-success' : 'bg-secondary'}">
|
||||
${activity.reprocessed ? 'Processed' : 'Not Processed'}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Render metrics
|
||||
const metrics = [
|
||||
{ name: 'Max Heart Rate', value: activity.max_heart_rate, unit: 'bpm' },
|
||||
{ name: 'Avg Heart Rate', value: activity.avg_heart_rate, unit: 'bpm' },
|
||||
{ name: 'Avg Power', value: activity.avg_power, unit: 'W' },
|
||||
{ name: 'Calories', value: activity.calories, unit: 'kcal' },
|
||||
{ name: 'Gear Ratio', value: activity.gear_ratio, unit: '' },
|
||||
{ name: 'Gear Inches', value: activity.gear_inches, unit: '' }
|
||||
];
|
||||
|
||||
const tableBody = document.getElementById('metrics-table').querySelector('tbody');
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
metrics.forEach(metric => {
|
||||
if (metric.value !== undefined) {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `<td>${metric.name}</td><td>${metric.value} ${metric.unit}</td>`;
|
||||
tableBody.appendChild(row);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function reprocessActivity(activityId) {
|
||||
const btn = document.getElementById('reprocess-btn');
|
||||
const spinner = document.getElementById('spinner');
|
||||
const resultEl = document.getElementById('reprocess-result');
|
||||
|
||||
btn.disabled = true;
|
||||
spinner.classList.remove('d-none');
|
||||
resultEl.innerHTML = '';
|
||||
resultEl.classList.remove('alert-success', 'alert-danger');
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/activities/${activityId}/reprocess`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
resultEl.innerHTML = `<div class="alert alert-success">Activity reprocessed successfully!</div>`;
|
||||
|
||||
// Reload activity data to show updated metrics
|
||||
await loadActivity(activityId);
|
||||
} catch (error) {
|
||||
console.error('Reprocess error:', error);
|
||||
resultEl.innerHTML = `<div class="alert alert-danger">${error.message || 'Reprocessing failed'}</div>`;
|
||||
} finally {
|
||||
spinner.classList.add('d-none');
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user