def __check__(self): Objective.__check__(self) # arrays self.edge = atleast_2d_col(self.edge) if not isinstance(self.scale,VyPy.data.scaling.ScalingFunction): self.scale = atleast_2d_col(self.scale)
def createObjective(self,sizeOfQuad): objective = Objective(sizeOfQuad) spawned = False while spawned==False: posx = randint(0,self.size-1) posy = randint(0,self.size-1) if(self.grid[posx,posy]!=1 and self.grid[posx,posy]!=2): self.grid[posx,posy] = 3 objective.pos = (posx,posy) spawned = True self.objective = objective return self.objective.pos
def __init__( self, evaluator=None, tag='c', sense='=', edge=0.0, scale=1.0, variables=None): Objective.__init__(self) self.evaluator = evaluator self.tag = tag self.sense = sense self.edge = edge self.scale = scale self.variables = variables
def add_objective(self, location, name, description): if self.started: raise AssertionError( "Can't add objective if game has already begun") objective = Objective(location, name, description, self.key) self.objectives[objective.id] = objective return objective
def generateObjective(numberOfObjectives): objectiveList = [] counter = 0 while len(objectiveList) < numberOfObjectives: newObjective = Objective() possible = True for objective in objectiveList: if objective == newObjective: possible = False if possible: objectiveList.append(newObjective) return objectiveList
def __init__(self, lectures=False): """ create a empty solution """ # arrange the courses in a more easy to work with way self.objective = Objective(self) if lectures != False: self.lectures = lectures return self.lectures = [] for item in Solution.structure: if type(item) == GADS.Course: for group in item.groups: self.arrange_course_group(group) for kita_type in group.lect_dict.keys(): for kita in group.lect_dict[kita_type]: kita.c_id = kita.c_id.strip() for lect in kita.lectures: if type(lect.start_time) == str: lect.start_time = datetime.datetime.strptime( lect.start_time[1:], '%H:%M').time() if type(lect.end_time) == str: lect.end_time = datetime.datetime.strptime( lect.end_time[1:], '%H:%M').time() if type(lect.day_in_week) == str: lect.day_in_week = ord( lect.day_in_week[1]) - ord('א') else: for course in item.courses: for group in course.groups: self.arrange_course_group(group) for kita_type in group.lect_dict.keys(): for kita in group.lect_dict[kita_type]: kita.c_id = kita.c_id.strip() for lect in kita.lectures: if type(lect.start_time) == str: lect.start_time = datetime.datetime.strptime( lect.start_time[1:], '%H:%M').time() if type(lect.end_time) == str: lect.end_time = datetime.datetime.strptime( lect.end_time[1:], '%H:%M').time() if type(lect.day_in_week) == str: lect.day_in_week = ord( lect.day_in_week[1]) - ord('א') for item in Solution.structure: if type(item) == GADS.Course: self.pick_courase(item, False) # else its a cluster else: self.pick_cluster(item)
def button_plot_photons(photons_json, points_cones, show_aperture, sample_thickness, working_distance, NA): objective = Objective(NA, working_distance, sample_thickness) photons = pickle.loads(photons_json) if points_cones == 'points': fig = utils.plot_photons(photons, objective, show_aperture=show_aperture, cones=False) else: fig = utils.plot_photons(photons, objective, show_aperture=show_aperture, cones=True) return fig
def __init__(self, numPlayers, mapInstance): self.endGame = False self.num = 0 self.numPlayers = numPlayers self.turnList = list(range(1, numPlayers + 1)) random.shuffle(self.turnList) self.numTerritories = mapInstance.numTerritories self.players = [] for k in range(0, numPlayers): self.players.append(Player(k + 1, mapInstance, self)) # assigns player goals self.goal = Goal(mapInstance, self) for k in range(0, numPlayers): self.players[k].obj = Objective(self.goal, self.players[k]) self.id_turnList = 0 self.map = mapInstance self.list_phase = ["Placement", "Attack", "Movement"] self.phase = 0 self._player_ = self.turnList[self.id_turnList]
def get_problem(location): """ use the parameters to generate the content such as distance matrix,decision variables,rows and etc. """ num_of_customers = len(location) - 1 cus_depot = len(location) # # manhatten distance # for i in range(len(location)): # for j in range(len(location)): # distance[i,j] = abs(location[i][0]-location[j][0])+abs(location[i][1]-location[j][1]) # euclidean distance distance = np.zeros((cus_depot, cus_depot), dtype=np.int32) for i in range(len(location)): for j in range(len(location)): distance[i, j] = ((location[i][0] - location[j][0])**2 + (location[i][1] - location[j][1])**2)**0.5 decision_variables = [] for i in range(num_of_customers + 1): decision_variables.append([]) for j in range(num_of_customers + 1): decision_variables[i].append( Variable('I', [0, 1], 'x%d%d' % (i, j))) for i in range(num_of_customers + 1): decision_variables[0][i]['upper_bound'] = 2.0 variables_1dim = [] rel = np.zeros((cus_depot, cus_depot), dtype=np.int16) x = 0 dist_1dim = [] mapping = dict( ) # get a dict like : mapping = {(0,1):0,(0,2):1,(0,3):2 ...} ind1 = [] # ind1 each customer has remain decision_variables list_customer = list(range(cus_depot)) for i in range(cus_depot): ind1.append(num_of_customers - i) for i in range(cus_depot): for j in range(ind1[i]): variables_1dim.append(decision_variables[i][i + j + 1]) dist_1dim.append(float(distance[i][i + j + 1])) rel[i][i + j + 1] = x mapping[(i, i + j + 1)] = x x += 1 # for customer i # m<i,give x_mi # m>i give x_im m\in {0,1,...,5} rows1 = [] for i in range(num_of_customers): rows1.append([]) for j in range(2): rows1[i].append([]) for i in range(1, cus_depot): list_cur = copy.deepcopy(list_customer) list_cur.remove(i) for j in list_cur: if j < i: rows1[i - 1][0].append(mapping[(j, i)]) rows1[i - 1][1].append(1) else: rows1[i - 1][0].append(mapping[(i, j)]) rows1[i - 1][1].append(1) ''' [[['x01', 'x12', 'x13', 'x14', 'x15'], [1, 1, 1, 1, 1]], [['x02', 'x12', 'x23', 'x24', 'x25'], [1, 1, 1, 1, 1]], [['x03', 'x13', 'x23', 'x34', 'x35'], [1, 1, 1, 1, 1]], [['x04', 'x14', 'x24', 'x34', 'x45'], [1, 1, 1, 1, 1]], [['x05', 'x15', 'x25', 'x35', 'x45'], [1, 1, 1, 1, 1]]] transfer to variables_1dim and get: [['x0', 'x5', 'x6', 'x7', 'x8'], [1, 1, 1, 1, 1]] [['x1', 'x5', 'x9', 'x10', 'x11'], [1, 1, 1, 1, 1]] [['x2', 'x6', 'x9', 'x12', 'x13'], [1, 1, 1, 1, 1]] [['x3', 'x7', 'x10', 'x12', 'x14'], [1, 1, 1, 1, 1]] [['x4', 'x8', 'x11', 'x13', 'x14'], [1, 1, 1, 1, 1]] [['x0', 'x1', 'x2', 'x3', 'x4'], [1, 1, 1, 1, 1]] ''' # for depot0 : row2 = [[]] for i in range(2): row2[0].append([]) for i in range(num_of_customers): row2[0][0].append(i) row2[0][1].append(1) ''' [['x01', 'x02', 'x03', 'x04', 'x05'], [1, 1, 1, 1, 1]] ''' rows = rows1 + row2 my_obj = Objective('min', dist_1dim) right_side = [2.0] * num_of_customers right_side.append(2.0 * K) constraints = [ Constraint('c%d' % (i + 1), rows[i], 'E', right_side[i]) for i in range(len(rows)) ] relation = ['E'] * len(constraints) var_names = [ 'x%d' % (i + 1) for i in range(int(cus_depot * (cus_depot - 1) / 2)) ] row_names = ['c%d' % (i + 1) for i in range(cus_depot)] lowerbounds = [] upperbounds = [] var_types = [] for i in range(len(variables_1dim)): # lowerbounds.append(float(variables_1dim[i].lower_bound)) # upperbounds.append(float(variables_1dim[i].upper_bound)) lowerbounds.append(variables_1dim[i].lower_bound) upperbounds.append(variables_1dim[i].upper_bound) var_types.append(variables_1dim[i].type) lin_expression = [ cplex.SparsePair(ind=rows[i][0], val=rows[i][1]) for i in range(len(rows)) ] return dist_1dim, cus_depot, num_of_customers, my_obj, lowerbounds, upperbounds, var_types, var_names, lin_expression, row_names, relation, right_side, mapping
g = 0.94 sample_depth = 250 focus_depth = 170 working_distance = 5940 NA = 0.54 fov = np.linspace(-2500, 2500, 3) distance_to_sample = working_distance + focus_depth num_photons = 1000 medium_shape = np.array([float('inf'), float('inf'), sample_depth]) medium = Medium(medium_shape, mu_s, mu_a, n_i, n_e, g) objective = Objective(NA, working_distance, sample_depth) photons = utils.fov_sim(medium, fov, num_photons, focus_depth, omit_bottom=True) acceptance_matrix = utils.calc_acceptance_matrix(photons, objective) fig = utils.plot_fov_heatmap(acceptance_matrix, fov) try: plotly.offline.plot(fig, filename='fov_heatmap/heatmap.html') except FileNotFoundError: os.mkdir('fov_heatmap') plotly.offline.plot(fig, filename='fov_heatmap/heatmap.html')
return data[0]**2 def X2_reverse(data): return 1 / (data[0]**2) def X4(data): return data[0]**4 if __name__ == "__main__": name = "Power2" numberOfSwarm = 50 firstObjective = Objective("X2", [0], X2) secondObjective = Objective("X2_reverse", [1], X2_reverse) objectiveFunction = [firstObjective, secondObjective] numOfFeature = 2 featureRange = ( (-100, 100), (-100, 100), ) numberOfIter = 150 q = 2 swarm = Swarm(name=name, numberOfSwarm=numberOfSwarm, objectiveFunction=objectiveFunction, numOfFeature=numOfFeature,
res.x_value)) outputfile = "output.txt" with open(outputfile, 'a+') as out: out.write("Solution status = {0}:{1}\n".format( my_prob.solution.get_status(), my_prob.solution.status[my_prob.solution.get_status()])) out.write("Optimal objective value = {0}".format( my_prob.solution.get_objective_value()) + '\n') for j in range(num_cols): out.write("x%d: %.1f" % (j, x[j]) + '\n') my_prob.write("cplex.lp") if __name__ == "__main__": # file_name = "input.txt" file_name = "input1.txt" # file_name = "input2.txt" # file_name = "input_vrp.txt" my_obj_type, my_obj_coe, my_lower_bounds, my_upper_bounds, type_of_variable, name_of_variable, tech_coe, sign_of_cons, right_of_cons = get_parameter( file_name) my_obj = Objective(my_obj_type, my_obj_coe) my_bounds = [my_lower_bounds, my_upper_bounds] type_of_var = type_of_variable[0] rows = [[name_of_variable, tech_coe[i]] for i in range(len(tech_coe))] relation = sign_of_cons[0] right_side = [int(i) for i in right_of_cons] calculate()
import plotly import plotly.graph_objects as go # Refractive index n_e = 1 # Objective parameters sample_depth = 900 working_distance = 5940 NA = 0.54 fov = np.linspace(-2500, 2500, 100) xx, yy = np.meshgrid(fov, fov, sparse=False) deviation = np.sqrt(xx ** 2 + yy ** 2) objective = Objective(NA, working_distance, sample_depth, n_e) efficiency = objective.theoretical_collection_efficiency(deviation, type='sphere') fig = go.Figure( data=go.Heatmap( x=xx[0], y=yy[:, 0], z=efficiency, # zmin=0, # zmax=1 ), ) fig.update_layout( autosize=False, width=800,
def findOptimumThreshold(self, score, known, calculate_auc=False): """Set the prediction threshold according to the objective function The objective function is set by self.objective_function Parameters ---------- score : dict output from from self.score, keys are edge types, values are dicts keyed by source node name and values are scores. known : list source nodes with an edge to the target of type self.to_predict calculate_auc : bool Whether or not to calculare and return the AUC. Default True. Returns ------- best : dict Contains many standard metrics for the model, e.g. F1 score, AUC, precision, recall, which have predictable names. Important proporties of the output are: 'threshold' : cutoff value that maximises the objective function 'unique_threshold' : bool, true if the same performance can be achieved with at least one different threshold 'hits_known' : hits from the model that are already known in the input graph 'hits_new' : hits from the model that are not already known in the input graph 'is_hit' : bool list, hit status for every source node. """ node_names = score.keys() score = np.array([score[x] for x in score]) known = np.in1d(node_names, known, assume_unique=True) thresholds = np.unique(score) placeholder = {} method = self.objective_function placeholder[ method] = -1 #all current objective functions are in range 0-1 so the first result always replaces the placeholder best_performance = [placeholder] obj = Objective(score, known) if calculate_auc: x = [] #FPR = FP/(population N) y = [] #TPR TP/(population P) pop_pos = float(np.sum(known)) pop_neg = float(len(known) - pop_pos) for t in thresholds: result = obj.evaluate(t) if result[method] > best_performance[0][method]: result['unique_threshold'] = True result['threshold'] = t best_performance = [ result ] #if there's a new best, reset to an array of one element elif result[method] == best_performance[0][method]: #keep track of different thresholds that give equivalent results result['threshold'] = t result['unique_threshold'] = False best_performance.append(result) best_performance[0]['unique_threshold'] = False #auc if calculate_auc: x.append(result['contingency']['fp'] / pop_neg) y.append(result['contingency']['tp'] / pop_pos) best = best_performance[ 0] #only return one result even if there are ties best['all_hits'] = set(itertools.compress(node_names, best['is_hit'])) del best['is_hit'] best['auc'] = "NA" if calculate_auc: x = np.array(x) y = np.array(y) best['auc'] = self.auc(x, y, True) return best