From 742fca831a88221792684486fc7e9fe4c14f62eb Mon Sep 17 00:00:00 2001 From: Sander Roosendaal Date: Fri, 29 Mar 2024 08:07:27 +0100 Subject: [PATCH] small speed up --- rowers/interactiveplots.py | 200 +++++-------------------------------- 1 file changed, 24 insertions(+), 176 deletions(-) diff --git a/rowers/interactiveplots.py b/rowers/interactiveplots.py index e915de3b..614a8f7a 100644 --- a/rowers/interactiveplots.py +++ b/rowers/interactiveplots.py @@ -623,47 +623,22 @@ def interactive_activitychart(workouts, startdate, enddate, stack='type', toolba def interactive_activitychart2(workouts, startdate, enddate, stack='type', toolbar_location=None, yaxis='duration'): - dates = [] - dates_sorting = [] - types = [] - rowers = [] - durations = [] - rscores = [] - trimps = [] - links = [] - distances = [] - - rowersinitials = {} - seen = ['seen'] - idseen = [] + print(timezone.now()) startdate = datetime.datetime( year=startdate.year, month=startdate.month, day=startdate.day) enddate = datetime.datetime( year=enddate.year, month=enddate.month, day=enddate.day) - duration = enddate-startdate + totaldays = (enddate-startdate).days - totaldays = duration.total_seconds()/(24*3600) + data_dicts = [] + aantal = 1 for w in workouts: - aantal = 1 - initials = w.user.user.first_name[0:aantal] + \ - w.user.user.last_name[0:aantal] - if w.user.id not in idseen: - while initials in seen: # pragma: no cover - aantal += 1 - initials = w.user.user.first_name[0:aantal] + \ - w.user.user.last_name[0:aantal] - - seen.append(initials) - idseen.append(w.user.id) - rowersinitials[w.user.id] = initials - - for w in workouts: - dd = w.date.strftime('%m/%d') - dd2 = w.date.strftime('%Y/%m/%d') - dd3 = w.date.strftime('%Y/%m') + rr = w.user + rowersinitials = rr.user.first_name[0:aantal]+rr.user.last_name[0:aantal] + dd = w.date.strftime('%Y-%m-%d') du = w.duration.hour*60+w.duration.minute trimp = w.trimp @@ -672,78 +647,24 @@ def interactive_activitychart2(workouts, startdate, enddate, stack='type', toolb if rscore == 0: # pragma: no cover rscore = w.hrtss - if totaldays <= 30: # pragma: no cover - dates.append(dd) - dates_sorting.append(dd2) - else: - dates.append(dd3) - dates_sorting.append(dd3) - durations.append(du) - trimps.append(trimp) - rscores.append(rscore) - distances.append(distance) - links.append( - "{siteurl}/rowers/workout/{code}/".format( + + link = "{siteurl}/rowers/workout/{code}/".format( siteurl=settings.SITE_URL, code=encoder.encode_hex(w.id) ) - ) - types.append(w.workouttype) - try: - rowers.append(rowersinitials[w.user.id]) - except IndexError: # pragma: no cover - rowers.append(str(w.user)) + data_dicts.append({ + 'date': dd, + 'duration': du, + 'distance': distance, + 'trimp': trimp, + 'rscore': rscore, + 'type': w.workouttype, + 'link': link, + 'rower': rowersinitials + }) - try: - d = utc.localize(startdate) - except (ValueError, AttributeError): # pragma: no cover - d = startdate - - try: - enddate = utc.localize(enddate) - except (ValueError, AttributeError): # pragma: no cover - pass - - # add dates with no activity - while d <= enddate: - dd = d.strftime('%d') - - dates.append(d.strftime('%Y-%m-%d')) - dates_sorting.append(d.strftime('%Y/%m/%d')) - - durations.append(0) - trimps.append(0) - rscores.append(0) - distances.append(0) - links.append('') - types.append('rower') - - try: - rowers.append(rowers[0]) - except IndexError: # pragma: no cover - try: - rowers.append(str(workouts[0].user)) - except IndexError: - rowers.append(' ') - - d += datetime.timedelta(days=1) - - thedict = { - 'date': dates, - 'date_sorting': dates_sorting, - 'duration': durations, - 'trimp': trimps, - 'rscore': rscores, - 'type': types, - 'rower': rowers, - 'distance': distances, - 'link': links, - } - - df = pd.DataFrame(thedict) - - data_dict = df.to_dict("records") + if totaldays < 30: datebin = "day" @@ -761,7 +682,7 @@ def interactive_activitychart2(workouts, startdate, enddate, stack='type', toolb } chart_data = { - 'data': data_dict, + 'data': data_dicts, 'title': 'Activity {d1} to {d2}'.format( d1=startdate.strftime("%Y-%m-%d"), d2=enddate.strftime("%Y-%m-%d"), @@ -774,83 +695,10 @@ def interactive_activitychart2(workouts, startdate, enddate, stack='type', toolb 'colors': mytypes.color_map, } - script, div = get_chart("/activity_bar", chart_data, debug=True) + print(timezone.now()) + + script, div = get_chart("/activity_bar", chart_data, debug=False) - return script, div - - if totaldays > 30 and yaxis == 'duration': # pragma: no cover - df['duration'] = df['duration']/60 - elif yaxis == 'TRIMP': - df.drop('duration', inplace=True, axis='columns') - df.drop('rscore', inplace=True, axis='columns') - df.drop('distance', inplace=True, axis='columns') - elif yaxis == 'rScore': # pragma: no cover - df.drop('duration', inplace=True, axis='columns') - df.drop('trimp', inplace=True, axis='columns') - df.drop('distance', inplace=True, axis='columns') - elif yaxis == 'distance': # pragma: no cover - df.drop('duration', inplace=True, axis='columns') - df.drop('trimp', inplace=True, axis='columns') - df.drop('rscore', inplace=True, axis='columns') - - df['color'] = df['type'].apply(lambda x: mapcolors(x)) - - df.sort_values('date_sorting', inplace=True) - - hv.extension('bokeh') - - # table = hv.Table(df,[('date','Date'),('type','Workout Type')], - # [('duration','Minutes'),('trimp','TRIMP'),('rscore','rScore'),('link','link')]) - - types_order = mytypes.workouttypes_ordered - # bars=table.to.bars(['date',stack],[yaxis]) - bars = hv.Bars(df, kdims=['date', stack]).aggregate( - function=np.sum).redim.values(types=types_order) - - # print(mytypes.color_map) - bars.opts( - opts.Bars(cmap=mytypes.color_map, show_legend=True, stacked=True, - tools=['tap', 'hover'], width=550, xrotation=45, padding=(0, (0, .1)), - legend_position='bottom', show_frame=True)) - - p = hv.render(bars) - - p.title.text = 'Activity {d1} to {d2}'.format( - d1=startdate.strftime("%Y-%m-%d"), - d2=enddate.strftime("%Y-%m-%d"), - ) - - p.xaxis.axis_label = 'Period' - if yaxis == 'duration': - p.yaxis.axis_label = 'Duration (min)' - if totaldays > 30: # pragma: no cover - p.yaxis.axis_label = 'Duration (h)' - elif yaxis == 'TRIMP': - p.yaxis.axis_label = 'TRIMP' - elif yaxis == 'distance': # pragma: no cover - p.yaxis.axis_label = 'Distance (m)' - else: # pragma: no cover - p.yaxis.axis_label = 'rScore' - - p.width = 550 - p.height = 350 - p.toolbar_location = toolbar_location - #p.sizing_mode = 'stretch_both' - p.y_range.start = 0 - taptool = p.select(type=TapTool) - - callback = CustomJS(args={'links': df['link']}, code=""" - var index = cb_data.source.selected['1d'].indices[0]; - console.log(links); - console.log(index); - console.log(links[index]); - window.location.href = links[index] - """) - - taptool.js_on_event('tap', callback) - - script, div = components(p) - return script, div def interactive_forcecurve(theworkouts, workstrokesonly=True, plottype='scatter',