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 add_run(gpx, name,act_type,filename,polyline): conn = sqlite3.connect('%s/activities.db' % filebase) cursor = conn.cursor() cursor.execute("""CREATE TABLE if not exists activities (id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text, speed text, act_type text,filename text,polyline text)""") sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)" start_time, end_time = gpx.get_time_bounds() l2d='{:.3f}'.format(gpx.length_2d() / 1000.) moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data() print(max_speed) #print('%sStopped distance: %sm' % stopped_distance) maxspeed = 'Max speed: {:.2f}km/h'.format(max_speed * 60. ** 2 / 1000. if max_speed else 0) duration = '{:.2f}'.format(gpx.get_duration() / 60) print("-------------------------") print(name) print(start_time) print(l2d) print(maxspeed) print("-------------------------") try: cursor.execute(sql, [None, name,start_time,l2d,duration,act_type,filename,polyline]) conn.commit() except sqlite3.Error as er: print("-------------______---_____---___----____--____---___-----") print(er) conn.close()
def publish_stat(self, client, device, tracker, gpx): time_data = self.get_time_bounds(gpx) move_data = gpx.get_moving_data() move_time = (time_data.end_time - time_data.start_time).total_seconds() avg_speed = (move_data.moving_distance / move_time) if move_time != 0 else 0 self.load_counters() if device not in self.counters: self.counters[device] = {'odo': 0, 'engine_time': 0} self.counters[device]['odo'] = self.counters[device][ 'odo'] + move_data.moving_distance / 1000 self.counters[device]['engine_time'] = self.counters[device][ 'engine_time'] + move_time / 3600.0 self.store_counters() stat = { '_type': 'stat', 'move_time': move_time, 'avg_speed': avg_speed * 3.6, 'max_speed': move_data.max_speed * 3.6, 'distance': move_data.moving_distance / 1000 } stat.update(self.counters[device]) logging.info("Sendning stat for device:%s %s", device, json.dumps(stat)) client.publish('owntracks/%s/%s/stat' % (device, tracker), json.dumps(stat), retain=True) pass
def add_run(gpx, name, act_type, filename, polyline): conn = sqlite3.connect("%s/activities.db" % filebase) cursor = conn.cursor() cursor.execute( """CREATE TABLE if not exists activities (id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text, speed text, act_type text,filename text,polyline text)""" ) sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)" start_time, end_time = gpx.get_time_bounds() l2d = "{:.3f}".format(gpx.length_2d() / 1000.0) moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data() print(max_speed) # print('%sStopped distance: %sm' % stopped_distance) maxspeed = "Max speed: {:.2f}km/h".format(max_speed * 60.0 ** 2 / 1000.0 if max_speed else 0) duration = "Duration: {:.2f}min".format(gpx.get_duration() / 60) print("-------------------------") print(name) print(start_time) print(l2d) print(maxspeed) print("-------------------------") try: cursor.execute(sql, [None, name, start_time, l2d, duration, act_type, filename, polyline]) conn.commit() except sqlite3.Error as er: print(er) conn.close()
def get_data(): moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data() return moving_distance, moving_time
import gpxpy import gpxpy.gpx from geopy.distance import vincenty gpx_file = open('data\CAStd_116.gpx', 'r+') gpx = gpxpy.parse(gpx_file) gpx_file.close() print('time_data/n', gpx.get_moving_data()) gpx_file1 = open('data\CAStd_116_out.gpx', "w") #打开文件,进行写操作 out = gpxpy.gpx.GPX() #分割 def splite(start, avg, seg, new_trk): i_p = 0 pre_point = None new_seg = gpxpy.gpx.GPXTrackSegment() for point in seg.points[start:]: i_p += 1 #访问到segment.points中第几个point index = i_p + start #判断distance if point.time: if pre_point: newport_ri = (point.latitude, point.longitude) distance = vincenty(pre_point, newport_ri).meters if distance > avg: # 出口1:查出不合格的distance,将当前new_seg加入
def main(): """Run the main programme.""" parser = setup_argparser() args = parser.parse_args() if args.plot_all: args.plot_heart_rate = True args.plot_speed = True args.plot_cadence = True args.show_summary = True gpx = get_gpx(args.filename, args.quiet) (track, data) = parse_gpx(gpx) duration = gpx.get_moving_data().moving_time distance = gpx.get_moving_data().moving_distance average_speed = distance / duration butterworth_filter = get_filter(average_speed) elevations_filtered = signal.filtfilt(butterworth_filter[0], butterworth_filter[1], data["elevations"]) gradient = np.diff(elevations_filtered) zero_crossings = np.where(np.diff(np.sign(gradient)))[0] markers = np.insert(zero_crossings, 0, 0) markers = np.append(markers, len(data["elevations"]) - 1) if not args.quiet: print("Calculating metrics") metrics = calculate_metrics(markers, data) summary = calculate_summary(data, metrics) if not args.quiet: print("Plotting") if args.plot_heart_rate and not data["heart_rates"]: print( "WARNING: Heart rate plot requested but no heart rate data could be found", file=sys.stderr) if args.plot_cadence and not data["cadences"]: print( "WARNING: Cadence plot requested but no cadence data could be found", file=sys.stderr) # https://www.codecademy.com/articles/seaborn-design-i sns.set_style(style="ticks", rc={"grid.linestyle": "--"}) sns.set_context(rc={"grid.linewidth": 0.3}) (_blue, orange, green, red, purple, _brown, _magenta, _grey, yellow, cyan) = sns.color_palette("deep") if args.interactive_plot: plt.ion() else: plt.ioff() (fig, (ax_elevation, ax_speed, ax_hr, ax_pedaling)) = get_figure(args, data["heart_rates"], data["cadences"]) axes = tuple( [a for a in (ax_elevation, ax_speed, ax_hr, ax_pedaling) if a]) plot_elevation(ax_elevation, data["cumulative_distances"], data["elevations"], elevations_filtered, gradient, summary, green, [yellow, orange, red]) ax_grade = ax_elevation.twinx() plot_grades(ax_grade, data["cumulative_distances"], metrics["grades"], orange) handles_ax_grade, legend_ax_grade = ax_grade.get_legend_handles_labels() # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot ax_grade.legend(handles_ax_grade, legend_ax_grade, loc="upper right", fontsize=_FONT_SIZE) if ax_speed: plot_speed(ax_speed, data["cumulative_distances"], metrics["speed_averages"], data["speed"], cyan) if ax_hr: plot_hr(ax_hr, data["cumulative_distances"], metrics["heart_rate_averages"], data["heart_rates"], red) if ax_pedaling: plot_pedaling(ax_pedaling, data["cumulative_distances"], metrics["cadence_percentages"], data["cadences"], purple) bottom_axis = axes[-1] bottom_axis.xaxis.set_major_formatter(ticker.ScalarFormatter()) bottom_axis.set_xlabel("Distance (km)", fontsize=_FONT_SIZE) fig.align_ylabels(axes) if track.name: # https://stackoverflow.com/questions/1111317/how-do-i-print-a-python-datetime-in-the-local-timezone # assume the gpx time is always UTC start_time = track.get_time_bounds().start_time.astimezone( get_localzone()) fig.suptitle("{name} on {date} at {time}".format( name=track.name.strip(), date=start_time.date(), time=start_time.time().strftime("%H:%M"))) # https://stackoverflow.com/questions/2507726/how-to-display-locale-sensitive-time-format-without-seconds-in-python # fig.suptitle("{name} on {date} at {time}".format(name=track.name.strip(), # date=start_time.date().strftime("%x"), # time=start_time.time().strftime("%X"))) save_figure(fig, args) if args.interactive_plot: plt.show() input("Press any key to quit ...") plt.close() if args.show_summary: print_summary(summary)
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 "?") 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"
def get_data(): moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data( ) return moving_distance, moving_time
import gpxpy import gpxpy.gpx from geopy.distance import vincenty gpx_file=open('data\CAStd_116.gpx','r+') gpx=gpxpy.parse(gpx_file) gpx_file.close() print('time_data/n',gpx.get_moving_data()) gpx_file1=open('data\CAStd_116_out.gpx', "w") #打开文件,进行写操作 out=gpxpy.gpx.GPX() #分割 def splite(start,avg,seg,new_trk): i_p=0 pre_point=None new_seg=gpxpy.gpx.GPXTrackSegment() for point in seg.points[start:]: i_p+=1 #访问到segment.points中第几个point index = i_p+start #判断distance if point.time: if pre_point: newport_ri = (point.latitude, point.longitude)
def getalldata(filepath): gpx_file = open(filepath, 'r') gpx = gpxpy.parse(gpx_file) moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data( ) dist_pace_calc = 0 dist_split_calc = 0 split_distance = 0 split_pace = [] split_dist = [] graph_distance = 0 graph_speed = [] graph_dist = [] all_pace = [] all_elev = [] all_points_x = [] all_points_y = [] dist_bw_pts = [] all_hr = [] def_origin = 1 # Get all x,y points and speed for track in gpx.tracks: for segment in track.segments: for point_no, point in enumerate(segment.points): pointxy = to_xy((point.latitude, point.longitude), r, math.sin(math.radians(point.longitude))) if def_origin: origin = pointxy origin_latlong = point prev_point_graph = origin_latlong prev_point_split = origin_latlong start_point = point def_origin = 0 else: end_point = point dist_from_prev = gpxpy.geo.distance( segment.points[point_no - 1].latitude, segment.points[point_no - 1].longitude, segment.points[point_no - 1].elevation, point.latitude, point.longitude, point.elevation, haversine=True) dist_bw_pts.append(dist_from_prev) dist_pace_calc = dist_pace_calc + dist_from_prev dist_split_calc = dist_split_calc + dist_from_prev time_diff = get_time_diff(segment.points[point_no - 1], point, 's') all_pace.append(mydiv(time_diff, dist_from_prev)) all_elev.append(point.elevation) all_points_x.append(pointxy[0] - origin[0]) all_points_y.append(pointxy[1] - origin[1]) if dist_pace_calc > DIST_BETWEEN_PACE: graph_distance = graph_distance + dist_pace_calc time_diff = get_time_diff(prev_point_graph, point, 's') m_per_s = mydiv(dist_pace_calc, time_diff) graph_speed.append(m_per_s) graph_dist.append(graph_distance) dist_pace_calc = 0 prev_point_graph = point if dist_split_calc > SPLIT_DIST_M: split_distance = split_distance + dist_split_calc time_diff = get_time_diff(prev_point_split, point, 'min') min_per_selected_split = mydiv( time_diff, (dist_split_calc / M_IN_KM)) split_pace.append(min_per_selected_split) split_dist.append(split_distance) dist_split_calc = 0 prev_point_split = point for ext in point.extensions: for child in ext: if 'hr' in child.tag: all_hr.append(int(child.text)) total_time = ( moving_time + stopped_time ) / SECONDS_IN_MINUTE #get_time_diff(start_point, end_point, 'min') ret_dict = { 'all_pace': all_pace, 'all_elev': all_elev, 'all_hr': all_hr, 'all_dist': dist_bw_pts, 'graph_speed': graph_speed, 'graph_dist': graph_dist, 'split_pace': split_pace, 'split_dist': split_dist, 'all_x': all_points_x, 'all_y': all_points_y, 'total_time': total_time, 'moving_dist': moving_distance, 'moving_time': moving_time } return ret_dict