From ddbb5f159f25ca1fc74421cfee2f8b5614943118 Mon Sep 17 00:00:00 2001 From: Thomas Klaehn Date: Wed, 14 Aug 2019 11:37:57 +0200 Subject: [PATCH] Refactor accumulated distance creation. --- gpx2html/__init__.py | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/gpx2html/__init__.py b/gpx2html/__init__.py index 0ac831e..b7c6e68 100755 --- a/gpx2html/__init__.py +++ b/gpx2html/__init__.py @@ -86,6 +86,25 @@ def generate_date_list(start_date, end_date): r = (end_date + datetime.timedelta(days=1) - start_date).days return[start_date + datetime.timedelta(days=i) for i in range(r)] +def get_distance_by_date(tracks, date): + '''Return accumulated distances [km] by date. + + Args: + tracks (list(Track)): List of tracks to be evaluated. + date (datetine.datetime): Date to be evaluated. + + Return (float): Accumulated distance [km] for date. + ''' + distance = 0 + for track in tracks: + if track.start_time.year == date.year and \ + track.start_time.month == date.month and \ + track.start_time.day == date.day: + distance += track.distance + if distance > 0: + distance /= 1000 + return distance + class Gpx2Html(object): def __init__(self, infolder, outfolder, logger): @@ -132,20 +151,13 @@ class Gpx2Html(object): end_date = now tracks = self.tracks.tracks(start_date, end_date) for date in generate_date_list(start_date, end_date): - for track in tracks: - if track.start_time.month == date.month and track.start_time.day == date.day: - if len(acc_year_dist) < date.timetuple().tm_yday: - acc_year_dist.append(track.distance / 1000) - else: - acc_year_dist.append(track.distance / 1000 + acc_year_dist[-1]) - elif len(acc_year_dist) < date.timetuple().tm_yday: - if len(acc_year_dist) > 0: - acc_year_dist.append(acc_year_dist[-1]) - else: - acc_year_dist.append(0) - if len(acc_year_dist) == 365: - acc_year_dist.append(acc_year_dist[-1]) + date_distance = get_distance_by_date(tracks, date) + try: + acc_year_dist.append(date_distance + acc_year_dist[-1]) + except IndexError: + acc_year_dist.append(date_distance) accumulated_distance[year] = acc_year_dist + plot_line_chart(accumulated_distance, MONTH_LABELS, "Accumulated Distance", 'Month', 'km', os.path.join(self.outfolder, 'acc_dist.png'))