import numpy as np import pandas as pd import pulp import itertools import gmplot import webbrowser import matplotlib.pyplot as plt # Set the file path for the Excel data excel_file_path = r'C:\Users\Administrateur\Desktop\PFE 2023\DATA\CS_DATA.xlsx' # Customer count ('0' is depot) cs = 10 # The number of vehicles v = 5 # The capacity of each vehicle Q = 100 # Maximum route length L = 400 # Fuel consumption rate when empty ρ0 = 0.165 # Fuel consumption rate when full ρ = 0.337 # Fuel consumption rate when idling ρidl = 0.05 # Conversion factor for fuel to CO2 emission η = 2.63 # Cost rate for CO2 emission ε = 0.025 # Cost rate for fuel p = 1.5 # Fixed Cost by vehicles f = 142.74 # Fix random seed np.random.seed(seed=777) # Set depot latitude and longitude depot_latitude = 45.9467803 depot_longitude = -71.9923369 # Read the customer data from the Excel file df = pd.read_excel(excel_file_path) # Set the depot as the center and make demand 0 ('0' = depot) df.iloc[0, df.columns.get_loc('latitude')] = depot_latitude df.iloc[0, df.columns.get_loc('longitude')] = depot_longitude df.iloc[0, df.columns.get_loc('waste_quantity')] = 0 df.iloc[0, df.columns.get_loc('service_time')] = 0 # Function for calculating distance between two locations using Haversine formula def haversine_distance(lat1, lon1, lat2, lon2): R = 6371.0 # Radius of the Earth in kilometers lat1_rad = np.radians(lat1) lon1_rad = np.radians(lon1) lat2_rad = np.radians(lat2) lon2_rad = np.radians(lon2) dlon = lon2_rad - lon1_rad dlat = lat2_rad - lat1_rad a = np.sin(dlat / 2)**2 + np.cos(lat1_rad) * np.cos(lat2_rad) * np.sin(dlon / 2)**2 c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) distance = R * c return distance # Function for calculating distance matrix between all locations def distance_calculator(_df): _distance_result = np.zeros((len(_df), len(_df))) for i in range(len(_df)): for j in range(len(_df)): if i != j: _distance_result[i][j] = haversine_distance( _df.at[i, 'latitude'], _df.at[i, 'longitude'], _df.at[j, 'latitude'], _df.at[j, 'longitude'] ) return _distance_result distance = distance_calculator(df) # Solve the CVRP for different vehicle counts for num_vehicles in range(1, v+1): # Definition of LpProblem instance problem = pulp.LpProblem("CVRP", pulp.LpMinimize) # Definition of variables which are 0/1 x = [[[pulp.LpVariable(f"x{i}_{j},{k}", cat="Binary") if i != j else None for k in range(num_vehicles)] for j in range(cs)] for i in range(cs)] service_time = df['service_time'].tolist() # Add objective function obj = ( pulp.lpSum( x[i][j][k] * distance[i][j] * ρ * p + x[i][j][k] * service_time[j] * ρidl * p + (ε * η) * (x[i][j][k] * distance[i][j] * ρ + x[i][j][k] * service_time[j] * ρidl) for i in range(cs) for j in range(cs) for k in range(num_vehicles) if i != j) + f * num_vehicles ) # Constraints # Each coffee shop must be visited once by a vehicle for j in range(1, cs): problem += pulp.lpSum(x[i][j][k] if i != j else 0 for i in range(cs) for k in range(num_vehicles)) == 1 # A vehicle begins at the depot and ends at the last visited customer for k in range(num_vehicles): problem += pulp.lpSum(x[0][j][k] for j in range(1, cs)) == 1 problem += pulp.lpSum(x[i][0][k] for i in range(1, cs)) == 1 # The number of vehicles coming in and out of a customer's location is the same # The amount of coffee for each path cannot be larger than the maximum load of the vehicle # The total length for each route does not exceed the longest length of a route # Subtour elimination subtours = [] for i in range(2, cs): subtours += itertools.combinations(range(1, cs), i) for s in subtours: problem += pulp.lpSum(x[i][j][k] if i != j else 0 for i, j in itertools.permutations(s, 2) for k in range(num_vehicles)) <= len(s) - 1 # Print vehicle count required for solving the problem # Print the calculated minimum distance value objective_function = obj # Set the objective function in the problem problem.setObjective(objective_function) if problem.solve() == 1: print('Vehicle Requirements:', num_vehicles) print('Travel cost:', pulp.value(problem.objective)) break total_distance = sum( distance[i][j] * pulp.value(x[i][j][k]) for i in range(cs) for j in range(cs) for k in range(num_vehicles) if i != j and pulp.value(x[i][j][k]) == 1) print("Total Distance Traveled: {:.2f} km".format(total_distance)) # Visualization: Plotting on Google Maps gmap = gmplot.GoogleMapPlotter(depot_latitude, depot_longitude, 13) # Add markers for each location for i in range(cs): if i == 0: gmap.marker(df.latitude[i], df.longitude[i], color='green', title="Depot") else: gmap.marker(df.latitude[i], df.longitude[i], color='orange', title=str(df['Name '][i])) # Add directions for each route color_list = ["red", "blue", "green"] for k in range(num_vehicles): for i in range(cs): for j in range(cs): if i != j and pulp.value(x[i][j][k]) == 1: # Get latitude and longitude coordinates for the two points lat1, lon1 = df.latitude[i], df.longitude[i] lat2, lon2 = df.latitude[j], df.longitude[j] # Create a list of latitude and longitude coordinates for the line line_lats = [lat1, lat2] line_lons = [lon1, lon2] # Plot the line gmap.plot(line_lats, line_lons, color=color_list[k], edge_width=2) # Save the map to an HTML file gmap.draw("mapS1.html") # Display the map webbrowser.open("mapS1.html") # Visualization: Plotting with Matplotlib plt.figure(figsize=(20, 8)) for i in range(cs): if i == 0: plt.scatter(df.latitude[i], df.longitude[i], c='green', s=200) plt.text(df.latitude[i], df.longitude[i], "depot", fontsize=12) else: plt.scatter(df.latitude[i], df.longitude[i], c='orange', s=400) plt.text(df.latitude[i], df.longitude[i], str(df['Name '][i]), fontsize=20) for k in range(num_vehicles): for i in range(cs): for j in range(cs): if i != j and pulp.value(x[i][j][k]) == 1: plt.plot([df.latitude[i], df.latitude[j]], [df.longitude[i], df.longitude[j]], c="black") plt.show() # Afficher les noms des coffee shops pour chaque route et voiture for k in range(num_vehicles): print(f"\nRoute pour le véhicule {k + 1}:") route_distance = 0 for i in range(cs): for j in range(cs): if i != j and pulp.value(x[i][j][k]) == 1: print(f"{df.iloc[i, 1]} ->{df.iloc[j, 1]}") route_distance += distance[i][j] print(f"Distance totale parcourue par le véhicule {k + 1}: {route_distance:.2f} km\n")
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |