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/Trackpoint.pm »
1 package Geo::TCX::Track;
2 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '1.04';
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 7 ▶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_orig);
221  
222 for my $i (1 .. $n_points) {
223 my $pt = $orig_t->trackpoint($n_points - $i + 1)->clone;
224  
225 if ($i == 1) {
226 $pt->_reset_distance( 0 );
227 $pt->_reset_time( $orig_t->trackpoint(1)->Time )
228 } else {
229 $pt->_reset_distance( $previous_pt->DistanceMeters + $previous_pt_orig->distance_elapsed, $previous_pt );
230 $pt->_reset_time_from_epoch( $previous_pt->time_epoch + $previous_pt_orig->time_elapsed, $previous_pt)
231 }
232  
233 $previous_pt = $pt;
234 $previous_pt_orig = $orig_t->trackpoint($n_points - $i + 1)->clone;
235 # need copy of the original previous pt bcs elapsed fields of $pt got updated above
236 push @{$t->{Points}}, $pt
237 }
238 return $t
239 }
240  
241 =over 4
242  
243 =item clone()
244  
245 Returns a deep copy of a C<Geo::TCX::Track> instance.
246  
247 $c = $track->clone;
248  
249 =back
250  
251 =cut
252  
253 sub clone {
254 my $clone;
255 eval(Data::Dumper->Dump([ shift ], ['$clone']));
256 confess $@ if $@;
257 return $clone
258 }
259  
260 =head2 Object Methods
261  
262 =over 4
263  
264 =item trackpoint( # )
265  
266 returns the trackpoint object corresponding to trackpoint number I<#> for the track.
267  
268 I<#> is 1-indexed but C<-1>, C<-2>, …, still refer to the last, second to last, …, points respectively.
269  
270 =back
271  
272 =cut
273  
274 sub trackpoint {
275 my ($t, $point_i) = (shift, shift);
276 croak 'trackpoints are 1-indexed, point 0 does not exist' if $point_i eq 0;
277 croak 'requires a single integer as argument' if ! $point_i or @_;
278 $point_i-- if $point_i > 0; # 1-indexed but want -1 to still refer to last
279 return $t->{Points}[$point_i]
280 }
281  
282 =over 4
283  
284 =item trackpoints( qw/ # # ... / )
285  
286 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.
287  
288 =back
289  
290 =cut
291  
292 sub trackpoints {
293 my ($t, @point_list) = @_;
294 my $points = $t->{Points};
295 my @points;
296 if (@point_list) {
297 map --$_, @point_list; # decrement to get array indices
298 @points = @$points[@point_list];
299 } else { @points = @$points }
300 return @points
301 }
302  
303 =over 4
304  
305 =item distance_add( $meters )
306  
307 =item distance_subtract( $meters )
308  
309 =item distance_net()
310  
311 Add or subtract to the DistanceMeters field of all points in a Track. Does not impact any other fields of trackpoints. Return true.
312  
313 C<distance_net> is equivalent to C<< $t->distance_subtract( $t->trackpoint(1)->DistanceMeters - $t->trackpoint(1)->distance_elapsed ) >>.
314  
315 =back
316  
317 =cut
318  
319 sub distance_add {
320 my ($t, $meters) = (shift, shift);
321 for my $i (0 .. $#{$t->{Points}}) {
322 my $tp = $t->{Points}[$i];
323 $tp->_set_distance_keys( $tp->DistanceMeters + $meters )
324 }
325 return 1
326 }
327  
328 sub distance_subtract {
329 my ($t, $meters) = (shift, shift);
330 $t->distance_add( - $meters );
331 return 1
332 }
333  
334 sub distance_net {
335 my $t = shift;
336 my $tp1 = $t->trackpoint(1);
337 $t->distance_subtract( $tp1->DistanceMeters - $tp1->distance_elapsed );
338 return 1
339 }
340  
341 =over 4
342  
343 =item time_add( @duration )
344  
345 =item time_subtract( @duration )
346  
347 Perform L<DateTime> math on the timestamps of each trackpoint in the track by adding or subtracting the specified duration. Return true.
348  
349 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() >>.
350  
351 =back
352  
353 =cut
354  
355 sub time_add {
356 my $t = shift;
357 if (ref $_[0] and $_[0]->isa('DateTime::Duration') ) {
358 my $dur = shift;
359 $t->{Points}[$_]->time_add($dur) for (0 .. $#{$t->{Points}})
360 } else {
361 my @dur= @_;
362 $t->{Points}[$_]->time_add(@dur) for (0 .. $#{$t->{Points}})
363 }
364 return 1
365 }
366  
367 sub time_subtract {
368 my $t = shift;
369 if (ref $_[0] and $_[0]->isa('DateTime::Duration') ) {
370 my $dur = shift;
371 $t->{Points}[$_]->time_subtract($dur) for (0 .. $#{$t->{Points}})
372 } else {
373 my @dur= @_;
374 $t->{Points}[$_]->time_subtract(@dur) for (0 .. $#{$t->{Points}})
375 }
376 return 1
377 }
378  
379 =over 4
380  
381 =item point_closest_to( $point or $trackpoint )
382  
383 Takes any L<Geo::Gpx::Point> or L<Geo::TCX::Trackpoint> and returns the trackpoint that is closest to it on the track.
384  
385 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.
386  
387 =back
388  
389 =cut
390  
391 # ::Lap calls it by inheritance from Geo::TCX's split_at_point_closest_to()
392  
393 sub point_closest_to {
394 my ($t, $to_pt) = (shift, shift);
395 croak 'closest_to() expects a single argument' if @_;
396 my $class = ref( $to_pt );
397 unless ($class->isa('Geo::TCX::Trackpoint') or $class->isa('Geo::Gpx::Point')) {
398 croak 'point_closest_to() expects a Geo::TCX::Trackpoint of Geo::Gpx::Point as argument'
399 }
400  
401 my ($closest_pt, $min_dist, $pt_no);
402 for (0 .. $#{$t->{Points}}) {
403 my $pt = $t->{Points}[$_];
404 my $lat = $pt->LatitudeDegrees;
405 my $lon = $pt->LongitudeDegrees;
406 if (!$lat or !$lon) {
407 print "point number ", ($_ + 1), " doesn't have coordinates\n";
408 next
409 }
410 my $distance = $to_pt->distance_to( lat => $lat, lon => $lon );
411 $min_dist ||= $distance; # the first iteration
412 $closest_pt ||= $pt; # the first iteration
413 if ($distance < $min_dist) {
414 $closest_pt = $pt;
415 $min_dist = $distance;
416 $pt_no = $_ + 1
417 }
418 }
419 return ($closest_pt, $min_dist, $pt_no) if wantarray;
420 return $closest_pt
421 }
422  
423 =over 4
424  
425 =item xml_string( # )
426  
427 returns a string containing the XML representation of the object, equivalent to the string argument expected by C<new()>.
428  
429 =back
430  
431 =cut
432  
433 sub xml_string {
434 my $t = shift;
435 my %opts = @_;
436  
437 my $newline = $opts{indent} ? "\n" : '';
438 my $tab = $opts{indent} ? ' ' : '';
439 my $n_tabs = $opts{n_tabs} ? $opts{n_tabs} : 3;
440  
441 my $str .= $newline . $tab x $n_tabs . '<Track>';
442 # here, create a accessor that lists how many points there are in the track and do for my $i (1.. # of trackpoints)
443 for my $pt (@{$t->{Points}}) {
444 # looks like I coded this to ignore points without a Position as point 2014-08-11T10:25:40Z
445 # look into this
446 # next unless ($pt->LatitudeDegrees);
447 $str .= $pt->xml_string( indent => $opts{indent}, n_tabs => ($n_tabs + 1) )
448 }
449 $str .= $newline . $tab x $n_tabs . '</Track>';
450 return $str
451 }
452  
453 =over 4
454  
455 =item summ()
456  
457 For debugging purposes, summarizes the fields of the track by printing them to screen. Returns true.
458  
459 =back
460  
461 =cut
462  
463 sub summ {
464 my $t = shift;
465 croak 'summ() expects no arguments' if @_;
466 my %fields;
467 foreach my $key (keys %{$t}) {
468 print "$key: ", $t->{$key}, "\n"
469 }
470 return 1
471 }
472  
473 =head2 Overloaded Methods
474  
475 =over 4
476  
477 =item +
478  
479 merge two tracks by calling C<$track = $track1 + $track2>.
480  
481 =back
482  
483 =cut
484  
485 #
486 # internal methods
487  
488 sub _speed_meters_per_second {
489 my $t = shift;
490 my ($distance, $speed);
491 $distance = $t->trackpoint(-1)->DistanceMeters - $t->trackpoint(1)->DistanceMeters + $t->trackpoint(1)->distance_elapsed;
492 $speed = $distance / $t->_totalseconds;
493 return $speed
494 }
495  
496 sub _totalseconds {
497 my ($t, $totalseconds) = (shift, 0);
498 $totalseconds += $t->trackpoint($_)->time_elapsed for (1 .. $t->trackpoints);
499 return $totalseconds
500 }
501  
502 =head1 EXAMPLES
503  
504 Coming soon.
505  
506 =head1 AUTHOR
507  
508 Patrick Joly
509  
510 =head1 VERSION
511  
512 1.04
513  
514 =head1 SEE ALSO
515  
516 perl(1).
517  
518 =cut
519  
520 1;
521  
« blib/lib/Geo/TCX.pm ↑ Summary blib/lib/Geo/TCX/Trackpoint.pm »