30
Aerospace Applications of Perl Presented by Ian Kluft Silicon Valley Perl Santa Clara, California March 3, 2016

Aerospace applications of Perl

Embed Size (px)

Citation preview

Aerospace Applications of Perl

Presented by Ian KluftSilicon Valley Perl

Santa Clara, CaliforniaMarch 3, 2016

Aerospace Applications of Perl

● Perl and its libraries on CPAN are versatile● Aerospace applications cover lots of topics

– Navigation/mapping

– Aviation

– Satellites

– Astronomy

● Also some examples from my own projects

Introducing the presenter

● Hi! I'm Ian Kluft● From San Jose and a native

of the Bay Area● Software engineer

– Primarily Perl & C/C++ on servers & embedded/IoT

– Perl is my favorite language

● Currently working on my MBA

● Aerospace enthusiast– Commerical pilot & flight

instructor– Co-founder of Stratofox

Aerospace Tracking Team

– Participated in world records for amateur aerospace

● 1st amateur rocket launch to space (CSXT 2004, Nevada)

● 1st transcontinental/transoceanic Ham Radio balloon (CNSP 2011)

Navigation & Mapping

● I presented a year ago at SVPerl on Geographic Computation● Quick overview here because positioning is integral to

aerospace– Next 7 slides are a review from last year's presentation

● Then we'll move on to look at aviation, satellites & astronomy

Coordinate systemLatitude and longitude

● Any position on Earth has a coordinate● 3-dimensional positioning uses 3 numbers

– Latitude (north/south)

– Longitude (east/west)

– Altitude (relative to mean sea level/MSL)

● Latitude & longitude are specified in degrees● Altitude is specified in distance

Latitude and longitudeWhat kind of degrees?

● Not from a university● Not related to temperature● They are angles!● More precisely, angles from the

center of the Earth● Latitude = 0-90° up or down● Longitude = 0-180° either way

around

7

Earth is not a perfect sphere

● Earth is an ellipsoid: bulges out at equator– Centrifugal force from rotation causes this

● Geoid: mathematical models for Earth ellipsoid– Good models come from satellite measurement

● Coordinates must use the same geographic reference system– Otherwise comparing apples and oranges

– WGS84 most widely used coordinate system today

● Sea level and altitude are relative to this model

8

Lots of angles in Geospatial Data

● Many computations involve angles– Latitude and longitude are angles

● Manipulations use trigonometric functions● Trig functions use radians

– So numbers in degrees must be converted to and from radians

– One circle = 360 degrees = 2 * pi radians

– Radians derive 2 * pi from distance around circle relative to radius

● Math::Trig module on CPAN can do this for you

9

Great Circle Routes

● Great Circle: direct route over Earth's surface– Along a line that goes around

the sphere

– i.e. from San Jose to London crosses Greenland

– Flat-projection maps distort great circle routes to look like curves

Map generated by the Great Circle Mapper copyright © Karl L. Swartz. http://www.gcmap.com/

10

Great Circle Formulas

● See “Aviation Formulary” sitehttp://williams.best.vwh.net/avform.htm

● Distance between points● Course between points● Latitude of point on GC● Lat/lon given radial & dist● Intersection of 2 radials● Max latitude of a GC

● GC crossing a parallel● Intermediate points on a GC● Cross track error● Along track distance● Point known offset from GC

Many of these are in Math::Trig

11

Example: Great CircleDistance between points

● From scratch:

d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))

● In Perl:

use Math::Trig 'great_circle_distance';

$distance = great_circle_distance($lon1, $lat1, $lon2, $lat2, $radius);

● Convert angles to radians● For the radius of the Earth, use 6366.71 km

– Don't forget to convert result from km to miles if needed

12

Navigation related Perl modules

● Net::GPSD3 – connect to GPSD v3 server so multiple processes can use a single GPS on laptop, IoT, drone, etc

● Geo::Coder – use online search sites to look up address of current location

● Geo::Cache – Look up geocaching sites nearby● Ham::APRS::IS – receive Ham Radio APRS positioning data,

open-sourced by the APRS.FI Ham Radio tracking web site● Many more

13

Aviation applications

● Adding to the navigation/planning capabilities…● Geo::METAR – decode text from airport weather observations● Geo::TAF – decode text from airport weather forecasts● Geo::ICAO – encode/decode international airport codes● And other variants of these

14

Aviation example:METAR weather observation (1/5)

#!/usr/bin/perl

use strict;

use warnings;

use Getopt::Long;

use LWP::UserAgent;

use HTTP::Response;

use XML::Simple;

my $url = "http://www.aviationweather.noaa.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=%s&hoursBeforeNow=4";

my @metar_fields = qw(observation_time temp_c dewpoint_c wind_dir_degrees

wind_speed_kt wind_gust_kt visibility_statute_mi altim_in_hg

sea_level_pressure_mb three_hr_pressure_tendency_mb wx_string

sky_condition vert_vis_ft maxT_c minT_c maxT24hr_c minT24hr_c precip_in

pcp3hr_in pcp6hr_in pcp24hr_in snow_in quality_control_flags

flight_category

);

my $ua = LWP::UserAgent->new();

15

Aviation example: METAR weather observation (2/5)

# convert temperature C to C & F

sub tempC2CF

{

my ( $tempc ) = @_;

my $tempf = int($tempc * 9 / 5 + 32 + .5); # .5 = round off

return sprintf "%dC/%dF", $tempc, $tempf;

}

# turn a sky condition structure into a string

sub sky2str

{

my ( $sky ) = @_;

if ( ref $sky eq "ARRAY" ) {

# handle arrays of cloud layers by recursive calls

my @result;

foreach my $layer ( @$sky ) {

push @result, sky2str( $layer );

}

return join " ", @result;

}

# report cloud layer

return $sky->{sky_cover}."@".$sky->{cloud_base_ft_agl};

}

16

Aviation example:METAR weather observation (3/5)

# get_metar function - download METAR by airport code

sub get_metar

{

my ( $code ) = @_;

my $url_with_code = sprintf( $url, $code );

print $url_with_code."\n";

my $response = $ua->get( $url_with_code );

if ( $response->is_error()) {

printf "%s failed: %s\n", $code, $response->status_line;

} else {

my $content = $response->content();

my $metar_tree = XMLin( $content );

print "$code:\n";

if ((!exists $metar_tree→{data})or (!exists $metar_tree→})

or (!exists $metar_tree->{data}{METAR})) {

print "unrecognized data: $content\n";

} else {

my $metar_ref = $metar_tree->{data}{METAR};

foreach my $metar ( @$metar_ref ) {

foreach my $field ( @metar_fields ) {

if ( exists $metar->{$field}) {

if ( $field eq "observation_time" ) {

print $metar->{$field}." ";

} elsif ( $field eq "sky_condition" ) {

print "sky: ".sky2str($metar->{$field})." ";

} elsif ( $field =~ /^(.*)_c$/ ) {

my $name = $1;

print "$name:".tempC2CF($metar->{$field})." ";

} elsif ( $field =~ /^(.*)_(kt|statute_mi|in_hg|degrees)$/ ) {

my $name = $1; my $unit = $2;

print "$name:".$metar->{$field}."$unit ";

} else {

print "$field:".$metar->{$field}." ";

}

}

}

print "\n";

}

}

}

}

17

Aviation example:METAR weather observation (4/5)

# main - get airport codes from command line, loop through them and get METARs

my $arg;

foreach $arg ( @ARGV ) {

get_metar( $arg );

}

18

Aviation example:METAR weather observation (5/5)

● Example usage: get_metar KRHV

krhv:

2016-03-04T01:51:00Z temp:19C/66F dewpoint:14C/57F wind_dir:320degrees wind_speed:4kt visibility:10.0statute_mi altim:30.050198in_hg sky: OVC@5000 flight_category:VFR

2016-03-04T00:51:00Z temp:19C/66F dewpoint:14C/57F wind_dir:0degrees wind_speed:4kt visibility:10.0statute_mi altim:30.050198in_hg sky: OVC@3500 flight_category:VFR

2016-03-03T23:53:00Z temp:21C/70F dewpoint:13C/55F wind_dir:320degrees wind_speed:11kt visibility:10.0statute_mi altim:30.041338in_hg sky: BKN@4000 OVC@6000 flight_category:VFR

2016-03-03T22:53:00Z temp:22C/72F dewpoint:13C/55F wind_dir:0degrees wind_speed:4kt visibility:10.0statute_mi altim:30.059055in_hg sky: BKN@4000 OVC@6000 flight_category:VFR

19

Satellite tracking

● Why would you want to track a satellite?– See visible passes of International Space Station (or Iridium Flares),

nighttime only– Ham Radio communication via OSCARs (Orbiting Satellite Carrying

Amateur Radio), day or night– If you make a commercial or research satellite, you'll build your own

ground station, day or night

● Astro::SpaceTrack – downloads satellite orbital elements● Astro::satpass – makes satellite pass predictions● Astro::App::SatPass2 – makes satellite pass predictions

20

Astronomy

● Astro::Sunrise – compute sunrise/sunset for your location/date● Astro::MoonPhase – compute phase of the moon for a date● Astro::Telescope – for astronomers accessing remote

telescopes● Various celestial database searches

21

Example: Missing rocket payloadat Black Rock Desert

Location: Black Rock Desert, Nevada

Problem: Rocket launched, payload missing● Soka University (Japan) students needed data● Payload was a “CanSat”, size of a soda can● AeroPac club knew rocket landing coordinates● Turned to Stratofox Aerospace Tracking Team● Transmitter batteries died before they contacted us● I wrote a Perl script to generate a grid search

22

Perl Script to Plot Search Grid

● Search area was 3x3 mile parallelogram– Top/bottom side east-west for typical non-storm wind direction

– Right/left sides NNE/SSW for typical storm wind direction

● Each side divided into 10 sections, 1584' long● 10x10 loop projects each computed waypoint● Command-line controls output to text or GPX● “gpsbabel” open source utility turns GPX into many formats

– Raw Garmin waypoint data for upload to GPS

– KML for display on Google Earth

23

Projecting Search Grid Waypoints

● Nested loop: i = 0-10 over, j = 0-10 up● Over = 270° heading, up = 330° heading● Convert lat/lon from degrees to radians● Use Great Circle projection formula

– Compute intermediate point from i “over”

– Compute final point from j “up”

● Convert new lat/lon from radians to degrees● Code available at slideshare.com with slides

24

Sample codeconvert feet to radians

● Convert distance in feet to radians over Earth's surface● Radians are angles – this is a tiny angle from center of Earth# conversion: distance in feet to radians

sub dist_ft2rad

{

my $ft = shift;

my $km = $ft / 3280.8399; # ft/km

return $km/6371.0; # divide by FAI standard Earth radius in km

}

25

Sample codecompute waypoint from course & distance

sub gc_waypoint

{

my $lat1 = shift; # latitude (radians)

my $lon1 = shift; # longitude (radians)

my $tc = shift; # true course (radians)

my $d = shift; # distance (radians)

my $lat = asin(sin($lat1)*cos($d)+cos($lat1)*sin($d)*cos($tc));

my $dlon = atan2(sin($tc)*sin($d)*cos($lat1),cos($d)-sin($lat1)*sin($lat));

my $lon=fmod($lon1-$dlon+pi,2*pi) - pi;

return ( $lat, $lon ); # lat/lon in radians

}

26

Example codecompute coordinates of search grid point

# project a waypoint in the search area

# shape of a parallelogram with sides at headings 030 (NNE) and 090 (east)

# sides are on heading 1 (030 degrees) and heading 2 (090 degrees)

# increments are 0-10

# each increment is 1584 ft so that 10 of them is 3 miles

sub project_waypoint

{

my $h1_inc = shift;

my $h2_inc = shift;

# compute intermediate point on the first side of parallelogram

my ( $lat_r1, $lon_r1 ) = gc_waypoint (

deg2rad( $point_start[0]), deg2rad( $point_start[1]),

$h1_heading, $rad_per_increment * $h1_inc );

27

Example code (continued)compute coordinates of search grid point

# compute final projected waypoint in search area

my ( $lat_r2, $lon_r2 ) = gc_waypoint (

$lat_r1, $lon_r1,

$h2_heading, $rad_per_increment * $h2_inc );

# convert radians to degrees

my $lat = rad2deg( $lat_r2 );

my $lon = rad2deg( $lon_r2 );

return ( $lat, $lon );

}

28

Search Area Grid Map

Result of the script shown on Google Earth

29

Result: Success!!!

Expected to be worse than needle in a haystack

Payload found 2500' west of rocket landing site

30

Conclusions

● The sky is not the limit● You can have fun and learn a lot solving problems like these

Q & A