Example #1
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
    """
Example #2
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()
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
Example #5
0
def gpxTracksTo45(gpx_content):
    gpx = gpxpy.parse(gpx_content)
    ecart45=0
    distance45=0
    breakpoint_lon=0
    wrongdir=False
    area=0
    temparea=0

    type_dict = {}
    pt_dict = {}
    prop_dict = {}

    version='20180109-a-3'
    now = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')

    # Process the total uphill/downhill elevation for the given track
    uphill, downhill = gpx.get_uphill_downhill()

    # initialize  a geo json dictionary to store result of the processing
    gjson_dict={}
    gjson_dict["type"]= "FeatureCollection"
    feat_list = []

    # Initialize a list to store all valid points to build a polygon for the area
    pointlist = []
    # Initialize a list to buffer point before calculating intermediate area
    templist = []

    # Need to determine overall direction (E->W is positive, W-> E is negative)
    # overall direction is determine by first and last point, regardless of the 
    # max or min longitude.
    # First determin first and last
    # Loop on all available points (WGS 84)
    for track in gpx.tracks:
        for segment in track.segments:
            previous = segment.points[0]
            firstpoint = previous
            for point in segment.points[1:]:
                 lastpoint = point
    # End looping on points in the tracks

    if (lastpoint.longitude-firstpoint.longitude) < 0:
	print 'Direction is East to West'
       	direction=1
    else: 
    	print 'Direction is West to East'
       	direction=-1

    # Loop on all available points (WGS 84)
    for track in gpx.tracks:
        print_gpx_part_info(track, indentation='        ')
        for segment in track.segments:
            # first point of track is always considered valid, will be used to 
            # determine the total distance projected on the 45 parralell
            previous = segment.points[0]
            firstpoint = previous
            # Add a marker for end of the actual track
            type_dict["type"]= "Feature"
            pt_dict["type"]="Point"
            type_dict["geometry"]=mapping(Point(firstpoint.longitude,firstpoint.latitude))
            prop_dict["name"]= 'start'
            prop_dict["popup"]='where the adventure started ...'
            prop_dict["marker"]='route_start'
            type_dict["properties"]=prop_dict
            feat_list.append(type_dict)
 
            lastpoint = previous

            # First point projected on the 45th line (will be used to build the line)
            pointzero = Point(firstpoint.longitude,45.0)
            pointlist.append(pointzero)
            pointlist.append(Point(firstpoint.longitude,firstpoint.latitude))
            templist.append(pointzero)
            templist.append(Point(firstpoint.longitude,firstpoint.latitude))

            for point in segment.points[1:]:
                # Discard point if going backward
                # Hopefully there won't be any track crossing lon 0 (which is the atlantic)

                if ((point.longitude - previous.longitude)*direction > 0) or ((point.longitude - breakpoint_lon)*direction > 0):
			# track is moving in the wrong direction 
			# or in the right direction but still not passed the breakpoint

                        if (wrongdir == False):
			                 breakpoint_lon = previous.longitude
                        wrongdir=True
                else:
                        wrongdir=False
                        # Check if segment is crossing the 45// ?
                        if ((lastpoint.latitude<45.0 and point.latitude >= 45.0) or (lastpoint.latitude>45.0 and point.latitude <= 45.0)):
                              print 'Crossing detected before: {:.7f}/{:.7f}  after {:.7f}/{:.7f} '.format(point.longitude,point.latitude,lastpoint.longitude,lastpoint.latitude)
                              # Set aside a polygon without intersection and calculate area
                              # first build a Point for the intersect on the 45
                              # use Thales to determine where segment cross the //
                              intersectlon=point.longitude-((point.longitude-lastpoint.longitude)*((45.0-point.latitude)/(lastpoint.latitude-point.latitude)))
                              print 'Crossing detected at longitude: {:.6f}'.format(intersectlon)
                              intersectpoint = Point(intersectlon,45.0)
                              templist.append(intersectpoint)
                              pointlist.append(Point(point.longitude,point.latitude))
    
                              # Build a polygon from the temporary list of points
                              temppoly=Polygon([[p.x, p.y] for p in templist])
                              temparea = getArea(temppoly)
                              print 'Buffering temprary area: {:.0f} m2'.format(temparea)
                              area = area + temparea
                              # reset templist
                              templist = []
                              templist.append(intersectpoint)
                              
                        # save current point in lastpoint
                        lastpoint = point
                        pointlist.append(Point(point.longitude,point.latitude))
                        templist.append(Point(point.longitude,point.latitude))
                previous=point

    # End looping on points in the track

    # Add a marker for end of the actual track
    type_dict = {}
    pt_dict = {}
    prop_dict = {}
    type_dict["type"]= "Feature"
    pt_dict["type"]="Point"
    type_dict["geometry"]=mapping(Point(lastpoint.longitude,lastpoint.latitude))
    prop_dict["name"]= 'end'
    prop_dict["popup"]='where the adventure ended ...'
    prop_dict["marker"]='route_end'
    type_dict["properties"]=prop_dict
    feat_list.append(type_dict)
 
    # Calculate distance from first to last (projected on the 45//)
    # Projection of the track on the 45//

    # Build a Point for the last point projected onthe 45
    thelastpoint = Point(lastpoint.longitude,45.0)
    pointlist.append(thelastpoint)
    templist.append(thelastpoint)
    # Build the latest polygon 
    temppoly=Polygon([[p.x, p.y] for p in templist])
    temparea = getArea(temppoly)
    print '(Last)Temp area to add: {:.0f} m2'.format(temparea)
    area = area + temparea
    
    #Build a polygon from the list of points
    newpoly=Polygon([[p.x, p.y] for p in pointlist])

    lastpoint.latitude=45.0
    firstpoint.latitude=45.0

    if firstpoint.time is None:
        starttime='no datetime<b>found within the track'
    else:
        starttime=firstpoint.time.strftime("%d %b %Y %H:%M")

    if lastpoint.time is None:
        endtime='no datetime<b>found within the track'
    else:
        endtime=lastpoint.time.strftime("%d %b %Y %H:%M")

    distance45 = lastpoint.distance_3d(firstpoint)
    ecart45 = getArea(newpoly)
    area_km2 = area / 1000000 
    # There is bonus for uphill gain
    score= ecart45/(distance45+(uphill*10))

    print 'ecart total={0} m2'.format(round(ecart45,0))
    print 'area total={0} m2'.format(round(area,0))
    print 'area total={0} km2'.format(round(area_km2,0))
    print 'distance={0:.0f} m'.format(round(distance45,0))
    print 'cumulative elevation gain={0} m'.format(round(uphill,0))
    print 'score={0}'.format(round(score,1))

    # Add two markers for start and end of the projected distance
    type_dict = {}
    pt_dict = {}
    prop_dict = {}
    type_dict["type"]= "Feature"
    pt_dict["type"]="Point"
    type_dict["geometry"]=mapping(thelastpoint)
    prop_dict["name"]= 'end'
    prop_dict["popup"]=endtime
    prop_dict["marker"]='marker45'
    type_dict["properties"]=prop_dict
    feat_list.append(type_dict)

    type_dict = {}
    pt_dict = {}
    prop_dict = {}
    type_dict["type"]= "Feature"
    pt_dict["type"]="Point"
    type_dict["geometry"]=mapping(pointzero)
    prop_dict["name"]= 'start'
    prop_dict["popup"]=starttime
    prop_dict["marker"]='marker45'
    type_dict["properties"]=prop_dict
    feat_list.append(type_dict)
 
    # Add a line in between the two markers
    type_dict = {}
    pt_dict = {}
    prop_dict = {}
    type_dict["type"]= "Feature"
    pt_dict["type"]="LineString"
    type_dict["geometry"]=mapping(LineString([pointzero,thelastpoint]))
    prop_dict["name"]= 'projection'
    prop_dict["popup"]= 'distance={0:.0f} m'.format(round(distance45,0))
    type_dict["properties"]=prop_dict
    feat_list.append(type_dict)

    # Add a polygon to delimit the area between track and the 45th line
    type_dict = {}
    pt_dict = {}
    prop_dict = {}
    type_dict["type"]= "Feature"
    pt_dict["type"]="Polygon"
    gjson_dict["features"] = feat_list
    type_dict["geometry"]=mapping(Polygon(newpoly))
    prop_dict["name"]= 'area'
    prop_dict["popup"]='<b>score={0:.0f} points</b><hr>surface={1:.0f} m2<br>distance={2:.0f} m<br>denivel&eacute;e={3:.0f} m<br><br><i>calculated on {4:}<br>[rev:{5:}]</i>'.format(round(score,0), round(ecart45,0),round(distance45,0),round(uphill,0),now,version)
    type_dict["properties"]=prop_dict
    feat_list.append(type_dict)

    return gjson_dict
Example #6
0
    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 "?")
    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)
    p.kill()
    sys.exit()