def gbfs(self, problem):
        q = [Path([problem.getInitial()])]
        visited = []
        i = 0
        while q:
            i = i + 1
            currentPath = q.pop(0)
            currentState = currentPath.getLast()

            if currentState == problem.getFinal():
                return currentPath, i

            visited.append(currentState)

            aux = []

            for child in currentState.allNextStates():
                if child not in visited:
                    aux.append(child)

            aux = self.orderStates(aux)

            for state in aux:
                p = Path(deepcopy(currentPath.getValues()))
                p.add(State(deepcopy(state.getValues())))
                q.append(p)

        return None, i
Пример #2
0
 def __init__(self,
              taxi_id,
              cur_lon,
              cur_lat,
              init_last_update_time,
              partition_id_belongto,
              seat_left,
              mobility_vector=None):
     self.seat_left = (3 if seat_left == None else seat_left)
     self.taxi_id = taxi_id
     self.cur_lon = cur_lon
     self.cur_lat = cur_lat
     self.schedule_list = [{
         'request_id': -1,
         'schedule_type': 'NO_ORDER',
         'lon': cur_lon,
         'lat': cur_lat,
         'arrival_time': init_last_update_time
     }]
     # schedule list中保存的是字典, 里面的内容包括: request_id: request_id, schedule_type: shedule的类型(出发或到达), lon: 经度, lat: 纬度, arrival_time: 计算出来的预期到达时间
     self.__last_update_time = init_last_update_time
     self.partition_id_belongto = partition_id_belongto
     self.mobility_vector = mobility_vector
     self.path = Path(init_last_update_time)
     self.cur_total_cost = 0
     self.seat_left = seat_left
     self.capability = self.seat_left
Пример #3
0
    def execute(self, g):

        gcodes = self.printer.config.get("Macros", "G29").split("\n")
        self.printer.path_planner.wait_until_done()
        for gcode in gcodes:
            G = Gcode({"message": gcode, "prot": g.prot})
            self.printer.processor.execute(G)
            self.printer.path_planner.wait_until_done()

        logging.debug(self.printer.probe_heights)

        # Remove the offset from the probed points
        if self.printer.probe_points[0][
                "X"] == 0 and self.printer.probe_points[0]["Y"] == 0:
            # If the origin is located in the first probe point, remove that.
            self.printer.probe_heights -= self.printer.probe_heights[0]
        else:
            # Else, remove the lowest.
            self.printer.probe_heights -= min(self.printer.probe_heights)

        # Log the found heights
        for k, v in enumerate(self.printer.probe_points):
            self.printer.probe_points[k]["Z"] = self.printer.probe_heights[k]
        logging.info("Found heights: ")
        logging.info(self.printer.probe_points)

        # Add 'S'=simulate To not update the bed matrix.
        if not g.has_letter("S"):
            # Update the bed compensation matrix
            Path.update_autolevel_matrix(self.printer.probe_points,
                                         self.printer.probe_heights)
            logging.debug("New Bed level matrix: ")
            logging.debug(Path.matrix_bed_comp)
Пример #4
0
    def execute(self, g):

        gcodes = self.printer.config.get("Macros", "G29").split("\n")
        self.printer.path_planner.wait_until_done()
        for gcode in gcodes:        
            G = Gcode({"message": gcode, "prot": g.prot})
            self.printer.processor.execute(G)
            self.printer.path_planner.wait_until_done()

        logging.debug(self.printer.probe_heights)

        # Remove the offset from the probed points        
        if self.printer.probe_points[0]["X"] == 0 and self.printer.probe_points[0]["Y"] == 0:
            # If the origin is located in the first probe point, remove that. 
            self.printer.probe_heights -= self.printer.probe_heights[0]
        else:
            # Else, remove the lowest. 
            self.printer.probe_heights -= min(self.printer.probe_heights)

        # Log the found heights
        for k, v in enumerate(self.printer.probe_points):
            self.printer.probe_points[k]["Z"] = self.printer.probe_heights[k]
        logging.info("Found heights: ")
        logging.info(self.printer.probe_points)

        # Add 'S'=simulate To not update the bed matrix.  
        if not g.has_letter("S"):
            # Update the bed compensation matrix
            Path.update_autolevel_matrix(self.printer.probe_points, self.printer.probe_heights)
            logging.debug("New Bed level matrix: ")
            logging.debug(Path.matrix_bed_comp)
Пример #5
0
def generate_slot_line(n, slot_position, slot_height, slot_width, base_height,
                       base_width):

    if slot_height == 0 and slot_width == 0:
        return []

    slot_height = min(slot_height, base_height)
    slot_width = min(slot_width, base_width)

    rect = [(0, 0), (0, slot_height), (slot_width, slot_height),
            (slot_width, 0)]

    dx = (base_width - slot_width) / 2
    if slot_position == -1:
        dy = 0
    elif slot_position == 0:
        dy = (base_height - slot_height) / 2
    elif slot_position == +1:
        dy = base_height - slot_height

    slot = Path(rect, 'c', closed=True) + (dx, dy)
    slots = [slot + (base_width * i, 0) for i in range(n)]

    divider = Path([(base_width, 0), (base_width, base_height)], style='m')
    dividers = [divider + (base_width * i, 0) for i in range(n - 1)]
    return slots + dividers
Пример #6
0
def main():
    print('initializing')
    #Constant Speed
    speed = 0.1
    direction = 0
    local = [-0.1,-0.1]
    coordsx = []
    coordsy = []
    #initialize w/ set of waypoints
    waypoints = util.generateWayPoints(1, (lambda x: 5*math.sin(x)), [0,10])
    path = Path(waypoints, 10)
    pathX = []
    pathY = []
    for point in waypoints:
        pathX.append(point[0])
        pathY.append(point[1])
    
    itter = 0
    while(not path.isEndOfPath(local)):
        itter += 1
        coordsx.append(local[0])
        coordsy.append(local[1])
        waypoint = path.getWaypoint(local)
        #calculate heading
        direction = path.getHeading(waypoint[0]-local[0], waypoint[1] - local[1])
        #calculate new position
        local = [local[0] + speed * math.cos(direction), local[1] + speed * math.sin(direction)]
    plt.plot(coordsx, coordsy, label = "Path")
    plt.scatter(pathX, pathY, label = "waypoints", color = '#88c999')
    plt.xlabel("X(m)")
    plt.ylabel("Y(m)")
    plt.title("Path Pursuit Algorithm")
    plt.legend()
    plt.show()
def BreadthWidthSearch(visibilityGraph, vrtx1, vrtx2):
    #Initialize the path
    path = Path()
    #Initialize the queue
    queue = Queue()
    #Add the starting vertex to the queue
    queue.Enqueue(vrtx1)
    #mark as visited
    visitedVrtcs = [vrtx1]

    #while the queue is not empty run until empty
    while (len(queue.GetQueue()) != 0):
        vrtx = queue.Dequeue()
        neighbor = visibilityGraph.GetVertexEdges(vrtx)
        for nxtVrtx in neighbor:
            #if the neighbor vertex has not been visited
            if ((visitedVrtcs.count(nxtVrtx) == 0)):
                #queue the next vertex
                queue.Enqueue(nxtVrtx)
                #mark as visited
                visitedVrtcs.append(nxtVrtx)

                path.AddToPath(vrtx, nxtVrtx)

    path.GetPaths()
    return path
Пример #8
0
def pruning_test():
    # Setup Team Object
    team_edm = Team()
    lines = list()
    lines.append(Line(0, 1.701))
    lines.append(Line(1, 0.658))
    lines.append(Line(2, 0.299))
    lines.append(Line(3, 0.433))
    team_edm.set_team("EDM", lines=lines,
                      start_line_index=0)  # Edmonton Oilers

    path = Path()
    path.team = team_edm

    values_best = []
    for i in range(30):
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, i)
        values_best.append(num_visited)

    path.team[path.team.curr_line_index].toi = 0
    values_worst = []
    for i in range(30):
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, i)
        values_worst.append(num_visited)

    theoretical_values = [theoretical_nodes(i) for i in range(30)]
    print(theoretical_values)
    print(values_best)
    print(values_worst)
Пример #9
0
 def check_constraints(self,req:Request, path:Path)->bool:
     # 检查时延
     if path.propagation_delay >= req.maxDelay:
         return False
     # 检查带宽和带宽费用
     for e in path.edges:
         if e.leftBandWidth < req.bandwidth:
             return False
         path.band_cost += e.unitprice*req.bandwidth
     if path.band_cost >= req.bid:
         return False
     # 处理时延
     path.process_delay = min(req.maxDelay - path.propagation_delay, len(req.sfc)*req.bandwidth)
     # 判断算力是否满足条件
     # 所需最低算力
     for vnf in req.sfc:
         path.process_source += config.VNF_DELAY[vnf]
     path.process_source *= 1/path.process_delay
     # 判断是否有足够算力和最低算力开销
     for node in path.nodes:
         node:DataCenter
         # 判断节点剩余算力是否足够部署sfc
         if node.leftcpu < path.process_source:
             continue
         # 判断在该节点部署SFC是否亏本
         profit = req.bid - path.band_cost - node.unitCpuPrice*path.process_source
         if profit <= 0:
             continue
         # 上述两个条件都满足,表示可以在该路径部署,计算或更新贪心利润
         path.greedy_cost = max(profit, path.greedy_cost)
     # 没有可部署的节点,返回False
     return path.greedy_cost > 0
Пример #10
0
def make_control(argv):
    # return a Bunch

    print argv
    if len(argv) not in (1, 2):
        usage('invalid number of arguments')

    pcl = ParseCommandLine(argv)
    arg = Bunch(
        base_name=argv[0].split('.')[0],
        test=pcl.has_arg('--test'),
    )

    random_seed = 123456
    random.seed(random_seed)

    path = Path()  # use the default dir_input

    debug = False

    return Bunch(
        arg=arg,
        debug=debug,
        path=path,
        path_out=path.dir_working() + arg.base_name + '-' + 'derived.csv',
        random_seed=random_seed,
        test=arg.test,
    )
Пример #11
0
    def getCustomPath(latitude, longitude, end_place):
        startCoord = Coordinate()
        startCoord.latitude = latitude
        startCoord.longitude = longitude
        
        #Get all coordinate in the database for our end place
        end_coordinates = Coordinate.getAllForBuilding(end_place)
        if len(end_coordinates) == 0:
            raise Exception(end_place + " is not a building in our database")
        
        #Figure out the two closest coordinates
        (startCoord, endCoord) = DB.getClosestCoords([startCoord], end_coordinates)
        
        #Find all floor plans for our end place
        #floorPlans = []
        #floors = Floor.getAllForBuilding(end_place)
        #for floor in floors:
        #    floorPlans.append(floor.floor_map)
        
        #Get building information for our end place
        building = Building()
        building.loadFromID(end_place)
        
        #Build path object to pass back
        path = Path()
        path.startCoord = startCoord.__dict__
        path.endCoord = endCoord.__dict__
        path.floorPlans = building.floorPlans
        path.buildingInfo = building.__dict__

        return path.__dict__
Пример #12
0
def make_control(argv):
    # return a Bunch

    print argv
    if len(argv) not in (3, 4):
        usage('invalid number of arguments')

    pcl = ParseCommandLine(argv)
    arg = Bunch(
        base_name=argv[0].split('.')[0],
        geo=pcl.get_arg('--geo'),
        test=pcl.has_arg('--test'),
    )
    if arg.geo is None:
        usage('missing --arg')
    if arg.geo not in ('census_tract', 'zip5'):
        usage('invalid GEO value: ', + arg.geo)

    random_seed = 123456
    random.seed(random_seed)

    path = Path()  # use the default dir_input

    debug = False

    return Bunch(
        arg=arg,
        debug=debug,
        max_sale_price=85e6,  # according to Wall Street Journal
        path=path,
        path_out_csv=path.dir_working() + arg.base_name + '-' + arg.geo + '.csv',
        path_out_occurs=path.dir_working() + arg.base_name + '-' + arg.geo + '-occurs.pickle',
        random_seed=random_seed,
        test=arg.test,
    )
Пример #13
0
def curvature_analysis(coordinatesIN, scaleIN):

    # read in coordinates and convert to path object
    p = Path(coordinatesIN)

    curvatures = []

    for unit_step in scaleIN:

        # subset path in segments in unit_steps
        p.subsetPath(unit_step)

        # list of projection vectors (minus the last vector, not to be used)
        projections = [
            ProjectionVector([segment[0], segment[-1]])
            for segment in p.segmented_coordinates[0:-1]
        ]

        # list of segments to be used for calculation (minus the first segment, not to be used)
        segments = [[i[0], i[-1]] for i in p.segmented_coordinates[1:]]

        # Build list of angles (same as above but faster)
        raw_angles = [
            findAngle(segments[i], projections[i])
            for i in range(len(projections))
            if len(projections) == len(segments)
        ]

        # list of curvatures
        curvature = np.abs(raw_angles) / unit_step

        curvatures.append(np.median(curvature) / 100)

    return (curvatures)
Пример #14
0
 def __init__(s):
       #Dane:
       win=Window("Point",0,0,600,600)
       master=win.getMaster()
       desk=Desk(master)
       C=desk.getC()
       
       
       p1=Point(100,100)
       p2=Point(200,100)
       p3=Point(200,200)
       p4=Point(100,200)
       
       desk.addPoint(p1)
       desk.addPoint(p2)
       desk.addPoint(p3)
       desk.addPoint(p4)
       
       path=Path()
       path.addPoint(p1)
       path.addPoint(p2)
       path.addPoint(p3)
       path.addPoint(p4)
       
       desk.addPath(path)
       
       
       win.loop()
Пример #15
0
 def test_add(self):
     t1 = Task(foo=1)
     t2 = Task(bar=2)
     p1 = Path([t1])
     p2 = Path([t2])
     self.assertEqual((p1 + p2).get_tasks(), [t1, t2])
     self.assertEqual((p2 + p1).get_tasks(), [t2, t1])
Пример #16
0
    def cwd_service(self, req, user):
        last_dir = user.dir
        if len(req["args"]) == 0:
            user.dir = "."
            return Res(212, msg="Successful change.", sid=user.sid)
        
        # #check if address is local 
        # if req["args"][0][0] == '/':
        #     norm_path = os.path.join(".", req["args"][0][1:])
        # else:
        #     norm_path = os.path.join(user.dir, req["args"][0])
        # # Normalizes the path -> ../..
        # norm_path = os.path.normpath(norm_path)
        dirpath = Path().join(self.base, req["args"][0], user.dir) #final destination
        norm_path = Path().join_user_dir(req["args"][0], user.dir)
        user.dir = norm_path

        mypath = os.path.join(self.base, user.dir)
        # check if it is a valid dir
        if os.path.exists(mypath) == 0:
            user.dir = last_dir
            return Res(214, msg="Dir doesnt exist")
        # elif user.dir[:2] == "..":
        #     user.dir = "."
        #     mypath = os.path.join(self.base, user.dir)
        #     return Res(214)
        elif os.path.isdir(mypath) == 0:
            user.dir = last_dir
            return Res(214, msg="is not a Dir")
            
        # print("This dir contains:",[f for f in listdir(mypath)])
        return Res(212, msg="Successful change.", sid=user.sid)
Пример #17
0
 def test_Expand(self):
     self.assertEqual(os.path.expanduser('~/'), Path.Expand('~/'))
     self.assertEqual(os.path.expanduser('~/A/B.c'), Path.Expand('~/A/B.c'))
     self.assertEqual(os.path.expandvars('$HOME/'), Path.Expand('$HOME/'))
     self.assertEqual(os.path.expandvars('$HOME/A/B.c'), Path.Expand('$HOME/A/B.c'))
     self.assertEqual(os.path.expandvars('${HOME}/A/B.c'), Path.Expand('${HOME}/A/B.c'))
     self.assertEqual(os.path.expandvars(os.path.expanduser('~/sub/${HOME}/A/B.c')), Path.Expand('~/sub/${HOME}/A/B.c'))
Пример #18
0
    def _insert_path(self,
                     agent: LearningAgent,
                     path: Path,
                     new_node: PathNode,
                     max_insert_idx: int = -1) -> Tuple[Path, int]:
        # Deal with deafult values
        if (max_insert_idx == -1):
            max_insert_idx = len(path.request_order)

        # Get info about new_node
        location, deadline = path.get_info(new_node)
        is_dropoff = new_node.is_dropoff

        # Find insertion point with minimum dropoff delay
        num_dropoffs_after = 0
        min_future_delay = float('inf')
        max_total_delay = Path.NOT_APPLICABLE
        min_delay_idx = Path.NOT_APPLICABLE

        # Check all insertion points by iterating backward through the request order
        for insert_idx in range(len(path.request_order), -1, -1):
            delay, delay_for_new_node, min_future_delay = self._can_insert_node(
                agent, path, new_node, insert_idx, min_future_delay)

            # If pickup node, only insert if it's before dropoff node
            if (insert_idx <= max_insert_idx):
                # If it can be inserted, check if it has less delay than previous feasible paths
                if (delay != Path.NOT_APPLICABLE):
                    total_delay = path.total_delay - (
                        delay * num_dropoffs_after) + delay_for_new_node

                    # Save if it has less delay
                    if (total_delay >= max_total_delay):
                        max_total_delay = total_delay
                        min_individual_delay = delay
                        min_delay_idx = insert_idx

                # Special check for capacity constratints
                if (not is_dropoff):
                    _, _, _, current_capacity = self._get_node_info(
                        agent, path, insert_idx - 1)
                    if (current_capacity >= self.envt.MAX_CAPACITY):
                        break

            # Update num_dropoffs_after
            if insert_idx > 0 and path.request_order[insert_idx -
                                                     1].is_dropoff:
                num_dropoffs_after += 1

        # If an insertion location is found, insert into path
        if (min_delay_idx != Path.NOT_APPLICABLE):
            # Fill in new_node's info
            self._insert_pathnode(agent, path, new_node, min_delay_idx,
                                  min_individual_delay, max_insert_idx)
            # Update total_delay
            path.total_delay = max_total_delay

        # If no insertion point was found, abort
        return path, min_delay_idx
Пример #19
0
 def export_gtfs(cls, directory):
     Agency.write_agencies(directory)
     Calendar.write_calendars(directory)
     Stop.write_stops(directory)
     Route.write_routes(directory)
     Trip.write_trips(directory)
     Frequency.write_frequencies(directory)
     Path.write_paths(directory)
Пример #20
0
 def import_gtfs(cls, directory):
     Agency.import_agencies(directory)
     Calendar.import_calendars(directory)
     Stop.import_stops(directory)
     Path.import_paths(directory)
     Route.import_routes(directory)
     Trip.import_trips(directory)
     Frequency.import_frequencies(directory)
Пример #21
0
def generate_path(board: Board, start: P2D, end: P2D) -> Path:
    path = Path(start, end)
    points = [start]
    # points.extend(generate_random_points(board, start, end))
    points.extend(generate_random_points(board))
    points.append(end)
    path.points = correct(points)
    return path
Пример #22
0
 def drawGridClicked(self, **kwargs):
     self.path = Path(n, blankGrid=True)
     self.label = self.ids['rLayout']
     self.squareSize = self.label.size[1] / n
     self.grid = self.path.getGrid()
     self.drawGrid(self.grid.getGrid())
     self.sol = self.path.solution()
     self.drawMode = True
Пример #23
0
def compute_curvature(list_of_coordinates, scale_in):
    """
    Main function collecting other functions.
    takes a scale (in the form of a list of numbers) and perfroms path computations according to the scale
    the list of coordinates ---> must be numpy a list of arrays <----
    """
    # stores curvatures for every sheet in xls file
    list_of_curvatures = []
    list_of_angles = []

    for coordinates in list_of_coordinates:
        # read in coordinates and convert to path object
        p = Path(coordinates)

        # stores single curvatures for single xls sheet
        curvatures = []

        # stores single angles for single xls sheet
        angles = []

        for unit_step in scale_in:

            # subset path in segments in unit_steps
            p.subset_path(unit_step)

            # list of projection vectors (minus the last vector, not to be used)
            projections = [ProjectionVector([segment[0], segment[-1]]) for segment in p.segmented_coordinates[0:-1]]

            # list of segments to be used for calculation (minus the first segment, not to be used)
            segments = [[i[0],i[-1]] for i in p.segmented_coordinates[1:]]
            
            # Build list of  raw angles (i.e. with +/- sign)
            raw_angles =[find_angle(segments[i],projections[i]) for i in range(len(projections)) if len(projections) == len(segments)]                
        
            # list of curvatures for individual path (segmented according to the scale)
            curvature = np.abs(raw_angles)/unit_step
            
            # median curvature for the selected path (segmented)
            curvatures.append(np.median(curvature))
            # curvatures.append(np.median(curvature)/100) # activate this is the unit step is < 1 (i.e. trichoplax)

            # find angles that are positive (True) and count them
            positive_angles = np.array(raw_angles)>0
            positive_angles = positive_angles.sum()

            # find negative angles
            negative_angles = len(raw_angles) - positive_angles

            # return list of [positive, negative] angles
            angles.append([positive_angles,negative_angles])
        
        list_of_curvatures.append(curvatures)
        list_of_angles.append(angles)

    print('\nList of angles is [POSITIVE, NEGATIVE], example:',list_of_angles[0])
    
    return list_of_curvatures, list_of_angles
Пример #24
0
    def hamiltonCycleAllPath(self):

        minPath = Path()
        for top in self.__tops:
            path = Path()
            path.addTop(top)
            self.__allPath(top, path, minPath)

        return minPath
Пример #25
0
def main():
    """
    Sets up and processes team, EXAMPLE;
    :return: NONE
    """
    # Setup Team Object
    team_edm = Team()
    lines = list()
    lines.append(Line(0, 1.701))
    lines.append(Line(1, 0.658))
    lines.append(Line(2, 0.299))
    lines.append(Line(3, 0.433))
    team_edm.set_team("EDM", lines=lines,
                      start_line_index=0)  # Edmonton Oilers

    print(team_edm)

    # Setup Path Object
    path = Path()
    path.team = team_edm

    schedule = []
    num_intervals = PERIOD_LENGTH // INTERVAL
    start = time.time()
    for i in range(num_intervals - 1):

        max_depth = MAX_DEPTH
        if num_intervals - i < MAX_DEPTH:
            max_depth = num_intervals - i

        # start = time.time()
        # find optimal path from curr_line for the next (MAX_DEPTH * INTERVAL) seconds
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, max_depth)

        # print("\n\n", path.team, "\n\n")
        path.team.update(optimal_path[1], INTERVAL)
        schedule.append(optimal_path[1].line_num)
        elapsed_time = time.time() - start

        t_nodes = theoretical_nodes(max_depth)

        # print("Optimal       ", optimal_path)
        #
        print("Progress:     {p:3.0f}% @ t: {e:5.2f}".format(
            p=i / (num_intervals - 1) * 100, e=elapsed_time))
        # print("Look Ahead:   ", LOOK_AHEAD)
        # print("Depth:        ", max_depth)
        # print("Visited:      ", num_visited)
        # print("Theoretical:  ", t_nodes)
        # print("Removal Rate: ", "{0:0.5f}".format((t_nodes - num_visited)/t_nodes))
        # print("Speed Up:     ", "{0:4.2f}".format(t_nodes/num_visited))
        #
        # print("\nTime:       ", elapsed_time)

    print(schedule)
Пример #26
0
def disable_temp_data():
    Course.db_setprefix('')
    Exam.db_setprefix('')
    ExamInfo.db_setprefix('')
    Path.db_setprefix('')
    Student.db_setprefix('')
    Applicant.db_setprefix('')
    CourseSemesterInfo.db_setprefix('')
    MetaData.db_setprefix('')
Пример #27
0
def stop_wanted(location):
  if location == 'tmp':
    loc = tmpdir
  elif location == 'workdir':
    loc = workdir
  else:
    loc = Path(location)  

  return loc.append('STOP').exists
Пример #28
0
 def __init__(self, game_map):
     # Keep a reference to the game_map object
     self.game_map = game_map
     # Keep a reference to the player object
     self.player = game_map.player
     # Create new path object and keep reference to it
     self.path = Path(self.game_map)
     # Winning path means can reach end goal by following the path
     self.winning_path = False
Пример #29
0
 def ToPath(self):
     """Convert to a path."""
     path = Path(source=self.headNode)
     headEdge = self.headEdge
     tail = self.tail
     while (headEdge is not None) and (tail is not None):
         path.Prepend(headEdge)
         headEdge = tail.headEdge
         tail = tail.tail
     return path
Пример #30
0
 def __init__(self, starting_country, starting_date, alg_graph, goal_function):
     """Method which initializes BruteAlgorithm object
         It takes start country and date plus the graph on which it should work on"""
     self.path = Path(starting_country, starting_date)
     self.graph = alg_graph
     self.possible_paths = [tuple([starting_country])]
     stats = self.graph.get_stats(starting_country)  # Here is a country which has latest data
     self.last_date = datetime.date(stats[0, 2], stats[0, 1], stats[0, 0])
     self.days_difference = int((self.last_date - starting_date).days)
     self.goal_function = goal_function
Пример #31
0
    def test_IsExpand_NotBool(self):
        v = 'TRUE'
        p = Path()
        with self.assertRaises(TypeError) as e:
            p.IsExpand = v
        self.assertEqual('IsExpandの値にはbool型の値を渡してください。型={}, 値={}'.format(type(v), v), e.exception.args[0])

        with self.assertRaises(TypeError) as e:
            p = Path(is_expand=v)
        self.assertEqual('IsExpandの値にはbool型の値を渡してください。型={}, 値={}'.format(type(v), v), e.exception.args[0])
Пример #32
0
 def path_weight(self, req: Request, path: Path) -> None:
     # path的最后两项是带宽成本和贪心利润
     min_band_edge: Edge = path.edges[0]
     for e in path.edges:
         e: Edge
         if e.leftBand < min_band_edge.leftBand:
             min_band_edge = e
     path.weight = path.greedy_profit  # 贪心利润
     if min_band_edge.leftBand < req.bandwidth:
         path.weight = -1000
Пример #33
0
 def test_Join(self):
     p = Path()
     self.assertEqual('/', p.Join())
     p = Path('/tmp', 'A')
     self.assertEqual('/tmp/B', p.Join('B'))
     p = Path('/tmp', 'A')
     self.assertEqual('/tmp/B/C.d', p.Join('B','C.d'))
Пример #34
0
    def markNodesPrunable(self):
        """ Prunes unneeded nodes."""

        for node in self.nodes:
            node.isPrunable = True

        # 1) Create a path for every query node. Each path will contain only that evidence node.
        startPaths = []
        for node in self.nodes:
            if node.type == NodeType["Query"]:
                p = Path(node, Direction["Start"])
                self.markActivePath(p)
                startPaths.append(p)

        #print "startPaths: {}".format(startPaths)
        # 2) Add the neighbors of each query node to the paths.
        paths = []
        for path in startPaths:
            for node in path[-1][0].parents:
                p = path.clone()
                p.append(node, Direction["Parent"])
                if node.type == NodeType["Evidence"]:
                    self.markActivePath(p)
                paths.append(p)
            for node in path[-1][0].children:
                p = path.clone()
                p.append(node, Direction["Child"])
                if node.type == NodeType["Evidence"]:
                    self.markActivePath(p)
                paths.append(p)

        # 3) Expand the paths as far as we can.
        while len(paths) > 0:
            #print "paths: {}".format(paths)
            prevPaths = paths
            paths = []
            for curPath in prevPaths:
                for node in curPath[-1][0].parents:
                    if not self.isBlocked(
                            curPath[-1],
                        (node, Direction["Parent"])) and not node in curPath:
                        p = curPath.clone()
                        p.append(node, Direction["Parent"])
                        paths.append(p)
                        if node.type == NodeType["Evidence"]:
                            self.markActivePath(p)
                for node in curPath[-1][0].children:
                    if not self.isBlocked(
                            curPath[-1],
                        (node, Direction["Child"])) and not node in curPath:
                        p = curPath.clone()
                        p.append(node, Direction["Child"])
                        paths.append(p)
                        if node.type == NodeType["Evidence"]:
                            self.markActivePath(p)
Пример #35
0
    def __load(self):
        try:
            with open(str(Path("src\\WordEmbeddings.txt")), "r") as f:
                data = json.load(f)

            return data
        except json.decoder.JSONDecodeError:
            data = {}
            return data
        except:
            raise IOError(str(Path("src\\WordEmbeddings.txt")))
Пример #36
0
 def refreshClicked(self, **kwargs):
     Clock.unschedule(self.event)
     # self.canvas.clear()
     self.counter = 0
     self.path = Path(n)
     self.grid = self.path.getGrid()
     self.label = self.ids['rLayout']
     self.squareSize = self.label.size[1] / n
     self.drawGrid(self.grid.getGrid())
     self.sol = self.path.solution()
     self.event = Clock.schedule_interval(self.pathSearch, 0.02)
Пример #37
0
    def __load(self):
        try:
            with open(str(Path("src\\known_devices.txt")), "r") as f:
                self.devices = json.load(f)

            return data
        except json.decoder.JSONDecodeError:
            self.devices = {}
            return data
        except:
            raise IOError(str(Path("src\\known_devices.txt")))
Пример #38
0
class PathfinderPlayer(sf.CircleShape):
    def __init__(self, x, y):
        sf.CircleShape.__init__(self)
        self.radius = 10
        self.position = (x, y)
        self.outline_color = sf.Color.BLUE
        self.outline_thickness = 5
        self.path = None

    def update(self, sight_blockers, mouse_position):
        self.path = Path(self.position, mouse_position)
        self.path.update(sight_blockers)
Пример #39
0
    def __init__(self, start=Coordinate(), end=Coordinate(), id=None, classes=None):
        """
		@param start: Coordinate of the first point of the line
		@type start: Coordinate
		@param end: Coordinate of the last point of the line
		@type end: Coordinate
		@param id: The unique ID to be used in the SVG document
		@type id: string
		@param classes: Classnames to be used in the SVG document
		@type classes: string or sequence of strings
		"""

        Path.__init__(self, (start, end), id=id, classes=classes)
        self.tag = u"line"
Пример #40
0
 def close(self):
     self._is_open = False
     self._dbname = None
     
     # clear everything
     Agency.clear()
     Calendar.clear()
     Stop.clear()
     Path.clear()
     Route.clear()
     TripRoute.clear()
     Trip.clear()
     Frequency.clear()
     Picture.clear()
Пример #41
0
def jarviswalk(points):
    """Implementation of Jarvis Walk aka Gift wrapping algorithm.
    Based on the article http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
    """
    hull = Path()
    xsorted = sorted(points, key=lambda point: point.x)
    hull.addPoint(xsorted[0])
    while True:
        nextP = None
        maxLinearPoint = None
        maxLinearDistance = -1.0
        possiblePoints = filter(lambda p: p not in hull.points[1:], xsorted) 
        for p in possiblePoints:
            if p is hull.points[-1]: continue
            line = Line(hull.points[-1], p)
            allright, localMaxLinear, localMaxLinearDistance = allrightAndMaxLinearPoint(line, xsorted)
            if allright:
                nextP = p
                break
            if localMaxLinear is not None and localMaxLinearDistance != -1.0 and localMaxLinearDistance > maxLinearDistance:
                maxLinearPoint, maxLinearDistance = (localMaxLinear, localMaxLinearDistance)
        assert(nextP is not None or (maxLinearPoint is not None and maxLinearDistance > 0.0))
        if nextP is not None:
            hull.addPoint(nextP)
        else:
            hull.addPoint(maxLinearPoint)
        if hull.isConnected():
            break
    return hull
Пример #42
0
	def listToFile(self, list_ = [], name_ = ''):
		fileName = ''
		if name_ != '' :
			fileName = Path.tempStruct(name_)
			with open(fileName, 'wb') as f :
				f.writelines(list_)
		return fileName
Пример #43
0
    def _home_internal(self, axis):
        """ Private method for homing a set or a single axis """
        logging.debug("homing " + str(axis))

        path_back = {}
        path_center = {}
        path_zero = {}

        speed = Path.home_speed[0]

        for a in axis:
            if not self.printer.steppers[a].has_endstop:
                logging.debug("Skipping homing for " + str(a))
                continue

            path_back[a] = -self.travel_length[a]
            path_center[a] = -self.center_offset[a]
            path_zero[a] = 0
            speed = min(speed, Path.home_speed[Path.axis_to_index(a)])

            # Move until endstop is hit
        p = RelativePath(path_back, speed, True)

        self.add_path(p)

        # Reset position to offset
        p = G92Path(path_center, speed)
        self.add_path(p)

        # Move to offset
        p = AbsolutePath(path_zero, speed)
        self.add_path(p)
        self.wait_until_done()
        logging.debug("homing done for " + str(axis))
Пример #44
0
def readPubKeyFromCache(_keyHash):
	path = Path.certificates(_keyHash)
	if not os.path.isfile(path) : return ''
	with open(path, 'rb') as f :
		str_ = f.read()
	(head, sep, tail) = str_.partition('\n-----END PUBLIC KEY-----')
	return ''.join((head, sep)).encode('utf-8')
Пример #45
0
    def _go_to_home(self, axis):
        """
        go to the designated home position
        do this as a separate call from _home_internal due to delta platforms 
        performing home in cartesian mode
        """
        
        path_home = {}
        
        speed = Path.home_speed[0]
        accel = self.printer.acceleration[0]

        for a in axis:
            path_home[a] = self.home_pos[a]
            speed = min(abs(speed), abs(Path.home_speed[Path.axis_to_index(a)]))
            
        logging.debug("Home: %s" % path_home)
            
        # Move to home position
        p = AbsolutePath(path_home, speed, accel, True, False, False, False)
        self.add_path(p)
        self.wait_until_done()
        
        # Due to rounding errors, we explicitly set the found 
        # position to the right value. 
        # Reset (final) position to offset
        p = G92Path(path_home, speed)
        self.add_path(p)

        return
Пример #46
0
 def set_extruder(self, ext_nr):
     if ext_nr in range(Path.NUM_AXES-3):
         logging.debug("Selecting "+str(ext_nr))
         Path.steps_pr_meter[3] = self.printer.steppers[
                 Path.index_to_axis(ext_nr+3)
                 ].get_steps_pr_meter()
         self.native_planner.setExtruder(ext_nr)
Пример #47
0
    def home(self, axis):
        """ Home the given axis using endstops (min) """
        logging.debug("homing " + str(axis))

        # Home axis for core X,Y and H-Belt independently to avoid hardware
        # damages.
        if Path.axis_config == Path.AXIS_CONFIG_CORE_XY or \
                        Path.axis_config == Path.AXIS_CONFIG_H_BELT:
            for a in axis:
                self._home_internal(a)
        # For delta, switch to cartesian when homing
        elif Path.axis_config == Path.AXIS_CONFIG_DELTA:
            if 0 < len({"X", "Y", "Z"}.intersection(set(axis))) < 3:
                axis = list(set(axis).union({"X", "Y", "Z"}))	# Deltas must home all axes.
            Path.axis_config = Path.AXIS_CONFIG_XY
            path_center, speed = self._home_internal(axis)
            Path.axis_config = Path.AXIS_CONFIG_DELTA

            # homing was performed in cartesian mode
            # need to convert back to delta

            Az = path_center['X']
            Bz = path_center['Y']
            Cz = path_center['Z']
            
            z_offset = Delta.vertical_offset(Az,Bz,Cz) # vertical offset
            xyz = Delta.forward_kinematics2(Az, Bz, Cz) # effector position
            xyz[2] += z_offset
            path = {'X':xyz[0], 'Y':xyz[1], 'Z':xyz[2]}
            
            p = G92Path(path, speed)
            self.add_path(p)
            self.wait_until_done()
            
        else:
            self._home_internal(axis)
            
        # go to the designated home position
        self._go_to_home(axis)

        # Reset backlash compensation
        Path.backlash_reset()

        logging.debug("homing done for " + str(axis))
            
        return
Пример #48
0
def readCashPolicy(str_, policy):
	fileName = hashKey(str_)
	path_ = Path.certificates(fileName)
	if os.path.isfile(path_) :
		with open(path_, 'rb') as f :
			data = f.read()
		chunks = data.split()
		policy = int(chunks[len(chunks) - 1])
	return policy
Пример #49
0
def saveContactPolicy(idx, fileName):
	path = Path.certificates(fileName)
	if not os.path.isfile(path) : return ''
	with open(path, 'rb') as f :
		str_ = f.read()
	(head, sep, tail) = str_.partition('\n-----END PUBLIC KEY-----\n')
	with open(path, 'wb') as f :
		str_ = ''.join((head, sep, str(idx)))
		f.write(str_)
Пример #50
0
def createStructure():
	for nameDir in [Path.TempAvatar, \
					Path.tempStruct('structure'), \
					Path.tempStruct('client'), \
					Path.tempStruct('server'), \
					Path.config('treeBackup'), \
					Path.Avatar, \
					Path.Certificates] :
		if not os.path.isdir(nameDir):
			os.makedirs(nameDir)
	cwd = os.getcwd()
	while os.path.basename(cwd) not in (os.sep, '', 'LightMight') :
		head, tail = os.path.split(cwd)
		cwd = head
	if os.path.basename(cwd) == 'LightMight' :
		moveFile(os.path.join(cwd, 'contents', 'icons', 'error.png'), \
							  os.path.join(Path.TempAvatar, 'error'), \
							  False)
Пример #51
0
    def get_paths_accessible_by_player(self, player, max_length=9999):
        paths = []
        seen_territory_ids = set()

        partial_paths = deque()
        for territory in player.territories:
            partial_paths.append(Path.create_with_single_territory(territory))
        while len(partial_paths) > 0:
            path = partial_paths.popleft()

            # prune paths that have less than 5% chance of being conquered
            if path.probability_of_conquering_path < 0.03:
                continue

            paths.append(path)
            for territory in path[-1].adjacent_territories:
                if territory.player != player and territory not in path:
                    partial_paths.append(Path.create_by_appending_path_with_territory(path, territory))

        return paths
Пример #52
0
    def execute(self, g):

        gcodes = self.printer.config.get("Macros", "G29").split("\n")
        self.printer.path_planner.wait_until_done()
        for gcode in gcodes:        
            G = Gcode({"message": gcode, "prot": g.prot})
            self.printer.processor.execute(G)
            self.printer.path_planner.wait_until_done()

        # Remove the offset from the probed points        
        self.printer.probe_heights -= min(self.printer.probe_heights)

        # Log the found heights
        for k, v in enumerate(self.printer.probe_points):
            self.printer.probe_points[k]["Z"] = self.printer.probe_heights[k]
        logging.info("Found heights: ")
        logging.info(self.printer.probe_points)

        # Update the bed compensation matrix
        Path.update_autolevel_matrix(self.printer.probe_points, self.printer.probe_heights)
Пример #53
0
 def __init__( self, path=None ):
     self._cachefile = Path( path )
     _cachefile = str( self._cachefile )
     self._entries = {}
     if self._cachefile.exists():
         with open( _cachefile ) as c:
             entries = filter( None, map( lambda x: CacheEntry( x ),
                                          c.readlines() ) )
             entries = filter( lambda x: x.value() != None, entries )
             for i in entries:
                 self._entries[i.name()] = i
Пример #54
0
    def testLength(self):
        p = Path()
        p.addPoint(self.p0)
        p.addPoint(self.p1)

        l0 = Line(self.p0, self.p1)
        l1 = Line(self.p1, self.p2)
        self.assertEquals(p.length(), l0.length())
        p.addPoint(self.p2)
        self.assertEquals(p.length(), l0.length() + l1.length())
Пример #55
0
def addToCertCache(str_, policy):
	fileName = hashKey(str_)
	path_ = Path.certificates(fileName)
	if not os.path.isfile(path_) :
		with open(path_, 'wb') as f :
			f.write(''.join((str_.encode('utf-8'), str(policy))))
	else :
		with open(path_, 'rb') as f :
			data = f.read()
		chunks = data.split()
		policy = int(chunks[len(chunks) - 1])
	return policy
Пример #56
0
 def testValid(self):
     validPath = Path()
     validPath.addPoint(self.p0)
     validPath.addPoint(self.p1)
     validPath.addPoint(self.p2)
     validPath.addPoint(self.p0)
     self.assertTrue(validPath.isConnected())
Пример #57
0
    def create(self, pathImage):
        logging.info(pathImage)
        if os.path.exists(pathImage) == False:  # 如果不存在目录退出
            return 1

        path = Path(pathImage, self.pathPrefix)  # path对象

        if path.batchIsExist(self.listProduct) == False:
            return 2

        gImage = GImage()
        imageExtendName = path.getImageExtend()  # 图片路径对象
        imageExtend = ImageExtendName(imageExtendName)  # 图片扩展对象
        imageSize = ImageSize(self.listProduct, path.getNoPrefixPath())  # 图片大小

        try:
            targetPath = path.getTargetPath(self.pathMoblePrefix)
            logging.info(targetPath)
            gImage.generateImage(pathImage, targetPath, imageSize.getSize(), imageExtend.formatImageExtendName())
        except Exception, e:
            logging.error(e.__str__())
            return 3
Пример #58
0
def make_control(argv):
    # return a Bunch

    print argv
    if len(argv) not in (1, 2):
        usage('invalid number of arguments')

    pcl = ParseCommandLine(argv)
    if pcl.has_arg('--help'):
        usage()
    arg = Bunch(
        base_name=argv[0].split('.')[0],
        test=pcl.has_arg('--test'),
    )

    random_seed = 123456
    random.seed(random_seed)

    path = Path()  # use the default dir_input

    debug = False

    file_out_transactions = (
        ('testing-' if arg.test else '') +
        arg.base_name + '-al-g-sfr' + '.csv'
    )

    return Bunch(
        arg=arg,
        debug=debug,
        max_sale_price=85e6,  # according to Wall Street Journal
        path=path,
        path_in_census_features=path.dir_working() + 'census-features-derived.csv',
        path_in_parcels_features_census_tract=path.dir_working() + 'parcels-features-census_tract.csv',
        path_in_parcels_features_zip5=path.dir_working() + 'parcels-features-zip5.csv',
        path_out_transactions=path.dir_working() + file_out_transactions,
        random_seed=random_seed,
        test=arg.test,
    )
Пример #59
0
    def dfs_search(self, source, dest):
        '''
        Finds all paths from the source vertex to the dettination vertex,
        creates a Path object for each of these paths, and adds those Paths
        to dfs_paths in order of discovery.

        @param sourcs: The ID of the source vertex.
        @param dest: The ID of the destination vertex.
        '''
        stack = [source]
        while (len(stack) > 0):
            current_vertex = self.vertex_list[stack[len(stack)-1]]
            next = current_vertex.get_next()
            if (next == dest):
                path = Path()
                path.add_vertices(stack)
                path.add_vertex(next)
                self.dfs_paths.append(path)
            elif (next != -1):
                stack.append(next)
            else:
                self.vertex_list[stack.pop()].reset_visited()
Пример #60
0
    def import_trips(cls, directory):
        from Route import Route
        from Calendar import Calendar
        from TripRoute import TripRoute
        from Path import Path
        from Stop import Stop

        try:
            f = open(os.path.join(directory, 'trips.txt'), 'rb')
            reader = csv.reader(f)

            mappings = {'route_id': ('route', lambda x: Route.get_by_gtfs_id(x)),
                        'service_id': ('calendar', lambda x: Calendar.get_by_gtfs_id(x)),
                        'trip_id': ('name', lambda x: x),
                        'trip_headsign': ('headsign', lambda x: x),
                        'direction_id': ('direction', lambda x: int(x) if x else 0),
                        'shape_id': ('path', lambda x: Path.get_by_gtfs_id(x)),
            }

            # create a headers with an index
            headers = reader.next()
            r_headers = dict([(x, i) for i, x in enumerate(headers)])

            for l2 in reader:
                if len(l2) != len(headers):
                    print >> sys.stderr, 'Invalid line', l2, headers
                    continue
                
                kw = {}
                for i, a in enumerate(l2):
                    key = headers[i]
                    if key in mappings:
                        kw[mappings[key][0]] = mappings[key][1](BaseObject.unquote(a))
                # create the trip route
                trip_route = TripRoute(**kw)
                # set the id
                trip_route.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])
                # create a trip
                trip = trip_route.add_trip()
                trip.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])

            # go through the list again and set block ids
            #!mwd - I'm not sure how to do this. We link
            #  blocks by trip ids, but block ids are 
            #  random in gtfs, so we have no way to link
            #  them back

        except IOError, e:
            print >> sys.stderr, 'Unable to open trips.txt:', e