Example #1
0
    def setup(self, sp=False, costModel=False):

        Srunway = Variable("S_{runway}", "ft", "runway length")
        PFEI = Variable("PFEI", "kJ/(kg*km)", "PFEI")
        "Parameters of interest"

        self.aircraft = Aircraft()

        takeoff = TakeOff(self.aircraft, sp=sp)
        cruise = Cruise(self.aircraft)
        mission = [cruise, takeoff]
        climb = Climb(self.aircraft)
        if costModel:
            cost = Cost(self.aircraft)
            mission.extend([cost])

        constraints = [
            self.aircraft["P_{shaft-max}"] >= cruise["P_{shaft}"],
            Srunway >= takeoff["S_{TO}"],
            PFEI == self.aircraft["h_{batt}"] * self.aircraft["W_{batt}"] /
            (cruise["R"] * self.aircraft["W_{pay}"])
        ]

        if sp:
            landing = Landing(self.aircraft)
            constraints.extend([Srunway >= landing["S_{land}"]])
            mission.extend([landing])
        else:
            landing = GLanding(self.aircraft)
            constraints.extend([Srunway >= landing["S_{land}"]])
            mission.extend([landing])

        return constraints, self.aircraft, mission, climb
def get_cost(traj_node, traj_mps, peri_boundary, total_traj_time, habitats,
             sharkGrid, weights):
    """
    Return the mean cost of the produced path

    Parameter: 
        trajectory: a list of Node objects
    """
    total_cost = 0
    num_steps = 0
    max_time = traj_node[-1].time_stamp
    time = 0
    cal_cost = Cost()
    while time < max_time:
        currPath_mps = get_curr_mps_path(time, traj_mps)
        currPath_node = get_curr_node_path(time, traj_node)
        cost = cal_cost.habitat_shark_cost_func(currPath_mps,
                                                currPath_node[-1].pathLen,
                                                peri_boundary, total_traj_time,
                                                habitats, sharkGrid, weights)
        # print ("habitat_shark_cost = ", cost[0], "currPath length = ", len(currPath_mps), "currPath_node[-1].pathLen = ", currPath_node[-1].pathLen)
        total_cost += cost[0]
        time += 2  # dt = 2s
        num_steps += 1
    mean_cost = total_cost / num_steps
    print("mean cost = ", total_cost, " / ", num_steps, " = ", mean_cost)

    return mean_cost
Example #3
0
def eliminate(patterns, sequence, cost_unit,
              transition_transversion_proportion):
    extended_patterns = extend_embiguous_patterns(patterns)
    cost = Cost(sequence, cost_unit, transition_transversion_proportion)
    result_seq = MultipleSoftElimination(sequence=sequence,
                                         patterns=extended_patterns,
                                         cost=cost,
                                         alphabet=dna_alphabet).eliminate()
    result_cost = cost.get_cost_of_seq(result_seq)
    return result_seq, result_cost
Example #4
0
def get_market_data():
    global username
    if request.method == "GET":
        band1 = Bandit()
        trader1 = Trader()
        police1 = Police()
        cost1 = Cost()

        market_inventory = regions.child(currRegion).child('inventory').get()
        ship_inventory = users.child(username).child('ship').child(
            'inventory').get()
        difficulty = users.child(username).child('difficulty').get()
        ship_cargo = users.child(username).child('ship').child('cargo').get()
        credit_val = users.child(username).child('credit').get()
        ship_health = users.child(username).child('ship').child('health').get()
        pilot_skill = users.child(username).child('skills').child(
            'pilot').get()
        engineer = users.child(username).child('skills').child(
            'engineer').get()
        fighter_skill = users.child(username).child('skills').child(
            'fighter').get()
        merchant_skill = users.child(username).child('skills').child(
            'merchant').get()
        fuel = users.child(username).child('ship').child('fuel').get()
        fuelcost = cost1.calculate_fuel(difficulty, credit_val)
        demand = band1.calculate_demand(difficulty, credit_val)
        repair = cost1.calculate_repair(difficulty, engineer, credit_val)
        price = trader1.item_to_sell(difficulty, credit_val)
        qty = trader1.qty
        item = trader1.item
        stolen = police1.stolen_item(ship_inventory)
        to_return = {
            'username': username,
            'currRegion': currRegion,
            'market_inventory': market_inventory,
            'ship_inventory': ship_inventory,
            'cargo': ship_cargo,
            'credit': credit_val,
            'health': ship_health,
            'demand': demand,
            'qty': qty,
            'item': item,
            'price': price,
            'eng': engineer,
            'stolen': stolen,
            'difficulty': difficulty,
            'pilot': pilot_skill,
            'fighter': fighter_skill,
            'fuel': fuel,
            'fuelcost': fuelcost,
            'merch': merchant_skill,
            'repair': repair
        }
        return to_return
    return None
Example #5
0
	def load_cost(self):
		"""
		This function is to load cost object data from storage.
		:return: cost object list.
		"""
		data_cost = []
		data_file = open(self.storage)
		deliveries_reader = csv.reader(data_file)
		for row in deliveries_reader:
			if row[0] == 'C':
				data_cost.append(Cost(row[1], row[2]))
		data_file.close()
		return data_cost
Example #6
0
def solve(pitches, wishes, relations=None, n=200, patience=200, diversity=.9):
    """
    Attempt to minimise the cost function with a naive evolutionnary solver
    :param pitches: <pitch, <role, load>>
    :param wishes: <student, [(pitch, role)]>
    :param relations: <student, <student, cost>>
    :param n: number of competing solutions
    :param patience: number of iteration without improvement before stopping
    :param diversity: proportion of kept solutions for the next iteration
    :return: [(student, wish index)]
    """
    assert n > 1 and patience > 0
    cost = Cost(pitches, wishes, relations)
    # precomputations to pick best solutions to clone and modify
    keep = int(n * diversity)
    discard = list(range(keep - 1, n))
    # the starting solutions {student, wish index}
    solutions = random_solutions(wishes, n)
    p = patience
    # for printing in the console with padded 0
    zfill_p = len(str(patience)) - 1
    best_cost = float("+inf")
    print("Cost so far:")
    start = time()
    count = 0
    while p > 0:
        count += 1
        # compute the cost of the solutions
        costs = [cost(s) for s in solutions]
        # sort the solutions by cost
        costs, solutions = zip(
            *sorted(zip(costs, solutions), key=lambda cs: cs[0]))
        solutions = list(solutions)
        # update the patience
        if best_cost == costs[0]:
            p -= 1
        else:
            p = patience
            best_cost = costs[0]
        print(
            f"{best_cost:.2f}  (patience = {str(int(p/10)).zfill(zfill_p)}) ",
            end="\r")
        # replace the worse solutions by modified clones of the best solutions
        for i in discard:
            solutions[i] = copy(solutions[i % keep])
            random_changes(wishes, solutions[i], 2)
    print()
    delta = time() - start
    print(f"in {delta:,.1f} sec - {1000*delta/count:.0f}ms/it")
    # [(student, wish index)]
    return solutions[0]
Example #7
0
def check_area_ytp(pickle_name):
    data = load(pickle_name)

    n_years = 15
    house_cost = data.loc[0].value
    appreciation = 3.0

    n_months = n_years * 12

    dates = pd.date_range(data.loc[0].date, periods=n_months, freq="M")

    rent = Revenue("rent", "monthly payment", 0.011 * house_cost)

    # costs
    utilities = Cost("utilities", "hvac", 150)
    insurance = Cost("insurance", "full coverage", 100)
    property_tax = Cost("insurance", "full coverage",
                        (house_cost * 0.019) / 12)

    mortgage = Mortgage(house_cost, 25000, dates, 3.0)

    # revenue
    revenues = [rent]
    costs = [utilities, insurance, property_tax]

    house = House(revenues, costs, mortgage, dates, appreciation)
    # house.summary()

    house.graph_net_profit()


    portfolio = Portfolio([house])

    ytp = portfolio.get_years_to_positive(house)
    print("years till positive", ytp)
    exit(0)

    return ytp
 def test_cost(self):
     seq = "aaAr"
     cost = Cost(sequence=seq,
                 cost_unit=1,
                 transition_transversion_proportion=2)
     assert 0 == cost.get(1, "a"), "cost is 0 for not changing the letter"
     assert 0 == cost.get(
         4, "a"), "cost is 0 for not changing the letter (r is a or g)"
     assert infinity == cost.get(
         3, "g"), "index 2 is not allowed to be changed (uppercase)"
     assert 1 == cost.get(1, "g"), "transition cost"
     assert 2 == cost.get(1, "t"), "transversion cost"
     assert 2 == cost.get(1, "c"), "transversion cost"
     assert 2 == cost.get(4, "t"), "transversion cost with IUPAC"
Example #9
0
    def __init__(self):
        self.tag           = self.__class__.__name__
        self.input_layer   = []      # <Sample Object>
        self.hidden_layer  = []      # <Net Object>
        self.output_layer  = []      # <Net Object>

        self.learning_rate = 1.0     # 学习速率
        self.max_iteration = 1       # 最大迭代数
        self.convergence   = 0.001   # 收敛误差
        self.activation    = Method.Sigmoid
        self.iteration     = 0       # 迭代次数
        self.cost          = Cost()  # Cost Function

        # Callbacks
        self.iteration_callback = None
        self.completion_callback = None
Example #10
0
    def __init__(self,
                 boundary,
                 obstacles,
                 shark_dict,
                 sharkGrid,
                 exp_rate=1,
                 dist_to_end=2,
                 diff_max=0.5,
                 freq=30):
        '''setting parameters:
            initial_location: initial Motion_plan_state of AUV, [x, y, z, theta, v, w, time_stamp]
            goal_location: Motion_plan_state of the shark, [x, y, z]
            obstacle_list: Motion_plan_state of obstacles [[x1, y1, z1, size1], [x2, y2, z2, size2] ...]
            boundary: max & min Motion_plan_state of the configuration space [[x_min, y_min, z_min],[x_max, y_max, z_max]]'''
        #initialize obstacle, boundary, habitats for path planning
        self.boundary = boundary
        #initialize corners for boundaries
        coords = []
        for corner in self.boundary:
            coords.append((corner.x, corner.y))
        self.boundary_poly = Polygon(coords)
        self.obstacle_list = obstacles

        self.mps_list = []  # a list of motion_plan_state
        self.time_bin = {}

        #if minimum path length is not achieved within maximum iteration, return the latest path
        self.last_path = []

        #setting parameters for path planning
        self.exp_rate = exp_rate
        self.dist_to_end = dist_to_end
        self.diff_max = diff_max
        self.freq = freq

        # initialize shark occupancy grid
        self.cell_list = splitCell(self.boundary_poly, 10)
        self.sharkGrid = sharkGrid
        self.sharkDict = shark_dict

        # initialize cost function
        self.cal_cost = Cost()

        # keep track of the longest single path in the tree to normalize every path length
        self.peri_boundary = self.cal_boundary_peri()
Example #11
0
    def __init__(self, env, trajectory):
        self.cfg = config.cfg
        self.trajectory = trajectory

        self.cost = Cost(env)
        self.optim = Optimizer(env, self.cost)

        if self.cfg.goal_set_proj:
            print("Not implemented")
            # if self.cfg.scene_file == "" or self.cfg.traj_init == "grasp":
            #     self.load_grasp_set(env)
            #     self.setup_goal_set(env)
            # else:
            #     self.load_goal_from_scene()

            # self.grasp_init(env)
            # self.learner = Learner(env, trajectory, self.cost)
        else:
            self.trajectory.interpolate_waypoints()
        self.history_trajectories = []
        self.info = []
        self.ik_cache = []
Example #12
0
def initialize_cost(total_income):
    bait = 20
    eaten = 180
    depreciation_of_tools = 1
    tax_rate = 0.05
    return Cost(bait, eaten, depreciation_of_tools, tax_rate, total_income)
Example #13
0
def main(Vxf0, urdf, options):
    modelNames = ['w.mat',
                  'Sshape.mat']  # Two example models provided by Khansari
    modelNumber = 1  # could be zero or one depending on the experiment the user is running

    data, demoIdx = load_saved_mat_file(lyap + '/' + 'example_models/' +
                                        modelNames[modelNumber])

    Vxf0['d'] = int(data.shape[0] / 2)
    Vxf0.update(Vxf0)

    Vxf0 = guess_init_lyap(data, Vxf0, options['int_lyap_random'])
    cost = Cost()

    while cost.success:
        print('Optimizing the lyapunov function')
        Vxf, J = cost.learnEnergy(Vxf0, data, options)
        old_l = Vxf0['L']
        Vxf0['L'] += 1
        print('Constraints violated. increasing the size of L from {} --> {}'.
              format(old_l, Vxf0['L']))
        if cost.success:
            print('optimization succeeded without violating constraints')
            break

    # Plot the result of V
    h1 = plt.plot(data[0, :], data[1, :], 'r.', label='demonstrations')

    extra = 30

    axes_limits = [
        np.min(data[0, :]) - extra,
        np.max(data[0, :]) + extra,
        np.min(data[1, :]) - extra,
        np.max(data[1, :]) + extra
    ]

    h3 = cost.energyContour(Vxf, axes_limits, np.array(()), np.array(()),
                            np.array(()), False)
    h2 = plt.plot(0, 0, 'g*', markersize=15, linewidth=3, label='target')
    plt.title('Energy Levels of the learned Lyapunov Functions', fontsize=12)
    plt.xlabel('x (mm)', fontsize=15)
    plt.ylabel('y (mm)', fontsize=15)
    h = [h1, h2, h3]

    # Run DS
    opt_sim = dict()
    opt_sim['dt'] = 0.01
    opt_sim['i_max'] = 4000
    opt_sim['tol'] = 1

    d = data.shape[0] / 2  # dimension of data
    x0_all = data[:int(d), demoIdx[0, :-1] -
                  1]  # finding initial points of all demonstrations

    # get gmm params
    gmm = GMM(num_clusters=options['num_clusters'])
    gmm.update(data.T, K=options['num_clusters'], max_iterations=100)
    mu, sigma, priors = gmm.mu.T, gmm.sigma.T, gmm.logmass.T

    # rho0 and kappa0 impose minimum acceptable rate of decrease in the energy
    # function during the motion. Refer to page 8 of the paper for more information
    rho0 = 1
    kappa0 = 0.1

    inp = list(range(Vxf['d']))
    output = np.arange(Vxf['d'], 2 * Vxf['d'])

    xd, _ = dsStabilizer(x0_all, Vxf, rho0, kappa0, priors, mu, sigma, inp,
                         output, cost)

    # Evalute DS
    xT = np.array([])
    d = x0_all.shape[0]  # dimension of the model
    if not xT:
        xT = np.zeros((d, 1))

    # initialization
    nbSPoint = x0_all.shape[1]
    x = []
    #x0_all[0, 1] = -180  # modify starting point a bit to see performance in further regions
    #x0_all[1, 1] = -130
    x.append(x0_all)
    xd = []
    if xT.shape == x0_all.shape:
        XT = xT
    else:
        XT = np.tile(
            xT,
            [1, nbSPoint
             ])  # a matrix of target location (just to simplify computation)

    t = 0  # starting time
    dt = 0.01
    for i in range(4000):
        xd.append(
            dsStabilizer(x[i] - XT, Vxf, rho0, kappa0, priors, mu, sigma, inp,
                         output, cost)[0])

        x.append(x[i] + xd[i] * dt)
        t += dt

    for i in range(nbSPoint):
        # Choose one trajectory
        x = np.reshape(x, [len(x), d, nbSPoint])
        x0 = x[:, :, i]
        if i == 0:
            plt.plot(x0[:, 0],
                     x0[:, 1],
                     linestyle='--',
                     label='DS eval',
                     color='blue')
        else:
            plt.plot(x0[:, 0], x0[:, 1], linestyle='--', color='blue')
    plt.legend()
    plt.show()
Example #14
0
    def astar(self, pathLenLimit, weights, shark_traj): 
        """
        Find the optimal path from start to goal avoiding given obstacles 
        Parameter: 
            pathLenLimit: in meters; the length limit of the A* trajectory 
            weights: a list of three numbers [w1, w2, w3] 
            shark_traj: a list of Motion_plan_state objects 
        """

        w1 = weights[0]
        w2 = weights[1]
        w3 = weights[2]
        w4 = weights[3]

        habitats_time_spent = 0
        cal_cost = Cost()

        start_node = Node(None, self.start)
        start_node.g = start_node.h = start_node.f = 0

        cost = []
        open_list = [] # hold neighbors of the expanded nodes
        closed_list = [] # hold all the exapnded nodes

        habitats = self.habitat_list[:]
        habitat_open_list = self.habitat_list[:] # hold haibitats that have not been explored 
        habitat_closed_list = [] # hold habitats that have been explored 

        open_list.append(start_node)

        while len(open_list) > 0:
            current_node = open_list[0] # initialize the current node
            current_index = 0

            for index, item in enumerate(open_list): # find the current node with the smallest f
                if item.f < current_node.f:
                    current_node = item
                    current_index = index
            
            open_list.pop(current_index)
            closed_list.append(current_node)
   
            if abs(current_node.pathLen - pathLenLimit) <= 10: # terminating condition
                path = []
                current = current_node

                while current is not None: # backtracking to find the d 
        
                    path.append(current)
                    cost.append(current.cost)
                    habitats_time_spent += self.habitats_time_spent(current)
                    current = current.parent
                    
                path_mps = [] 
        
                for node in path:
                    mps = Motion_plan_state(node.position[0], node.position[1], traj_time_stamp=round(node.time_stamp, 2))
                    path_mps.append(mps)
                
                trajectory = path_mps[::-1]
                
                # print ("\n", "Original Trajectory: ", trajectory)
                print ("\n", "Original Trajectory length: ", len(trajectory))

                smoothPath = self.smoothPath(trajectory, habitats)
                
                # return {"path length" : len(trajectory), "path" : trajectory, "cost" : cost[0], "cost list" : cost}
                return {"path length" : len(smoothPath), "path" : smoothPath, "cost" : cost[0], "cost list" : cost, "node" : path[::-1]} 
                
            current_neighbors = self.curr_neighbors(current_node, self.boundary_list)

            children = []

            for neighbor in current_neighbors: # create new node if the neighbor is collision-free

                if self.collision_free(neighbor, self.obstacle_list):

                    new_node = Node(current_node, neighbor)

                    children.append(new_node)
           
            for child in children: 

                if child in closed_list:
                    continue
                
                child.pathLen = child.parent.pathLen + euclidean_dist(child.parent.position, child.position)
                dist_left = abs(pathLenLimit - child.pathLen)
                child.time_stamp = int(child.pathLen/self.velocity)
                currGrid = self.findCurrSOG(self.sharkGrid, child.time_stamp) 
                
                child.g = child.parent.cost - w4 * self.get_cell_prob(child, currGrid)
                child.cost = child.g
                # child.h = - w2 * dist_left - w3 * len(habitat_open_list) - w4 * dist_left * self.get_max_prob_from_grid(currGrid)
                child.h = - w2 * dist_left - w3 * len(habitat_open_list) - w4 * self.get_top_n_prob(int(dist_left), currGrid)
                child.f = child.g + child.h 

                # check if child exists in the open list and have bigger g 
                for open_node in open_list:
                    if child == open_node and child.g > open_node.g:
                        continue
                
                x_pos, y_pos = self.get_indices(child.position[0], child.position[1])

                if self.visited_nodes[x_pos, y_pos] == 0: 
                    open_list.append(child)
                    self.visited_nodes[x_pos, y_pos] = 1
Example #15
0
    def astar(self, habitat_list, obs_lst, boundary_list, start, goal,
              weights):
        """
        Find the optimal path from start to goal avoiding given obstacles 

        Parameter: 
            obs_lst - a list of motion_plan_state objects that represent obstacles 
            start - a tuple of two elements: x and y coordinates
            goal - a tuple of two elements: x and y coordinates
        """

        habitats_time_spent = 0
        cal_cost = Cost()
        path_length = 0

        start_node = Node(None, start)
        start_node.g = start_node.h = start_node.f = 0
        end_node = Node(None, goal)
        end_node.g = end_node.h = end_node.f = 0

        dynamic_path = []  # append new node as a* search goes

        cost = []
        open_list = []  # hold neighbors of the expanded nodes
        closed_list = []  # hold all the exapnded nodes
        habitat_open_list = habitat_list  # hold haibitats that have not been explored
        habitat_closed_list = []  # hold habitats that have been explored

        open_list.append(start_node)

        while len(open_list) > 0:
            current_node = open_list[0]  # initialize the current node
            current_index = 0

            for index, item in enumerate(
                    open_list
            ):  # find the current node with the smallest f(f=g+h)
                if item.f < current_node.f:
                    current_node = item
                    current_index = index

            open_list.pop(current_index)

            closed_list.append(current_node)
            dynamic_path.append(current_node.position)
            print("dynamic path: ", dynamic_path)
            # print ('dynamic_path: ', dynamic_path)

            if self.near_goal(current_node.position, end_node.position):
                path = []
                current = current_node

                while current is not None:  # backtracking to find the path
                    path.append(current.position)
                    cost.append(current.cost)
                    # if current.parent is not None:
                    #     current.cost = current.parent.cost + cal_cost.cost_of_edge(current, path, habitat_open_list, habitat_closed_list, weights=[1, 1, 1])
                    path_length += 10
                    habitats_time_spent += self.habitats_time_spent(current)
                    # print ("\n", "habitats_time_spent: ", habitats_time_spent)
                    current = current.parent

                path_mps = []

                for point in path:
                    mps = Motion_plan_state(point[0], point[1])
                    path_mps.append(mps)

                # print ("\n", 'actual path length: ', path_length)
                # print ("\n", 'time spent in habitats: ', habitats_time_spent)
                # print ("\n", "cost list: ", cost)
                # print ("\n", 'cost list length: ', len(cost))
                # print ("\n", 'path list length: ', len(path_mps))
                return ([path_mps[::-1], cost])

            # find close neighbors of the current node

            current_neighbors = self.curr_neighbors(current_node,
                                                    boundary_list)
            print("\n", "current neighbors: ", current_neighbors)

            # make current neighbors Nodes

            children = []
            grid = []  # holds a list of tuples (neighbor, grid value)

            for neighbor in current_neighbors:  # create new node if the neighbor is collision-free
                if self.check_collision(neighbor, obs_lst):
                    """
                    SELECTION 
                    """
                    grid_val = self.create_grid_map(current_node, neighbor)
                    grid.append((neighbor, grid_val))
                    print("\n", "grid value: ", grid_val)

            print("\n", 'grid list: ', grid)
            # remove two elements with the lowest grid values
            grid.remove(min(grid))
            print("selected grid list: ", grid)
            # grid.remove(min(grid))

            # append the selected neighbors to children
            for neighbor in grid:
                new_node = Node(current_node, neighbor[0])
                children.append(new_node)
                # update habitat_open_list and habitat_closed_list
                result = self.check_cover_habitats(new_node, habitat_open_list,
                                                   habitat_closed_list)
                habitat_open_list = result[0]
                # print ("habitat_open_list: ", habitat_open_list)
                habitat_closed_list = result[1]
                # print ("habitat_closed_list: ", habitat_closed_list)

            for child in children:
                if child in closed_list:
                    continue

                # dist_child_current = self.euclidean_dist(child.position, current_node.position)
                if child.parent is not None:
                    result = cal_cost.cost_of_edge(child,
                                                   dynamic_path,
                                                   habitat_open_list,
                                                   habitat_closed_list,
                                                   weights=weights)
                    child.cost = child.parent.cost + result[0]
                # child.g = current_node.g + dist_child_current
                child.g = current_node.cost
                child.h = weights[0] * self.euclidean_dist(
                    child.position,
                    goal) - weights[1] * result[1]  # result=(cost, d_2)
                child.f = child.g + child.h

                # check if child exists in the open list and have bigger g
                for open_node in open_list:
                    if child == open_node and child.g > open_node.g:
                        continue

                open_list.append(child)
Example #16
0
    def astar(self, habitat_list, obs_lst, boundary_list, start, pathLenLimit,
              weights):
        """
        Find the optimal path from start to goal avoiding given obstacles 

        Parameter: 
            obs_lst - a list of motion_plan_state objects that represent obstacles 
            start - a tuple of two elements: x and y coordinates
            goal - a tuple of two elements: x and y coordinates
        """

        w1 = weights[0]
        w2 = weights[1]
        w3 = weights[2]

        habitats_time_spent = 0
        cal_cost = Cost()

        start_node = Node(None, start)
        start_node.g = start_node.h = start_node.f = 0

        cost = []
        open_list = []  # hold neighbors of the expanded nodes
        closed_list = []  # hold all the exapnded nodes
        habitat_open_list = habitat_list  # hold haibitats that have not been explored
        habitat_closed_list = []  # hold habitats that have been explored

        open_list.append(start_node)

        while len(open_list) > 0:
            current_node = open_list[0]  # initialize the current node
            current_index = 0

            for index, item in enumerate(
                    open_list):  # find the current node with the smallest f
                if item.f < current_node.f:
                    current_node = item
                    current_index = index

            open_list.pop(current_index)
            closed_list.append(current_node)

            if abs(current_node.pathLen -
                   pathLenLimit) <= 10:  # terminating condition
                path = []
                current = current_node

                while current is not None:  # backtracking to find the d

                    path.append(current.position)
                    cost.append(current.cost)
                    habitats_time_spent += self.habitats_time_spent(current)
                    current = current.parent

                path_mps = []

                for point in path:
                    mps = Motion_plan_state(point[0], point[1])
                    path_mps.append(mps)
                return ([path_mps[::-1], cost])

            current_neighbors = self.curr_neighbors(current_node,
                                                    boundary_list)

            children = []
            grid = []
            '''Old Cost Function'''
            for neighbor in current_neighbors:  # create new node if the neighbor is collision-free

                if self.collision_free(neighbor, obs_lst):

                    new_node = Node(current_node, neighbor)
                    result = self.update_habitat_coverage(
                        new_node, habitat_open_list, habitat_closed_list
                    )  # update habitat_open_list and habitat_closed_list
                    habitat_open_list = result[0]
                    habitat_closed_list = result[1]

                    cost_of_edge = cal_cost.cost_of_edge(
                        new_node, habitat_open_list, habitat_closed_list,
                        weights)
                    new_node.cost = new_node.parent.cost + cost_of_edge[0]

                    children.append(new_node)
            '''New Cost Function'''
            # for neighbor in current_neighbors: # create new node if the neighbor is collision-free

            #     if self.collision_free(neighbor, obs_lst):

            #         """
            #         SELECTION
            #         """
            #         grid_val = self.create_grid_map(current_node, neighbor)
            #         grid.append((neighbor, grid_val))

            # grid.remove(min(grid))

            # append the selected neighbors to children
            for neighbor in grid:
                new_node = Node(current_node, neighbor[0])
                children.append(new_node)

                result = self.update_habitat_coverage(
                    new_node, habitat_open_list, habitat_closed_list
                )  # update habitat_open_list and habitat_closed_list
                habitat_open_list = result[0]
                habitat_closed_list = result[1]

            for child in children:

                if child in closed_list:
                    continue

                result = cal_cost.cost_of_edge(child, habitat_open_list,
                                               habitat_closed_list, weights)
                d_2 = result[1]
                d_3 = result[2]

                child.g = child.parent.cost - w2 * d_2 - w3 * d_3
                child.cost = child.g
                child.h = -w2 * abs(pathLenLimit - child.pathLen) - w3 * len(
                    habitat_open_list)
                child.f = child.g + child.h
                child.pathLen = child.parent.pathLen + euclidean_dist(
                    child.parent.position, child.position)

                # check if child exists in the open list and have bigger g
                for open_node in open_list:
                    if child == open_node and child.g > open_node.g:
                        continue

                x_pos, y_pos = self.get_indices(child.position[0],
                                                child.position[1])
                print('\n', "x_in_meter, y_in_meter: ", child.position[0],
                      child.position[1])
                print('\n', "x_pos, y_pos", x_pos, y_pos)

                if self.visited_nodes[x_pos, y_pos] == 0:
                    open_list.append(child)
                    self.visited_nodes[x_pos, y_pos] = 1
                else:
                    print("False attempt : ", child.position)
Example #17
0
    def astar(self, habitat_list, obs_lst, boundary_list, start, pathLenLimit, weights): 
        """
        Find the optimal path from start to goal avoiding given obstacles 
        Parameter: 
            obs_lst - a list of motion_plan_state objects that represent obstacles 
            start - a tuple of two elements: x and y coordinates
            goal - a tuple of two elements: x and y coordinates
        """
        
        w1 = weights[0]
        w2 = weights[1]
        w3 = weights[2]

        habitats_time_spent = 0
        cal_cost = Cost()

        start_node = Node(None, start)
        start_node.g = start_node.h = start_node.f = 0

        cost = []
        open_list = [] # hold neighbors of the expanded nodes
        closed_list = [] # hold all the exapnded nodes

        # habitats = habitat_list[:]

        open_list.append(start_node)

        while len(open_list) > 0:
            current_node = open_list[0] # initialize the current node
            current_index = 0

            for index, item in enumerate(open_list): # find the current node with the smallest f
                if item.f < current_node.f:
                    current_node = item
                    current_index = index
            
            open_list.pop(current_index)
            closed_list.append(current_node)
   
            if abs(current_node.pathLen - pathLenLimit) <= 10: # terminating condition
                path = []
                current = current_node

                while current is not None: # backtracking to find the d 
        
                    path.append(current.position)
                    cost.append(current.cost)
                    habitats_time_spent += self.habitats_time_spent(current)
                    current = current.parent
                    
                path_mps = [] 
        
                for point in path:
                    mps = Motion_plan_state(point[0], point[1])
                    path_mps.append(mps)
                
                trajectory = path_mps[::-1]

                # smoothPath = self.smoothPath(trajectory, habitats)

                return ({"path" : trajectory, "cost list" : cost, "cost" : cost[0]})
            
            current_neighbors = self.curr_neighbors(current_node, boundary_list)

            children = []

            for neighbor in current_neighbors: # create new node if the neighbor is collision-free

                if self.collision_free(neighbor, obs_lst):

                    new_node = Node(current_node, neighbor)
                    self.update_habitat_coverage(new_node, self.habitat_open_list, self.habitat_closed_list)  
        
                    cost_of_edge = cal_cost.cost_of_edge(new_node, self.habitat_open_list, self.habitat_closed_list, weights)
                    new_node.cost = new_node.parent.cost + cost_of_edge[0]
  
                    children.append(new_node)

            for child in children: 

                if child in closed_list:
                    continue

                habitatInfo = cal_cost.cost_of_edge(child, self.habitat_open_list, self.habitat_closed_list, weights) 
                insideAnyHabitats = habitatInfo[1]
                insideOpenHabitats = habitatInfo[2]
                
                child.g = child.parent.cost - w2 * insideAnyHabitats - w3 * insideOpenHabitats 
                child.cost = child.g
                child.h = - w2 * abs(pathLenLimit - child.pathLen) - w3 * len(self.habitat_open_list)
                child.f = child.g + child.h 
                child.pathLen = child.parent.pathLen + euclidean_dist(child.parent.position, child.position)
                child.time_stamp = int(child.pathLen/self.velocity)

                # check if child exists in the open list and have bigger g 
                for open_node in open_list:
                    if child == open_node and child.g > open_node.g:
                        continue
                
                x_pos, y_pos = self.get_indices(child.position[0], child.position[1])

                if self.visited_nodes[x_pos, y_pos] == 0: 
                    open_list.append(child)
                    self.visited_nodes[x_pos, y_pos] = 1
Example #18
0
def main(Vxf0, urdf, options):
    gmm = GMM(num_clusters=options['num_clusters'])

    if options['args'].data_type == 'h5_data':
        filename = '{}.h5'.format('torobo_processed_data')
        with h5py.File(filename, 'r+') as f:
            data = f['data/data'].value
        logging.debug(''.format(data.shape))
    elif options['args'].data_type == 'pipe_et_trumpet':
        path = 'data'
        name = 'cart_pos.csv'
        data, data6d = format_data(path, name, learn_type='2d')

    if options['use_6d']:
        data = data6d

    Vxf0['d'] = int(data.shape[0] / 2)
    Vxf0.update(Vxf0)

    Vxf0 = guess_init_lyap(data, Vxf0, options['int_lyap_random'])
    cost = Cost()

    # cost.success = False
    while cost.success:
        # cost.success = False
        Vxf, J = cost.learnEnergy(Vxf0, data, options)
        # if not cost.success:
        # increase L and restart the optimization process
        old_l = Vxf0['L']
        Vxf0['L'] += 1
        rospy.logwarn(
            'Constraints violated. increasing the size of L from {} --> {}'.
            format(old_l, Vxf0['L']))
        if cost.success:
            rospy.logdebug(
                'optimization succeeded without violating constraints')
            break

    # get gmm params
    gmm.update(data.T, K=options['num_clusters'], max_iterations=100)
    mu, sigma, priors = gmm.mu, gmm.sigma, gmm.logmass

    if options['disp']:
        logging.debug(' mu {}, sigma {}, priors: {}'.format(
            mu.shape, sigma.shape, priors.shape))

    inp = slice(0, Vxf['d'])  #np.array(range(0, Vxf['d']))
    out = slice(Vxf['d'],
                2 * Vxf['d'])  #np.array(range(Vxf['d'], 2* Vxf['d']))
    rho0, kappa0 = 1.0, 1.0

    gmr_handle = lambda x: GMR(priors, mu, sigma, x, inp, out)
    stab_handle = lambda dat: dsStabilizer(dat, gmr_handle, Vxf, rho0, kappa0)

    x0_all = data[0, :]
    XT = data[-1, :]

    logger.debug('XT: {} x0: {} '.format(XT.shape, x0_all.shape))
    home_pos = [0.0] * 7
    executor = ToroboExecutor(home_pos, urdf)
    x, xd = executor.optimize_traj(data6d, stab_handle, opt_exec)
Example #19
0
if __name__ == "__main__":
    train, valid, test = load('mnist.pkl.gz')
    trans_train, shift_train, ori_train = translation(train[0], 28)
    trans_train, shift_train, ori_train = shared(
        (trans_train, shift_train, ori_train))
    trans_valid, shift_valid, ori_valid = translation(valid[0], 28)
    trans_valid, shift_valid, ori_valid = shared(
        (trans_valid, shift_valid, ori_valid))
    trans_test, shift_test, ori_test = translation(test[0], 28)
    trans_test, shift_test, ori_test = shared(
        (trans_test, shift_test, ori_test))

    num_capsules = 60
    in_dim = 784
    recog_dim = 10
    gener_dim = 20
    activation = 'sigmoid'

    input = T.matrix('input')
    extra_input = T.matrix('extra')
    output = T.matrix('output')
    transae = TransAE(num_capsules, in_dim, recog_dim, gener_dim, activation)
    cost = Cost(transae, input, extra_input)
    train = SGDTrain(input, extra_input, output,
                     (trans_train, shift_train, ori_train), transae, cost)
    train.main_loop((trans_valid, shift_valid, ori_valid),
                    (trans_test, shift_test, ori_test),
                    epochs=800,
                    serialize=True)
Example #20
0
        print(f'x == {x}')
        raise e

    myctparam.xlog(x, myctparam.i, total_cost, var_bool)
    print(f'ITERATION = {myctparam.i}\t\t***   TOTAL COST = {total_cost}')
    return total_cost


mypl = Plant()
mypl.run(Const.PLANT_PATH)

mymrg = Margin()
mymrg.run(mypl.freqhz, mypl.freqhzunit)

# IN THIS SCRIPT
mycost = Cost(mymrg, mypl)
myct = Controller(mypl.freq)
myctparam = ControlParam()
xparam = myctparam.xinitial(4)
#iter_num = myctparam.i
#mybound = Bounds(Const.XMIN, Const.XMAX, keep_feasible=False)
#xu      = minimize(fun = IO, x0= ControlParam.x_notch4 , method ='COBYLA', options={'rhobeg': 1.0, 'maxiter': 20, 'disp': True, 'catol': 0.0002})

Const.OPTMETHOD = 'Nelder-Mead'

tstart = time.monotonic()
xu = minimize(fun=IO,
              x0=xparam,
              method=Const.OPTMETHOD,
              options={
                  'rhobeg': 1.0,
Example #21
0
    def execute_command(self, command):
        """
		This function is to execute the command entered
		Do pre processing before call the execution function is need
		:param command: Command entered
		:return: value form execute function
		"""
        if command == 'exit':
            sys.exit()
        elif command.startswith('todo '):
            if self.current_user_level >= 2:
                """Team leader and above is access to add task"""
                description = command.split(' ', 1)[1]
                return self.project.add_task(ToDo(description, False))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('deadline '):
            if self.current_user_level >= 2:
                """Team leader and above is access to add task"""
                command_part = command.split(' ', 1)[1]
                description = self.remove_from_word(command_part, 'by')
                by = self.remove_to_word(command_part, 'by')
                return self.project.add_task(Deadline(description, False, by))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('timeline '):
            if self.current_user_level >= 2:
                """Team leader and above is access to add task"""
                command_part = command.split(' ', 1)[1]
                description = self.remove_from_word(command_part, 'from')
                date = self.remove_to_word(command_part, 'from')
                start_date = self.remove_from_word(date, 'to')
                end_date = self.remove_to_word(date, 'to')
                return self.project.add_task(
                    TimeLine(description, False, start_date, end_date))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('done '):
            if self.current_user_level >= 2:
                """Team leader and above is access to update task"""
                user_index = command.split(' ', 1)[1]
                index = int(user_index) - 1
                if index < 0:
                    raise Exception('Index must be grater then 0')
                else:
                    try:
                        self.project.tasks[index].mark_as_done()
                        return 'Congrats on completing a task ! :-)'
                    except Exception:
                        raise Exception('No item at index ' + str(index + 1))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('pending '):
            if self.current_user_level >= 2:
                """Team leader and above is access to update task"""
                user_index = command.split(' ', 1)[1]
                index = int(user_index) - 1
                if index < 0:
                    raise Exception('Index must be grater than 0')
                else:
                    try:
                        self.project.tasks[index].mark_as_pending()
                        return 'Task mark as pending'
                    except Exception:
                        raise Exception('No item at index' + str(index + 1))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('resource '):
            if self.current_user_level >= 2:
                """Team leader and above is access to add resource"""
                command_part = command.split(' ', 1)[1]
                description = self.remove_from_word(command_part, 'is')
                quantity = self.remove_to_word(command_part, 'is')
                return self.project.add_resources(
                    Resource(description, quantity))
            else:
                raise ValueError('Team leader or above only can add task')

        elif command.startswith('cost of '):
            if self.current_user_level >= 3:
                """Manager and above is access to add cost"""
                command_part = command.split(' ', 2)[2]
                description = self.remove_from_word(command_part, 'is')
                cost = self.remove_to_word(command_part, 'is')
                return self.project.add_cost(Cost(description, cost))
            else:
                raise ValueError('Manager and above only can add cost')

        elif command.startswith('remove '):
            try:
                command_part = command.split(' ', 2)[1]
                command_index = command.split(' ', 2)[2]
                index = int(command_index) - 1
                if command_part == 'task':
                    if self.current_user_level >= 2:
                        """Team leader and above to access to remove task"""
                        return self.project.remove_task(index)
                    else:
                        raise ValueError(
                            'Team leader and above only can remove task')
                elif command_part == 'resource':
                    if self.current_user_level >= 2:
                        """Team Leader and above to access to remove resource"""
                        return self.project.remove_resource(index)
                    else:
                        raise ValueError(
                            'Team leader and above only can remove resource')
                elif command_part == 'cost':
                    if self.current_user_level >= 3:
                        """Manager and above to access to remove cost"""
                        return self.project.remove_cost(index)
                    else:
                        raise ValueError('Manager adn above only remove cost')
            except Exception:
                raise ValueError(
                    'Command format not recognize.\n Command: >>> remove [task/resource/cost] [index]'
                )
        else:
            logging.error('Command not recognized.')
            raise Exception('Command not recognized')
Example #22
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("csv_file_path")
    parser.add_argument("--encoding", default="utf_8")
    options = parser.parse_args()
    _utObject = utils()
    testCsv, aircraftCode, aircraftRange = _utObject.input(options)
    # print("TESTCSV:::::::::",testCsv)
    # print(aircraftCode)
    # print(aircraftRange)
    outputList = []
    _airdict = Airport()
    parsedAirportDict = _airdict.parseAirport('airport.csv')
    for tCi, tC in enumerate(testCsv):
        #Iterates over IATA code in testCsv storing their into a dictionary as tuples
        #Saving lat and long values for each IATA
        distances = {}
        for row in tC:
            data = parsedAirportDict.get(row)
            distances[row] = data
        # print(distances)

        #Calculating all possible distances between routes and storing them in a dict
        dict_air = {}
        for airs in distances:
            src = airs
            indivDist = []
            for airs2 in distances:
                dest = airs2
                indivDist.append(
                    _airdict.distanceBetweenAirports(distances[src][0],
                                                     distances[src][1],
                                                     distances[dest][0],
                                                     distances[dest][1]))
            dict_air[src] = indivDist
        #print(dict_air)

        #transform nodes(keys) of dict into a sequence
        graph_nodes = (list(dict_air.keys()))

        # _min_distance_obj = MinDist()
        # shortest_path = _min_distance_obj.bruteForce(graph_nodes,dict_air)

        airports_visited = []
        min_dist = []
        airIndices = []
        new_source = graph_nodes[0]
        # airIndices.append(0)
        for s in graph_nodes:
            # print("Destination:", new_source)
            airports_visited.append(new_source)
            distances = dict_air.get(new_source)
            for i in airIndices:
                # print(s)
                distances[i] = 9999999
            # print(distances)
            index = -1
            for i, element in enumerate(distances):
                if element == 0:
                    index = i
                    distances[i] = 9999999
            airIndices.append(index)
            mDist = min(distances)
            #print(mDist)
            airpIndex = distances.index(mDist)
            airIndices.append(airpIndex)
            #print("Index:",airpIndex)
            new_source = graph_nodes[airpIndex]
            min_dist.append(min(distances))

        #Popping last element off stack to get 4 shortest distances
        min_dist.pop()
        #print(min_dist)

        finalSource = airports_visited[-1]
        finalDestination = airports_visited[0]
        finalSourceDist = parsedAirportDict.get(finalSource)
        finalDestinationDist = parsedAirportDict.get(finalDestination)

        finalDistance = _airdict.distanceBetweenAirports(
            finalSourceDist[0], finalSourceDist[1], finalDestinationDist[0],
            finalDestinationDist[1])
        #print(finalDistance)
        #Append final dist to list of distances
        airports_visited.append(finalDestination)
        print("Itinerary:", airports_visited, '\n')

        min_dist.append(finalDistance)
        print("Itinerary Distances:", min_dist, '\n')
        print('________________________________________________', '\n')
        #Destination is the last index of airports_visited list
        _currencyobject = Currency()
        parsedCurrencyCost = _currencyobject.currencyParser(
            'Currency_code_concat.csv')

        billingCountry = airports_visited[-1]

        _costObject = Cost()
        toEuroRate = _costObject.toEuroRate(billingCountry, 'airport.csv',
                                            'countrycurrency.csv',
                                            'currencyrates.csv')
        print(toEuroRate)

        print("Cost of round trip: ", "€", (sum(min_dist) // toEuroRate))

        #Also calculate distance from last dest in list to home
        #

        print('________________________________________________')
        print("Checking if Itinerary is possible with provided aircraft")
        journeyPossible = _airdict.isItineraryPossible(aircraftRange[tCi],
                                                       min_dist)
        if journeyPossible == False:
            print(
                "Sorry, with the provided aircraft this journey cannot be made. Try again!"
            )
            airports_visited.append("No Route")
            outputList.append(airports_visited)
        else:
            remainingFuel = aircraftRange[tCi]
            print("\t\t\tRemaining Fuel::: ", remainingFuel)
            totalCosttoRefuel = 0
            toEuroRate = _costObject.toEuroRate(airports_visited[0],
                                                'airport.csv',
                                                'countrycurrency.csv',
                                                'currencyrates.csv')
            print("\t\t\t\t\tItinerary Scheduled:  ", airports_visited)
            print("\t\t\t\t\tItinerary Scheduled:  ", min_dist)
            totalCosttoRefuel += aircraftRange[tCi] * toEuroRate
            for i, val in enumerate(min_dist):
                toEuroRate = _costObject.toEuroRate(airports_visited[i + 1],
                                                    'airport.csv',
                                                    'countrycurrency.csv',
                                                    'currencyrates.csv')

                print("\t\t\tAT Airport: ", airports_visited[i + 1])
                print("\t\t\tAT Airport: ", airports_visited[i + 1],
                      "the EURO Rate is: ", toEuroRate)
                if remainingFuel >= val:
                    print("\t\t\t\tProceeding")
                    remainingFuel -= val
                else:
                    print("\t\t\tRefueling")
                    costOfRefuel = (aircraftRange[tCi] -
                                    remainingFuel) * toEuroRate
                    totalCosttoRefuel += costOfRefuel
                    remainingFuel = aircraftRange[tCi] - val
                    print("\t\t\t\t", costOfRefuel)
                print("\t\t\t\tRemaining", remainingFuel)
            airports_visited.append(totalCosttoRefuel)
            outputList.append(airports_visited)
            print("TOTAL COST FOR ITINERARY IS: ", totalCosttoRefuel)

    print("Generating output csv file")
    _utObject.tocsv(outputList)
Example #23
0
            start -- a position tuple (x, y)
            pathLenLimit -- the path length limit in meters
            weights -- a list of coefficients [w1, w2, w3]
        
        Returns:
            The optimal trajectory
        """
        # Initialize weights
        weight_10 = weights[0]
        weight_1000 = weights[1]
        weight_100 = weights[2]
        # Initialize time spent in habitats
>>>>>>> 96f4bdb0ee8c8c20b7f0c4becf194855f19cc5a6
        habitats_time_spent = 0
        # Initialize cost
        cal_cost = Cost()
        cost = []
        # Initialize start node
        start_node = Node(None, start)
        start_node.g = start_node.h = start_node.f = 0
        
        open_list = [] # List hold sneighbors of the expanded nodes
        closed_list = [] # List holds all the exapnded nodes
        open_list.append(start_node)
        while len(open_list) > 0:
            current_node = open_list[0] # Initialize the current node
            current_index = 0
            # Find the current node with the smallest f
            for index, item in enumerate(open_list): 
                if item.f < current_node.f:
                    current_node = item