The Snippets repository contains a collection of snippets for different functionalities.
Please feel free to edit, modify and experiment with the code.
The code combines the Google Maps Directions API, GeoJSON data, and folium library to calculate and visualize routes between conflict zones and camps by the steps below:
- Imports necessary libraries: requests, json, folium, lru_cache from functools, and LineString from shapely.geometry. Defines the Google Maps Directions API key.
- Defines a function calculate_route that calculates the route between two locations using the Google Maps Directions API and caches the results using the LRU cache decorator.
- Reads location data from a CSV file, extracting conflict zone and camp locations into separate lists.
- Processes each conflict zone location and calculates routes to all other conflict zones and camps.
- Creates features for each route and adds them to a GeoJSON object.
- Prints the total number of coordinates in the GeoJSON file (excluding start/end) and the number of coordinates per route.
- Saves the GeoJSON object to a file named "routes.geojson".
- Reads the GeoJSON file and loads the data.
- Creates a folium Map object and adds PolyLine features for each route and CircleMarker features for conflict zones and camps.
- Saves the map as an HTML file named "map.html".
- Displays the map.
This snippet enhances the previous code by introducing parallel processing using the multiprocessing module to calculate routes more efficiently. It splits the location pairs into chunks and assigns them to multiple worker processes for concurrent processing. The results from all processes are combined to generate the final set of routes by the steps below:
- Imports necessary libraries: requests, json, folium, lru_cache from functools, LineString from shapely.geometry, and Pool, cpu_count from multiprocessing. Defines the Google Maps Directions API key.
- Creates a cache using the LRU cache decorator for route calculations.
- Defines a function calculate_route_for_pair to calculate the route for a given pair of locations.
- Reads location data from a CSV file, extracting conflict zone and camp locations into separate lists.
- Sets up variables and lists for multiprocessing calculations.
- Defines a function calculate_routes_batch to calculate routes for a batch of location pairs.
- Splits the location pairs into chunks for parallel processing.
- Creates a multiprocessing Pool and maps the chunks to worker processes to calculate routes in parallel.
- Flattens the results from all processes to obtain a list of routes.
- Adds the routes as features to a GeoJSON object.
- Saves the GeoJSON object to a file named "routes.geojson".
- Reads the GeoJSON file and loads the data.
- Creates a folium Map object and adds PolyLine features for each route and CircleMarker features for conflict zones and camps.
- Saves the map as an HTML file named "map.html".
- Displays the map.
This snippet is for creating conflict scenarios and analyzing their distribution over time. Here's a breakdown of the code:
- The code imports the necessary libraries: pandas, numpy, random, and matplotlib.pyplot.
- There is a custom function generate_conflict_zones_csv that generates a CSV file with all zeros. The function takes a filename, a list of conflict zones, and the simulation period as inputs. It creates a DataFrame with a column '#Days' representing the days and other columns for each conflict zone with all values set to zero. The DataFrame is then saved as a CSV file.
- There is a custom distribution function custom_distribution1 that calculates the conflict intensity values based on a Gaussian curve. It takes the x-axis values as input and computes the spreading factor using a Gaussian curve formula. It also adds random fluctuations to the spreading factor using np.random.normal. The function returns the conflict intensity values.
- The conflict_zones variable is a list of conflict zone names.
- The period variable specifies the simulation period, which is the total number of days.
- The generate_conflict_zones_csv function is called to create an initial CSV file with all zeros representing the conflict scenarios.
- The CSV file is read into a DataFrame using pd.read_csv.
- The x-axis values are generated using np.linspace from 0 to 731.
- The y-axis values are computed by calling the custom_distribution1 function with the x-axis values.
- Subplots are created using plt.subplots, and two axes objects ax1 and ax2 are obtained.
- The first subplot ax1 is used to plot the conflict distribution over time. The plot function is called on ax1 with the x-axis values and y-axis values. Titles, labels, and legends are set for this subplot.
- The y-axis values are converted to integers.
- The code iterates over each row in the DataFrame and modifies the values based on the assigned conflict counts from the y-axis values. It updates the row values until the assigned count for a conflict zone is reached.
- The modified rows are stored in a new DataFrame called modified_df.
- The sum of each row (excluding the '#Days' column) is computed using the sum function, and the result is stored in the sum_values variable.
- The second subplot ax2 is used to plot the summed values over time. The plot function is called on ax2 with the x-axis values and summed values. Titles, labels, and legends are set for this subplot.
- The modified DataFrame is written back to the CSV file, replacing the initial all-zeros file.
The code provided performs the following tasks:
- Imports the necessary libraries: pandas, numpy, random, matplotlib.pyplot, and date from datetime.
- Defines a custom function generate_conflict_zones_csv to generate a CSV file with all zeros based on the provided conflict zones and period.
- Defines two custom distribution functions: custom_distribution1 and custom_distribution2, which generate random numbers with variations based on specified parameters.
- Specifies the conflict zones as a list of strings.
- Specifies the simulation period as the number of days.
- Calls the generate_conflict_zones_csv function to create a CSV file named "modified-conflicts.csv" with all zeros.
- Reads the "modified-conflicts.csv" file into a DataFrame.
- Generates the x-axis values using np.linspace for the days passed since a specified start date and the remaining period.
- Generates the y-axis values using the custom distribution functions for the corresponding x-axis values.
- Combines the generated x-axis values and y-axis values into the arrays x and y.
- Creates subplots using plt.subplots and assigns the subplot axes to ax1 and ax2.
- Plots the graph of conflict distribution on ax1 using ax1.plot.
- Sets the titles, x-axis labels, and y-axis labels for the plots.
- Converts the y-axis values to integers.
- Modifies the rows of the DataFrame based on the generated y-axis values.
- Creates a new DataFrame modified_df with the modified rows.
- Computes the sum of each row (excluding the '#Days' column) using modified_df.iloc[:, 1:].sum(axis=1).
- Sets the maximum value for the y-axis in ax2 to the maximum value among the generated y-axis values and the summed values.
- Trims the x-axis values to match the length of the summed values.
- Plots the summed values on ax2.
- Writes the modified DataFrame to the CSV file "modified-conflicts.csv".
The code provided is responsible for finding routes between locations, creating a GeoJSON object, and displaying the locations and routes on a folium map. Here's a breakdown of the code:
- It begins by importing the necessary libraries, including pandas, requests, json, and LineString from shapely.geometry.
- The Google Maps Directions API key is stored in the API_KEY variable.
- The locations are read from the 'locations.csv' file using pd.read_csv('locations.csv') and stored in the DataFrame df.
- A cache is created using the route_cache dictionary to store route calculations and avoid redundant API calls.
- The calculate_route function is defined to calculate the route between two locations using the Google Maps Directions API. The function checks the cache first and returns the result if it exists, otherwise makes an API request and stores the result in the cache.
- The folium map object m is created, centered around the coordinates [49.0, 31.0] with a zoom level of 7.
- Variables num_locations_not_found and num_routes_not_found are initialized to track the number of locations and routes that are not found.
- The code iterates over the locations in the DataFrame df using nested loops, comparing origin and destination locations for routes.
- If the origin and destination are the same or have different location types, the iteration continues to the next location pair. 10 For each origin and destination pair, the calculate_route function is called to retrieve the route data.
- If the route is found (data['status'] == 'OK'), the route coordinates are extracted, a simplified LineString object is created, and the simplified coordinates are added to the features list as a GeoJSON feature.
- The simplified coordinates are also added as a PolyLine to the folium map, representing the route.
- If the route is not found, the num_routes_not_found variable is incremented.
- The code then prints the number of routes not found.
- The GeoJSON object is created using the features list.
- The GeoJSON is saved to a file named "routes.geojson".
- Markers for conflict zones, towns, and camps are added to the folium map.
- The folium map is saved as an HTML file.
- The folium map is displayed.