blib/lib/Geo/TCX/Track.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/Geo/TCX.pm ↑ Summary blib/lib/Geo/TCX/Lap.pm »
1 package Geo::TCX::Track;
2 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '1.00';
6  
7 =encoding utf-8
8  
9 =head1 NAME
10  
11 Geo::TCX::Track - Class to store and edit a TCX track and its trackpoints
12  
13 =head1 SYNOPSIS
14  
15 use Geo::TCX::Track;
16  
17 =head1 DESCRIPTION
18  
19 This package is mainly used by the L<Geo::TCX> module and serves little purpose on its own. The interface is documented mostly for the purpose of code maintainance.
20  
21 L<Geo::TCX::Track> provides a data structure for tracks in TCX files as well as methods to store, edit and obtain information from its trackpoints.
22  
23 =cut
24  
25 5 ▶use Geo::TCX::Trackpoint;
Subroutine BEGIN: called CC=1 SCAR=2.6
26 use Carp qw(confess croak cluck);
27 use Data::Dumper;
28 use overload '+' => \&merge;
29  
30 =head2 Constructor Methods (class)
31  
32 =over 4
33  
34 =item new( xml_string )
35  
36 takes an I<xml_string> in the form recorded by Garmin devices (and its TCX format) and returns a track object composed of various L<Geo::TCX::Trackpoint> objects.
37  
38 The string argument is expected to be flat i.e. no line breaks as per the example below.
39  
40 $xml_string = '<Track><Trackpoint><Time>2014-08-11T10:25:23Z</Time><Position><LatitudeDegrees>45.305054</LatitudeDegrees><LongitudeDegrees>-72.637287</LongitudeDegrees></Position><AltitudeMeters>210.963</AltitudeMeters><DistanceMeters>5.704</DistanceMeters><HeartRateBpm><Value>75</Value></HeartRateBpm></Trackpoint></Track>';
41  
42 $t = Geo::TCX::Track->new( $xml_string );
43  
44 =back
45  
46 =cut
47  
48 sub new {
49 my ($proto, $track_str, $previous_pt) = (shift, shift, shift);
50 if (ref $previous_pt) {
51 croak 'second argument must be a Trackpoint object' unless $previous_pt->isa('Geo::TCX::Trackpoint')
52 }
53 croak 'new() takes only one or two arguments' if @_;
54 my $class = ref($proto) || $proto;
55 my ($chomped_str, $t);
56 if ( $track_str =~ m,\s*^\<Track\>(.*)\</Track\>\s*$,gs ) {
57 $chomped_str = $1
58 } else { croak 'not a proper track string' }
59  
60 $t = {};
61 $t->{Points} = [];
62  
63 while ($chomped_str=~ m,(\<Trackpoint\>.*?\</Trackpoint\>),gs) {
64 my $pt = Geo::TCX::Trackpoint::Full->new($1, $previous_pt);
65 $previous_pt = $pt;
66 push @{$t->{Points}}, $pt
67 }
68 bless($t, $class);
69 return $t
70 }
71  
72 =head2 Constructor Methods (object)
73  
74 =over 4
75  
76 =item merge( $track, as_is => boolean, speed => value )
77  
78 Returns a new merged with the track specified in I<$track>.
79  
80 $merged = $track1->merge( $track2 );
81  
82 Adjustments for the C<DistanceMeters> and C<Time> fields of each trackpoint in the track are made unless C<as_is> is set to true.
83  
84 If a I<value> is passed to field C<speed>, that value will be used to ajust the time elapsed between the first point of the I<$track> and the last point of the track to be merged with. Otherwise the speed will be estimated based on the total distance and time elapsed of all the trackpoints in the I<$track>. C<speed> has not effect if C<as_is> is true.
85  
86 =back
87  
88 =cut
89  
90 sub merge {
91 my ($x, $y) = (shift, shift);
92 croak 'both operands must be Track objects' unless $y->isa('Geo::TCX::Track');
93 $x = $x->clone;
94 $y = $y->clone;
95 my %opts = @_; # option are as_is => boole and speed => value
96  
97 unless ($opts{as_is}) {
98 $opts{tolerance} ||= 50;
99  
100 my ($gap, $msg);
101 $gap = $x->trackpoint(-1)->distance_to( $y->trackpoint(1) );
102 $msg = 'distance between the two tracks to merge is ' . $gap . ' meters, which '
103 . 'is larger than the tolerance of ' . $opts{tolerance} . ' meters';
104 croak $msg if $gap > $opts{tolerance};
105  
106 #
107 # Distance: adjust DistanceMeters of all trackpoints, elapsed of just the 1st one
108 my $dist_to_add;
109 $dist_to_add = $x->trackpoint(-1)->DistanceMeters + $gap - $y->trackpoint(1)->distance_elapsed;
110  
111 $y->distance_net;
112 $y->distance_add( $dist_to_add );
113  
114 $y->trackpoint(1)->distance_elapsed( $gap, force => 1);
115  
116 #
117 # Time: adjust Time of all trackpoints, elapsed of just the 1st one
118  
119 my ($duration, $speed, $elapsed_t);
120 $duration = $y->trackpoint(1)->time_duration( $x->trackpoint(-1) );
121 $speed = $opts{speed} ? $opts{speed} : $y->_speed_meters_per_second;
122 $elapsed_t = sprintf '%.0f', $gap / $speed;
123  
124 $y->time_subtract( $duration );
125 $y->time_add( DateTime::Duration->new( seconds => $elapsed_t ));
126  
127 $y->trackpoint(1)->time_elapsed($elapsed_t, force => 1);
128  
129  
130 # my $epoch_gap = $x->trackpoint(-1)->time_epoch + $delay;
131 # my $delta_epoch = $epoch_gap - $y->trackpoint(1)->time_epoch;
132 #
133 # my $delta_dist = $x->trackpoint(1)->DistanceMeters;
134 # adjust DistanceMeters of x points, netting to 0 at point 1
135  
136 # now applying both the distance netting and delta_epoch to each y point
137 # for my $pt (@{$y->{Points}}) {
138 # my $epoch = $pt->time_epoch;
139 # $epoch += $delta_epoch;
140 # $pt->time_epoch( $epoch );
141 # $pt->DistanceMeters( $pt->DistanceMeters - $delta_dist );
142 # push @{$x->{Points}}, $pt
143 }
144  
145 my @points_to_merge = @{$y->{Points}};
146 for my $pt (@points_to_merge) {
147 push @{$x->{Points}}, $pt
148 }
149 return $x
150 }
151  
152 =over 4
153  
154 =item split( # )
155  
156 Returns a 2-element array of C<Geo::TCX::Track> objects with the first consisting of the track up to and including point number I<#> and the second consisting of the all trackpoints after that point.
157  
158 ($track1, $track2) = $merged->split( 45 );
159  
160 Will raise exception unless called in list context.
161  
162  
163 =back
164  
165 =cut
166  
167 sub split {
168 my ($t, $pt_no) = @_;
169 croak 'split() expects to be called in list context' unless wantarray;
170 my $n_pts = $t->trackpoints;
171 my ($t1, $t2) = ($t->clone, $t->clone);
172 my @slice1 = @ { $t1->{Points} } [0 .. $pt_no - 1];
173 my @slice2 = @ { $t1->{Points} } [$pt_no .. $n_pts- 1];
174 $t1->{Points} = \@slice1;
175 $t2->{Points} = \@slice2;
176 return $t1, $t2
177 }
178  
179 # keep undocumented for now, serves little purpose unless Lap.pm would want to call it directly, which it does not at this time.
180  
181 # =over 4
182 #
183 # =item split_at_point_closest_to( $point or $trackpoint or $coord_str )
184 #
185 # Equivalent to C<split()> but splits at the trackpoint that lies closest to a given L<Geo::Gpx::Point>, L<Geo::TCX::Trackpoint>, or a string that can be interpreted as coordinates by C<< Geo::Gpx::Point->flex_coordinates >>.
186 #
187 # =back
188 #
189 # =cut
190  
191 sub split_at_point_closest_to {
192 my ($t, $to_pt) = (shift, shift);
193 croak 'split() expects to be called in list context' unless wantarray;
194 croak 'split_at_point_closest_to() expects a single argument' if ! defined $to_pt or @_;
195 # can leverage most of the checks that will be done by point_closest_to
196 $to_pt = Geo::Gpx::Point->flex_coordinates( \$to_pt ) unless ref $to_pt;
197 my ($closest_pt, $min_dist, $pt_no) = $t->point_closest_to( $to_pt );
198 # here we can print some info about the original track and where it will be split
199 my ($t1, $t2) = $t->split( $pt_no );
200 return $t1, $t2
201 }
202  
203 =over 4
204  
205 =item reverse()
206  
207 Returns a clone of a track with the order of the trackpoints reversed.
208  
209 $reversed = $track->reverse;
210  
211 =back
212  
213 =cut
214  
215 sub reverse {
216 my $orig_t = shift;
217 my $t = $orig_t->clone;
218 my $n_points = $t->trackpoints;
219 $t->{Points} = [];
220 my ($previous_pt, $previous_pt_distance_elapsed, $previous_pt_time_elapsed);
221  
222 for my $i (1 .. $n_points) {
223 my $pt = $orig_t->trackpoint($n_points - $i + 1)->clone;
224 my $dist_meters;
225  
226 if ($i == 1) {
227 $dist_meters = 0;
228 $pt->time( $orig_t->trackpoint(1)->Time )
229 } else {
230 $dist_meters = $previous_pt->DistanceMeters + $previous_pt_distance_elapsed;
231 $pt->time_epoch( $previous_pt->time_epoch + $previous_pt_time_elapsed )
232 }
233 # we need to capture the following before they get modified by _set_* below
234 $previous_pt_distance_elapsed = $pt->distance_elapsed;
235 $previous_pt_time_elapsed = $pt->time_elapsed;
236  
237 $pt = $pt->_set_time( $pt->Time, $previous_pt );
238 $pt = $pt->_set_distance( $dist_meters, $previous_pt );
239 $previous_pt = $pt;
240 push @{$t->{Points}}, $pt
241 }
242 return $t
243 }
244  
245 =over 4
246  
247 =item clone()
248  
249 Returns a deep copy of a C<Geo::TCX::Track> instance.
250  
251 $c = $track->clone;
252  
253 =back
254  
255 =cut
256  
257 sub clone {
258 my $clone;
259 eval(Data::Dumper->Dump([ shift ], ['$clone']));
260 confess $@ if $@;
261 return $clone
262 }
263  
264 =head2 Object Methods
265  
266 =over 4
267  
268 =item trackpoint( # )
269  
270 returns the trackpoint object corresponding to trackpoint number I<#> for the track.
271  
272 I<#> is 1-indexed but C<-1>, C<-2>, …, still refer to the last, second to last, …, points respectively.
273  
274 =back
275  
276 =cut
277  
278 sub trackpoint {
279 my ($t, $point_i) = (shift, shift);
280 croak 'trackpoints are 1-indexed, point 0 does not exist' if $point_i eq 0;
281 croak 'requires a single integer as argument' if ! $point_i or @_;
282 $point_i-- if $point_i > 0; # 1-indexed but want -1 to still refer to last
283 return $t->{Points}[$point_i]
284 }
285  
286 =over 4
287  
288 =item trackpoints( qw/ # # ... / )
289  
290 returns an array of L<Geo::TCX::Trackpoint> objects for the number of points specified in list if specified, or all trackpoints if called without arguments.
291  
292 =back
293  
294 =cut
295  
296 sub trackpoints {
297 my ($t, @point_list) = @_;
298 my $points = $t->{Points};
299 my @points;
300 if (@point_list) {
301 map --$_, @point_list; # decrement to get array indices
302 @points = @$points[@point_list];
303 } else { @points = @$points }
304 return @points
305 }
306  
307 =over 4
308  
309 =item distance_add( $meters )
310  
311 =item distance_subtract( $meters )
312  
313 =item distance_net()
314  
315 Add or subtract to the DistanceMeters field of all points in a Track. Does not impact any other fields of trackpoints. Return true.
316  
317 C<distance_net> is equivalent to C<< $t->distance_subtract( $t->trackpoint(1)->DistanceMeters - $t->trackpoint(1)->distance_elapsed ) >>.
318  
319 =back
320  
321 =cut
322  
323 sub distance_add {
324 my ($t, $meters) = (shift, shift);
325 for my $i (0 .. $#{$t->{Points}}) {
326 my $tp = $t->{Points}[$i];
327 $tp->distance( $tp->DistanceMeters + $meters )
328 }
329 return 1
330 }
331  
332 sub distance_subtract {
333 my ($t, $meters) = (shift, shift);
334 $t->distance_add( - $meters );
335 return 1
336 }
337  
338 sub distance_net {
339 my $t = shift;
340 my $tp1 = $t->trackpoint(1);
341 $t->distance_subtract( $tp1->DistanceMeters - $tp1->distance_elapsed );
342 return 1
343 }
344  
345 =over 4
346  
347 =item time_add( @duration )
348  
349 =item time_subtract( @duration )
350  
351 Perform L<DateTime> math on the timestamps of each trackpoint in the track by adding or subtracting the specified duration. Return true.
352  
353 The duration can be provided as an actual L<DateTime::Duration> object or an array of arguments as per the syntax of L<DateTime>'s C<add()> or C<subtract()> methods. See the pod for C<< Geo::TCX::Trackpoint->time_add() >>.
354  
355 =back
356  
357 =cut
358  
359 sub time_add {
360 my $t = shift;
361 if (ref $_[0] and $_[0]->isa('DateTime::Duration') ) {
362 my $dur = shift;
363 $t->{Points}[$_]->time_add($dur) for (0 .. $#{$t->{Points}})
364 } else {
365 my @dur= @_;
366 $t->{Points}[$_]->time_add(@dur) for (0 .. $#{$t->{Points}})
367 }
368 return 1
369 }
370  
371 sub time_subtract {
372 my $t = shift;
373 if (ref $_[0] and $_[0]->isa('DateTime::Duration') ) {
374 my $dur = shift;
375 $t->{Points}[$_]->time_subtract($dur) for (0 .. $#{$t->{Points}})
376 } else {
377 my @dur= @_;
378 $t->{Points}[$_]->time_subtract(@dur) for (0 .. $#{$t->{Points}})
379 }
380 return 1
381 }
382  
383 =over 4
384  
385 =item point_closest_to( $point or $trackpoint )
386  
387 Takes any L<Geo::Gpx::Point> or L<Geo::TCX::Trackpoint> and returns the trackpoint that is closest to it on the track.
388  
389 If called in list context, returns a three element array consisting of the trackpoint, the distance from the coordinate to the trackpoint (in meters), and the point number of that trackpoint in the track.
390  
391 =back
392  
393 =cut
394  
395 # ::Lap calls it by inheritance from Geo::TCX's split_at_point_closest_to()
396  
397 sub point_closest_to {
398 my ($t, $to_pt) = (shift, shift);
399 croak 'closest_to() expects a single argument' if @_;
400 my $class = ref( $to_pt );
401 unless ($class->isa('Geo::TCX::Trackpoint') or $class->isa('Geo::Gpx::Point')) {
402 croak 'point_closest_to() expects a Geo::TCX::Trackpoint of Geo::Gpx::Point as argument'
403 }
404  
405 my $gc = $to_pt->to_geocalc;
406 my ($closest_pt, $min_dist, $pt_no);
407 for (0 .. $#{$t->{Points}}) {
408 my $pt = $t->{Points}[$_];
409 my $lat = $pt->LatitudeDegrees;
410 my $lon = $pt->LongitudeDegrees;
411 if (!$lat or !$lon) {
412 print "point number ", ($_ + 1), " doesn't have coordinates\n";
413 next
414 }
415 my $distance = $gc->distance_to({ lat => $lat, lon => $lon });
416 $min_dist ||= $distance; # the first iteration
417 $closest_pt ||= $pt; # the first iteration
418 if ($distance < $min_dist) {
419 $closest_pt = $pt;
420 $min_dist = $distance;
421 $pt_no = $_ + 1
422 }
423 }
424 return ($closest_pt, $min_dist, $pt_no) if wantarray;
425 return $closest_pt
426 }
427  
428 =over 4
429  
430 =item xml_string( # )
431  
432 returns a string containing the XML representation of the object, equivalent to the string argument expected by C<new()>.
433  
434 =back
435  
436 =cut
437  
438 sub xml_string {
439 my $t = shift;
440 my %opts = @_;
441  
442 my $newline = $opts{indent} ? "\n" : '';
443 my $tab = $opts{indent} ? ' ' : '';
444 my $n_tabs = $opts{n_tabs} ? $opts{n_tabs} : 3;
445  
446 my $str .= $newline . $tab x $n_tabs . '<Track>';
447 # here, create a accessor that lists how many points there are in the track and do for my $i (1.. # of trackpoints)
448 for my $pt (@{$t->{Points}}) {
449 # looks like I coded this to ignore points without a Position as point 2014-08-11T10:25:40Z
450 # look into this
451 # next unless ($pt->LatitudeDegrees);
452 $str .= $pt->xml_string( indent => $opts{indent}, n_tabs => ($n_tabs + 1) )
453 }
454 $str .= $newline . $tab x $n_tabs . '</Track>';
455 return $str
456 }
457  
458 =over 4
459  
460 =item summ()
461  
462 For debugging purposes, summarizes the fields of the track by printing them to screen. Returns true.
463  
464 =back
465  
466 =cut
467  
468 sub summ {
469 my $t = shift;
470 croak 'summ() expects no arguments' if @_;
471 my %fields;
472 foreach my $key (keys %{$t}) {
473 print "$key: ", $t->{$key}, "\n"
474 }
475 return 1
476 }
477  
478 =head2 Overloaded Methods
479  
480 =over 4
481  
482 =item +
483  
484 merge two tracks by calling C<$track = $track1 + $track2>.
485  
486 =back
487  
488 =cut
489  
490 #
491 # internal methods
492  
493 sub _speed_meters_per_second {
494 my $t = shift;
495 my ($distance, $speed);
496 $distance = $t->trackpoint(-1)->DistanceMeters - $t->trackpoint(1)->DistanceMeters + $t->trackpoint(1)->distance_elapsed;
497 $speed = $distance / $t->_totalseconds;
498 return $speed
499 }
500  
501 sub _totalseconds {
502 my ($t, $totalseconds) = (shift, 0);
503 $totalseconds += $t->trackpoint($_)->time_elapsed for (1 .. $t->trackpoints);
504 return $totalseconds
505 }
506  
507 =head1 EXAMPLES
508  
509 Coming soon.
510  
511 =head1 AUTHOR
512  
513 Patrick Joly
514  
515 =head1 VERSION
516  
517 1.00
518  
519 =head1 SEE ALSO
520  
521 perl(1).
522  
523 =cut
524  
525 1;
526  
« blib/lib/Geo/TCX.pm ↑ Summary blib/lib/Geo/TCX/Lap.pm »