##
## Python program will run on selection.
##
from GC_Wrapper import GC_wrapper as GC
import pathlib
from datetime import datetime
import time
import collections
import tempfile
import plotly
import plotly.graph_objs as go
import numpy as np
import statistics

compares = GC.season(compare=True)
activities_list = GC.activities(filter='isRun<>0')
athlete_zones = GC.athleteZones()
hr_max = max(athlete_zones['hrmax'])

temp_file = tempfile.NamedTemporaryFile(mode="w+t",
                                        prefix="GC_",
                                        suffix=".html",
                                        delete=False)

# Define GC background color
gc_bg_color = 'rgb(52,52,52)'
# Define GC Text color
gc_text_color = 'rgb(255,255,255)'


# For an given subset of activities this function will return a data frame that contains all hr with corresponding speed
def main():
    start_time = datetime.now()
    season = GC.season(compare=True)
    all_lat_long_df = pd.DataFrame()
    activities_list = GC.activities(filter='Data contains "G"')

    start_dt = datetime.combine(season['start'][0], datetime.min.time())
    end_dt = datetime.combine(season['end'][0], datetime.min.time())
    activities_sub_list = []

    for i in np.arange(0, len(activities_list)):
        if start_dt <= activities_list[i] <= end_dt:
            activities_sub_list.append(activities_list[i])

    activity_time_calculation = round(len(activities_sub_list) * 0.5)
    map_time_calculation = round(len(activities_sub_list) * 0.05)
    html_write_time_calculation = round(len(activities_sub_list) * 0.2)
    duration = activity_time_calculation + map_time_calculation + html_write_time_calculation
    msg = """You are about to process: """ + str(len(activities_sub_list)) + """ (activities)

Based on your selection an rough estimation on how long the script will run: """ +\
          str(timedelta(seconds=duration)) + """

Do you want to continue?
"""
    if mb.askyesno("Expected run time", msg):
        for activity in activities_sub_list:
            current_activity = GC.activity(activity=activity)
            current_activity_df = pd.DataFrame(
                current_activity, index=current_activity['seconds']).filter(
                    ["longitude", "latitude"])
            all_lat_long_df = all_lat_long_df.append(current_activity_df)
        heat_data = all_lat_long_df[['latitude', 'longitude']].to_numpy()

        print('Gathering data est:{} act:{} '.format(
            activity_time_calculation,
            round((datetime.now() - start_time).total_seconds(), 2)))

        before = datetime.now()
        fmap = folium.Map(
            tiles='CartoDB positron' if light_map else 'CartoDB dark_matter',
            prefer_canvas=True)

        HeatMap(heat_data,
                radius=radius,
                blur=blur,
                gradient=heatmap_grad['light' if light_map else 'dark'],
                min_opacity=0.3,
                max_val=1).add_to(fmap)
        fmap.fit_bounds(fmap.get_bounds())
        print('Create map est:{} act:{}'.format(
            map_time_calculation,
            round((datetime.now() - before).total_seconds(), 2)))

        before = datetime.now()
        html = fmap.get_root().render()
        temp_file.writelines(html)
        temp_file.close()
        print('Write HTML est:{} act:{}'.format(
            html_write_time_calculation,
            round((datetime.now() - before).total_seconds()), 2))

        print('Total time est:{} act:{}'.format(
            timedelta(seconds=duration),
            str(datetime.now() - start_time).split('.')[0]))
    else:
        create_cancel_html()

    GC.webpage(pathlib.Path(temp_file.name).as_uri())
Ejemplo n.º 3
0
def main():
    compares = GC.season(compare=True)
    activities_list = GC.activities(
        filter='Data contains "P" and Data contains "H"')
    athlete_zones = GC.athleteZones()
    hr_max = max(athlete_zones['hrmax'])

    start_time = time.time()

    data = []
    for start, end, color, name in zip(compares['start'], compares['end'],
                                       compares['color'], compares['name']):
        #    print("start: " + str(start) + ", end: " + str(end) + ", color: " + str(color))
        start_dt = datetime.combine(start, datetime.min.time())
        end_dt = datetime.combine(end, datetime.min.time())
        activities_sub_list = []
        for i in np.arange(0, len(activities_list)):
            if activities_list[i] >= start_dt and activities_list[i] <= end_dt:
                activities_sub_list.append(activities_list[i])
        #    print(activities_sub_list)
        heart_rate_power_dict = get_hr_list_of_activities(activities_sub_list)
        mean_power_by_hr = create_mean_power_by_hr(heart_rate_power_dict)
        #    print(mean_power_by_hr)

        trace = go.Scatter(
            x=list(mean_power_by_hr.keys()),
            y=list(mean_power_by_hr.values()),
            mode='lines+markers',
            line=dict(color=color, ),
            name=name,
            showlegend=True,
        )
        data.append(trace)
    # End for

    layout = go.Layout(
        title="Average power at HR",
        paper_bgcolor=gc_bg_color,
        plot_bgcolor=gc_bg_color,
        font=dict(color=gc_text_color, size=12),
        yaxis=dict(
            title="Watts",
            nticks=50,
            rangemode='nonnegative',
            showgrid=True,
            zeroline=True,
            showline=True,
            gridcolor="grey",
        ),
        xaxis=dict(
            range=[90, hr_max + 5],
            nticks=int(hr_max / 5),
            ticks='outside',
            showgrid=True,
            zeroline=True,
            showline=True,
            gridcolor="grey",
            title="HR",
            rangemode='nonnegative',
        ),
        margin=go.layout.Margin(l=100, r=0, b=100, t=150, pad=0),
    )

    fig = go.Figure(data=data, layout=layout)
    plotly.offline.plot(fig, auto_open=False, filename=temp_file.name)
    GC.webpage(pathlib.Path(temp_file.name).as_uri())
    print("Total graph time: " + str(time.time() - start_time))