# Correctly Specifying “Logical Conditions” (in R)

I am using the R programming language - I am trying to perform "multi objective constrained optimization".

I defined a function ("funct_set") with "4 objectives" ( `f, f, f, f` ) which are to be minimized for a set of "seven inputs" ( `[x1], [x2], [x3], x, x, x, x` ):

``````#load libraries
library(dplyr)
library(mco)

#define function

funct_set <- function (x) {
x1 <- x; x2 <- x; x3 <- x ; x4 <- x; x5 <- x; x6 <- x; x <- x
f <- numeric(4)

#bin data according to random criteria
train_data <- train_data %>%
mutate(cat = ifelse(a1 <= x1 & b1 <= x3, "a",
ifelse(a1 <= x2 & b1 <= x4, "b", "c")))

train_data\$cat = as.factor(train_data\$cat)

#new splits
a_table = train_data %>%
filter(cat == "a") %>%
select(a1, b1, c1, cat)

b_table = train_data %>%
filter(cat == "b") %>%
select(a1, b1, c1, cat)

c_table = train_data %>%
filter(cat == "c") %>%
select(a1, b1, c1, cat)

#calculate  quantile ("quant") for each bin

table_a = data.frame(a_table%>% group_by(cat) %>%
mutate(quant = ifelse(c1 > x,1,0 )))

table_b = data.frame(b_table%>% group_by(cat) %>%
mutate(quant = ifelse(c1 > x,1,0 )))

table_c = data.frame(c_table%>% group_by(cat) %>%
mutate(quant = ifelse(c1 > x,1,0 )))

f = -mean(table_a\$quant)
f = -mean(table_b\$quant)
f = -mean(table_c\$quant)

#group all tables

final_table = rbind(table_a, table_b, table_c)
# calculate the total mean : this is what needs to be optimized

f = -mean(final_table\$quant)

return (f);
}
``````

Next, I define a series of 4 "restrictions" (i.e. logical conditions/constrains) used in the optimization:

``````#define restrictions

restrictions <- function (x) {
x1 <- x; x2 <- x; x3 <- x; x4 <- x; x5<- x ; x6 <- x; x7 <- x
restrictions <- logical(4)
restrictions <- (x3 - x1 >= 0)
restrictions <- (x4 - x2 >= 0)
restrictions <- (x7 - x6 >= 0)
restrictions <- (x6 - x5 >= 0)
return (restrictions);
}
``````

Finally, I run the optimization algorithm that attempts to simultaneously minimize all 4 objectives with respect to the restrictions:

``````#run optimization

optimization <- nsga2(funct_set, idim = 7, odim = 4 ,   constraints = restrictions, cdim = 4,

generations=150,
popsize=100,
cprob=0.7,
cdist=20,
mprob=0.2,
mdist=20,
lower.bounds=rep(80,80,80,80, 100,200,300),
upper.bounds=rep(120,120,120,120,200,300,400)
)
``````

The above code works fine.

Problem : I noticed that in the output of this code, the optimization algorithm is not respecting the restrictions. For example: In the above picture, I have identified some rows where the logical conditions specified in the restrictions are violated.

Does anyone know why this is happening? Have I incorrectly specified the restrictions? Can someone please show me how to fix this?

Thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.