Open RicardoDominguez opened 5 years ago
Tried to do it fully in tensorflow, got various errors
def getConstrainViolation(self, candidates):
# Over/under bounds
under_bounds = tf.reduce_any(tf.less_equal(candidates, self.lb), 1)
over_bounds = tf.reduce_any(tf.greater_equal(candidates, self.ub), 1)
bounds = tf.logical_or(under_bounds, over_bounds)
v = candidates[:,0]
q = candidates[:,1]
# Constrain 1, q/v
q_over_v = q / v
c1_1 = tf.less_equal(q_over_v, 80)
c1_2 = tf.greater_equal(q_over_v, 160)
c1 = tf.logical_or(c1_1, c1_2)
# Constrain 2, q/sqrt(v)
q_over_sqrt_v = q / tf.sqrt(v)
c2_1 = tf.less_equal(q_over_sqrt_v, 80)
c2_2 = tf.greater_equal(q_over_sqrt_v, 185)
c2 = tf.logical_or(c2_1, c2_2)
c = tf.logical_or(c1, c2)
return tf.where(tf.logical_or(bounds, c))
def sampleCandidatesTF(self, mu, var):
sigma = tf.sqrt(var)
samples = tf.truncated_normal([self.popsize, self.sol_dim], mu, sigma) # (samples, nsol)
for n in range(self.max_resamples-1):
indx_violation = self.getConstrainViolation(samples)
n_violations = tf.shape(indx_violation)[0]
if tf.equal(n_violations, 0): return samples
new_samples = tf.truncated_normal([n_violations, self.sol_dim], mu, sigma)
samples = tf.scatter_update(samples, indx_violation, new_samples)
samples[indx_violation].assign(new_samples)
return samples
# def continue_resampling(samples, indices, n, mean, constrained_var):
# # Continue resampling for max_resamples or indices does not have shape (0, nsol)
# return tf.logical_and(tf.less(n, self.max_resamples), tf.greater(tf.shape(indices)[0], 0))
#
# def resample(samples, indices, n, mean, constrained_var):
# new_samples = tf.truncated_normal([tf.shape(indices)[0], self.sol_dim], mean, tf.sqrt(constrained_var)) # (samples, nsol)
# samples = tf.scatter_update(self.sol_var, indices, new_samples)
# indices = self.getConstrainViolation(samples)
# return samples, indices+1, n, mean, constrained_var
#
#
# #samples = tf.truncated_normal([self.popsize, self.sol_dim], mean, tf.sqrt(constrained_var))
# self.sol_var.assign(tf.truncated_normal([self.popsize, self.sol_dim], mean, tf.sqrt(constrained_var)))
# indices = self.getConstrainViolation(self.sol_var)
# self.sol_var, _, n, _, _ = tf.while_loop(
# cond=continue_resampling, body=resample,
# loop_vars=[self.sol_var, indices, 0, mean, constrained_var])
# samples = self.sol_var
# samples = tf.Print(samples,[n], "Number of repeats: ", summarize=10)
#samples = tf.numpy_function(self.sampleCandidates, [mean, constrained_var], tf.float32)
#samples = tf.py_function(self.sampleCandidatesTF, [mean, constrained_var], tf.float32)
After 85c52db, there are two issues:
q/v over bounds and q/sqrt(v) also over bounds