Operations research provides a range of algorithms for determining exact optimal solutions to discrete warehouse location problems. However, these algorithms require a cost matrix, specifying the cost for supplying customer i from warehouse j, for each customer and each warehouse.
Below, I propose an algorithm for specifying this cost matrix such that one can apply these algorithms. The calculation is based on euclidean distances as a cost measure, i.e. assumes linearly scaled variable costs based on euclidean distances.
# a function for calculating euclidean distances, based on two numeric vectors as input
euclidean_distance <- function(df1,df2){
sqrt((df1[,1]-df2[,1])**2+(df1[,2]-df2[,2])**2)
}
# parameters: df with warehouse coordinates, df with customers coordinates
cost_matrix <- function(warehouses,customers){
matrix <- as.data.frame(matrix(nrow=nrow(customers),ncol=nrow(warehouses)))
# applying euclidean distances
for(i in 1:nrow(customers)){
df <- as.data.frame(matrix(nrow=nrow(warehouses),ncol=2))
df[,1] <- as.numeric(rep(customers[i,1],times=nrow(df)))
df[,2] <- as.numeric(rep(customers[i,2],times=nrow(df)))
matrix[i,] <- euclidean_distance(df,warehouses)
}
# return cost matrix
matrix
}
I perform a simple test in the code snippet below, and print the cost matrix at the bottom.
# discrete candidate warehouse locations, by latitude and longitude
warehouse_df <- as.data.frame(matrix(nrow=3,ncol=2))
colnames(warehouse_df)<-c("lat","long")
warehouse_df$lat <- runif(n=3,min=-90,max=90)
warehouse_df$long <- runif(n=3,min=-180,max=180)
head(warehouse_df)
## lat long
## 1 -44.17554 102.08728
## 2 -58.51864 -160.25027
## 3 -56.54944 -11.30273
# customer locations
customers_df <- as.data.frame(matrix(nrow=4,ncol=2))
colnames(customers_df)<-c("lat","long")
customers_df$lat <- runif(n=4,min=-90,max=90)
customers_df$long <- runif(n=4,min=-180,max=180)
head(customers_df)
## lat long
## 1 -15.70044 171.1968
## 2 -87.68773 -156.7455
## 3 -62.35740 117.7821
## 4 -85.57747 -102.7820
# test cost matrix function
cost_matrix(warehouse_df,customers_df)
## V1 V2 V3
## 1 74.74596 334.20139 187.0153
## 2 262.46471 29.37890 148.7387
## 3 24.01888 278.05884 129.2154
## 4 209.01088 63.51993 95.9744
I some of my other posts you can find examples on how to locate warehouses at center of mass (center of mass calculation in R) and how to assign customers to the nearest warehouse (customer assignment problem). I also provided an example on how to cluster customers into groups, based on their spatial proximity (spatial proximity customer grouping in R).
Lastly, I also have written a post on how to locate multiple warehouses at each their center of mass (locating multiple warehouses at center of mass).
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python
Leave a Reply