Пример #1
0
def leave(gpx):
    global info_display
    filename = str(round(time.time() * 1000))
    os.system('clear')
    print('\nGPX file Created : ' + filename + ".gpx")
    file = open("/home/phablet/Downloads/" + filename + ".gpx", "w+")
    file.write(gpx.to_xml())
    file.close()
    gpx_file = "/home/phablet/Downloads/" + filename + ".gpx"
    shutil.chown(gpx_file, user="******", group="phablet")
    gpx = gpxpy.parse(open(gpx_file))
    indentation = '   '
    info_display = ""
    length_2d = gpx.length_2d()
    length_3d = gpx.length_3d()
    info_display += "\n%sLength 2D: %s" % (indentation, format_long_length(length_2d))
    info_display += "\n%sLength 3D: %s" % (indentation, format_long_length(length_3d))
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    info_display += "\n%sMoving time: %s" %(indentation, format_time(moving_time))
    info_display += "\n%sStopped time: %s" %(indentation, format_time(stopped_time))
    info_display += "\n%sMax speed: %s" % (indentation, format_speed(max_speed))
    info_display += "\n%sAvg speed: %s" % (indentation, format_speed(moving_distance / moving_time) if moving_time > 0 else "?")
    uphill, downhill = gpx.get_uphill_downhill()
    info_display += "\n%sTotal uphill: %s" % (indentation, format_short_length(uphill))
    info_display += "\n%sTotal downhill: %s" % (indentation, format_short_length(downhill))
    info_display += "\n\n\n"
    print(info_display)
    if args.activity:
        newlocation="/home/phablet/.local/share/activitytracker.cwayne18/{}".format(filename + ".gpx")
        copyfile(gpx_file, newlocation)
        shutil.chown(newlocation, user="******", group="phablet")
        add_run(gpx,filename,"", newlocation)
    p.kill()
    sys.exit()
Пример #2
0
def analyse_gpx(file, index=-1):
    gpx = gpxpy.parse(file)
    data = {}
    data["length2D"] = gpx.length_2d()
    data["length3D"] = gpx.length_3d()
    c = gpx.get_uphill_downhill()
    data["pos_climb"] = c.uphill
    data["pos_climb"] = c.downhill
    gpx.smooth()
    d = gpx.get_uphill_downhill()
    data["pos_climb_smooth"] = d.uphill
    data["neg_climb_smooth"] = d.downhill
    data["duration"] = gpx.get_duration()
    data["average_speed"] = 3.6 * data["length3D"] / data["duration"]
    data["elevation_extreme"] = gpx.get_elevation_extremes()
    #print(data["elevation_extreme"])

    raw_data_lat = []
    raw_data_lon = []
    raw_data_alt = []
    for track_idx, track in enumerate(gpx.tracks):
        for seg_idx, segment in enumerate(track.segments):
            for point_idx, point in enumerate(segment.points):
                raw_data_lat.append(point.latitude)
                raw_data_lon.append(point.longitude)
                raw_data_alt.append(point.elevation)

    #gmap = gmplot.GoogleMapPlotter(raw_data_lat[0], raw_data_lon[0], 14)
    #gmap.scatter(raw_data_lat, raw_data_lon, 'k', marker=True)

    #gmap.draw(os.path.join(settings.MEDIA_ROOT, str(index) + ".html"))

    return data
    """
def getInfos(gpx): 
    # creates json with infos about gpx track e.g. uphill, downhill, distance etc.
    indentation = '   '
    infos = {}
    infos['uphill'], infos['downhill'] = gpx.get_uphill_downhill()
    infos['uphill'] = int(round(infos['uphill']))
    infos['downhill'] = int(round(infos['downhill']))
    #print('%sTotal uphill: %sm' % (indentation, infos['uphill']))
    #print('%sTotal downhill: %sm' % (indentation, infos['downhill']))
    infos['length_2d'] = round(gpx.length_2d()/1000., 2)
    infos['length_3d'] = round(gpx.length_3d()/1000., 2)
    #print('%sLength 2D: %s' % (indentation, infos['length_2d'] / 1000.))
    #print('%sLength 3D: %s' % (indentation, infos['length_3d'] / 1000.))
    #infos['start_time'], infos['end_time'] = gpx.get_time_bounds()
    #print('%sStarted: %s' % (indentation, infos['start_time']))
    #print('%sEnded: %s' % (indentation, infos['end_time']))

    return infos
def getInfos(gpx):
    # creates json with infos about gpx track e.g. uphill, downhill, distance etc.
    indentation = '   '
    infos = {}
    infos['uphill'], infos['downhill'] = gpx.get_uphill_downhill()
    infos['uphill'] = int(round(infos['uphill']))
    infos['downhill'] = int(round(infos['downhill']))
    #print('%sTotal uphill: %sm' % (indentation, infos['uphill']))
    #print('%sTotal downhill: %sm' % (indentation, infos['downhill']))
    infos['length_2d'] = round(gpx.length_2d() / 1000., 2)
    infos['length_3d'] = round(gpx.length_3d() / 1000., 2)
    #print('%sLength 2D: %s' % (indentation, infos['length_2d'] / 1000.))
    #print('%sLength 3D: %s' % (indentation, infos['length_3d'] / 1000.))
    #infos['start_time'], infos['end_time'] = gpx.get_time_bounds()
    #print('%sStarted: %s' % (indentation, infos['start_time']))
    #print('%sEnded: %s' % (indentation, infos['end_time']))

    return infos
Пример #5
0
def gpx_run():

    gpx_file = open(dirName + fileList[fileName], 'r')
    gpx = gpxpy.parse(gpx_file)

    length = gpx.length_3d()
    print('Distance: %s' % length)

    # this is simly removing all points with no change in 3m
    gpx.reduce_points(2000, min_distance=3)
    # smoothin both
    gpx.smooth(vertical=True, horizontal=True)
    # and again smoothing just vertical
    gpx.smooth(vertical=True, horizontal=False)

    # Variables for power calculation
    mRider = 80  # mass in kg of the rider
    mBike = 7  # mass in kg of the bike
    M = mBike + mRider  # mass in kg of the bike + rider
    h = 1.92  # hight in m of rider
    A = 0.0276 * h**0.725 * mRider**0.425 + 0.1647
    # cross sectional area of the rider, bike and wheels
    Crr = 0.3386 / M  # coefficient of rolling resistance
    # v = gear * RPM  # velocity in m/s

    # Constants
    g = 9.8067  # acceleration in m/s^2 due to gravity
    p = 1.225  # air density in kg/m^3 at 15°C at sea level
    CD = 0.725  # coefficient of drag
    E = 1  # drive chain efficiency

    # datafild for calculation and plotting
    df = pd.DataFrame(columns=['lon', 'lat', 'alt', 'time',
                               'dist', 'ele', 'grad', 'pow'])

    for track in gpx.tracks:
        for segment in track.segments:
            for point_no, point in enumerate(segment.points):
                # print the current point information from GPX file
                # print('Point at ({0},{1}) -> {2} -> {3}'
                #       .format(point.latitude,
                #               point.longitude,
                #               point.elevation,
                #               point.time))
                # calculate the distance between two point in 3D
                distance = mod_geo.distance(point.latitude,
                                            point.longitude,
                                            point.elevation,
                                            segment.points[point_no - 1].latitude,
                                            segment.points[point_no - 1].longitude,
                                            segment.points[point_no - 1].elevation)

                # calculate the elevation between points
                elevation = point.elevation - segment.points[point_no - 1].elevation

                # avoid division by 0
                if distance == 0:
                    gradient = 0
                else:
                    # calculate gradient between points
                    gradient = elevation / distance * 100

                # test with simulated velocity of 20km/h == 5.55 m/s
                v = 5.55

                # inputs for power calculation
                G = gradient/100

                # output of power calculation
                P = E * (M * g * v * math.cos(math.atan(G)) * Crr + M * g * v
                         * math.sin(math.atan(G)) + 1/2*p * CD * A * v**3)

                """
                the simulation is close to the calculator found here:
                https://www.gribble.org/cycling/power_v_speed.html

                gpx.py:
                Gradient:   3.00 %
                Power:   194.46 W
                gribble.org:
                Gradient:   3.00 %
                Power:   194.82 W

                """
                # this is the procesing time for each point to point (segment)
                # but what if the speed (RPM) changes in between this time?
                # this will not work, but good for simulation with constant speed
                # another for loop will be neccesarry with a sleep of 1sec for
                # recalculation of dynamic sleep time based on
                # the refreshed velocity

                # load gpx information into a datafild for calculation and plotting

                df = df.append({'lon': point.longitude,
                                'lat': point.latitude,
                                'alt': point.elevation,
                                'time': point.time,
                                'dist': distance,
                                'ele': elevation,
                                'grad': gradient,
                                'pow': P},
                               ignore_index=True)

                # time.sleep(wait)

    # start of plotting
    def make_patch_spines_invisible(ax):
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        for sp in ax.spines.values():
            sp.set_visible(False)

    fig, host = plt.subplots()
    fig.subplots_adjust(right=0.75)

    par1 = host.twinx()
    par2 = host.twinx()

    # Offset the right spine of par2.  The ticks and label have already been
    # placed on the right by twinx above.
    par2.spines["right"].set_position(("axes", 1.2))
    # Having been created by twinx, par2 has its frame off, so the line of its
    # detached spine is invisible.  First, activate the frame but make the patch
    # and spines invisible.
    make_patch_spines_invisible(par2)
    # Second, show the right spine.
    par2.spines["right"].set_visible(True)

    p1, = host.plot(df['time'], df['alt'], "b-", label="Altitude")
    p2, = par1.plot(df['time'], df['ele'], "r-", label="Elevation")
    p3, = par2.plot(df['time'], df['pow'], "g-", label="Power")

    # host.set_xlim(0, 2)
    # host.set_ylim(0, 2)
    # par1.set_ylim(0, 4)
    # par2.set_ylim(1, 65)

    host.set_xlabel("Time")
    host.set_ylabel("Altitude")
    par1.set_ylabel("Elevation")
    par2.set_ylabel("Power")

    host.yaxis.label.set_color(p1.get_color())
    par1.yaxis.label.set_color(p2.get_color())
    par2.yaxis.label.set_color(p3.get_color())

    tkw = dict(size=4, width=1.5)
    host.tick_params(axis='y', colors=p1.get_color(), **tkw)
    par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
    par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
    host.tick_params(axis='x', **tkw)

    lines = [p1, p2, p3]

    host.legend(lines, [l.get_label() for l in lines])

    plt.show()

    for index, row in df.iterrows():
        print("Gradient:  ", f"{row['grad']:4.2f}", "%", "Power:   ",
              f"{row['pow']:4.2f}", "W")

        wait = row['dist'] / v

        print("Wait:      ", f"{wait:4.2f}", "s")

        time.sleep(wait)
Пример #6
0
def gpx_run():

    gpx_file = open(dirName + fileList[fileName], 'r')
    gpx = gpxpy.parse(gpx_file)

    length = gpx.length_3d()
    print('Distance: %s' % length)

    # this is simly removing all points with no change in 3m
    gpx.reduce_points(2000, min_distance=3)
    # smoothin both
    gpx.smooth(vertical=True, horizontal=True)
    # and again smoothing just vertical
    gpx.smooth(vertical=True, horizontal=False)

    # Variables for power calculation
    mRider = 80  # mass in kg of the rider
    mBike = 7  # mass in kg of the bike
    M = mBike + mRider  # mass in kg of the bike + rider
    h = 1.92  # hight in m of rider
    A = 0.0276 * h**0.725 * mRider**0.425 + 0.1647
    # cross sectional area of the rider, bike and wheels
    Crr = 0.3386 / M  # coefficient of rolling resistance
    # v = gear * RPM  # velocity in m/s

    # Constants
    g = 9.8067  # acceleration in m/s^2 due to gravity
    p = 1.225  # air density in kg/m^3 at 15°C at sea level
    CD = 0.725  # coefficient of drag
    E = 1  # drive chain efficiency

    # datafild for calculation and plotting
    df = pd.DataFrame(
        columns=['lon', 'lat', 'alt', 'time', 'dist', 'ele', 'grad', 'pow'])

    for track in gpx.tracks:
        for segment in track.segments:
            for point_no, point in enumerate(segment.points):
                # print the current point information from GPX file
                # print('Point at ({0},{1}) -> {2} -> {3}'
                #       .format(point.latitude,
                #               point.longitude,
                #               point.elevation,
                #               point.time))
                # calculate the distance between two point in 3D
                distance = mod_geo.distance(
                    point.latitude, point.longitude, point.elevation,
                    segment.points[point_no - 1].latitude,
                    segment.points[point_no - 1].longitude,
                    segment.points[point_no - 1].elevation)

                # calculate the elevation between points
                elevation = point.elevation - segment.points[point_no -
                                                             1].elevation

                # avoid division by 0
                if distance == 0:
                    gradient = 0
                else:
                    # calculate gradient between points
                    gradient = elevation / distance * 100
                """
                the simulation is close to the calculator found here:
                https://www.gribble.org/cycling/power_v_speed.html

                gpx.py:
                Gradient:   3.00 %
                Power:   194.46 W
                gribble.org:
                Gradient:   3.00 %
                Power:   194.82 W

                """

                # load gpx information into a datafild for
                # calculation and plotting

                df = df.append(
                    {
                        'lon': point.longitude,
                        'lat': point.latitude,
                        'alt': point.elevation,
                        'time': point.time,
                        'dist': distance,
                        'ele': elevation,
                        'grad': gradient
                    },
                    ignore_index=True)

    for index, row in df.iterrows():
        # define cylce in 10th of wait
        cycle = 10
        # recalculation of dynamic sleep time based on
        # the refreshed velocity
        for i in range(0, 10):
            # test with simulated velocity of 20km/h == 5.55 m/s
            v = 5.55
            G = row['grad'] / 100
            # output of power calculation
            P = E * (M * g * v * math.cos(math.atan(G)) * Crr + M * g * v *
                     math.sin(math.atan(G)) + 1 / 2 * p * CD * A * v**3)

            print("Gradient:  ", f"{row['grad']:4.2f}", "%", "Power:   ",
                  f"{P:4.2f}", "W")

            wait = row['dist'] / v / cycle
            print("Wait:      ", f"{wait:4.2f}", "s")
            time.sleep(wait)
Пример #7
0
 filename = str(round(time.time() * 1000))
 os.system('clear')
 print('\nGPX file Created : ' + filename + ".gpx")
 file = open(filename + ".gpx", "w+")
 file.write(gpx.to_xml())
 file.close()
 gpx_file = filename + ".gpx"
 shutil.chown(gpx_file, user="******", group="phablet")
 gpx = gpxpy.parse(open(gpx_file))
 indentation = '   '
 info_display = ""
 """
 gpx_part may be a track or segment.
 """
 length_2d = gpx.length_2d()
 length_3d = gpx.length_3d()
 info_display += "\n%sLength 2D: %s" % (indentation,
                                        format_long_length(length_2d))
 info_display += "\n%sLength 3D: %s" % (indentation,
                                        format_long_length(length_3d))
 moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data(
 )
 info_display += "\n%sMoving time: %s" % (indentation,
                                          format_time(moving_time))
 info_display += "\n%sStopped time: %s" % (indentation,
                                           format_time(stopped_time))
 info_display += "\n%sMax speed: %s" % (indentation,
                                        format_speed(max_speed))
 info_display += "\n%sAvg speed: %s" % (
     indentation, format_speed(moving_distance /
                               moving_time) if moving_time > 0 else "?")
Пример #8
0
def gpx_covid_regulations_check_compliance(gpx_file, domicile):
    d_max = 1.0
    d_runner = 0.0
    gpx = gpxpy.parse(gpx_file)
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                gps_pos = Position_GPS(point.longitude, point.latitude, "")
                distance = domicile.calculateDistanceVolOiseau(gps_pos)
                if distance > d_max and distance > d_runner:
                    d_runner = distance

    #
    # Quelques rappels sur les timezones et conversions de timestamps créés avec une timezone UTC
    #   But de cette manipulation: pas trouvé de documentation sur le package GpxPi pour changer la timezone...
    #   et données Strava utilisent UTC comme Timezone et Paris est à UTC+2 (GMT+1)
    #   donc on utilse la fonction astimezone de la classe datetime :-)
    #
    utc = timezone('UTC')
    paris = timezone('Europe/Paris')
    berlin = timezone('Europe/Berlin')
    tokyo = timezone('Asia/Tokyo')
    new_york = timezone('America/New_York')
    los_angeles = timezone('America/Los_Angeles')
    paris_time = datetime.now(paris)
    berlin_time = datetime.now(berlin)
    tokyo_time = datetime.now(tokyo)
    new_york_time = datetime.now(new_york)
    los_angeles_time = datetime.now(los_angeles)
    utc_time = datetime.now(utc)
    # print("UTC Time", utc_time)
    # print("Europe/Paris", paris_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("Europe/Berlin", berlin_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("Asia/Tokyo", tokyo_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("America/New_York", new_york_time.strftime('%Y-%m-%d_%H-%M-%S'))
    # print("America/Los_Angeles", los_angeles_time.strftime('%Y-%m-%d_%H-%M-%S'))

    locale.setlocale(locale.LC_TIME, 'fr_FR')
    time_bound = gpx.get_time_bounds()
    #print("Old Timezone", time_bound.start_time.tzinfo)
    start_time = time_bound.start_time.astimezone(paris)
    #print("New Timezone", start_time.tzinfo)
    end_time = time_bound.end_time.astimezone(paris)
    day = start_time.strftime('%A %d %B %Y')
    hour = start_time.strftime('%Hh%M')
    elapsed_time = gpx.get_duration()
    distance2d = gpx.length_2d() / 1000
    distance3d = gpx.length_3d() / 1000
    duration_OK = True
    distance_OK = True
    amende = False
    exceeded_time = 0
    exceeded_distance = 0

    if d_runner > d_max:
        distance_OK = False
        exceeded_distance = d_runner - d_max
    if elapsed_time > 3600:
        duration_OK = False
        exceeded_time = elapsed_time - 3600

    if not (duration_OK and distance_OK):
        amende = True

    return day, hour, amende, distance3d, elapsed_time, distance_OK, duration_OK, exceeded_time, exceeded_distance