def finish(self, zeta1=0.1, zeta2=0.1): ''' Args: zeta1: for ip, op zeta2: for decision layers ''' # update layer mass global layer_graph_table nodes = self.get_nodes() ipop = [] dl = [] pl_lm = 0 for node in nodes: if self.get_node_attr(node) in self.iop_layers: ipop.append(node) elif self.get_node_attr(node) in self.decision_layers: dl.append(node) else: total_filters = 0 for n in self._graph.predecessors(node): total_filters += self._graph.node[n]['num_of_filters'] k = 0.1 if self._graph.node[node]['type'] == LAYERS.fc else 1 self._graph.node[node]['layer_mass'] = k * total_filters * self._graph.node[node]['num_of_filters'] pl_lm += self._graph.node[node]['layer_mass'] self.total_lm = pl_lm for node in ipop: self._graph.node[node]['layer_mass'] = zeta1 * pl_lm self.total_lm += self._graph.node[node]['layer_mass'] for node in dl: self._graph.node[node]['layer_mass'] = zeta2 * pl_lm / len(dl) self.total_lm += self._graph.node[node]['layer_mass'] # update distance for graph in layer_graph_table: get_distance(graph, self, update=True)
def K_single(x1, x2): first_term = self.alpha * np.exp( sum([ -self.betas[i] * get_distance(x1, x2, self.v_str[i])[0] for i in range(self.num_beta) ])) second_term = self.alpha_bar * np.exp( sum([ -self.beta_bars[i] * (get_distance(x1, x2, self.v_str[i])[1])**2 for i in range(self.num_beta) ])) return first_term + second_term
def estimate_dist(): directions = ['right', 'left'] dist_dict = {} for direction in directions: servo.change_pos(pos=direction) dist = distance.get_distance() if not math.isnan(dist): dist_dict[direction] = distance.get_distance() ##back to neutral servo.change_pos(pos='neutral') return dist_dict
def cluster_aspects(existing_clusters, sim_dict, word_tagfreq_dict, delta): phi = deepcopy(existing_clusters) processed_cluster_flag = False while not processed_cluster_flag: clusters_to_loop_thro = deepcopy(phi) for i, cluster_i in enumerate(clusters_to_loop_thro): cluster_i_dist_map = {} for j, cluster_j in enumerate(clusters_to_loop_thro[i + 1:]): cluster_dist = get_distance(cluster_i, cluster_j, sim_dict, word_tagfreq_dict) cluster_i_dist_map[(i, i + 1 + j)] = cluster_dist if cluster_i_dist_map: index_tup_of_closest_clusters, dist_bw_closest_cluster = \ sorted(cluster_i_dist_map.items(),key=operator.itemgetter(1))[0] del cluster_i_dist_map if dist_bw_closest_cluster < delta: phi[index_tup_of_closest_clusters[0]].\ extend(phi[index_tup_of_closest_clusters[1]]) del phi[index_tup_of_closest_clusters[1]] break else: continue else: processed_cluster_flag = True break return phi
def test_get_distance(): points = generate_points(5) for a in points: for b in points: distance = abs(a[0] - b[0]) + abs(a[1] - b[1]) assert get_distance(a, b) == distance, \ "get_distance({a}, {b}) != {distance}".format(a=a, b=b, distance=distance)
def __init__(self, fruit): self.box = fruit.box self.score = fruit.score self.cls = 'Apple' if fruit.class_id == 48 else 'Banana' distance = get_distance(fruit.box) self.distance = distance if fruit.class_id == 48 else distance * 1.25 self.size = get_size(fruit.box)
def verification(pos_list, neg_list, dist_type = 'L2'): ''' [ [feat1, feat2, ..], ... [feat1, feat2, ..] ] ''' # distance measure if isinstance(dist_type, str): dist_func = get_distance(dist_type) else: dist_func = dist_type # get dist pos_dist = [] for i in pos_list: dist = dist_func(i[0], i[1]) diff = i[0] - i[1] pos_dist.append([dist]) neg_dist = [] for i in neg_list: dist = dist_func(i[0], i[1]) neg_dist.append([dist]) precision, threshold, accu_list = test_kfold(pos_dist, neg_dist) pos = sorted(pos_dist, key=lambda x: x[0]) neg = sorted(neg_dist, key=lambda x: x[0], reverse=True) pos = [x[0] for x in pos] neg = [x[0] for x in neg] acc, std = np.mean(accu_list), np.std(accu_list) return acc, std, threshold, pos, neg
def main(): directions = load_directions('directions.txt') starting_point = (0, 0) starting_orientation = 'N' ending_point, _ = follow_directions(starting_point, starting_orientation, *directions) print(get_distance(starting_point, ending_point))
def added_distance(self, delivery_start_time, delivery_to_measure: Delivery): """ Complexity: Big O(n) Calculate HOw many miles would be added if appending this delivery to this route """ if len(self.deliveries) == 0: distance = get_distance(self.starting_location.address, delivery_to_measure.location.address) delivery_ETA = get_ETA(delivery_start_time, [delivery_to_measure]).time() if delivery_to_measure.earliest_deadline() > delivery_ETA: return distance, 0 min_distance = None add_index = None for index in range(0, len(self.deliveries) + 1): deliveries_copy = self.deliveries.copy() deliveries_copy.insert(index, delivery_to_measure) added_distance_for_delivery = get_miles_of_delivery_route( self.starting_location, deliveries_copy) checks_pass = check_all_deliveries_arrive_by_deadline( delivery_start_time, deliveries_copy) if checks_pass is False: continue if (min_distance is None or added_distance_for_delivery < min_distance): min_distance = round(added_distance_for_delivery, 2) add_index = index return (min_distance, add_index)
def distance(): result = None if request.method == 'POST': location_a = request.form['location_a'] location_b = request.form['location_b'] result = get_distance(location_a, location_b) return render_template('distance.html', title='Afstand', result=result)
def get_nearest_to_hub(input_route): # bigO O(n)-linear cost_matrix = [] for location in get_unvisited_locations(input_route): cost = get_distance('WGU_HUB', location) cost_matrix.append((location, cost)) nearest_to_hub = heapq.nsmallest(1, cost_matrix, key=lambda x: float(x[1])) return nearest_to_hub
def get_nearest_location(last_visited, unvisited): # bigO O(n)-linear cost_matrix = [] for destination in unvisited: cost = get_distance(last_visited, destination) cost_matrix.append((destination, cost)) nearest_location = heapq.nsmallest(1, cost_matrix, key=lambda x: float(x[1])) return nearest_location
def get_miles_to_next_location(self): """ Complexity: Big O(n) return the amount of miles to the next delivery location """ next_location = self.get_next_location() if next_location is None: return None return get_distance(self._current_location.address, next_location.address)
def get_nearby_items(self, user_id, point, R=0.5): items = self.get_all(user_id) nearby_items = [] for item in items: if not item[3]: continue lat, lon = [float(c.strip()) for c in item[3][1:-1].split(',')] if get_distance(lat, lon, *point) <= R: nearby_items.append(item) return nearby_items
def callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data) depth_matrix = get_distance(cv_image) print depth_matrix.max() print coor_trans(depth_matrix) except CvBridgeError as e: print e
def distance_filter(row): """ :param row: :return row: """ if row[1] != 0.0 and row[2] != 0.0 and row[3] != 0.0 and row[4] != 0.0 and row[5] != 0.0 and row[6] != 0.0: # filters out rows with zero elements plong,plat,dlong,dlat=row[-4:] if 100 > get_distance(plat,plong,dlat,dlong) > 0: # one of the many cool features of python return True return False
def k_means(dataset, k_value): sample_count = len(dataset) is_centroids_changed = True # set the start centroids centroids, centroids_index = set_centroids(dataset, k_value) cluster_result = np.zeros(sample_count, dtype=int).tolist() centroids_change_record = [] centroids_change_record.append(centroids) loop_count = 0 while is_centroids_changed == True: loop_count += 1 print("Loop :", loop_count) is_centroids_changed = False # calculate the min distance to the every centroids for i in range(sample_count): min_distance = distance.get_distance("E", dataset[i].data, centroids[0]) min_cluster_index = 0 for j in range(k_value): temp_distance = distance.get_distance("E", dataset[i].data, centroids[j]) if min_distance > temp_distance: min_distance = temp_distance min_cluster_index = j # refresh the cluster if cluster_result[i] != min_cluster_index: is_centroids_changed = True cluster_result[i] = min_cluster_index # refresh the centorid for m in range(k_value): temp_cluster = [] for n in range(sample_count): if cluster_result[n] == m: temp_cluster.append(dataset[n].data) # temp_cluster = np.array(temp_cluster) new_centroid = get_matrix_mean(temp_cluster) centroids[m] = new_centroid return centroids, cluster_result, loop_count
def get_distance(): # Print results to LCD mylcd.lcd_display_string("Calculating Distance", 1) sleep(1) mylcd.lcd_display_string("...", 2) sleep(1) mylcd.lcd_display_string(dst.get_distance(), 4) sleep(10) mylcd.lcd_clear()
def get_ETA_back_at_depot(self): """ Complexity: Big O(1) """ last_delivery = self.deliveries[-1] miles_to_deport_from_last_location = get_distance( last_delivery.location.address, self.starting_location.address) minutes_to_depot_from_last_location = miles_to_minutes( miles_to_deport_from_last_location) return (datetime.combine(datetime.today(), last_delivery.ETA) + timedelta(minutes=minutes_to_depot_from_last_location)).time()
def return_to_base(self, truck_id): """ Complexity: Big O(n) When the route is complete instuct return the Truck back to base """ drive_distance = get_distance(self._current_location.address, self.starting_location.address) self._miles_driven += drive_distance timestamp = self.miles_traveled_time_delivered(self._miles_driven) self._current_location = self.starting_location self.time_route_complete = timestamp print(f'Truck {truck_id} back at base at', timestamp)
def trainJump(save, save_as=None, curr_checkpoint=None): model.train() global variance for episode in range(num_episodes): print("-----------------------------------------") print("Episode:", episode) # Get state state = get_distance() prev_score = getScore() print("Distance:", state) state = np.array([state]) state = torch.from_numpy(state) state = state.float() # Calculate mean and variance mean = model(state) variance = final_variance + (initial_variance - final_variance) * \ math.exp(-1. * episode / variance_decay) print("Mean:", float(mean), "Deviation:", float(variance)) # Construct normal distribution based off of mean and variance and sample from it m = Normal(mean, variance) action = m.sample() # Perform action print("Action:", action) os.system("adb shell input swipe 500 500 500 500 " + str(int(action))) # Get reward and optimize model time.sleep(0.5) reward = getReward(prev_score) if reward >= 2: reward = 10 elif reward == 1: reward = 1 elif reward < 0: onDeath() print("Reward:", reward) loss = -m.log_prob(action) * reward optimizer.zero_grad() loss.backward() optimizer.step() if save: if (episode + 1) % 501 == 0: save_file = { 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), } file_name = save_as + str((episode // 1000) + curr_checkpoint) + ".pth" torch.save(save_file, file_name)
def get_miles_to_location(self, location): """ Complexity: Big O(n) return the amount of miles to a specified location """ if location is self.starting_location: return 0 try: end_location = self._route.index(location) except ValueError: print('Location not in route') return miles_to_location = 0 for loc_idx, location_iter in enumerate(self._route[:end_location]): if loc_idx == len(self._route[:end_location]): miles_to_location += get_distance(location_iter.address, location.address) miles_to_location += get_distance(location_iter.address, self._route[loc_idx + 1].address) return round(miles_to_location, 2)
def getReply(message, from_number): message = message.lower().strip() answer = "" if "transaction" in message: answer = "here is your latest transaction" elif " near " in message: typeOfResource = message.split("near", 1)[0] location = message.split("near", 1)[1] catagory = "" if "food pantry" in typeOfResource: catagory = "Food Pantry" elif "summer meal" in typeOfResource: catagory = "Summer Meals" elif "education" in typeOfResource or "school" in typeOfResource: catagory = "Educational Resource" elif "free meal" in typeOfResource or "meal" in typeOfResource: catagory = "Free Meal" elif "convenience strore" in typeOfResource: catagory = "Convenience Store" elif "garden" in typeOfResource: catagory = "Community Garden" elif "backpack" in typeOfResource: catagory = "BackPack Program" elif "grocery" in typeOfResource or "coop" in typeOfResource or "co-op" in typeOfResource: catagory = "Grocery/Co-Op" elif "farm" in typeOfResource or "csa" in typeOfResource: catagory = "CSA Program" elif "mobile" in typeOfResource: catagory = "Mobile market" else: catagory = "all" latlng = database.get_home_address_by_phone(from_number) result = distance.get_distance(latlng, catagory) print(catagory) answer = "Closest " + result[1][3] + " is " + result[1][ 1] + " on " + result[1][8] + ", " + result[1][9] + ". " # if result[1][7] != "": # answer += "Phone # is " +str(result[1][7]) + ". " # if result[1][12] != "": # answer += "Open on " +str(result[1][12]) + " " # if result[1][12] != "": # answer += " " +str(result[1][13]) else: answer = "please try another question?" return answer
def start_play(): garbage_dis = 0 try: garbage_dis = distance.get_distance() print ("Distance 1 : %.1f " % garbage_dis) if garbage_dis < 3: pass elif garbage_dis < length_threshold: playwav.play(0) pass #ws2812.light(0) else: pass #ws2812.light(1) except Exception: pass
def main(): directions = load_directions('directions.txt') starting_point = point = (0, 0) orientation = 'N' visited = [] for step in directions: next_point, orientation = follow_directions(point, orientation, step) expanded = expand_path(point, next_point) for intermediate_point in expanded[1:]: if intermediate_point in visited: print(get_distance(starting_point, intermediate_point)) return else: visited.append(intermediate_point) point = next_point print('No points visited twice.')
def irdar_sweep(channel, start, end, incr=5, distances=None): """ Sweep IRDAR and record distances :param channel: channel the servo is connected to :param start: starting angle :param end: ending angle :param incr: increment by this many degrees :param distances: add data to this dict """ angle = start if not distances: distances = {} while True: setAngle(channel, angle, incr, min_delay=MIN_DELAY) distances[angle] = distance.get_distance() angle += incr if start > end and angle < end: break elif start < end and angle > end: break return distances
def get_current_location(self): """ Complexity: Big O(n) Get the current location of truck within the route """ if self._miles_driven == 0: return self._route[0] if self.route_complete is True: return self._route[-1] miles_driven_accu = 0 for loc_idx, location in enumerate(self._route): delivered_location = self._route[loc_idx + 1] driven_distance = get_distance(location.address, delivered_location.address) if miles_driven_accu + driven_distance > self._miles_driven: return delivered_location miles_driven_accu += driven_distance
def advance_by_miles(self, new_miles_driven): """ Complexity: Big O(n) Move the route forward the amount of the new miles driven. """ print(f'have driven a total of {self._miles_driven} miles') # if there is no next delivery we have completed our route if self.get_next_delivery() is None: self._current_location = self.deliveries[-1].location self.route_complete = True while self.get_next_delivery(): miles_driven_to_current_location = self.get_miles_to_location( self._current_location) # if we are not in the starting point unused_miles_driven = self._miles_driven - miles_driven_to_current_location print( f'driven {miles_driven_to_current_location} miles from starting point' ) # Get the next delivery and the distance from here to there. next_delivery = self.get_next_delivery() drive_distance = get_distance(self._current_location.address, next_delivery.location.address) # if we drove less miles than the distance to the next delivery # Break since we haven't reached our destination yet if self._miles_driven < miles_driven_to_current_location + drive_distance: break total_miles_to_next_location = miles_driven_to_current_location + drive_distance timestamp = self.miles_traveled_time_delivered( total_miles_to_next_location) next_delivery.mark_as_delivered(timestamp) self._current_location = next_delivery.location miles_driven_to_current_location += drive_distance if self.get_next_delivery() is None: self._current_location = self.deliveries[-1].location self.route_complete = True self._miles_driven += new_miles_driven
def trainJump(save, save_as=None, curr_checkpoint=None): model.train() for episode in range(num_episodes): prev_score = getScore() print("-----------------------------------------") print("Episode:", episode) # Get state state = torch.Tensor(get_distance()) # Select action based off state node_activated, action = select_action(state) os.system("adb shell input swipe 500 500 500 500 " + str(action)) # Optimize model optimize_model() # Optimize here to save time # Get reward and push state, node_activated, and actual_reward to memory time.sleep(0.5) actual_reward = getReward(prev_score) print("Node Activated:", node_activated, "Action:", action) if actual_reward >= 2: actual_reward = 10 elif actual_reward < 0: onDeath() memory.push(state, node_activated, actual_reward) # Print difference between predicted and actual rewards predicted_reward = model(state).view(16)[node_activated] print("Predicted Reward:", float(predicted_reward), "Actual Reward:", actual_reward) print("-----------------------------------------") if save: if (episode + 1) % 1001 == 0: save_file = { 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), } file_name = save_as + str((episode // 1000) + curr_checkpoint) + ".pth" torch.save(save_file, file_name)
def cluster_features(existing_clusters, candi_features, sim_dict, word_tagfreq_dict, delta): phi = deepcopy(existing_clusters) for word in candi_features: clusters_to_loop_thro = deepcopy(phi) word_dist_map = {} for i, cluster_i in enumerate(clusters_to_loop_thro): cluster_dist = get_distance(cluster_i, [word], sim_dict, word_tagfreq_dict) word_dist_map[i] = cluster_dist if word_dist_map: index_of_closest_cluster, dist_of_closest_cluster = \ sorted(word_dist_map.items(),key=operator.itemgetter(1))[0] del word_dist_map if dist_of_closest_cluster < delta: phi[index_of_closest_cluster].append(word) break else: continue return phi
def add_destination(self, name, latitude, longitude, bing_api_key): """ Will append the given destination to the destination dictionary attribute with name and distance from Location object to destination. :param name: str, the name used to identify the destination. :param latitude: float, the latitude of the destination. :param longitude: float, the longitude of the destination. :param bing_api_key: str, the Bing Maps API key used to make the request to Bing Maps' distance matrix API :return: float, the distance in miles from the Location to the given coordinates. """ dest_distance = distance.get_distance(origin_lat=self.latitude, origin_lon=self.longitude, dest_lat=latitude, dest_lon=longitude, bing_api_key=bing_api_key) self.destinations[name] = dest_distance return dest_distance
if __name__ == '__main__': # Usage: python filtereddistance.py 'data.csv' nameOfOutputDataFile import sys import pandas as pd from distance import get_distance from pprint import pprint distances = [] error_count = 0 # create a pandas dataframe with the location data df = pd.read_csv(sys.argv[1]) dfWithLocData = df[['pickup_longitude','pickup_latitude','dropoff_longitude', 'dropoff_latitude']] for index, plong, plat, dlong, dlat in dfWithLocData.itertuples(): plong = float(plong) plat = float(plat) dlong = float(dlong) dlat = float(dlat) try: distances.append(get_distance(plat,plong,dlat,dlong)) except: distances.append('ERROR') error_count += 1 print plat, plong, dlat, dlong print error_count filterData(distances, sys.argv[1], sys.argv[2])