lib/Astro/MoonPhase/Simple.pm

filter: Statementstmt 45.5% 66 / 145 Branchbran 28.0% 23 / 82 Conditioncond 34.0% 16 / 47 MC/DCmcdc 13.7% 4 / 29 Subroutinesub 92.3% 12 / 13 Podpod 100% 1 / 1 totaltotal 38.4% 122 / 317 CC 59 SCAR 54.5
CC
59
Cov
38%
_parse_event
404.8
calculate_moon_phase
173.2
_event2str
20.0
CRAP 231.7
↑ Summary script/moon-phase-calculator.pl »
1 package Astro::MoonPhase::Simple;
2  
3 4 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use DateTime::Format::ISO8601;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use DateTime::TimeZone;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Data::Roundtrip qw/perl2dump no-unicode-escape-permanently/;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 ####
12 # Note that we require conditionally Geo::Location::TimeZone, see below
13 ####
14  
15 # the real heavy lifter!!! thank you :
16 4 ▶use Astro::MoonPhase;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 4 our $VERSION = '0.03';
19  
20 4 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 our (@EXPORT, @EXPORT_OK);
22  
23 4 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
24 4 @EXPORT_OK = ('calculate_moon_phase');
25 # nothing exported by default:
26 4 @EXPORT = ('calculate_moon_phase');
27 } # end BEGIN
28  
29 # The input is a HASHref consisting of
30 # date : the date of when you want to calculate the moon phase, YYYY-MM-DD
31 # time : optional time in hh:mm:ss
32 # timezone : optional timezone as a TZ identifier e.g. Africa/Abidjan
33 # location : optionally deduce timezone from location if above timezone is absent,
34 # it is a nameplace string, e.g. 'Abidjan'
35 # OR it is a HASHref with keys 'lat' and 'lon'
36 # verbosity: optionally specify a positive integer to increase verbosity, default is zero for no verbose messages (only errors and warnings)
37 # Returns:
38 # a hash with results including 'asString' which contains a string description of the results.
39 # or undef on failure
40 3 ▶sub calculate_moon_phase {
Subroutine calculate_moon_phase: called CC=29 SCAR=51.5
Pod documented
41 3 my $params = $_[0];
42 3 ▶ my $parent = ( caller(1) )[3] || "N/A";
Condition100%2/2
(caller 1)[3] || 'N/A'
l!l
12
MC/DC100%1/1
(caller 1)[3] || 'N/A'
(caller 1)[3]
Truth table100%2/2
A
A= (caller 1)[3]
Aresult
11
00
43 3 my $whoami = ( caller(0) )[3];
44  
45 3 ▶ if( ! defined($params) || ref($params) ne 'HASH' ){
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $params or ref $params ne "HASH") 1 2 3
Condition66%2/3
not defined $params or ref $params ne "HASH"
l!l&&r!l&&!r
102
MC/DC50%1/2
not defined $params or ref $params ne "HASH"
not defined $params ref $params ne "HASH"
Truth table66%2/3
not(A) or B
A= not defined $paramsB= ref $params ne "HASH"
ABresult
1X1
011
000
46 1 print STDERR "$whoami (via $parent) : parameters in the form of a HASHref are required.";
47 return undef
48 1 }
49 2 ▶ my $verbosity = exists($params->{'verbosity'}) && defined($params->{'verbosity'}) ? $params->{'verbosity'} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'verbosity'} && defined $params->{'verbosity'} ? : 2 0 2
Condition33%1/3
exists $params->{"verbosity"} and defined $params->{"verbosity"}
!ll&&!rl&&r
002
MC/DC0%0/2
exists $params->{"verbosity"} and defined $params->{"verbosity"}
exists $params->{"verbosity"} defined $params->{"verbosity"}
Truth table33%1/3
A and B
A= exists $params->{"verbosity"}B= defined $params->{"verbosity"}
ABresult
0X0
100
111
50  
51 2 ▶ if( exists($params->{'date'}) && defined($params->{'date'}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{'date'} and defined $params->{'date'}) { } 2 0 2
Condition33%1/3
exists $params->{"date"} and defined $params->{"date"}
!ll&&!rl&&r
002
MC/DC0%0/2
exists $params->{"date"} and defined $params->{"date"}
exists $params->{"date"} defined $params->{"date"}
Truth table33%1/3
A and B
A= exists $params->{"date"}B= defined $params->{"date"}
ABresult
0X0
100
111
52 2 ▶ if( $params->{'date'} !~ /^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/ ){
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"date"} =~ /^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/) 0 2 2
53 0 print STDERR "$whoami (via $parent) : parameter 'date' does not parse YYYY-MM-DD : ".$params->{'date'}."\n";
54 return undef
55 0 }
56 2 ▶ print STDOUT "$whoami (via $parent) : found parameter 'date' : '".$params->{'date'}."'.\n" if $verbosity > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 1 2 0 2
57 } else {
58 0 print STDERR "$whoami (via $parent) : parameter 'date' was not specified.\n";
59 return undef
60 0 }
61 2 ▶ if( exists($params->{'time'}) && defined($params->{'time'}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"time"} and defined $params->{"time"}) 1 1 2
Condition66%2/3
exists $params->{"time"} and defined $params->{"time"}
!ll&&!rl&&r
101
MC/DC50%1/2
exists $params->{"time"} and defined $params->{"time"}
exists $params->{"time"} defined $params->{"time"}
Truth table66%2/3
A and B
A= exists $params->{"time"}B= defined $params->{"time"}
ABresult
0X0
100
111
62 1 ▶ if( $params->{'time'} !~ /^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/ ){
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"time"} =~ /^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/) 0 1 1
63 0 print STDERR "$whoami (via $parent) : parameter 'time' does not parse hh:mm:ss : ".$params->{'time'}."\n";
64 return undef
65 0 }
66 1 ▶ print STDOUT "$whoami (via $parent) : found parameter 'time' : '".$params->{'time'}."'.\n" if $verbosity > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 1 1 0 1
67 }
68 2 ▶ if( exists($params->{'location'}) && defined($params->{'location'}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"location"} and defined $params->{"location"}) 1 1 2
Condition66%2/3
exists $params->{"location"} and defined $params->{"location"}
!ll&&!rl&&r
101
MC/DC50%1/2
exists $params->{"location"} and defined $params->{"location"}
exists $params->{"location"} defined $params->{"location"}
Truth table66%2/3
A and B
A= exists $params->{"location"}B= defined $params->{"location"}
ABresult
0X0
100
111
69 1 ▶ if( (ref($params->{'location'})eq'' && ($params->{'location'}=~/^[- a-zA-Z]+$/)) ){
Branch: 2 branches
BranchTrueFalseTotal
if (ref $params->{'location'} eq '' and $params->{'location'} =~ /^[- a-zA-Z]+$/) { } 0 1 1
elsif (ref $params->{'location'} eq 'HASH' and exists $params->{'location'}{'lon'} and exists $params->{'location'}{'lat'}) { } 1 0 1
Condition33%1/3
ref $params->{"location"} eq "" and $params->{"location"} =~ /^[- a-zA-Z]+$/
!ll&&!rl&&r
100
MC/DC0%0/2
ref $params->{"location"} eq "" and $params->{"location"} =~ /^[- a-zA-Z]+$/
ref $params->{"location"} eq "" $params->{"location"} =~ /^[- a-zA-Z]+$/
Truth table33%1/3
A and B
A= ref $params->{"location"} eq ""B= $params->{"location"} =~ /^[- a-zA-Z]+$/
ABresult
0X0
100
111
70 0 ▶ print STDOUT "$whoami (via $parent) : found parameter 'location' (as a nameplace) : '".$params->{'location'}."'\n" if $verbosity > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 1 0 0 0
71 ▶ } elsif( (ref($params->{'location'})eq'HASH' && exists($params->{'location'}->{'lon'}) && exists($params->{'location'}->{'lat'})) ){
Condition33%2/6
ref $params->{"location"} eq "HASH" and exists $params->{"location"}{"lon"} and exists $params->{"location"}{"lat"}
!ll&&!rl&&r
001
ref $params->{"location"} eq "HASH" and exists $params->{"location"}{"lon"}
!ll&&!rl&&r
001
MC/DC0%0/3
ref $params->{"location"} eq "HASH" and exists $params->{"location"}{"lon"} and exists $params->{"location"}{"lat"}
ref $params->{"location"} eq "HASH" exists $params->{"location"}{"lon"} exists $params->{"location"}{"lat"}
Truth table25%1/4
A and B and C
A= ref $params->{"location"} eq "HASH"B= exists $params->{"location"}{"lon"}C= exists $params->{"location"}{"lat"}
ABCresult
0XX0
10X0
1100
1111
72 1 ▶ print STDOUT "$whoami (via $parent) : found parameter 'location' (as coordinates) : '".perl2dump($params->{'location'})."'\n" if $verbosity > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 1 1 0 1
73 } else {
74 0 print STDERR "$whoami (via $parent) : parameter 'location' is not a string of a location name (e.g. London) or it is not a HASHref which contains the two keys 'lon' and 'lat' : ".perl2dump(\$params->{'location'})."\n";
75 return undef
76 0 }
77 }
78 2 ▶ if( exists($params->{'localtimezone'}) && defined($params->{'localtimezone'}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"localtimezone"} and defined $params->{"localtimezone"}) 0 2 2
Condition33%1/3
exists $params->{"localtimezone"} and defined $params->{"localtimezone"}
!ll&&!rl&&r
200
MC/DC0%0/2
exists $params->{"localtimezone"} and defined $params->{"localtimezone"}
exists $params->{"localtimezone"} defined $params->{"localtimezone"}
Truth table33%1/3
A and B
A= exists $params->{"localtimezone"}B= defined $params->{"localtimezone"}
ABresult
0X0
100
111
79 0 ▶ print STDOUT "$whoami (via $parent) : found parameter 'localtimezone' : '".$params->{'localtimezone'}."'.\n" if $verbosity > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 1 0 0 0
80 }
81  
82 2 my $parsed_results = _parse_event($params);
83 0 ▶ if( ! defined $parsed_results ){ print STDERR perl2dump($params)."$whoami (via $parent) : error, call to ".'_parse_event()'." has failed for above parameters.\n"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $parsed_results) 0 0 0
84 0 my $epoch = $parsed_results->{'localepoch'};
85  
86 0 ▶ print STDOUT _event2str($params)."\n$whoami (via $parent) : deduced epoch as '$epoch' for above parameters, now calling Astro::MoonPhase::phase() ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
87 if $verbosity > 0;
88  
89 0 my ( $MoonPhase,
90 $MoonIllum,
91 $MoonAge,
92 $MoonDist,
93 $MoonAng,
94 $SunDist,
95 $SunAng
96 ) = Astro::MoonPhase::phase($epoch);
97  
98 # the phases are unix epoch for each of the below moon phase names
99 # we are printing the date via DateTime on that epoch and adjusting for the timezone
100 # the user asked or UTC/or-local-see-below if none was specified.
101 # localtime() uses locale timezone or envvar TZ
102 # the DateTime as came from $parsed_results{'datetime'} knows the used timezone
103 # so we will use that same timezone.
104 #'New Moon' => scalar localtime($phases[0]), #<<< don't use this
105 0 my @phases = phasehunt($epoch);
106 0 my @phases_names = ('New Moon', 'First quarter', 'Full moon', 'Last quarter', 'Next New Moon');
107 0 my %phases = map { $phases_names[$_] => DateTime->from_epoch(epoch => $phases[$_], time_zone => $parsed_results->{'datetime'}->time_zone())->strftime('%a %b %d %T %Y') } 0..$#phases;
108  
109 0 my $outstr = "Moon age: $MoonAge days\n";
110 0 $outstr .= "Moon phase: " . sprintf("%.1f", 100.0*$MoonPhase) . " % of cycle (birth-to-death)\n";
111 0 $outstr .= "Moon's illuminated fraction: " . sprintf("%.1f", 100.0*$MoonIllum) . " % of full disc\n";
112 0 $outstr .= "important moon phases around specified date ".$params->{'date'}.":\n";
113  
114 0 $outstr .= sprintf(" %-14s= %s\n", $phases_names[$_], $phases{$phases_names[$_]}) for 0..$#phases;
115  
116 0 my %ret = (
117 'MoonPhase' => $MoonPhase,
118 'MoonPhase%' => 100.0*$MoonPhase,
119 'MoonIllum' => $MoonIllum,
120 'MoonIllum%' => 100.0*$MoonIllum,
121 'MoonAge' => $MoonAge,
122 'MoonDist' => $MoonDist,
123 'MoonAng' => $MoonAng,
124 'SunDist' => $SunDist,
125 'SunAng' => $SunAng,
126 'phases' => \%phases,
127 'asString' => $outstr,
128 );
129  
130 0 return \%ret;
131 }
132  
133 0 ▶sub _event2str {
Subroutine _event2str: not called CC=4 SCAR=30.0
134 0 my $params = shift;
135  
136 0 ▶ if( ! exists $params->{datetime} ){
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{"datetime"}) 0 0 0
137 0 return "event has not been parsed, just dumping it:\n".perl2dump($params);
138 }
139 my $str =
140 "Moon phase on ".$params->{datetime}
141 . " (".$params->{datetime}->epoch." seconds unix-epoch)"
142 . " timezone: ".$params->{datetime}->time_zone->name
143 0 ;
144 0 ▶ if( exists $params->{location} ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"location"}) 0 0 0
145 0 ▶ if( ref($params->{location}) eq 'HASH' ){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params->{'location'} eq 'HASH') { } 0 0 0
146 0 $str .= " (lat: ".$params->{location}->{lat}.", lon: ".$params->{location}->{lon}.")"
147 0 } else { $str .= "(".$params->{location}.")" }
148 }
149 0 return $str
150 }
151  
152 # it expects a HASHref of input parameters which contain:
153 # date : the date of when you want to calculate the moon phase, YYYY-MM-DD
154 # time : optional time in hh:mm:ss
155 # localtimezone : optional LOCAL timezone for making the corrections to the UTC-based epoch
156 #
157 # timezone : optional timezone as a TZ identifier e.g. Africa/Abidjan
158 # location : optionally deduce timezone from location if above timezone is absent,
159 # it is a nameplace string, e.g. 'Abidjan'
160 # OR it is a HASHref with keys 'lat' and 'lon'
161 # verbosity: optionally specify a positive integer to increase verbosity, default is zero for no verbose messages (only errors and warnings)
162 # On failure it returns undef
163 # On success it returns the input parameters HASH complemented with
164 # various calculated things, most useful of which is 'localepoch' (based on timezone and time, date of the input params)
165 # and also the DateTime object for calculating the above 'localepoch' under key: 'datetime'
166 2 ▶sub _parse_event {
Subroutine _parse_event: called CC=28 SCAR=60.0
167 2 my $_params = shift;
168  
169 # we are returning our input plus some more ...
170 2 my $params = { %$_params };
171  
172 2 ▶ my $verbosity = exists($params->{'verbosity'}) && defined($params->{'verbosity'}) ? $params->{'verbosity'} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'verbosity'} && defined $params->{'verbosity'} ? : 2 0 2
Condition33%1/3
exists $params->{"verbosity"} and defined $params->{"verbosity"}
!ll&&!rl&&r
002
MC/DC0%0/2
exists $params->{"verbosity"} and defined $params->{"verbosity"}
exists $params->{"verbosity"} defined $params->{"verbosity"}
Truth table33%1/3
A and B
A= exists $params->{"verbosity"}B= defined $params->{"verbosity"}
ABresult
0X0
100
111
173  
174 0 ▶ if( ! exists $params->{date} ){ print STDERR "_parse_event() : 'date' field is missing from params.\n"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params->{"date"}) 0 2 2
175  
176 2 my $datestr = $params->{date};
177  
178 2 my $timestr = "00:00:01";
179 2 ▶ if( exists $params->{time} ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{'time'}) { } 1 1 2
180 1 $timestr = $params->{time};
181 1 ▶ print "_parse_event(): setting time to '$timestr' ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 1 0 1
182 if $verbosity > 0;
183 0 ▶ if( $timestr !~ /^\d{2}:\d{2}:\d{2}$/ ){ print STDERR "_parse_event() : time '$timestr' is not valid, it must be in the form 'hh:mm:ss'.\n"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless ($timestr =~ /^\d{2}:\d{2}:\d{2}$/) 0 1 1
184 1 } else { $params->{time} = $timestr }
185  
186 # create the DateTime object but on UTC timezone,
187 # then we calculate the epoch (which is always UTC-based)
188 # then we add the timezone offset to that epoch
189 2 my $isostr = $datestr . 'T' . $timestr;
190 2 my $dt = eval { DateTime::Format::ISO8601->parse_datetime($isostr) };
191 0 ▶ if( ! defined($dt) || $@ ){ print STDERR "_parse_event() : failed to parse date '$isostr', check date and time fields.\n"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $dt or $@) 0 2 2
Condition33%1/3
not defined $dt or $@
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $dt or $@
not defined $dt $@
Truth table33%1/3
not(A) or B
A= not defined $dtB= $@
ABresult
1X1
011
000
192 2 $params->{datetime} = $dt;
193  
194 # our local timezone:
195 2 $params->{localtimezone} = DateTime::TimeZone->new( name => "local")->name();
196  
197 # this is the default timezone if user did not specify one
198 # DateTime::TimeZone->new( name => "local")->name();
199 # will print the local timezone if you want to set that
200 # but if you use local timezone then make sure that in the tests
201 # you always specify a location/timezone else some will fail!!!!!!!
202 # see https://rt.cpan.org/Ticket/Display.html?id=154400
203 # by using UTC, as default we are saying that if no location was specified
204 # then the user-specified times are in UTC
205 # but if we use that the tests break if test machine's local timezone is different
206 0 $dt->set_time_zone('UTC');
207 #$dt->set_time_zone($params->{localtimezone}); # make sure the tests don't break
208 #print "_parse_event(): found local timezone to be '".$params->{localtimezone}."' (this can be overriden by user) ...\n"
209 # if $verbosity > 2;
210  
211 0 my $tzstr = undef;
212 0 ▶ if( exists $params->{timezone} ){
Branch: 2 branches
BranchTrueFalseTotal
if (exists $params->{'timezone'}) { } 0 0 0
elsif (exists $params->{'location'}) { } 0 0 0
213 0 $tzstr = $params->{timezone};
214 0 ▶ print "_parse_event(): found a timezone via 'timezone' field as '$tzstr' (that does not mean it is valid) ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
215 if $verbosity > 0;
216 } elsif( exists $params->{location} ){
217 0 my $loc = $params->{location};
218 0 ▶ if( (ref($loc) eq '') && ($loc =~ /^[- a-zA-Z]+$/) ){
Branch: 2 branches
BranchTrueFalseTotal
if (ref $loc eq '' and $loc =~ /^[- a-zA-Z]+$/) { } 0 0 0
elsif (ref $loc eq 'HASH' and exists $loc->{'lat'} and exists $loc->{'lon'}) { } 0 0 0
Condition0%0/3
ref $loc eq "" and $loc =~ /^[- a-zA-Z]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
ref $loc eq "" and $loc =~ /^[- a-zA-Z]+$/
ref $loc eq "" $loc =~ /^[- a-zA-Z]+$/
Truth table0%0/3
A and B
A= ref $loc eq ""B= $loc =~ /^[- a-zA-Z]+$/
ABresult
0X0
100
111
219 # we have a location NAME string (like 'London')
220 0 my @alltzs = grep { m#/${loc}$#i } DateTime::TimeZone->all_names;
221 0 ▶ if( scalar(@alltzs) == 0 ){ print STDERR "_parse_event(): error, the timezone of specified nameplace '$loc' can not be deduced from the TZ identifiers. You can specify coordinates of the location or the timezone explicitly.\n"; return undef }
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @alltzs == 0) { } 0 0 0
elsif (scalar @alltzs > 1) { } 0 0 0
222 0 elsif( scalar(@alltzs) > 1 ){ print STDERR "_parse_event(): warning more than one timezones matched location nameplace '$loc': @alltzs. The first timezone will be used. If this is incorrect please specify the timezone explicitly, via the 'timezone' parameter.\n"; }
223 0 $tzstr = $alltzs[0];
224 0 ▶ print STDOUT "_parse_event(): setting timezone via 'location' nameplace to '$tzstr' ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
225 if $verbosity > 0;
226 ▶ } elsif( (ref($loc) eq 'HASH') && (exists $loc->{lat}) && (exists $loc->{lon}) ){
Condition0%0/6
ref $loc eq "HASH" and exists $loc->{"lat"} and exists $loc->{"lon"}
!ll&&!rl&&r
000
ref $loc eq "HASH" and exists $loc->{"lat"}
!ll&&!rl&&r
000
MC/DC0%0/3
ref $loc eq "HASH" and exists $loc->{"lat"} and exists $loc->{"lon"}
ref $loc eq "HASH" exists $loc->{"lat"} exists $loc->{"lon"}
Truth table0%0/4
A and B and C
A= ref $loc eq "HASH"B= exists $loc->{"lat"}C= exists $loc->{"lon"}
ABCresult
0XX0
10X0
1100
1111
227 # we have a [lat,lon] array for location
228 0 require Geo::Location::TimeZone;
229 0 my $gltzobj = Geo::Location::TimeZone->new();
230 0 $tzstr = $gltzobj->lookup(lat => $loc->{lat}, lon => $loc->{lon});
231 0 ▶ if( ! $tzstr ){ print STDERR "_parse_event() : timezone lookup from location coordinates lat:".$loc->{lat}.", lon:".$loc->{lon}." has failed.\n"; return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless ($tzstr) 0 0 0
232 0 ▶ print STDOUT "_parse_event(): setting timezone via 'location' coordinates lat:".$loc->{lat}.", lon:".$loc->{lon}." ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
233 if $verbosity > 0
234 }
235 }
236 0 my $localepoch = $dt->epoch; # this is UTC-based but the specified date+time has perhaps a timezone ...
237  
238 0 ▶ if( defined $tzstr ){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tzstr) 0 0 0
239 # the DateTime object now has the specified timezone
240 # but its epoch will still be UTC-based (as always) ...
241 # our "localepoch" is adjusted though, see below,
242 0 $dt->set_time_zone($tzstr);
243  
244 # we have a timezone, find the offset and add it to the epoch
245 0 ▶ print "_parse_event(): deduced timezone to '$tzstr' and adjusting epoch to it ...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
246 if $verbosity > 0;
247 0 my $tzobj = eval { DateTime::TimeZone->new( name => $tzstr ) };
248 0 ▶ if( ! defined($tzobj) || $@ ){
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $tzobj or $@) 0 0 0
Condition0%0/3
not defined $tzobj or $@
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $tzobj or $@
not defined $tzobj $@
Truth table0%0/3
not(A) or B
A= not defined $tzobjB= $@
ABresult
1X1
011
000
249 0 print STDERR "_parse_event(): failed to set the timezone '$tzstr', is it valid? : $@\n";
250 0 return undef;
251 }
252 0 my $offset = $tzobj->offset_for_datetime($dt);
253 # we should not change the DateTime, just our own 'localepoch'
254 #$dt->add(seconds => $offset);
255 0 $localepoch += $offset;
256 0 ▶ print STDOUT "_parse_event(): adjusted epoch for timezone '$tzstr' to $localepoch (offset of $offset).\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
257 if $verbosity > 0;
258 }
259 0 ▶ print STDOUT "DateTime: $dt\n(timezone: ".$dt->time_zone().")\n_parse_event(): above is the DateTime object for the moon phase calculations, with adjusted timezone.\n"
Branch: 1 branch
BranchTrueFalseTotal
if $verbosity > 0 0 0 0
260 if $verbosity > 0;
261 0 $params->{localepoch} = $dt->epoch;
262 # this is our input hash with added fields, the most important is 'localepoch'
263 # of the input date/time/timezone
264 0 return $params
265 }
266  
267  
268  
269 =pod
270  
271 =head1 NAME
272  
273 Astro::MoonPhase::Simple - Calculate the phase of the Moon on a given time without too much blah blah
274  
275 =head1 VERSION
276  
277 Version 0.03
278  
279  
280 =head1 SYNOPSIS
281  
282 This package provides a single subroutine to calculate the phase of the moon
283 on a given time. The results are returned as a hash.
284  
285 The heavy lifting is done by L<Astro::MoonPhase>. All this package does
286 is to wrap the functionality of L<Astro::MoonPhase> adding some parameter
287 checking.
288  
289 use Astro::MoonPhase::Simple;
290  
291 my $res = calculate_moon_phase({
292 'date' => '1974-07-15',
293 'timezone' => 'Asia/Nicosia',
294 });
295 print "moon is ".$res->{'MoonPhase%'}."% full\n";
296 print "moon is illuminated by ".$res->{'MoonIllum%'}."%\n";
297  
298 print $res->{'asString'};
299  
300 # alternatively provide location coordinates
301 # (instead of timezone) to deduce the timezone
302 my $res = calculate_moon_phase({
303 'date' => '1974-07-15',
304 'time' => '04:00',
305 'location' => {lat=>49.180000, lon=>-0.370000}
306 });
307  
308 # alternatively provide a nameplace instead of a timezone
309 # to deduce the timezone
310 my $res = calculate_moon_phase({
311 'date' => '1974-07-15',
312 'time' => '04:00',
313 'location' => 'Nicosia',
314 });
315  
316 ...
317  
318 =head1 EXPORT
319  
320 =over 2
321  
322 =item * C<calculate_moon_phase()>
323  
324 =back
325  
326 =head1 SUBROUTINES
327  
328 =head2 calculate_moon_phase
329  
330 This is the main and only subroutine which is
331 exported by default. It expects a HASH reference
332 as its input parameter containing C<date>, in the
333 form "YYYY-MM-DD", and optionally C<time>, in
334 the form "hh:mm:ss". The timezone the date is pertaining
335 to can be specified using key "timezone", in the form
336 of a TZ identifier, e.g. "Africa/Abidjan". Alternatively,
337 specify the location, as a HASHref of C<{lon, lat}>,
338 the moon is observed from and this
339 will deduce the timezone, albeit not always as accurately
340 as with specifying a "timezone" explicitly.
341  
342 Warning: if the caller does not specify a C<timezone> or C<location>
343 then the specified C<time> will be assumed to be B<UTC time> and not
344 at the local timezone of the host.
345  
346 L<Astro::MoonPhase> calculates the moon phase
347 given an I<epoch>. Which is the number of seconds
348 since 1970-01-01 B<on a UTC timezone>. This epoch
349 is corrected to a "I<localepoch>" by adding to it
350 the specific timezone offset. For example, if you
351 specified the timezone to be "China/Beijing" and
352 the local time (at the specified timezone) to be 23:00.
353 It means UTC time is 15:00. The epoch will be calculated
354 on UTC time. However, we add C<23:00-15:00=8:00> hours to
355 that epoch to make it "I<localepoch>" and this is
356 what we pass on to L<Astro::MoonPhase> to calculate
357 the moon phase.
358  
359 On failure it returns C<undef>.
360 On success it returns a HASHref with keys:
361  
362 =over 2
363  
364 =item * C<MoonPhase> : the moon phase (terminator phase angle) as a number between 0 and 1. New Moon (dark) being 0 and Full Moon (bright) being 1.
365  
366 =item * C<MoonPhase%> : the above as a percentage.
367  
368 =item * C<MoonIllum> : the illuminated fraction of the moon's disc as a number between 0 and 1. New Moon (dark) being 0 and Full Moon (bright) being 1.
369  
370 =item * C<MoonIllum%> : the above as a percentage.
371  
372 =item * C<MoonAge> : the fractional number of days since the Moon's birth (new moon), at specified date.
373  
374 =item * C<MoonDist> : the distance of the Moon from the centre of the Earth (kilometers).
375  
376 =item * C<MoonAng> : the angular diameter subtended by the Moon as seen by an observer at the centre of the Earth
377  
378 =item * C<SunDist> : Moon's distance from the Sun (kilometers).
379  
380 =item * C<SunAng> : the angular size of Sun (degrees).
381  
382 =item * C<phases> : a HASHref containing the date and time for the various Moon phases (at specified date). It contains keys C<New Moon, First quarter, Full moon, Last quarter, Next New Moon>
383  
384 =item * C<asString> : a string representation of the above.
385  
386 =back
387  
388 =head1 SCRIPT
389  
390 The script C<moon-phase-calculator.pl> is provided for doing
391 the calculations via the command line.
392  
393 Example usage: C<moon-phase-calculator.pl --date 1974-07-14 --timezone 'Asia/Nicosia'>
394  
395 =head1 SEE ALSO
396  
397 This package summarises the post and
398 discussion L<this post|https://perlmonks.org/?node_id=11137299>
399 over at PerlMonks.org
400  
401 There are some more goodies in that post e.g. PerlMonk Aldebaran provides
402 code for tracking the planets and at different altitudes.
403  
404 I can't iterate enough that this module wraps the
405 functionality of L<Astro::MoonPhase>.
406 L<Astro::MoonPhase> does all the heavy lifting.
407  
408 =head1 CAVEATS
409  
410 In L<calculate_moon_phase>, if the caller does not specify a C<timezone> or C<location>
411 then the specified C<time> will be assumed to be B<UTC time> and not
412 at the local timezone of the host.
413  
414  
415 =head1 AUTHOR
416  
417 Andreas Hadjiprocopis, C<< <bliako at cpan.org> >>
418  
419 =head1 DEDICATIONS
420  
421 Marathon Almaz
422  
423 =head1 BUGS
424  
425 Please report any bugs or feature requests to C<bug-astro-moonphase-simple at rt.cpan.org>, or through
426 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Astro-MoonPhase-Simple>. I will be notified, and then you'll
427 automatically be notified of progress on your bug as I make changes.
428  
429  
430  
431  
432 =head1 SUPPORT
433  
434 You can find documentation for this module with the perldoc command.
435  
436 perldoc Astro::MoonPhase::Simple
437  
438  
439 You can also look for information at:
440  
441 =over 4
442  
443 =item * RT: CPAN's request tracker (report bugs here)
444  
445 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Astro-MoonPhase-Simple>
446  
447 =item * Search CPAN
448  
449 L<https://metacpan.org/release/Astro-MoonPhase-Simple>
450  
451 =back
452  
453  
454 =head1 ACKNOWLEDGEMENTS
455  
456 The authors of L<Astro::MoonPhase> take all the credit.
457  
458  
459 =head1 LICENSE AND COPYRIGHT
460  
461 This software is Copyright (c) 2024 by Andreas Hadjiprocopis.
462  
463 This is free software, licensed under:
464  
465 The Artistic License 2.0 (GPL Compatible)
466  
467  
468 =cut
469  
470 4 1; # End of Astro::MoonPhase::Simple
↑ Summary script/moon-phase-calculator.pl »