<jupyter_start><jupyter_text>Vehicle → vehicleID:int, assignedTrips:list(trips), currTrip:int (indexes into assignedTrips), currLocation: (long, lat), Trip → tripID:int, type, startLoc, endLocdictionary of vehicles and its associated trips -- { vehicle: list(trips) }incompleteTasks - either map or list of requestIDsAssuming that total tasks = all(lists of trips) + incomplete tasks<jupyter_code>class Trip:
    def __init__(self, id:int, type:str, startLoc: tuple, endLoc: tuple):
        self.tripID = id
        self.type = type
        self.startLoc = startLoc  # tuple of long and lat
        self.endLoc = endLoc

class Vehicle:
    def __init__(self, id:int):
        self.vehicleID = id
        self.assignedTrips = []  # ordered list of Trip objects
        currTrip = 0  # index of current trip we're on
        currLocation = ()  # pair of longitude and latitude
        
    def assignTrips(self, trip: Trip):
        # adds trip to list of assignedTrips
        self.assignedTrips.append(trip)
        
    def getAssignedTrips(self):
        return self.assignedTrips
        
        

    
    
output = {}  # key: Vehicle, value: list of Trip objects 
# make sure you have Medical_dataset.csv in your directory to import
df_medicalTrips = pd.read_csv('medical_dataset.csv')
df_medicalTrips
temp = df_medicalTrips[['Longitude', 'Latitude', 'DropOff_Longitude', 'DropOff_Latitude']]
temp
entry = temp.iloc[0]
print(entry)
print('distance in miles', calculateDistance(entry[0], entry[1], entry[2], entry[3]))
distance = []
for index, entry in temp.iterrows():
    dist = calculateDistance(entry[0], entry[1], entry[2], entry[3])
    distance.append(dist)
df_medicalTrips['Distance'] = distance
df_medicalTrips
df_medicalTrips['City'].unique()
len(df_medicalTrips['trip_id'].unique())
tripMap = {}  # key: tripID, value: Trip object

for index, entry in df_medicalTrips.iterrows():
    tripID = entry['trip_id']
    tripType = None
    startLoc = (entry['Longitude'], entry['Latitude'])
    endLoc = (entry['DropOff_Longitude'], entry['DropOff_Latitude'])
    t = Trip(tripID, tripType, startLoc, endLoc)
    tripMap[tripID] = t
trip = tripMap[1165742]
print('id:', trip.tripID)
print('type:', trip.type)
print('start location:', trip.startLoc)
print('end location:', trip.endLoc)
VehicleIDs = []
for i in range(16):
    VehicleIDs.append("Vhc" + str(i))
AllTripID = list(df_medicalTrips['trip_id'])

def assignTrips(VehicleIDs, tripMap):  
    # Assign initial locations for the 15 vehicles (vehicle hub locations).
    DOVIDALOTO = {}  # Dictionary of Vehicle IDs and list of trip objects. 
    for i, VID in enumerate(VehicleIDs):
        DOVIDALOTO[VID] = [tripMap[AllTripID[i]]]
       
    for ID in AllTripID[15:]:
        CrTOj = tripMap[ID] #Current trip Object .
        DOVIDAD = {}  #Dictionary of Vehicle ID and distance.
        for VID in VehicleIDs:
            LOTOj = DOVIDALOTO[VID] #List of trip objects.
            LTOj = LOTOj[len(LOTOj) - 1] #Last trip object.   
            DOVIDAD[VID] = calculateDistance(LTOj.endLoc[0], LTOj.endLoc[1], CrTOj.startLoc[0], CrTOj.startLoc[1])
        NVID = min(DOVIDAD, key = DOVIDAD.get) #Vehicle Id of the vehicle nearest to the current trip object's pick up location. 
        DOVIDALOTO[NVID].append(CrTOj)
            
    return DOVIDALOTO

assignTrips(VehicleIDs, tripMap)
#------------DifferentMETHOD FOR ASSIGNING TRIPS-------------------
#only consider Columbus, Ohio
df_medicalTrips
#Jasmine -> try to create clustering model & visualisations
#plot Long, Lat on map
import matplotlib.pyplot as plt

#plt.scatter(x=df_medicalTrips['Longitude'], y=df_medicalTrips['Latitude'])
#plt.show()

from shapely.geometry import Point
import geopandas as gpd
from geopandas import GeoDataFrame
import geopandas as gpd
from shapely.geometry import Point, Polygon
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline

geometry = [Point(xy) for xy in zip(df_medicalTrips['Longitude'], df_medicalTrips['Latitude'])]
gdf = GeoDataFrame(df_medicalTrips, geometry=geometry)   

#this is a simple map that goes with geopandas
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
states = gpd.read_file('cb_2018_us_state_20m.shp')
type(states)
states = states.to_crs("EPSG:4326")
gdf.plot(ax=states.plot(figsize=(50, 50)), marker='o', color='red', markersize=15);
gdf.plot(marker='o', color='red', markersize=15);
#points on the rightmost in Pennsylvania
#points in leftmost in Ohio
#only consider Ohio
df_Ohio = df_medicalTrips[df_medicalTrips.State != 'PA']
df_Ohio

#plot
geometry1 = [Point(xy) for xy in zip(df_Ohio['Longitude'], df_Ohio['Latitude'])]
gdf1 = GeoDataFrame(df_Ohio, geometry=geometry1) 
gdf1.plot(marker='o', color='red', markersize=15);
df_Ohio
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import seaborn as sns; sns.set()
import csv

X=df_Ohio.loc[:,['trip_id','Latitude','Longitude']]
X.head(10)

K_clusters = range(1,10)
kmeans = [KMeans(n_clusters=i) for i in K_clusters]
Y_axis = df_Ohio[['Latitude']]
X_axis = df_Ohio[['Longitude']]
score = [kmeans[i].fit(Y_axis).score(Y_axis) for i in range(len(kmeans))]

# Visualize
plt.plot(K_clusters, score)
plt.xlabel('Number of Clusters')
plt.ylabel('Score')
plt.title('Elbow Curve')
plt.show()
#k=2 is the best cluster --> separate into 2 clusters
#k=3 is the next best --> can separate into 3 clusters as well

kmeans = KMeans(n_clusters = 3, init ='k-means++')
kmeans.fit(X[X.columns[1:3]]) # Compute k-means clustering.
X['cluster_label'] = kmeans.fit_predict(X[X.columns[1:3]])
centers = kmeans.cluster_centers_ # Coordinates of cluster centers.
labels = kmeans.predict(X[X.columns[1:3]]) # Labels of each point
X
X.plot.scatter(x = 'Latitude', y = 'Longitude', c=labels, s=50, cmap='viridis')
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)
#adding/assigning cluster labels to df_Ohio 
df_Ohio['cluster_label'] = pd.Series(X['cluster_label'])
df_Ohio
#try kmeans by distance and time<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1304992585269402, 'fraction_numerical': 0.012687427912341407, 'mean_word_length': 4.4832881662149955, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '534496', 'license': 'MIT', 'n_tokens_mistral': 2195, 'n_tokens_neox': 2069, 'n_words': 549, 'path': 'EDA/clustering_model.ipynb', 'repo_name': '0613magicshop/UC-Berkeley-DataX_Honda_Fleet-Optimization-Project', 'size': '6069'}