Private
Public Access
1
0

simple performance chart

This commit is contained in:
Sander Roosendaal
2020-11-30 21:50:25 +01:00
parent 7ccc7f109b
commit 65648e4ef3
8 changed files with 454 additions and 30 deletions

View File

@@ -703,6 +703,36 @@ class FitnessMetricForm(forms.Form):
class Meta:
fields = ['startdate','enddate','mode']
class PerformanceManagerForm(forms.Form):
startdate = forms.DateField(
initial=timezone.now()-datetime.timedelta(days=365),
# widget=SelectDateWidget(years=range(1990,2050)),
widget=AdminDateWidget(),
label='Start Date')
enddate = forms.DateField(
initial=timezone.now(),
widget=AdminDateWidget(),
label='End Date')
metricchoices = (
('trimp','Use Heart Rate Data'),
('rscore','Use Power and Heart Rate Data'),
)
metricchoice = forms.ChoiceField(
required=True,
choices=metricchoices,
initial='trimp',
label='Data',
widget=forms.RadioSelect
)
dofatigue = forms.BooleanField(required=False,initial=False,
label='Fatigue')
doform = forms.BooleanField(required=False,initial=False,
label='Freshness')
class FitnessFitForm(forms.Form):
startdate = forms.DateField(
initial=timezone.now()-datetime.timedelta(days=365),

View File

@@ -1631,6 +1631,238 @@ def interactive_forcecurve(theworkouts,workstrokesonly=True,plottype='scatter'):
return [script,div,js_resources,css_resources]
def getfatigues(
fatigues,fitnesses,dates,testpower,
startdate,enddate,user,metricchoice,kfatigue,kfitness):
fatigue = 0
fitness = 0
lambda_a = 2/(kfatigue+1)
lambda_c = 2/(kfitness+1)
nrdays = (enddate-startdate).days
for i in range(nrdays):
date = startdate+datetime.timedelta(days=i)
ws = Workout.objects.filter(user=user.rower,date=date,duplicate=False)
weight = 0
for w in ws:
weight += getattr(w,metricchoice)
if getattr(w,metricchoice) == 0:
if metricchoice == 'rscore' and w.hrtss != 0:
weight+= w.hrtss
else:
trimp,hrtss = dataprep.workout_trimp(w)
rscore,normp = dataprep.workout_rscore(w)
fatigue = (1-lambda_a)*fatigue+weight*lambda_a
fitness = (1-lambda_c)*fitness+weight*lambda_c
fatigues.append(fatigue)
fitnesses.append(fitness)
dates.append(datetime.datetime.combine(date,datetime.datetime.min.time()))
testpower.append(np.nan)
return fatigues,fitnesses,dates,testpower
def performance_chart(user,startdate=None,enddate=None,kfitness=42,kfatigue=7,
metricchoice='trimp',doform=False,dofatigue=False):
TOOLS = 'save,pan,box_zoom,wheel_zoom,reset,tap,hover,crosshair'
fatigues = []
fitnesses = []
dates = []
testpower = []
modelchoice = 'coggan'
p0 = 0
k1 = 1
k2 = 1
fatigues,fitnesses,dates,testpower = getfatigues(fatigues,
fitnesses,
dates,
testpower,
startdate,enddate,
user,metricchoice,
kfatigue,kfitness)
df = pd.DataFrame({
'date':dates,
'testpower':testpower,
'fatigue':fatigues,
'fitness':fitnesses,
})
if modelchoice == 'banister':
df['fatigue'] = k2*df['fatigue']
df['fitness'] = p0+k1*df['fitness']
df['form'] = df['fitness']-df['fatigue']
df.sort_values(['date'],inplace=True)
df = df.groupby(['date']).max()
df['date'] = df.index.values
source = ColumnDataSource(
data = dict(
testpower = df['testpower'],
date = df['date'],
fdate = df['date'].map(lambda x: x.strftime('%d-%m-%Y')),
fitness = df['fitness'],
fatigue = df['fatigue'],
form = df['form'],
)
)
plot = Figure(tools=TOOLS,x_axis_type='datetime',
plot_width=900,
toolbar_location="above",
toolbar_sticky=False)
# add watermark
watermarkurl = "/static/img/logo7.png"
watermarksource = ColumnDataSource(dict(
url = [watermarkurl],))
watermarkrange = Range1d(start=0,end=1)
watermarkalpha = 0.6
watermarkx = 0.99
watermarky = 0.01
watermarkw = 184
watermarkh = 35
watermarkanchor = 'bottom_right'
plot.extra_y_ranges = {"watermark": watermarkrange}
plot.extra_x_ranges = {"watermark": watermarkrange}
plot.image_url([watermarkurl],watermarkx,watermarky,
watermarkw,watermarkh,
global_alpha=watermarkalpha,
w_units='screen',
h_units='screen',
anchor=watermarkanchor,
dilate=True,
x_range_name = "watermark",
y_range_name = "watermark",
)
if modelchoice == 'banister':
fitlabel = 'PTE (fitness)'
fatiguelabel = 'NTE (fatigue)'
formlabel = 'Performance'
rightaxlabel = 'NTE'
if doform:
yaxlabel = 'PTE/Performance'
else:
yaxlabel = 'PTE'
else:
fitlabel = 'Fitness'
fatiguelabel = 'Fatigue'
formlabel = 'Freshness'
rightaxlabel = 'Fatigue'
if doform:
yaxlabel = 'Fitness/Freshness'
else:
yaxlabel = 'Fitness'
#plot.circle('date','testpower',source=source,fill_color='green',size=10,
# legend_label=legend_label.format(fitnesstest=fitnesstest))
plot.xaxis.axis_label = 'Date'
plot.yaxis.axis_label = yaxlabel
y2rangemin = df.loc[:,['form']].min().min()
y2rangemax = df.loc[:,['form']].max().max()
if dofatigue:
y1rangemin = df.loc[:,['fitness','fatigue']].min().min()
y1rangemax = df.loc[:,['fitness','fatigue']].max().max()
else:
y1rangemin = df.loc[:,['fitness']].min().min()
y1rangemax = df.loc[:,['fitness']].max().max()
if doform:
plot.extra_y_ranges["yax2"] = Range1d(start=y2rangemin,end=y2rangemax)
plot.add_layout(LinearAxis(y_range_name="yax2",axis_label=rightaxlabel),"right")
plot.line('date','fitness',source=source,color='blue',
legend_label=fitlabel)
band = Band(base='date', upper='fitness', source=source, level='underlay',
fill_alpha=0.2, fill_color='blue')
plot.add_layout(band)
if dofatigue:
plot.line('date','fatigue',source=source,color='red',
legend_label=fatiguelabel)
if doform:
plot.line('date','form',source=source,color='green',
legend_label=formlabel,y_range_name="yax2")
plot.legend.location = "top_left"
plot.xaxis.formatter = DatetimeTickFormatter(
days=["%d %B %Y"],
months=["%d %B %Y"],
years=["%d %B %Y"],
)
plot.xaxis.major_label_orientation = pi/4
plot.sizing_mode = 'stretch_both'
#plot.y_range = Range1d(0,1.5*max(df['testpower']))
startdate = datetime.datetime.combine(startdate,datetime.datetime.min.time())
enddate = datetime.datetime.combine(enddate,datetime.datetime.min.time())
plot.x_range = Range1d(
startdate,enddate+datetime.timedelta(days=5),
)
plot.y_range = Range1d(
start=0,end=y1rangemax,
)
plot.title.text = 'Performance Manager '+user.first_name
hover = plot.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
#(legend_label,'@testpower'),
('Date','@fdate'),
(fitlabel,'@fitness'),
(fatiguelabel,'@fatigue'),
(formlabel,'@form')
])
try:
script,div = components(plot)
except Exception as e:
df.dropna(inplace=True,axis=0,how='any')
return (
'',
'Something went wrong with the chart ({nrworkouts} workouts, {nrdata} datapoints, error {e})'.format(
nrworkouts = workouts.count(),
nrdata = len(df),
e = e,
)
)
return [script,div]
def fitnessfit_chart(workouts,user,workoutmode='water',startdate=None,
enddate=None,kfitness=42,kfatigue=7,fitnesstest=20,
metricchoice='rscore',
@@ -1681,34 +1913,10 @@ def fitnessfit_chart(workouts,user,workoutmode='water',startdate=None,
fatigues = df['fatigue'].values.tolist()
fitnesses = df['fitness'].values.tolist()
fatigue = 0
fitness = 0
lambda_a = 2/(kfatigue+1)
lambda_c = 2/(kfitness+1)
nrdays = (enddate-startdate).days
for i in range(nrdays):
date = startdate+datetime.timedelta(days=i)
ws = Workout.objects.filter(user=user.rower,date=date,duplicate=False)
weight = 0
for w in ws:
weight += getattr(w,metricchoice)
if getattr(w,metricchoice) == 0:
if metricchoice == 'rscore' and w.hrtss != 0:
weight+= w.hrtss
else:
trimp,hrtss = dataprep.workout_trimp(w)
rscore,normp = dataprep.workout_rscore(w)
fatigue = (1-lambda_a)*fatigue+weight*lambda_a
fitness = (1-lambda_c)*fitness+weight*lambda_c
fatigues.append(fatigue)
fitnesses.append(fitness)
dates.append(datetime.datetime.combine(date,datetime.datetime.min.time()))
testpower.append(np.nan)
fatigues,fitnesses,dates,testpower = getfatigues(
fatigues,fitnesses,dates,testpower,
startdate,enddate,user,metricchoice,kfatigue,kfitness
)
df = pd.DataFrame({

View File

@@ -11,6 +11,18 @@
<ul class="main-content">
<li class="rounder">
<h2>Performance Manager</h2>
<a href="/rowers/performancemanager/">
<div class="vignet">
<img src="/static/img/perfmanager.png"
alt="Performance Manager">
</div>
</a>
<p>
Manager Fitness, Fatigue and Freshness
</p>
</li>
<li class="rounder">
<h2>Compare Workouts</h2>
{% if team %}

View File

@@ -0,0 +1,107 @@
{% extends "newbase.html" %}
{% load staticfiles %}
{% load rowerfilters %}
{% block title %}Rowsandall Fitness Progress {% endblock %}
{% block main %}
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function() {
// Get the form fields and hidden div
var checkbox = $("#id_water");
var hidden = $("#id_waterboattype");
// Hide the fields.
// Use JS to do this in case the user doesn't have JS
// enabled.
hidden.hide();
// Setup an event listener for when the state of the
// checkbox changes.
checkbox.change(function() {
// Check to see if the checkbox is checked.
// If it is, show the fields and populate the input.
// If not, hide the fields.
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
// Make sure that the hidden fields are indeed
// hidden.
hidden.hide();
// You may also want to clear the value of the
// hidden fields here. Just in case somebody
// shows the fields, enters data to them and then
// unticks the checkbox.
//
// This would do the job:
//
// $("#hidden_field").val("");
}
});
});
</script>
<script src="https://cdn.pydata.org/bokeh/release/bokeh-2.2.3.min.js"></script>
<script async="true" type="text/javascript">
Bokeh.set_log_level("info");
</script>
{{ chartscript |safe }}
<script>
// Set things up to resize the plot on a window resize. You can play with
// the arguments of resize_width_height() to change the plot's behavior.
var plot_resize_setup = function () {
var plotid = Object.keys(Bokeh.index)[0]; // assume we have just one plot
var plot = Bokeh.index[plotid];
var plotresizer = function() {
// arguments: use width, use height, maintain aspect ratio
plot.resize_width_height(true, false, false);
};
window.addEventListener('resize', plotresizer);
plotresizer();
};
window.addEventListener('load', plot_resize_setup);
</script>
{% if rower.user %}
<h1>Fitness Progress for {{ rower.user.first_name }} </h1>
{% else %}
<h1>Fitness Progress for {{ user.first_name }} </h1>
{% endif %}
<p>
Text Explaining Performance Manager
</p>
<ul class="main-content">
<li class="grid_2">
<form enctype="multipart/form-data" action="/rowers/performancemanager/user/{{ rower.user.id }}/" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input name='daterange' class="button green" type="submit" value="Submit">
</form>
</li>
<li class="grid_4">
{{ the_div|safe }}
</li>
</ul>
{% endblock %}
{% block sidebar %}
{% include 'menu_analytics.html' %}
{% endblock %}

View File

@@ -355,6 +355,9 @@ urlpatterns = [
re_path(r'^fitness-fit/$',views.fitness_from_cp_view,name='fitness_from_cp_view'),
re_path(r'^fitness-fit/user/(?P<userid>\d+)/$',views.fitness_from_cp_view,name='fitness_from_cp_view'),
re_path(r'^fitness-fit/user/(?P<userid>\d+)/(?P<mode>\w+.*)/$',views.fitness_from_cp_view,name='fitness_from_cp_view'),
re_path(r'^performancemanager/$',views.performancemanager_view,name='performancemanager_view'),
re_path(r'^performancemanager/user/(?P<userid>\d+)/$',views.performancemanager_view,name='performancemanager_view'),
re_path(r'^performancemanager/user/(?P<userid>\d+)/(?P<mode>\w+.*)/$',views.performancemanager_view,name='performancemanager_view'),
# re_path(r'^ote-bests/user/(?P<theuser>\d+)/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',views.rankings_view,name='rankings_view'),
re_path(r'^ote-bests/user/(?P<userid>\d+)/$',views.rankings_view,name='rankings_view'),
# re_path(r'^ote-bests/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',views.rankings_view,name='rankings_view'),

View File

@@ -1539,6 +1539,70 @@ def fitnessmetric_view(request,userid=0,mode='rower',
'form':form,
})
@user_passes_test(ispromember, login_url="/rowers/paidplans",
message="This functionality requires a Pro plan or higher. If you are already a Pro user, please log in to access this functionality",
redirect_field_name=None)
@permission_required('rower.is_promember',fn=get_user_by_userid,raise_exception=True)
def performancemanager_view(request,userid=0,mode='rower',
startdate=timezone.now()-timezone.timedelta(days=365),
enddate=timezone.now()):
therower = getrequestrower(request,userid=userid)
theuser = therower.user
kfitness = 42
kfatigue = 7
fitnesstest = 20
metricchoice = 'trimp'
modelchoice = 'tsb'
usefitscore = False
doform = False
dofatigue = False
if request.method == 'POST':
form = PerformanceManagerForm(request.POST)
if form.is_valid():
startdate = form.cleaned_data['startdate']
enddate = form.cleaned_data['enddate']
metricchoice = form.cleaned_data['metricchoice']
dofatigue = form.cleaned_data['dofatigue']
doform = form.cleaned_data['doform']
else:
form = PerformanceManagerForm()
script, thediv = performance_chart(
theuser,startdate=startdate,enddate=enddate,
kfitness = kfitness,
kfatigue = kfatigue,
metricchoice = metricchoice,
doform = doform,
dofatigue = dofatigue,
)
breadcrumbs = [
{
'url':'/rowers/analysis',
'name':'Analysis'
},
{
'url':reverse('fitnessmetric_view'),
'name': 'Power Progress'
}
]
return render(request,'performancemanager.html',
{
'rower':therower,
'active':'nav-analysis',
'chartscript':script,
'breadcrumbs':breadcrumbs,
'the_div':thediv,
'mode':mode,
'form':form,
})
@user_passes_test(isplanmember,login_url="/rowers/paidplans",
message="This functionality requires a Coach or Self-Coach plan",
redirect_field_name=None)
@@ -1555,7 +1619,7 @@ def fitness_from_cp_view(request,userid=0,mode='rower',
kfitness = 42
kfatigue = 7
fitnesstest = 20
metricchoice = 'rscore'
metricchoice = 'trimp'
modelchoice = 'tsb'
usefitscore = False

View File

@@ -76,7 +76,7 @@ from rowers.forms import (
disqualifiers,SearchForm,BillingForm,PlanSelectForm,
VideoAnalysisCreateForm,WorkoutSingleSelectForm,
VideoAnalysisMetricsForm,SurveyForm,HistorySelectForm,
StravaChartForm,FitnessFitForm
StravaChartForm,FitnessFitForm,PerformanceManagerForm,
)
from django.urls import reverse, reverse_lazy