class Optimizer(): def __init__(self, input_file, N): self.input_constraints = Constraint(input_file) #print(self.input_constraints.get_ndim()) #print(self.input_constraints.get_example()) #print(self.input_constraints.get_constraints()) #exam = np.array(list(self.input_constraints.get_example()), dtype=float) #print(self.input_constraints.apply(exam)) self.x = self.sample(N) self.get_output() def sample(self, N): count = 0 ndim = int(self.input_constraints.get_ndim()) x = np.empty((0, ndim)) while (count < int(N)): n_samples = int(N) * 10 smpls = lhs(ndim, samples=n_samples) for i in range(len(smpls)): if self.input_constraints.apply(smpls[i]) and (count < int(N)): #print(smpls[i]) x = np.append(x, np.array([smpls[i]]), axis=0) count += 1 print(count) print(x.shape) return x def get_output(self): return self.x
def main(argv): if len(sys.argv) < 3: print( 'Please provide 3 command line arguments (e.g. input_filename, output_filename, n_results' ) exit(-1) in_filename = '' out_filename = '' niteration = 0 in_filename = sys.argv[1] out_filename = sys.argv[2] niteration = int(sys.argv[3]) c = Constraint(in_filename) v = c.get_example() print(v) n = c.get_ndim() #this is the chromosome size for each population print(n) # print(c.apply([0.5, 1.0, 0.0, 0.5])) s = 300 #population size ga = Genetic( s, n, in_filename ) #initializes ga type object with populaton size, chromosome size, input file name p = ga.get_population() print(p) print(ga.cal_pop_fitness()) temp_solution = ga.eval_ga(niteration) # print(temp_solution) # write result to the output with open(out_filename, 'w') as filehandle: for item in temp_solution: s = " ".join(str(e) for e in item) # print(s) l = s # l = item print(l) filehandle.write('%s\n' % l) filehandle.close()
def sampler(input_file, output_file, n_result): ct = Constraint(input_file) ndim = ct.get_ndim() current_results = [] while len(current_results) < n_result: res = np.random.random(ndim) res = (res / sum(res) * sum(ct.get_example())).round(5) if not ct.apply(res): continue current_results.append(res) print('example:', ct.get_example()) print('res:', res) with open(output_file, 'a') as f: for l, el in enumerate(current_results): string = ' '.join(map(str, el)) # for item in string: f.write(string) f.write('\n') return current_results
def get_constraints(input_file): """reads the input file and creates an instance of the Constraint class """ # create a new instance of the Constraint class by reading input_file # catch several errors: file not found, first two lines (number of # dimensions and starting vector) not formatted correctly, or syntax # error in the constraints try: space = Constraint(input_file) except FileNotFoundError: sys.exit("Error: input file not found") except ValueError: sys.exit("Error: input file formatted improperly") except SyntaxError: sys.exit("Error: syntax error in constraints") # get the example point and make sure it has the correct dimensionality example = space.get_example() if len(example) < space.get_ndim(): sys.exit("Error: example point does not have enough dimensions") # check and make sure the example point actually satisfies all of the # constraints. This additionally serves to make sure the constraints # are specified correctly try: check_example = space.apply(example) except IndexError: sys.exit("Error: invalid constraints") except NameError: sys.exit("Error: invalid constraints") # if space.apply(example) returned false, then throw an error if not check_example: sys.exit("Error: example point is invalid") return space
class SCMC(): """Use sequentially constrained Monte Carlo method to sample given constrained domains uniformly Methods ------- write_ouput: write the final sample in given path get_correctness: return the correctness of the final state get_history: return a List, the history all samples in the sequential diffusion process plot_results: scatter plot the results along two arbitrary axes params ------ comp1, int: first axis (h) comp2, int: second axis (v) n_iter, int: if want history instead of final state print_constraints: print the original constraints """ def __init__(self, input_path, n_results, beta_max=10**4, p_beta=1, p_rw_step=0, track_correctness=False, threshold=.999): self.input_path = input_path self.constraints = Constraint(input_path) constraints_funcs = self.constraints.get_functions() self.n_dim = self.constraints.get_ndim() self.n_results = n_results self.beta_max = beta_max self.p_beta = p_beta self.p_rw_step = p_rw_step #call sampling method scmc i_sample = init_sample(self.n_dim, self.n_results, self.constraints.bounds, self.constraints.get_example()) self.i_samples = [] self.i_samples.append(i_sample) self.histories = [] self.correctnesses = [] print(len(constraints_funcs)) for i in range(1, len(constraints_funcs) + 1): history, correctness = scmc( self.n_dim, self.n_results, self.i_samples[i - 1], constraints_funcs[0:i], beta_max, self.constraints.bounds, p_beta, p_rw_step, track_correctness=track_correctness, given_example=self.constraints.get_example(), threshold=threshold) self.i_samples.append(history[-1]) self.histories.append(history) self.correctnesses.append(correctness) self.results = self.histories[-1][-1] # self.history, self.correctness = scmc(self.n_dim, self.n_results, i_sample ,constraints_funcs, beta_max, self.constraints.bounds, # p_beta,p_rw_step, # track_correctness=track_correctness, # given_example = self.constraints.get_example()) # self.results = self.history[-1] # self.history, self.correctness = scmc(self.n_dim, self.n_results, constraints_funcs, beta_max, self.constraints.bounds, # p_beta,p_rw_step, # track_correctness=track_correctness, # given_example = self.constraints.get_example()) # self.results = self.history[-1] # self.write_ouput(output_path) def write_output(self, output_path): """ save the sample to a output_path """ np.savetxt(output_path, self.results) def get_correctness(self): """ get correctness """ correctness = [self.constraints.apply(x) for x in self.results] correctness = sum(correctness) / self.n_results return correctness def get_history(self): return self.history def get_results(self): """ get the sample """ return self.results def plot_results(self, comp1, comp2, n_iter=None): """ Plot the sample in x[comp1],x[comp2] """ if n_iter is None: sample = self.results else: sample = self.history[n_iter - 1] plt.figure() plt.scatter(sample[:, comp1], sample[:, comp2]) plt.xlim(0, 1) plt.ylim(0, 1) def plot_all_axis(self, n_iter=None): n_dim = self.n_dim for i in range(n_dim): for j in range(i + 1, n_dim): self.plot_results(i, j, n_iter) plt.xlabel('x_{}'.format(i)) plt.ylabel('x_{}'.format(j)) def print_constraints(self): print(self.constraints.get_exprs_string())