CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
DanielBarnes18

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: DanielBarnes18/IBM-Data-Science-Professional-Certificate
Path: blob/main/10. Applied Data Science Capstone/04. Interactive Visual Analytics/04. Interactive Visual Analytics - Folium.ipynb
Views: 4598
Kernel: Python 3.8
cognitiveclass.ai logo

Launch Sites Locations Analysis with Folium

Estimated time needed: 40 minutes

The launch success rate may depend on many factors such as payload mass, orbit type, and so on. It may also depend on the location and proximities of a launch site, i.e., the initial position of rocket trajectories. Finding an optimal location for building a launch site certainly involves many factors and hopefully we could discover some of the factors by analyzing the existing launch site locations.

In the previous exploratory data analysis labs, you have visualized the SpaceX launch dataset using matplotlib and seaborn and discovered some preliminary correlations between the launch site and success rates. In this lab, you will be performing more interactive visual analytics using Folium.

Objectives

This lab contains the following tasks:

  • TASK 1: Mark all launch sites on a map

  • TASK 2: Mark the success/failed launches for each site on the map

  • TASK 3: Calculate the distances between a launch site to its proximities

After completed the above tasks, you should be able to find some geographical patterns about launch sites.

Let's first import required Python packages for this lab:

!pip3 install folium !pip3 install wget
Collecting folium Downloading folium-0.12.1.post1-py2.py3-none-any.whl (95 kB) ---------------------------------------- 95.0/95.0 KB 2.7 MB/s eta 0:00:00 Requirement already satisfied: numpy in c:\users\dan\anaconda3\lib\site-packages (from folium) (1.21.5) Collecting branca>=0.3.0 Downloading branca-0.4.2-py3-none-any.whl (24 kB) Requirement already satisfied: jinja2>=2.9 in c:\users\dan\anaconda3\lib\site-packages (from folium) (2.11.1) Requirement already satisfied: requests in c:\users\dan\anaconda3\lib\site-packages (from folium) (2.27.1) Requirement already satisfied: MarkupSafe>=0.23 in c:\users\dan\anaconda3\lib\site-packages (from jinja2>=2.9->folium) (1.1.1) Requirement already satisfied: idna<4,>=2.5 in c:\users\dan\anaconda3\lib\site-packages (from requests->folium) (2.8) Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\dan\anaconda3\lib\site-packages (from requests->folium) (1.25.8) Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\dan\anaconda3\lib\site-packages (from requests->folium) (2.0.11) Requirement already satisfied: certifi>=2017.4.17 in c:\users\dan\anaconda3\lib\site-packages (from requests->folium) (2019.11.28) Installing collected packages: branca, folium Successfully installed branca-0.4.2 folium-0.12.1.post1
WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: You are using pip version 22.0.3; however, version 22.0.4 is available. You should consider upgrading via the 'C:\Users\Dan\anaconda3\python.exe -m pip install --upgrade pip' command.
Requirement already satisfied: wget in c:\users\dan\anaconda3\lib\site-packages (3.2)
WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -umpy (c:\users\dan\anaconda3\lib\site-packages) WARNING: You are using pip version 22.0.3; however, version 22.0.4 is available. You should consider upgrading via the 'C:\Users\Dan\anaconda3\python.exe -m pip install --upgrade pip' command.
import folium import wget import pandas as pd
# Import folium MarkerCluster plugin from folium.plugins import MarkerCluster # Import folium MousePosition plugin from folium.plugins import MousePosition # Import folium DivIcon plugin from folium.features import DivIcon

If you need to refresh your memory about folium, you may download and refer to this previous folium lab:

Task 1: Mark all launch sites on a map

First, let's try to add each site's location on a map using site's latitude and longitude coordinates

The following dataset with the name spacex_launch_geo.csv is an augmented dataset with latitude and longitude added for each site.

# Download and read the `spacex_launch_geo.csv` spacex_csv_file = wget.download('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_geo.csv') spacex_df=pd.read_csv(spacex_csv_file)

Now, you can take a look at what are the coordinates for each site.

# Select relevant sub-columns: `Launch Site`, `Lat(Latitude)`, `Long(Longitude)`, `class` spacex_df = spacex_df[['Launch Site', 'Lat', 'Long', 'class']] launch_sites_df = spacex_df.groupby(['Launch Site'], as_index=False).first() launch_sites_df = launch_sites_df[['Launch Site', 'Lat', 'Long']] launch_sites_df

Above coordinates are just plain numbers that can not give you any intuitive insights about where are those launch sites. If you are very good at geography, you can interpret those numbers directly in your mind. If not, that's fine too. Let's visualize those locations by pinning them on a map.

We first need to create a folium Map object, with an initial center location to be NASA Johnson Space Center at Houston, Texas.

We can show a blue circle and a popup label for the NASA Johnson Space Center.

# Start location is NASA Johnson Space Center nasa_coordinate = [29.559684888503615, -95.0830971930759] #Initialise the map site_map = folium.Map(location=nasa_coordinate, zoom_start=12) #define the circle (blue circle at NASA JSC) nasa_circle = folium.Circle(nasa_coordinate, radius=1000, color='#001cd3', fill=True).add_child(folium.Popup('NASA Johnson Space Center')) #popup label of name #Add the NASA circle to the map site_map.add_child(nasa_circle) #show the map site_map

TODO: Create and add folium.Circle and folium.Marker for each launch site on the site map

An example of folium.Circle:

folium.Circle(coordinate, radius=1000, color='#000000', fill=True).add_child(folium.Popup(...))

An example of folium.Marker:

folium.map.Marker(coordinate, icon=DivIcon(icon_size=(20,20),icon_anchor=(0,0), html='<div style="font-size: 12; color:#d35400;"><b>%s</b></div>' % 'label', ))

# Initialise the map site_map = folium.Map(location=nasa_coordinate, zoom_start=5) # For each launch site, add a Circle object based on its coordinate (Lat, Long) values. # In addition, add Launch site name as a popup label for index, row in launch_sites_df.iterrows(): #define the position and name of sites lat = row['Lat'] long = row['Long'] launch_site = row['Launch Site'] #Define the Circle object circle = folium.Circle( #properties of circle (location, radius, color, fill) [lat, long], radius=50, color='#d35400', fill=True ).add_child(folium.Popup(launch_site)) #popup label of site name #Add the Circle objects to the map (in the loop) site_map.add_child(circle) site_map

Now, you can explore the map by zoom-in/out the marked areas , and try to answer the following questions:

  • Are all launch sites in proximity to the Equator line?

  • Are all launch sites in very close proximity to the coast?

Also please try to explain your findings.

Task 2: Mark the success/failed launches for each site on the map

Next, let's try to enhance the map by adding the launch outcomes for each site, and see which sites have high success rates. Recall that data frame spacex_df has detailed launch records, and the class column indicates if this launch was successful or not

spacex_df.tail(10)

Next, let's create markers for all launch records. If a launch was successful (class=1), then we use a green marker and if a launch was failed, we use a red marker (class=0)

Note that a launch only happens in one of the four launch sites, which means many launch records will have the exact same coordinate. Marker clusters can be a good way to simplify a map containing many markers having the same coordinate.

TODO: Create a new column in launch_sites dataframe called marker_color to store the marker colors based on the class value

# Function to assign color to launch outcome def assign_marker_color(launch_outcome): # If class=1, marker_color value will be green # If class=0, marker_color value will be red if launch_outcome == 1: return 'green' else: return 'red' spacex_df['marker_color'] = spacex_df['class'].apply(assign_marker_color) spacex_df.tail(10)

TODO: For each launch result in spacex_df data frame, add a folium.Marker to marker_cluster

#put launches into clusters and put onto map marker_cluster = MarkerCluster() site_map.add_child(marker_cluster) #note, this won't show up unless the individual launches are put onto the map (the next lines of code cover this) for index, row in spacex_df.iterrows(): #define the position and launch site for each launch lat = row['Lat'] long = row['Long'] launch_site = row['Launch Site'] #deine the launch marker for each launch launch_marker = folium.Marker( [lat, long], # Create an icon as a text label and colour depending on launch success/failure (marker colour) icon=folium.Icon(color='white', icon_color=row['marker_color']) ) # Add the launch marker for each launch to the launch clusters (not the map, the launch clusters themselves) marker_cluster.add_child(launch_marker) #show the map zoomed out with the centre at NASA site_map

From the color-labeled markers in marker clusters, you should be able to easily identify which launch sites have relatively high success rates.

TASK 3: Calculate the distances between a launch site to its proximities

Next, we need to explore and analyze the proximities of launch sites.

Let's first add a MousePosition on the map to get coordinate for a mouse over a point on the map. As such, while you are exploring the map, you can easily find the coordinates of any points of interests (such as railway)

# Add Mouse Position to get the coordinate (Lat, Long) for a mouse over on the map # (This is shown in the top right hand corner) formatter = "function(num) {return L.Util.formatNum(num, 5);};" mouse_position = MousePosition( position='topright', separator=' Long: ', empty_string='NaN', lng_first=False, num_digits=20, prefix='Lat:', lat_formatter=formatter, lng_formatter=formatter, ) site_map.add_child(mouse_position) site_map

Now zoom in to a launch site and explore its proximity to see if you can easily find any railway, highway, coastline, etc. Move your mouse to these points and mark down their coordinates (shown on the top-right) in order to the distance to the launch site.

You can calculate the distance between two points on the map based on their Lat and Long values using the following method:

from math import sin, cos, sqrt, atan2, radians def calculate_distance(lat1, lon1, lat2, lon2): # approximate radius of earth in km R = 6373.0 lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance

TODO: Mark down a point on the closest coastline using MousePosition and calculate the distance between the coastline point and the launch site.

# find coordinate of the closet coastline launch_site_lat = 28.56319 launch_site_long = -80.57683 launch_site_coordinates = [launch_site_lat, launch_site_long] coastline_lat = launch_site_lat #same latitude, so the line is directly east coastline_long = -80.56794 coastline_coordinates = [coastline_lat, coastline_long] distance_coastline = calculate_distance(launch_site_lat, launch_site_long, coastline_lat, coastline_long)
print(f"The coastline is {distance_coastline:.2f} km due East from the launch site")
The coastline is 0.87 km due East from the launch site

TODO: After obtained its coordinate, create a folium.Marker to show the distance

#define the distance marker (which will be shown at the coastline) distance_marker = folium.Marker( coastline_coordinates, icon=DivIcon( icon_size=(20,20), icon_anchor=(0,0), html='<div style="font-size: 12; color:#ff5c33;"><b>%s</b></div>' % "{:10.2f} KM".format(distance_coastline), ) ) #add the distance marker to the map and show the map site_map.add_child(distance_marker) site_map

TODO: Draw a PolyLine between a launch site to the selected coastline point

#define the distance line (between the coastline and the launch site) distance_line=folium.PolyLine( locations=[launch_site_coordinates, coastline_coordinates], weight=1 ) #add the distance line to the map and show the map site_map.add_child(distance_line) site_map

Your updated map with distance line should look like the following screenshot:

TODO: Similarly, you can draw a line betwee a launch site to its closest city, railway, highway, etc. You need to use MousePosition to find the their coordinates on the map first

A railway map symbol may look like this:

A highway map symbol may look like this:

A city map symbol may look like this:

def distance_and_line(destination_coordinates): # Create a marker with distance to a closest city, railway, highway, etc. # Draw a line between the marker to the launch site #calculate the distance between the chosen destination and the launch site defined previously, using the calculate_distance function distance_to_destination = calculate_distance(launch_site_lat, launch_site_long, destination_coordinates[0], destination_coordinates[1]) #define the distance marker (which will be shown at the chosen destination) distance_marker = folium.Marker( destination_coordinates, icon=DivIcon( icon_size=(20,20), icon_anchor=(0,0), html='<div style="font-size: 12; color:#ff5c33;"><b>%s</b></div>' % "{:10.2f} KM".format(distance_to_destination), ) ) #define the distance line (between the chosen destination and the launch site) distance_line=folium.PolyLine( locations=[launch_site_coordinates, destination_coordinates], weight=1 ) #add the distance marker to the map site_map.add_child(distance_marker) #add the distance line to the map site_map.add_child(distance_line) closest_city_coordinates = [28.10106, -80.6369] closest_railway_coordinates = [28.57208, -80.58528] closest_highway_coordinates = [28.56327, -80.57076] #add distance markers and lines for closest city, railway and highway, using the above function distance_and_line(closest_city_coordinates) distance_and_line(closest_railway_coordinates) distance_and_line(closest_highway_coordinates) #show the map site_map

After you plot distance lines to the proximities, you can answer the following questions easily:

  • Are launch sites in close proximity to railways?

  • Are launch sites in close proximity to highways?

  • Are launch sites in close proximity to coastline?

  • Do launch sites keep certain distance away from cities?

Also please try to explain your findings.

Next Steps:

Now you have discovered many interesting insights related to the launch sites' location using folium, in a very interactive way. Next, you will need to build a dashboard using Ploty Dash on detailed launch records.

Authors

Other Contributors

Joseph Santarcangelo

Change Log

Date (YYYY-MM-DD)VersionChanged ByChange Description
2021-05-261.0YanCreated the initial version

Copyright © 2021 IBM Corporation. All rights reserved.