# Optimization gives me negative value

Not sure if this question is appropriate, but there is some error in my code which I just cannot seem to find. Probably been staring myself blind to this, so I could really use some help.

It is a MILP, which I am solving in R

model<- MIPModel() %>%
# 1 if i gets assigned to facility j
add_variable(x[i, j], i = 1:n, j = 1:m, type = "binary") %>%

# 1 if facility j is a collection point
add_variable(y[j], j = 1:m, type = "binary") %>%

# 1 if facility j is a pick-up point
add_variable(u[j], j = 1:m, type = "binary")  %>%

#C1
add_variable(C1[j], j=1:m, type = "continuous") %>%

#C
add_variable(C2[j], j=1:m, type = "continuous") %>%

# minimize the total cost
set_objective((S * sum_expr(y[j], j = 1:m)) +
(a * sum_expr(C1[j], j = 1:m)) +
(T * sum_expr(u[j], j = 1:m)) +
(b * sum_expr(C2[j], j = 1:m)) +
((sum_expr(1-sum_expr(x[i,j], i = 1:n), j= 1:m)) * kR)
, "min") %>%

#1

#2

#3
add_constraint(C1[j]>=x[i,j]+w-(m+w)*(1-y[j]), i = 1:n, j = 1:m) %>%

#4

#5

#6
add_constraint(C2[j]>=x[i,j]+w-(n+w)*(1-u[j]), i = 1:n, j = 1:m) %>%

#7
add_constraint(sum_expr(x[i,j], j = 1:m)<= 1 , i=1:n) %>%

#8
add_constraint(x[i,j]<=(delta(i,j))*(y[j]+u[j]), i =1:n, j =1:m) %>%

#9


The basic idea is that you can assign customers to a facility (Xij). Assigning customers to a facility costs "a" without an upgrade, opening a facility without an upgrade (Y) costs S. A facility has a capacity (p) and an internal demand (w). If the amount of customers assigned and internal demand exceeds p, the facility needs an upgrade (U). Assigning customers to a facility costs "b" with an upgrade, opening a facility with an upgrade costs T. Customers can only be assigned if they find themselves close enough to the facility, which is indicated by delta.

e <- function(i, j) {
customer <- data[i, ]
facility <- facility_locations[j, ]
(sqrt((customer$$x - facility$$x)^2 + (customer$$y - facility$$y)^2))
}

delta <- function (i,j){
ifelse(e(i,j)<=z,1,0)
}



When a customer is not assigned, there is a "k" likelihood that it will undertake action, which costs "R"

However, when solving the model, it gives me a minus, which should not be possible as assigning customers and opening facilities is costly.

The ompr::add_variable function has a default value of -Inf for the lower bound (lb) parameter. Assuming you intended C1 and C2 to be nonnegative, you need to explicitly set lb=0 for them.
I assume your term sum_expr(1-sum_expr(x[i,j], i = 1:n), j= 1:m) in set_objective is intended to be the number of unassigned customers; however, it actually evaluates to the number of facilities minus the number of assigned customers. Presumably there are more customers than facilities, which means this term would probably be negative and could be responsible for driving the total cost negative.