Browsed by
Category: Uncategorized

Mapping the World’s Flight Routes

Mapping the World’s Flight Routes

Why?

I find global flight path maps mesmerizing. In a single image these maps present the vastness of our interconnected civilization on a global scale. These maps are by no means rare. However, they can be a fun programing exercise to generate.

Where to get flight data?

OpenFlights.org has assembled several databases relate to air travel. Their database on air routes and airports provided the necessary information to determine flight paths. The database contains nearly 60,000 routes from 3200 airports.

Flight paths were colored based on the departure continent. To correlate the departure airport, with a depature continent, an ISO-3166 database was utilized.

The aforementioned datasets were assembled as MATLAB Tables for use by the plotting script.

The shapefile for the world map was obtained from ArcGIS.

How to calculate the flight path.

The great-circle is the shortest distance between any two points traveling along the surface of a sphere. The great-circle is defined as a circle centered on the centroid of the sphere and orientated such that the perimeter of the circle passes through the two locations. The arc defined by the great-circle provides the shortest travel route often used for long-distance air travel.

Algebraic formulas for calculating the great circle distance as well as latitude and longitude values of intermediate points along the arc can be found here: https://www.movable-type.co.uk/scripts/latlong.html

A MATLAB function for calculating the great circle distance as well as intermediate points along the route is included at the bottom of this article.

The result

The map below shows the results of this exercise.

 

Creating AVI Videos in MATLAB

Creating AVI Videos in MATLAB

This video will demonstrate how to make a simple AVI video file of a MATLAB plot.

The following functions will be essential for this tutorial:

  • VideoWriter – This function create the video file. The input to the function is the video name.
  • getFrame – This function captures the current state of the figure which is to be written as a frame to the video file.
  • writeVideo This function write the capture frame to the video file.

I will also persistent variables. Persistent variables are local variables within a function that are retained for subsequent function calls. Nested functions will also be employed. Nested functions can be a bit confusing at first to a novice. However, they are an excellent way to keep code clean. Nested functions also have access to the variables within their parent function and thus it is not necessary to pass them through as inputs.

Source Code for Simple Video

function Made_Video_of_Equation

%% Setup the figure size and frame rate
xPixels = 1280;
FPS = 30; % frames per second
Ratio = 16/9;
yPixels = xPixels/Ratio;
AVI_Name = 'Simple_Video.avi';

T_Span = 5;

%% Create the figure
f = figure();
set(f, 'Units', 'pixels', 'Resize', 'off',...
    'MenuBar', 'none', 'ToolBar', 'none');

% Figure location on the screen, can be larger than screen resolution
f.Position = [50 50 xPixels yPixels];
hold on;
xlim([0 5]);
ylim([-1 1]);
grid('on');
xlabel('Time (s)');
ylabel('Amplitude');

%% Now Let's Plot
zeta = 0.1;
omega = 2*pi;
alpha = omega*zeta;
gamma = omega*sqrt(1-zeta^2);

t = linspace(0,5,T_Span*FPS);
y = exp(-alpha*t).*(alpha*sin(gamma*t)./gamma + cos(gamma*t));

for Frame = 1:length(t)
    
    % Update objects within figure and plot
    UpdateFigure(Frame)
    
    % Grab the frame and add to avi
    if Frame ~= length(t)
        CreateAvi(false)
    else
        CreateAvi(true)
    end
    pause(1/FPS);
end
    function UpdateFigure(Frame)
        % Persistent variables are stored between function calls and are
        % accessible in subsequent calls
        persistent h
        if Frame == 1
            % First frame, create object handle
            h = plot(t(1:Frame), y(1:Frame), 'LineWidth', 4);
        else
            set(h, 'XData', t(1:Frame), 'YData', y(1:Frame));
            set(gca, 'FontSize',18,...
                'FontName', 'Times New Roman');
            set(findall(gca,'type','text'),'FontSize',18,...
                'FontName', 'Times New Roman');
        end
        
    end

    function CreateAvi(FinalFrame)
        persistent CreateAVIFile
        frame = getframe(f);
        % Create the video
        
        if isempty(CreateAVIFile)
            % Create and open file during first call
            CreateAVIFile = VideoWriter(AVI_Name, 'Motion JPEG AVI');
            CreateAVIFile.Quality = 100;
            CreateAVIFile.FrameRate = FPS;
            open(CreateAVIFile);
            writeVideo(CreateAVIFile,frame)
        elseif FinalFrame
            % Close avi file on final frame
            writeVideo(CreateAVIFile,frame)
            close(CreateAVIFile)
        else
            writeVideo(CreateAVIFile,frame)
            % Already created, do nothing
        end
    end

end

The type of videos one can create with MATLAB can be rather complex. The video below is a portion which was used to plot and track orbital debris in Earth orbit (debris not included in this snippet). The source code is included below the video file. Credit should be given to Ryan Gray for the snippet of code used to map the texture map to the globe. Keep in mind, due to the large size of the image used for the texture map, this video may take a while to render. Render time can be decreased by reducing the texture map image size.

Source Code for Globe Video
Globe_Files

Weather Forecast

Weather Forecast

Getting the Current Weather Conditions

First, we will start off by using the Weather API to get the current weather conditions. This data will be obtained in a json format and read with the webread function.

%% Get the current weather conditions
% Assemble the URL
% http://api.wunderground.com/api/{key}/conditions/q/CA/San_Francisco.json

CallURL_current = ['http://api.wunderground.com/api/', key,...
 '/conditions/q/', State, '/' City, '.json'];

% Grab the data from the API
Current_Data = webread(CallURL_current, options);

The webread function will return the data in a structure format. The current weather conditions are stored as strings and numbers, so some formatting is required:

%% Display the current information
disp(Current_Data.current_observation.display_location.full);
disp('Current Conditions');
disp([num2str(Current_Data.current_observation.temp_f, 3) char(176) 'F, ',...
 Current_Data.current_observation.relative_humidity ' Humidity, ',...
 Current_Data.current_observation.weather]);
disp(['Wind: ' Current_Data.current_observation.wind_string, char(10)]);

The previous code will write the current weather conditions to the display window in the following style:

Houghton, MI
Current Conditions
21.5°F, 88% Humidity, Snow
Wind: From the South at 7.0 MPH Gusting to 11.0 MPH

Getting the Forecast Conditions

Next, we will acquire forecasted weather conditions using the same API. The call url for the forecast will be slightly different from previously. This API will provide the weather forecast for the current plus next three days:

%% Get the forecast
% http://api.wunderground.com/api/{key}/forecast/q/CA/San_Francisco.json
CallURL_forecast = ['http://api.wunderground.com/api/', key,...
'/forecast/q/', State, '/' City, '.json'];

% Grab the data from the API
Forecast_Data = webread(CallURL_forecast, options);

disp('Forecast');
% Display Forecast
for ii = 1:8
disp(Forecast_Data.forecast.txt_forecast.forecastday(ii).title);
disp([strrep(Forecast_Data.forecast.txt_forecast.forecastday(ii).fcttext,...
'. ', char(10)) char(10)])
end

The previous code will provide the following output style:

Forecast
Wednesday
Occasional snow showers
High 27F
Winds SSW at 5 to 10 mph
Chance of snow 70%.

Wednesday Night
Snow this evening will transition to snow showers overnight
Low 26F
Winds W at 20 to 30 mph
Chance of snow 70%
About one inch of snow expected.

...

Saturday Night
Mainly cloudy with snow showers around before midnight
Low 14F
Winds WNW at 10 to 20 mph
Chance of snow 40%.

Current Radar Map

Now it is time to acquire the animated radar map. The map can be obtained in either a *.png, *.gif, or *.swf format. For this tutorial we will request the *.gif format so that we do not need to concern ourselves with making the animation. Matlab can play gif videos using the implay function. However, I find it easier to simply open the image with a web browser using the web function.

%% Get the radar data
CallURL_radar = ['http://api.wunderground.com/api/', key,...
 '/animatedradar/q/', State, '/' City,...
 '.gif?newmaps=1&timelabel=1&timelabel.y=10&num=5&delay=50',...
 '&width=600&height=480'];
web(CallURL_radar,'-new','-notoolbar');

The obtained radar for Houghton, MI on December 28th 2016 is:

 

Plotting the Forecast Conditions

Finally, using the forecast weather results, I will plot the high and low temperature as well as the icon describing the weather for each day. The forecast data structure contains a field for each day containing an icon name for each day. The Weather Underground API documentation contains a detailed list of the icon sets available and how to use them: https://www.wunderground.com/weather/api/d/docs?d=resources/icon-sets

I will not display the code to generate this plot.

Download the Code

I’ve uploaded the code for this work to the MATLAB file exchange. You can access the upload here: https://www.mathworks.com/matlabcentral/fileexchange/60935-get-current-weather-conditions