Exemple #1
0
def averagePathLength(graph):
    total = 0
    for v in graph.vertices():
        pf = PathFinder(graph, v)
        for w in graph.vertices():
            total += pf.distanceTo(w)
    return 1.0 * total / (graph.countV() * (graph.countV() - 1))
Exemple #2
0
 def computePath(self, coord):
     pf = PathFinder(self.map.successors, self.map.move_cost,
                     self.map.move_cost)
     path_list = list(pf.compute_path(coord, self.goal))
     for i, path_coord in enumerate(path_list):
         next_i = i if i == len(path_list) - 1 else i + 1
         self.path_cache[path_coord] = path_list[next_i]
Exemple #3
0
 def computePath(self,coord):
     pf = PathFinder(self.map.successors, self.map.move_cost,
             self.map.move_cost)
     path_list = list(pf.compute_path(coord, self.goal) )
     for i, path_coord in enumerate(path_list):
         next_i = i if i==len(path_list)-1 else i+1
         self.path_cache[path_coord] = path_list[next_i]
Exemple #4
0
 def __init__(self, binary):
     self.vars = self.__initvars()
     PathFinder.__init__(self, binary)
     self.solver = Solver()
     print("============== Solver ===============")
     for func in self.get_all_functions():
         self.__iterate_targets(func)
Exemple #5
0
def averagePathLength(graph):
    total = 0
    for v in graph.vertices():
        pf = PathFinder(graph, v)
        for w in graph.vertices():
            total += pf.distanceTo(w)
    return 1.0 * total / (graph.countV() * (graph.countV() - 1))
Exemple #6
0
    def reset(self, level=1):
        pygame.mixer.music.stop()
        pygame.mixer.music.play(10**8)
        self.menu = Menu()
        self.menu.add_button('Continue', (self.width // 2 - 150, 200),
                             target=self.open_menu)
        self.menu.add_button('Music', target=self.switch_music, switch=True)
        self.menu.add_button('Sounds', target=self.switch_sounds, switch=True)
        self.menu.add_button('Quit game', target=self.terminate)

        self.sprite_groups = {k: pygame.sprite.Group() for k in range(20, 30)}

        self.conditions = {k: False for k in range(40, 50)}
        self.conditions[RUNNING] = True
        self.conditions[FULLSCREEN] = True

        self.keys_pressed = []

        self.terrain = Terrain(16 * 3 * 3, 16 * 3 * 3, level)
        self.sprite_groups[CHUNKS] = pygame.sprite.Group(self.terrain.chunks)
        for chunk in self.sprite_groups[CHUNKS]:
            self.sprite_groups[ALL].add(chunk)
        self.screen2 = pygame.Surface((self.width, self.height),
                                      pygame.HWSURFACE, 32)
        self.player = Player(
            (self.sprite_groups[ENTITIES], self.sprite_groups[ALL]),
            (500, 500))
        self.camera = Camera(self.terrain.get_width(),
                             self.terrain.get_height(), self.player,
                             self.width // 2, self.height // 2)

        self.pathfinder = PathFinder(self.terrain.obst_grid)
        self.paths = dict()
        self.sprite_groups[PLAYER].add(self.player)
        self.camera.update()
Exemple #7
0
def simulation():
	inputfile = ''
	c1 = 1
	c2 = 2
	delta = 4
	B = 0
	L = 0 
	try:
		opt, args = getopt.getopt(sys.argv[1:],"f:c:d:v:l:h",["help"])
	except:
		print("Invalid parameters!")
		sys.exit()
	for o, a in opt:
		if o == '-f':
			inputfile = a
		elif o == 'c':
			c1,c2 = map(float,a.split(','))
		elif o == '-d':
			try:
				d = float(a)
			except:
				print("invalid delta parameter!")
				sys.exit()
		elif o == '-v':
			try:
				B = float(a)
			except:
				print("Invalid speed specification!")
				sys.exit()
		elif o == '-l':
			try:
				L = float(a)
			except:
				print("Invalid time interval bound!")
				sys.exit()
		elif o in ['-h','--help']:
			usage()
			sys.exit()
	# Get the optimum solution
	complete_graph = GraphGenerator(inputfile).getGraph()
	'''
	start = time.time()
	opt_alg = BFTSP(B)
	opt_weight, opt_path = opt_alg.opt(complete_graph)
	print("Optimal running time : ", time.time() - start)
	print("Optimal weight, " + str(opt_weight))
	print("Optimal path, " + ','.join(map(str,opt_path)))	
	'''
	# Get the approximate solution
	start = time.time()
	path_finder = PathFinder(complete_graph, c1, c2, B, L, delta)
	print("Approximate algorithm running time: ", time.time() - start)
	aprox_weight = path_finder.findPath()
	aprox_path = path_finder.path
	accumulate_weight = path_finder.block_weight
	print("Appoximate weight, " + str(aprox_weight))
	print("Approximate path, " + ','.join(map(str,aprox_path)))	
	print("Accumulate weight, " + ','.join(map(str,accumulate_weight)))	
Exemple #8
0
def simulation():
    inputfile = ''
    c1 = 1
    c2 = 2
    delta = 4
    B = 0
    L = 0
    try:
        opt, args = getopt.getopt(sys.argv[1:], "f:c:d:v:l:h", ["help"])
    except:
        print("Invalid parameters!")
        sys.exit()
    for o, a in opt:
        if o == '-f':
            inputfile = a
        elif o == 'c':
            c1, c2 = map(float, a.split(','))
        elif o == '-d':
            try:
                d = float(a)
            except:
                print("invalid delta parameter!")
                sys.exit()
        elif o == '-v':
            try:
                B = float(a)
            except:
                print("Invalid speed specification!")
                sys.exit()
        elif o == '-l':
            try:
                L = float(a)
            except:
                print("Invalid time interval bound!")
                sys.exit()
        elif o in ['-h', '--help']:
            usage()
            sys.exit()
    # Get the optimum solution
    complete_graph = GraphGenerator(inputfile).getGraph()
    '''
	start = time.time()
	opt_alg = BFTSP(B)
	opt_weight, opt_path = opt_alg.opt(complete_graph)
	print("Optimal running time : ", time.time() - start)
	print("Optimal weight, " + str(opt_weight))
	print("Optimal path, " + ','.join(map(str,opt_path)))	
	'''
    # Get the approximate solution
    start = time.time()
    path_finder = PathFinder(complete_graph, c1, c2, B, L, delta)
    print("Approximate algorithm running time: ", time.time() - start)
    aprox_weight = path_finder.findPath()
    aprox_path = path_finder.path
    accumulate_weight = path_finder.block_weight
    print("Appoximate weight, " + str(aprox_weight))
    print("Approximate path, " + ','.join(map(str, aprox_path)))
    print("Accumulate weight, " + ','.join(map(str, accumulate_weight)))
Exemple #9
0
    def _recompute_path(self, map, start, end):
        pf = PathFinder(map.successors, map.move_cost, map.move_cost)
        t = time.clock()
        pathlines = list(pf.compute_path(start, end))

        dt = time.clock() - t
        if pathlines == []:
            print "No path found" 
            return pathlines
        else:
            print "Found path (length %d)" % len(pathlines)
            return pathlines
Exemple #10
0
    def _recompute_path(self, _map, start, end):
        pf = PathFinder(_map.successors, _map.move_cost, _map.move_cost)
        # t = time.process_time()
        pathlines = list(pf.compute_path(start, end))

        # dt = time.process_time() - t
        if pathlines == []:
            print("No path found")
            return pathlines
        else:
            print("Found path (length %d)" % len(pathlines))
            return pathlines
Exemple #11
0
 def _compute_path(self, coord):
     pf = PathFinder(self.map.successors, self.map.move_cost,
             self.map.move_cost)
     
     # Get the whole path from coord to the goal into a list,
     # and for each coord in the path write the next coord in
     # the path into the path cache
     #
     path_list = list(pf.compute_path(coord, self.goal))
     
     for i, path_coord in enumerate(path_list):
         next_i = i if i == len(path_list) - 1 else i + 1
         self._path_cache[path_coord] = path_list[next_i]
def main():
    main_square = PathFinder.get_all_coordinates_within_bounds(0, 0, 4, 4)
    lower_row = PathFinder.get_all_coordinates_within_bounds(1, -1, 3, -1)
    upper_row = PathFinder.get_all_coordinates_within_bounds(1, 5, 3, 5)
    available_coordinates = main_square + lower_row + upper_row
    duplicate_allowed_coordinates = lower_row + upper_row
    pf = PathFinder(available_coordinates, duplicate_allowed_coordinates, 3,
                    True, main_square)
    pf.generate_paths(Coordinate(2, 0), Coordinate(2, 4))
    print pf.get_shortest_path()
Exemple #13
0
	def __init__(self, owner):
		self.owner = owner
		self.walls = set()
		self.floors = set()
		self.entities = set()
		self.path = []
		self.pathfinder = PathFinder(self.get_adjacents, self.get_cost, self.get_heuristic)
Exemple #14
0
 def make_path_grid(self):
     # for our pathfinding, we're going to overlay a grid over the field with
     # squares that are sized by a constant in the config file
     self.path_grid = GridMap(self.scale2path(self.m_xmax_field),
                              self.scale2path(self.m_ymax_field))
     self.pathfinder = PathFinder(self.path_grid.successors, self.path_grid.move_cost, 
                                  self.path_grid.estimate)
Exemple #15
0
    def __init__(self):

        self.tablero = Tablero(80, 80)

        self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10,
                    len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF)

        pygame.display.set_caption("Pathfinder")

        self.clock = pygame.time.Clock()

        self.pausa = True
        self.velocidad = 100
        self.velocidad_algoritmo = 8

        # a star
        self.pathfinder = PathFinder(self.tablero)

        # cursor
        self.cursor = Cursor(self.tablero, self.pathfinder)

        #fuente
        pygame.font.init()
        self.fuente = pygame.font.SysFont("default", 24)
        self.texto = self.fuente.render("Pausado", True, (255, 0, 255))
        self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo),
                                True, (255, 0, 255))
    def _recompute_path(self):
        self.blocked_list = self.map.blocked

        pf = PathFinder(self.map.successors, self.map.move_cost, self.map.move_cost)

        t = time.clock()
        self.path = list(pf.compute_path(self.start_pos, self.goal_pos))
        dt = time.clock() - t

        if self.path == []:
            self.msg1 = "No path found"
        else:
            self.msg1 = "Found path (length %d)" % len(self.path)

        self.msg2 = "Elapsed: %s seconds" % dt
        self.path_valid = True
    def _recompute_path(self):
        self.blocked_list = self.map.blocked

        pf = PathFinder(self.map.successors, self.map.move_cost,
                        self.map.move_cost)

        t = time.clock()
        self.path = list(pf.compute_path(self.start_pos, self.goal_pos))
        dt = time.clock() - t

        if self.path == []:
            self.msg1 = "No path found"
        else:
            self.msg1 = "Found path (length %d)" % len(self.path)

        self.msg2 = "Elapsed: %s seconds" % dt
        self.path_valid = True
Exemple #18
0
 def load_data(self):
     self.map = TiledMap("Images/til.tmx")
     self.transicio = ''
     self.pf = PathFinder(self.map)
     self.gchamp = pygame.sprite.Group()
     self.champ = champs.Champ2(np.true_divide(self.map.camera.size,2),conf.mides_champ)
     self.gchamp.add(self.champ)
     self.pressed_keys = []
     self.npcs = pygame.sprite.Group()
     self.z1 = zombie.Zombie(np.multiply(conf.tile_size,2))
Exemple #19
0
 def make_path_grid(self):
     # for our pathfinding, we're going to overlay a grid over the field with
     # squares that are sized by a constant in the config file
     origdim = (self.m_xmax_field, self.m_ymax_field)
     newdim = self.rescale_pt2path(origdim)
     self.m_pathgrid = GridMap(*self.rescale_pt2path((self.m_xmax_field,
                                                      self.m_ymax_field)))
     self.m_pathfinder = PathFinder(self.m_pathgrid.successors,
                                    self.m_pathgrid.move_cost,
                                    self.m_pathgrid.estimate)
Exemple #20
0
def update_pars_and_pather(pars, pather, filename, **kwargs):
    if kwargs:
        pars = pars.copy()
        pars.update(kwargs)
        if pather is not None:
            warnings.warn("tensorstorer was given both a pather and kwargs. "
                          "Generating a new pather.")
    if kwargs or pather is None:
        # If kwargs, we need to make a pather to make sure that path
        # matches contents.
        pather = PathFinder(filename, pars)
    return pars, pather
Exemple #21
0
 def get_path(self, destination):
     gridmap = GridMap(
         len(entities.shop['object'].shop_grid[0]),
         len(entities.shop['object'].shop_grid)
     )
     blocked_tiles = self.get_tiles('passable', False)
     for blocked_tile in blocked_tiles:
         gridmap.set_blocked(blocked_tile)
     self.pathfinder = PathFinder(gridmap.successors, gridmap.move_cost, gridmap.move_cost)
     self.path = self.pathfinder.compute_path(
         self.get_shop_grid_location(),
         destination
     )
Exemple #22
0
    def analyze(self,
                carbon_only=True,
                use_antimotifs=True,
                draw_scenes=False):
        for line in util.parse_text_file("../rec/" + self.modules_file +
                                         ".txt"):
            if (line[0] == '@'):
                line = line[1:]
                self.pathfinder = PathFinder(carbon_only=carbon_only,
                                             pruning_method=None,
                                             ignore_chirality=False,
                                             use_antimotifs=use_antimotifs,
                                             outstream=self.logfile)
            else:
                self.pathfinder = PathFinder(carbon_only=carbon_only,
                                             pruning_method=None,
                                             ignore_chirality=True,
                                             use_antimotifs=use_antimotifs,
                                             outstream=self.logfile)

            pathway = line.split(';')
            self.find_modules(pathway, draw_scenes=draw_scenes)
            self.line_counter += 1
    def __init__(self):
        self.server = actionlib.SimpleActionServer('track_object', TrackObjectAction, self.execute, False)
        self.server.start()

        self.lower = None
        self.upper = None
        self.targetType = None

        self.srv = Server(ThresholdsConfig, self.updateThresholds)

        self.thresholds = {int(k):v for k,v in rospy.get_param("/vision_thresholds").items()}

        self.bridge = CvBridge()

        self.leftImage = np.zeros((1,1,3), np.uint8)
        self.leftModel = image_geometry.PinholeCameraModel()
        self.newLeft = False

        self.rightImage = np.zeros((1,1,3), np.uint8)
        self.rightModel = image_geometry.PinholeCameraModel()
        self.newRight = False

        self.downImage = np.zeros((1,1,3), np.uint8)
        self.downModel = image_geometry.PinholeCameraModel()
        self.newDown = False

        self.disparityImage = np.zeros((1,1,3), np.uint8)
        self.stereoModel = image_geometry.StereoCameraModel()
        self.newDisparity = False

        self.poleFinder = PoleFinder()
        self.gateFinder = GateFinder()
        self.diceFinder = DiceFinder()
        self.pathFinder = PathFinder()
        self.response = TrackObjectResult()

        self.downSub = rospy.Subscriber('/down_camera/image_color', Image, self.downwardsCallback)
        self.downInfoSub = rospy.Subscriber('/down_camera/info', CameraInfo, self.downInfoCallback)
        
        self.stereoSub = rospy.Subscriber('/stereo/disparity', Image, self.stereoCallback)
        #self.stereoInfoSub = rospy.Subscriber('/stereo/info', CameraInfo, self.stereoInfoCallback)

        self.leftSub = rospy.Subscriber('/stereo/left/image', WFOVImage, self.leftCallback)
        #self.leftInfoSub = rospy.Subscriber('/stereo/left/image', WFOVImage, self.leftInfoCallback)
        
        self.rightSub = rospy.Subscriber('/stereo/right/image', WFOVImage, self.rightCallback)
        #self.rightInfoSub = rospy.Subscriber('/stereo/right/image', WFOVImage, self.rightInfoCallback)

        self.bridge = CvBridge()
        self.image_pub = rospy.Publisher("/thresh_image", Image, queue_size=10)
Exemple #24
0
def main():
    pars = parse()
    id_pars = get_tensor_id_pars(pars)
    filename = os.path.basename(__file__)
    pather = PathFinder(filename, id_pars)

    # - Infoprint -
    print("\n" + ("="*70) + "\n")
    print("Running %s with the following parameters:"%filename)
    for k,v in sorted(pars.items()):
        print("%s = %s"%(k, v))

    scaldims, c, momenta = get_scaldims(pars)
    scaldim_plot.plot_and_print(scaldims, c, pars, pather, momenta=momenta,
                                id_pars=id_pars)
def main():
    pars = parse()
    id_pars = get_tensor_id_pars(pars)
    filename = os.path.basename(__file__)
    pather = PathFinder(filename, id_pars)

    # - Infoprint -
    print("\n" + ("=" * 70) + "\n")
    print("Running %s with the following parameters:" % filename)
    for k, v in sorted(pars.items()):
        print("%s = %s" % (k, v))

    maxi = 5
    leigs_by_theta = {}
    for g in np.linspace(*pars["gs"]):
        theta = np.arctan((1 - g) / (1 + g))

        eigs = get_eigs(pars, g=g)
        leigs = eigs.log()
        leigs *= -pars["block_width"] / (2 * np.pi)
        if pars["symmetry_tensors"]:
            leigs -= leigs[(0, )][0]
            for qnum, sect in leigs.sects.items():
                leigs[qnum] = sect[sect < maxi]
        else:
            leigs -= leigs[0]
            leigs = leigs[leigs < maxi]
        leigs_by_theta[theta] = leigs

    exacts_by_theta = {}
    exact_degs_by_theta = {}
    for g in {0, 1}:
        theta = np.arctan((1 - g) / (1 + g))
        prim_data = modeldata.get_primary_data(maxi * 2, pars, 0, g=g)
        exacts_by_theta[theta] = np.array(
            prim_data[0]) * (0.5 if g == 0 else 1)
        exact_degs_by_theta[theta] = prim_data[2]

    scaldim_plot.plot_dict(leigs_by_theta,
                           pars,
                           x_label=r"$\theta$",
                           exacts_dict=exacts_by_theta,
                           exact_degs_dict=exact_degs_by_theta,
                           y_label=r"$\Delta_\alpha(\theta)$",
                           id_pars=id_pars)
Exemple #26
0
def main():
    tStart = time.time()
    # print(sys.getrecursionlimit())
    # resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
    sys.setrecursionlimit(0x100000)
    # print(sys.getrecursionlimit())
    tMap = TMap("inputMaps\\Prob16Corner.test.txt")
    # tMap = TMap("inputMaps\\judge\\Prob16.in.txt")
    pathfinder = PathFinder(tMap.startNode, tMap)

    tFinish = time.time()
    tDif = (tFinish - tStart) * 1000 # execution time in ms

    # print(len(pathfinder.successfulPath)) # debugging
    for node in pathfinder.successfulPath: # debugging
        if node.char == " ": # debugging
            node.char = "O" # debugging
    print(tMap) # debugging

    print(f"\n\tsolution: {pathfinder.bestFound}\tInstances: {pathfinder.totalProcesses}")
    print(f"\texecution time: {round(tDif, 3)} ms")
Exemple #27
0
class Brain(object):
	def __init__(self, owner):
		self.owner = owner
		self.walls = set()
		self.floors = set()
		self.entities = set()
		self.path = []
		self.pathfinder = PathFinder(self.get_adjacents, self.get_cost, self.get_heuristic)
	def observe(self):
		self.area = self.owner.owner.owner
		self.entities = set()
		for point in self.owner.fov:
			if point in self.area.terrain and self.area.terrain[point]['chasm'] == False:
				self.floors.add(point)
			else:
				self.floors.discard(point)
			if point in self.area.features:
				self.walls.add(point)
			else:
				self.walls.discard(point)
			if point in self.area.entities:
				self.entities.add(point)
		entities = self.area.entities.get_nodes(self.owner.fov)
		for node in entities:
			if 'player' in node and 'player' not in self.owner:
				self.entities.discard(node.pos)
				self.path = []
				path = self.pathfinder.compute_path(self.owner.pos, node.pos)
				for point in path:
					if point == self.owner.pos: continue
					self.path.append(point)
	def get_adjacents(self, point):
		return [pos for pos in M_NEIGHBORS[point] if pos in self.floors and pos not in self.walls and pos not in self.entities]
	def get_cost(self, start, end):
		return 1
	def get_heuristic(self, start, end):
		return len(build_line(start, end)) - 1
Exemple #28
0
    pathfinder.plotPaths()


def computeAndDisplayDijkstra(pathfinder):
    path, time = pathfinder.computePathDijkstra()
    pathfinder.plotPaths()


def computeAndDisplayDFS(pathfinder):
    path, time = pathfinder.computePathDFS()
    pathfinder.displayEnv()


def computeAndDisplayBidirAStar(pathfinder):
    path, time = pathfinder.computePathBidirAStar()
    pathfinder.plotPaths()


def showComparisonPlots(pathfinder, test_samples):
    pathfinder_api.benchmark(test_samples, True, True)


if __name__ == "__main__":
    env = World(filename="worlds/colliders.csv")
    pathfinder_api = PathFinder(env)
    #pathfinder_api.displayEnvFigure()
    showComparisonPlots(pathfinder_api, 10)
    #computeAndDisplayDFS(pathfinder_api)
    #computeAndDisplayAStar(pathfinder_api)
    #computeAndDisplayDijkstra(pathfinder_api)
    #computeAndDisplayBidirAStar(pathfinder_api)
def changepoint_path(wav_fn,
                     length,
                     graph=None,
                     markers=None,
                     sim_mat=None,
                     avg_duration=None,
                     APP_PATH=None,
                     nchangepoints=4,
                     min_start=None):
    """wave filename and graph from that wav, length in seconds"""
    # generate changepoints
    try:
        cpraw = subprocess.check_output([
            APP_PATH + 'music_changepoints/novelty', wav_fn, '64', 'rms',
            'euc',
            str(nchangepoints) * 3
        ])
        tmp_changepoints = [float(c) for c in cpraw.split('\n') if len(c) > 0]
        changepoints = []
        cp_idx = 0
        while len(changepoints) < nchangepoints:
            if min_start is None:
                changepoints.append(tmp_changepoints[cp_idx])
            elif tmp_changepoints[cp_idx] >= min_start:
                changepoints.append(tmp_changepoints[cp_idx])
            cp_idx += 1

    except:
        changepoints = novelty(wav_fn, k=64, nchangepoints=nchangepoints)

    print "Change points", changepoints

    if graph is not None:
        edge_lens = [graph[e[0]][e[1]]["duration"] for e in graph.edges_iter()]
        avg_duration = N.mean(edge_lens)
        nodes = sorted(graph.nodes(), key=float)
    else:
        nodes = map(str, markers)

    node_count = int(float(length) / avg_duration)

    closest_nodes = []
    node_to_cp = {}
    for cp in changepoints:
        closest_nodes.append(
            N.argmin([N.abs(float(node) - float(cp)) for node in nodes]))
        node_to_cp[str(closest_nodes[-1])] = cp

    out = []

    for pair in itertools.permutations(closest_nodes, r=2):
        # print "Finding path for pair", pair, "of length", node_count

        avoid_nodes = [cn for cn in closest_nodes if cn != pair[1]]
        # avoid_nodes = closest_nodes

        if graph is not None:
            try:
                shortest_path = nx.astar_path_length(graph, nodes[pair[0]],
                                                     nodes[pair[1]])
                # print "# shortest path:", shortest_path
                if shortest_path <= node_count:

                    pf = PathFinder(graph=graph,
                                    start=pair[0],
                                    end=pair[1],
                                    length=node_count)
                    res, cost = pf.find(avoid=avoid_nodes)
                    if res is not None:
                        out.append((res, cost))
                        break
            except:
                pass

        else:
            pf = PathFinder(start=pair[0],
                            sim_mat=sim_mat.copy(),
                            end=pair[1],
                            nodes=nodes,
                            length=node_count)
            res, cost = pf.find(avoid=avoid_nodes)
            if res is not None:
                out.append((res, cost, map(lambda x: node_to_cp[str(x)],
                                           pair)))

    return out, changepoints
Exemple #30
0
    def analyze_pairs(self,
                      carbon_only=True,
                      use_antimotifs=True,
                      max_distance=4):
        distances = [
        ]  # the minimal pathway length between the substrate and the product
        alternatives = [
        ]  # each value is the number of alternative pathways with the minimal distance

        line_counter = 0
        for line in util.parse_text_file("../rec/" + self.modules_file +
                                         ".txt"):
            if (line[0] == '@'):
                line = line[1:]
                self.pathfinder = PathFinder(carbon_only=carbon_only,
                                             pruning_method=None,
                                             ignore_chirality=False,
                                             use_antimotifs=use_antimotifs,
                                             outstream=self.logfile)
            else:
                self.pathfinder = PathFinder(carbon_only=carbon_only,
                                             pruning_method=None,
                                             ignore_chirality=True,
                                             use_antimotifs=use_antimotifs,
                                             outstream=self.logfile)

            (subs, prod, max_steps) = line.split(";", 2)
            if (max_steps in ['-1', 'inf', '']):
                sys.stdout.write(subs + " -(?)-> " + prod)
                sys.stdout.flush()
                (scenes,
                 dist) = self.get_shortest_pathways(subs, prod, max_distance)
            else:
                dist = int(max_steps)
                sys.stdout.write(subs + " -(%d)-> " % dist + prod)
                sys.stdout.flush()
                scenes = self.get_all_pathways(subs, prod, dist)

            if (dist == -1):
                sys.stdout.write(", Distance(L) = inf, N = 0\n")
                sys.stdout.flush()
                distances.append("inf")
                alternatives.append(0)
                self.html_writer.write(
                    "<li><span style=color:red>%s <-> %s (distance > %d)</span></li>\n"
                    % (subs, prod, self.max_module_size))
                self.html_writer.flush()
            else:
                sys.stdout.write(", Distance(L) = %d, N = %d\n" %
                                 (dist, len(scenes)))
                sys.stdout.flush()
                distances.append(dist)
                alternatives.append(len(scenes))
                self.html_writer.write(
                    "<li><span style=color:green>%s <-> %s (distance = %d)</span></li>\n"
                    % (subs, prod, dist))
                for i in range(len(scenes)):
                    self.html_writer.write("<li>")
                    self.html_writer.write_svg(
                        scenes[i], "pathologic_" + self.experiment_name +
                        "/pair%d_path%d" % (line_counter, i))
                    self.html_writer.write("</li>\n")
                self.html_writer.flush()
            line_counter += 1

        result_file = open("../results/" + self.experiment_name + ".txt", "w")
        result_file.write(str(distances) + "\n" + str(alternatives) + "\n")
        result_file.close()
Exemple #31
0
class MyField(Field):
    """An object representing the field.  """

    cellClass = MyCell
    connectorClass = MyConnector

    def __init__(self):

        self.m_xmin_field = XMIN_FIELD
        self.m_ymin_field = YMIN_FIELD
        self.m_xmax_field = XMAX_FIELD
        self.m_ymax_field = YMAX_FIELD
        self.m_xmin_vector = XMIN_VECTOR
        self.m_ymin_vector = YMIN_VECTOR
        self.m_xmax_vector = XMAX_VECTOR
        self.m_ymax_vector = YMAX_VECTOR
        self.m_xmin_screen = XMIN_SCREEN
        self.m_ymin_screen = YMIN_SCREEN
        self.m_xmax_screen = XMAX_SCREEN
        self.m_ymax_screen = YMAX_SCREEN
        self.m_path_unit = PATH_UNIT
        self.m_output_mode = MODE_DEFAULT
        self.m_path_scale = 1
        self.m_screen_scale = 1
        self.m_vector_scale = 1
        # our default margins, one will be overwriten below
        self.m_xmargin = int(self.m_xmax_screen*DEF_MARGIN)
        self.m_ymargin = int(self.m_ymax_screen*DEF_MARGIN)
        self.set_scaling()
        self.m_screen = object
        self.path_grid = object
        self.pathfinder = object
        super(MyField, self).__init__()

        self.make_path_grid()

    # Screen Stuff

    def init_screen(self):
        # initialize window
        #(xmax_screen,ymax_screen) = self.screenMax()
        #self.m_screen = pyglet.window.Window(width=xmax_screen,height=ymax_screen)
        width = self.m_xmax_screen - self.m_xmin_screen
        height = self.m_ymax_screen - self.m_ymin_screen
        if dbug.LEV & dbug.FIELD: print "field:init_screen"
        self.m_screen = Window(self,width=width,height=height)
        # set window background color = r, g, b, alpha
        # each value goes from 0.0 to 1.0
        # ... perform some additional initialisation
        pyglet.gl.glClearColor(*DEF_BKGDCOLOR)
        self.m_screen.clear()
        # register draw routing with pyglet
        # TESTED: These functions are being called correctly, and params are
        # being passed correctly
        self.m_screen.set_minimum_size(XMAX_SCREEN/4, YMAX_SCREEN/4)
        self.m_screen.set_visible()

    # Scaling

    def set_scaling(self,pmin_field=None,pmax_field=None,pmin_vector=None,pmax_vector=None,
                      pmin_screen=None,pmax_screen=None,path_unit=None,output_mode=None):
        """Set up scaling in the field.

        A word about graphics scaling:
         * The vision tracking system (our input data) measures in meters.
         * The laser DAC measures in uh, int16? -32,768 to 32,768
         * Pyglet measures in pixels at the screen resolution of the window you create
         * The pathfinding units are each some ratio of the smallest expected radius

         So we will keep eveything internally in centemeters (so we can use ints
         instead of floats), and then convert it to the appropriate units before 
         display depending on the output mode

         """

        if pmin_field is not None:
            self.m_xmin_field = pmin_field[0]
            self.m_ymin_field = pmin_field[1]
        if pmax_field is not None:
            self.m_xmax_field = pmax_field[0]
            self.m_ymax_field = pmax_field[1]
        if pmin_vector is not None:
            self.m_xmin_vector = pmin_vector[0]
            self.m_ymin_vector = pmin_vector[1]
        if pmax_vector is not None:
            self.m_xmax_vector  = pmax_vector[0]
            self.m_ymax_vector  = pmax_vector[1]
        if pmin_screen is not None:
            self.m_xmin_screen = pmin_screen[0]
            self.m_ymin_screen = pmin_screen[1]
        if pmax_screen is not None:
            self.m_xmax_screen = pmax_screen[0]
            self.m_ymax_screen = pmax_screen[1]
        if path_unit is not None:
            self.m_path_unit = path_unit
            self.m_path_scale = float(1)/path_unit
        if output_mode is not None:
            self.m_output_mode = output_mode
        xmin_field = self.m_xmin_field
        ymin_field = self.m_ymin_field
        xmax_field = self.m_xmax_field
        ymax_field = self.m_ymax_field
        xmin_vector = self.m_xmin_vector
        ymin_vector = self.m_ymin_vector
        xmax_vector = self.m_xmax_vector
        ymax_vector = self.m_ymax_vector
        xmin_screen = self.m_xmin_screen
        ymin_screen = self.m_ymin_screen
        xmax_screen = self.m_xmax_screen
        ymax_screen = self.m_ymax_screen

        # in order to find out how to display this,
        #   1) we find the aspect ratio (x/y) of the screen or vector (depending on the
        #      mode). 
        #   2) Then if the aspect ratio (x/y) of the reported field is greater, we
        #      set the x axis to stretch to the edges of screen (or vector) and then use
        #      that value to determine the scaling.
        #   3) But if the aspect ratio (x/y) of the reported field is less than,
        #      we set the y axis to stretch to the top and bottom of screen (or
        #      vector) and use that value to determine the scaling.

        # aspect ratios used only for comparison
        field_aspect = float(xmax_field-xmin_field)/(ymax_field-ymin_field)
        if self.m_output_mode == MODE_SCREEN:
            display_aspect = float(xmax_screen-xmin_screen)/(ymax_screen-ymin_screen)
        else:
            display_aspect = float(xmax_vector-xmin_vector)/(ymax_vector-ymin_vector)
        if field_aspect > display_aspect:
            if dbug.LEV & dbug.FIELD: print "Field:SetScaling:Longer in the x dimension"
            field_xlen=xmax_field-xmin_field
            if field_xlen:
                self.m_xmargin = int(xmax_screen*DEF_MARGIN)
                # scale = vector_width / field_width
                self.m_vector_scale = \
                    float(xmax_vector-xmin_vector)/field_xlen
                # scale = (screen_width - margin) / field_width
                self.m_screen_scale = \
                    float(xmax_screen-xmin_screen-(self.m_xmargin*2))/field_xlen
                self.m_ymargin = \
                    int(((ymax_screen-ymin_screen)-((ymax_field-ymin_field)*self.m_screen_scale)) / 2)
        else:
            if dbug.LEV & dbug.FIELD: print "Field:SetScaling:Longer in the y dimension"
            field_ylen=ymax_field-ymin_field
            if field_ylen:
                self.m_ymargin = int(ymax_screen*DEF_MARGIN)
                self.m_vector_scale = \
                    float(ymax_vector-ymin_vector)/field_ylen
                self.m_screen_scale = \
                    float(ymax_screen-ymin_screen-(self.m_ymargin*2))/field_ylen
                self.m_xmargin = \
                    int(((xmax_screen-xmin_screen)-((xmax_field-xmin_field)*self.m_screen_scale)) / 2)
        if dbug.LEV & dbug.MORE: print "Field dims:",(xmin_field,ymin_field),(xmax_field,ymax_field)
        if dbug.LEV & dbug.MORE: print "Screen dims:",(xmin_screen,ymin_screen),(xmax_screen,ymax_screen)
        #print "Screen scale:",self.m_screen_scale
        #print "Screen margins:",(self.m_xmargin,self.m_ymargin)
        if dbug.LEV & dbug.MORE: print "Used screen space:",self.rescale_pt2out((xmin_field,ymin_field)),self.rescale_pt2out((xmax_field,ymax_field))

    # Everything

    def render_all(self):
        """Render all the cells and connectors."""
        self.render_all_cells()
        self.render_all_connectors()

    def draw_all(self):
        """Draw all the cells and connectors."""
        self.draw_guides()
        self.draw_all_cells()
        self.draw_all_connectors()

    # Guides

    def draw_guides(self):
        # draw boundaries of field (if in screen mode)
        if self.m_output_mode == MODE_SCREEN:
            pyglet.gl.glColor3f(DEF_GUIDECOLOR[0],DEF_GUIDECOLOR[1],DEF_GUIDECOLOR[2])
            points = [(self.m_xmin_field,self.m_ymin_field),
                      (self.m_xmin_field,self.m_ymax_field),
                      (self.m_xmax_field,self.m_ymax_field),
                      (self.m_xmax_field,self.m_ymin_field)]
            if dbug.LEV & dbug.GRAPH: print "boundary points (field):",points
            index = [0,1,1,2,2,3,3,0]
            screen_pts = self.rescale_pt2out(points)
            if dbug.LEV & dbug.GRAPH: print "boundary points (screen):",screen_pts
            # boundary points (screen): [(72, 73), (72, 721), (1368, 721), (1368, 73)]
            if dbug.LEV & dbug.GRAPH: print "proc screen_pts:",tuple(chain(*screen_pts))
            # proc screen_pts: (72, 73, 72, 721, 1368, 721, 1368, 73)
            if dbug.LEV & dbug.GRAPH: print "PYGLET:pyglet.graphics.draw_indexed(",len(screen_pts),", pyglet.gl.GL_LINES,"
            if dbug.LEV & dbug.GRAPH: print "           ",index
            if dbug.LEV & dbug.GRAPH: print "           ('v2i',",tuple(chain(*screen_pts)),"),"
            if dbug.LEV & dbug.GRAPH: print "       )"
            pyglet.graphics.draw_indexed(len(screen_pts), pyglet.gl.GL_LINES,
                index,
                ('v2i',tuple(chain(*screen_pts))),
            )
            #point = (self.m_xmin_field,self.m_ymin_field)
            #radius = self.rescale_num2out(DEF_RADIUS)
            #shape = Circle(self,point,radius,DEF_LINECOLOR,solid=False)
            #shape.render()
            #shape.draw()
            if dbug.LEV & dbug.MORE: print "Field:drawGuides"

    # Cells
    #def create_cell(self, id):
    # moved to superclass
    #def update_cell(self, id, p=None, r=None, effects=None, color=None):
    # moved to superclass
    #def is_cell_good_to_go(self, id):
    # moved to superclass
    #def del_cell(self, id):
    # moved to superclass
    #def check_people_count(self,reported_count):
    # moved to superclass
    #def hide_cell(self, id):
    # moved to superclass
    #def hide_all_cells(self):
    # moved to superclass

    def render_cell(self,cell):
        """Render a cell.

        We first check if the cell is good.
        If not, we increment its suspect count
        If yes, render it.
        """
        if self.is_cell_good_to_go(cell.m_id):
            cell.render()
            #del self.m_suspect_cells[cell.m_id]
        else:
            if dbug.LEV & dbug.FIELD: print "Field:renderCell:Cell",cell.m_id,"is suspected lost for",\
                  self.m_suspect_cells[cell.m_id],"frames"
            if self.m_suspect_cells[cell.m_id] > MAX_LOST_PATIENCE:
                self.del_cell(cell.m_id)
            else:
                self.m_suspect_cells[cell.m_id] += 1

    def render_all_cells(self):
        # we don't call the Cell's render-er directly because we have some
        # logic here at this level
        for cell in self.m_cell_dict.values():
            self.render_cell(cell)

    def draw_cell(self,cell):
        cell.draw()

    def draw_all_cells(self):
        # we don't call the Cell's draw-er directly because we may want
        # to introduce logic at this level
        for cell in self.m_cell_dict.values():
            self.draw_cell(cell)

    # Connectors

    #def create_connector(self, id, cell0, cell1):
    # moved to superclass

    #def del_connector(self,conxid):
    # moved to superclass

    def render_connector(self,connector):
        """Render a connector.

        We first check if the connector's two cells are both good.
        If not, we increment its suspect count
        If yes, render it.
        """
        if self.is_cell_good_to_go(connector.m_cell0.m_id) and \
           self.is_cell_good_to_go(connector.m_cell1.m_id):
            connector.render()
            if connector.m_id in self.m_suspect_conxs:
                del self.m_suspect_conxs[connector.m_id]
        else:
            if dbug.LEV & dbug.FIELD: print "Field:renderConnector:Conx",connector.m_id,"between",\
                connector.m_cell0.m_id,"and",connector.m_cell1.m_id,"is suspected lost"
            if self.m_suspect_conxs[connector.m_id] > MAX_LOST_PATIENCE:
                self.del_connector(connector.m_id)
            else:
                self.m_suspect_conxs[connector.m_id] += 1

    def render_all_connectors(self):
        # we don't call the Connector's render-er directly because we have some
        # logic here at this level
        for connector in self.m_connector_dict.values():
            self.render_connector(connector)

    def draw_connector(self,connector):
        connector.draw()

    def draw_all_connectors(self):
        # we don't call the Connector's draw-er directly because we may want
        # to introduce logic at this level
        for connector in self.m_connector_dict.values():
            self.draw_connector(connector)

    # Distances - TODO: temporary -- this info will come from the conduction subsys

    #def dist_sqd(self,cell0,cell1):
    # moved to superclass
    #def calc_distances(self):
    # moved to superclass

    # Paths

    # should the next two functions be in the gridmap module? No, because the GridMap
    # and Pathfinder classes have to be instantiated from somewhere. And if not
    # here they have to be called from the main loop. Better here.
    def make_path_grid(self):
        # for our pathfinding, we're going to overlay a grid over the field with
        # squares that are sized by a constant in the config file
        self.path_grid = GridMap(self.scale2path(self.m_xmax_field),
                                 self.scale2path(self.m_ymax_field))
        self.pathfinder = PathFinder(self.path_grid.successors, self.path_grid.move_cost, 
                                     self.path_grid.estimate)

    def reset_path_grid(self):
        self.path_grid.reset_grid()
        # we store the results of all the paths, why? Not sure we need to anymore
        #self.allpaths = []

    def path_score_cells(self):
        #print "***Before path: ",self.m_cell_dict
        for cell in self.m_cell_dict.values():
            self.path_grid.set_blocked(self.scale2path(cell.m_location),
                                       self.scale2path(cell.m_radius),BLOCK_FUZZ)

    def path_find_connectors(self):
        """ Find path for all the connectors.

        We sort the connectors by distance and do easy paths for the closest 
        ones first.
        """
        #connector_dict_rekeyed = self.m_connector_dict
        #for i in connector_dict_rekeyed.iterkeys():
        connector_dict_rekeyed = {}
        for connector in self.m_connector_dict.values():
            p0 = connector.m_cell0.m_location
            p1 = connector.m_cell1.m_location
            # normally we'd take the sqrt to get the distance, but here this is 
            # just used as a sort comparison, so we'll not take the hit for sqrt
            score = ((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2) 
            # here we save time by sorting as we go through it
            connector_dict_rekeyed[score] = connector
        for i in sorted(connector_dict_rekeyed.iterkeys()):
            connector = connector_dict_rekeyed[i]
            print "findpath--id:",connector.m_id,"dist:",i**0.5
            connector.add_path(self.find_path(connector))

    def find_path(self, connector):
        """ Find path in path_grid and then scale it appropriately."""
        start = self.scale2path(connector.m_cell0.m_location)
        goal = self.scale2path(connector.m_cell1.m_location)
        # TODO: Either here or in compute_path we first try several simple/dumb
        # paths, reserving A* for the ones that are blocked and need more
        # smarts. We sort the connectors by distance and do easy paths for the
        # closest ones first.
        #path = list(self.path_grid.easy_path(start, goal))
        #print "connector:id",connector.m_id,"path:",path
        #if not path:
        path = list(self.pathfinder.compute_path(start, goal))
        # take results of found paths and block them on the map
        self.path_grid.set_block_line(path)
        #self.allpaths = self.allpaths + path
        return self.path2scale(path)
        
    def print_grid(self):
        self.path_grid.printme()
    # Scaling conversions

    def _convert(self,obj,scale,min1,min2):
        """Recursively converts numbers in an object.

        This function accepts single integers, tuples, lists, or combinations.

        """
        if isinstance(obj, (int, float)):
            #return(int(obj*scale) + min)
            return int((obj-min1)*scale) + min2
        elif isinstance(obj, list):
            mylist = []
            for i in obj:
                mylist.append(self._convert(i,scale,min1,min2))
            return mylist
        elif isinstance(obj, tuple):
            mylist = []
            for i in obj:
                mylist.append(self._convert(i,scale,min1,min2))
            return tuple(mylist)

    def scale2out(self,n):
        """Convert internal unit (cm) to units usable for the vector or screen. """
        if self.m_output_mode == MODE_SCREEN:
            return self._convert(n,self.m_screen_scale,self.m_xmin_field,self.m_xmin_screen)
        return self._convert(n,self.m_vector_scale,self.m_xmin_field,self.m_xmin_vector)

    def scale2path(self,n):
        """Convert internal unit (cm) to units usable for pathfinding. """
        return self._convert(n,self.m_path_scale,self.m_xmin_field,0)

    def path2scale(self,n):
        """Convert pathfinding units to internal unit (cm). """
        #print "m_path_scale",self.m_path_scale
        return self._convert(n,1/self.m_path_scale,0,self.m_xmin_field)

    def _rescale_pts(self,obj,scale,orig_pmin,new_pmin):
        """Recursively rescales points or lists of points.

        This function accepts single integers, tuples, lists, or combinations.

        """
        # if this is a point, rescale it
        if isinstance(obj, tuple) and len(obj) == 2 and \
           isinstance(obj[0], (int,float)) and isinstance(obj[1], (int,float)):
            x = int((obj[0]-orig_pmin[0])*scale) + new_pmin[0]
            y = int((obj[1]-orig_pmin[1])*scale) + new_pmin[1]
            return x,y
        # if this is a list, examine each element, return list
        elif isinstance(obj, (list,tuple)):
            mylist = []
            for i in obj:
                mylist.append(self._rescale_pts(i,scale,orig_pmin,new_pmin))
            return mylist
        # if this is a tuple, examine each element, return tuple
        elif isinstance(obj, tuple):
            mylist = []
            for i in obj:
                mylist.append(self._rescale_pts(i,scale,orig_pmin,new_pmin))
            return tuple(mylist)
        # otherwise, we don't know what to do with it, return it
        # TODO: Consider throwing an exception
        else:
            print "ERROR: Can only rescale a point, not",obj
            return obj

    def rescale_pt2out(self,p):
        """Convert coord in internal units (cm) to units usable for the vector or screen. """
        orig_pmin = (self.m_xmin_field,self.m_ymin_field)
        if self.m_output_mode == MODE_SCREEN:
            scale = self.m_screen_scale
            new_pmin = (self.m_xmin_screen+self.m_xmargin,self.m_ymin_screen+self.m_ymargin)
        else:
            scale = self.m_vector_scale
            new_pmin = (self.m_xmin_vector,self.m_ymin_vector)
        return self._rescale_pts(p,scale,orig_pmin,new_pmin)

    def rescale_num2out(self,n):
        """Convert num in internal units (cm) to units usable for the vector or screen. """
        if self.m_output_mode == MODE_SCREEN:
            scale = self.m_screen_scale
        else:
            scale = self.m_vector_scale
        return n*scale
Exemple #32
0
# These are parameters that affect the way the search graph works.
# It if probably best not to change them.
use_antimotifs = False
carbon_only = True
ignore_chirality = False
max_depth = 2
reaction_database_fname = "../rec/reaction_templates.dat"

# the substrate and product must be listed in '../metacyc/mcard_sdf_extra.txt'
# which uses the MOL format for describing molecules.
# each one of them can also be a sum of more than one compound (i.e. ribitol + CO2)
substrate, product = 'D-ribulose-5P', 'L-ribulose-5P'

pathfinder = PathFinder(carbon_only=True,
                        pruning_method=None,
                        ignore_chirality=ignore_chirality,
                        use_antimotifs=True,
                        reaction_database_fname=reaction_database_fname)

# This loop tries to find all the paths with lengths less than 'max_depth'
for depth in xrange(1, max_depth + 1):
    sys.stderr.write(substrate + " <=> " + product +
                     ", depth = %d ... " % depth)
    G_subs = compound2graph(substrate)
    G_prod = compound2graph(product)
    (original_compound_map, possible_paths,
     D) = pathfinder.find_shortest_pathway([G_subs], [G_prod],
                                           max_levels=depth)

    for (substrate_pathways, product_pathways, h_bridge) in possible_paths:
        # the results are given as 3-tuples, characterized by the compound where the two ends
Exemple #33
0
    def execute(self):

        self.salir = False

        while not self.salir:

            self.clock.tick(self.velocidad)

            # eventos de teclado

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.salir = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.pausa = True

            # submenu

            if self.pausa:
                while self.pausa:

                    self.clock.tick(self.velocidad)

                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            self.pausa = False
                            self.salir = True
                        if event.type == pygame.KEYDOWN:
                            if event.key == pygame.K_SPACE:

                                self.pausa = False

                            if event.key == pygame.K_2:
                                if self.velocidad_algoritmo < 30:
                                    self.velocidad_algoritmo += 1
                            if event.key == pygame.K_1:
                                if self.velocidad_algoritmo > 0:
                                    self.velocidad_algoritmo -= 1

                            if event.key == pygame.K_d:
                                if self.cursor.modo_borrar:
                                    self.cursor.modo_borrar = False
                                    self.texto = self.fuente.render("Pausado",
                                                True, (255, 0, 255))
                                else:
                                    self.cursor.modo_borrar = True
                                    self.texto = self.fuente.render("Pausado  Modo borrar paredes",
                                                True, (255, 0, 255))

                            if event.key == pygame.K_r:
                                self.tablero.matrix = self.tablero.rellenaRandom()
                                self.pathfinder.reset()
                                self.tablero.reset_ab()

                    if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]:

                        self.tablero = Tablero(80, 80)
                        self.pathfinder = PathFinder(self.tablero)
                        self.cursor = Cursor(self.tablero, self.pathfinder)

                    #updates
                    self.cursor.update()
                    self.cursor.changeState()

                    self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo),
                                True, (255, 0, 255))

                    # draws
                    self.screen.fill((0, 0, 0))
                    self.draw_matriz()
                    self.screen.blit(self.texto, (8, self.screen.get_height() - 28))
                    self.screen.blit(self.texto_algo, (self.screen.get_width() - 200,
                                 self.screen.get_height() - 28))
                    pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect)
                    pygame.display.update()

             #pathfinder

            #self.pathfinder.run2()
            for i in range(self.velocidad_algoritmo):
                self.pathfinder.run()  # el que funciona
            # updates
            self.cursor.update()

            # draws
            self.screen.fill((0, 0, 0))
            self.draw_matriz()
            pygame.display.update()
Exemple #34
0
        timer.print_elapsed()
        if pars["save_scaldim_file"]:
            write_tensor_file(data=res,
                              prefix="scals_by_alpha",
                              pars=id_pars,
                              filename=filename)
    return res


#=============================================================================#

if __name__ == "__main__":
    pars = parse()
    id_pars = get_id_pars(pars)
    filename = os.path.basename(__file__)
    pather = PathFinder(filename, id_pars)

    # - Infoprint -
    print("\n" + ("=" * 70) + "\n")
    print("Running %s with the following parameters:" % filename)
    for k, v in sorted(pars.items()):
        print("%s = %s" % (k, v))

    res = load_cft_data(pars)
    scaldims_by_alpha, c = res[:2]
    if pars["do_momenta"]:
        momenta_by_alpha = res[2]
    else:
        momenta_by_alpha = None

    scaldim_plot.plot_and_print_dict(scaldims_by_alpha,
Exemple #35
0
class Hero():
    """Class holding unique hero object"""

    def __init__(self):
        self.hero_id = None 
        self.alive = True
        self.location = [None, None]
        self.shop_location = None
        self.shop_destination = None
        self.pathfinder = None
        self.path = None
        self.name = None
        self.home = None
        self.inventory = []
        self.coins = {
            'copper': 0,
            'silver': 0,
            'gold': 0
        }
        self.kills = []
        self.size = 100 #represents percent of "normal" size
        self.goals = []
        self.needs = []
        self.wants = []
        self.personality = None
        self.experience = None
        self.perceptions = None
        self.boredom = 0
        self.traveling = False
        self.destination = [None, None]
        self.coins = {
            'copper': 0,
            'silver': 0,
            'gold': 0
        }


    def tick(self, game):
        self.think()

        if self.location == entities.town['object'].location:
            if 'shopping' in self.wants:
                self.enter_shop(game)
                self.wants.remove('shopping')
            if self.shop_location == None:
                if randint(1, 5) == 1:
                    self.boredom += randint(1, 50)
                if self.boredom >= 100 and 'adventure' not in self.wants:
                #if self.boredom >= 1 and 'adventure' not in self.wants: #TODO: Remove line; just for testing
                    self.wants.append('adventure')
            else:
                if ('transaction' in self.wants and 
                    entities.shop['object'].get_shop_tile(self.get_shop_grid_location()) == 'transaction'
                ):
                    if self not in entities.shop['object'].transaction_queue:
                        entities.shop['object'].transaction_queue.append(self)

        if self.traveling:
            self.step_to(self.destination)
            if self.location == self.destination:
                self.traveling = False
                if self.location == entities.town['object']:
                    self.perceptions.economy.be_influenced(entities.town['object'].economy)
                for site in entities.sites['object list']:
                    if self.destination == site.location:
                        site.structure.add_hero(self.hero_id)
                        self.destination = None
                        break
                    
        if 'adventure' in self.wants:
            shuffle(entities.sites['object list'])
            for site in entities.sites['object list']:
                if (site.structure.get_attribute('site type') == 'adventure' and
                    site.structure.worker_capacity > 0
                ):
                    self.traveling = True
                    self.wants.remove('adventure')
                    self.boredom = 0
                    self.destination = site.location
                    break


    def think(self):
        if self.shop_location == None and len(self.inventory) >= 2 and 'shopping' not in self.wants:
            self.wants.append('shopping')
        if self.shop_location != None: #if hero is in the shop
            if self.inventory >= 2 and 'transaction' not in self.wants:
                self.wants.append('transaction')
            if 'transaction' in self.wants and self.pathfinder == None:
                transaction_tiles = self.get_tiles('transaction')
                self.shop_destination = choice(transaction_tiles)
                self.get_path(self.shop_destination)


    def get_path(self, destination):
        gridmap = GridMap(
            len(entities.shop['object'].shop_grid[0]),
            len(entities.shop['object'].shop_grid)
        )
        blocked_tiles = self.get_tiles('passable', False)
        for blocked_tile in blocked_tiles:
            gridmap.set_blocked(blocked_tile)
        self.pathfinder = PathFinder(gridmap.successors, gridmap.move_cost, gridmap.move_cost)
        self.path = self.pathfinder.compute_path(
            self.get_shop_grid_location(),
            destination
        )

    def get_shop_grid_location(self):
        return tuple(map(lambda x: x/ref.tile_size, self.shop_location))


    def step_to(self, destination=None):
        x = False
        y = False
        if destination[0] != self.location[0]:
            x = True
        if destination[1] != self.location[1]:
            y = True
        if x and randint(1,3) != 3:
            self.location[0] = self.location[0] - int(
                copysign(1, self.location[0]-destination[0])
            )
        if y and randint(1,3) != 3:
            self.location[1] = self.location[1] - int(
                copysign(1, self.location[1]-destination[1])
            )


    def get_tiles(self, tile_type, positive=True):
        """Returns a list of coordinates where that type of tile exists in the shop grid"""
        if tile_type not in ref.tile_type_list:
            tester = tile_type
            tile_type = positive
        else:
            tester = 'tile type'
        tiles = []
        for row in xrange(len(entities.shop['object'].shop_grid)):
            for column in xrange(len(entities.shop['object'].shop_grid[row])):
                tile = entities.shop['object'].shop_grid[row][column]
                if tile in ref.shop_tile_dct.keys():
                    if ref.shop_tile_dct[tile][tester] == tile_type:
                        tiles.append((column, row))
        return tiles


        
    def enter_shop(self, game):
        shop_grid = entities.shop['object'].shop_grid
        door_locs = []
        for y in xrange(len(shop_grid)):
            for x in xrange(len(shop_grid[0])):
                if shop_grid[y][x] != 0:
                    if ref.shop_tile_dct[shop_grid[y][x]]['tile type'] == 'door':
                        door_locs.append((x, y))
        entrance_loc = choice(door_locs)
        self.shop_location = [
            entrance_loc[0] * ref.tile_size,
            entrance_loc[1] * ref.tile_size
        ]
        game.message_log += "%s has entered your shop." % self.name
        game.screens['world'].initialize_shop_sprites(game)


    def generate(self, location='random', weapon='random'):
        """Generates a hero."""
        import item_data
        import language
        self.personality = Personality()
        self.perceptions = Perceptions().generate(self)
        self.coins['copper'] = randint(10,300)
        if location == 'town':
            self.home = entities.town['object']
            self.location = copy.deepcopy(self.home.location)
        if weapon != None:
            if weapon == 'random':
                self.inventory.append(item_data.Weapon().generate('random'))
            else:
                return NotImplementedError(weapon) #TODO
        self.name = language.create_name('human')
        if type(self.location) == list:
            entities.town['object'].population += 1
            entities.town['object'].occupations['adventurer'] += 1
        self.set_hero_id()
        return self


    def set_hero_id(self):
        """Gives hero object uniquue ID."""
        self.hero_id = entities.heroes['next id']
        entities.heroes['object list'].append(self)
        entities.heroes['next id'] += 1
		

    def __repr__(self):
        return 'Hero(ID: %r, Name:%r)' % (self.hero_id, self.name)
class VisionServer:
    def __init__(self):
        self.server = actionlib.SimpleActionServer('track_object', TrackObjectAction, self.execute, False)
        self.server.start()

        self.lower = None
        self.upper = None
        self.targetType = None

        self.srv = Server(ThresholdsConfig, self.updateThresholds)

        self.thresholds = {int(k):v for k,v in rospy.get_param("/vision_thresholds").items()}

        self.bridge = CvBridge()

        self.leftImage = np.zeros((1,1,3), np.uint8)
        self.leftModel = image_geometry.PinholeCameraModel()
        self.newLeft = False

        self.rightImage = np.zeros((1,1,3), np.uint8)
        self.rightModel = image_geometry.PinholeCameraModel()
        self.newRight = False

        self.downImage = np.zeros((1,1,3), np.uint8)
        self.downModel = image_geometry.PinholeCameraModel()
        self.newDown = False

        self.disparityImage = np.zeros((1,1,3), np.uint8)
        self.stereoModel = image_geometry.StereoCameraModel()
        self.newDisparity = False

        self.poleFinder = PoleFinder()
        self.gateFinder = GateFinder()
        self.diceFinder = DiceFinder()
        self.pathFinder = PathFinder()
        self.response = TrackObjectResult()

        self.downSub = rospy.Subscriber('/down_camera/image_color', Image, self.downwardsCallback)
        self.downInfoSub = rospy.Subscriber('/down_camera/info', CameraInfo, self.downInfoCallback)
        
        self.stereoSub = rospy.Subscriber('/stereo/disparity', Image, self.stereoCallback)
        #self.stereoInfoSub = rospy.Subscriber('/stereo/info', CameraInfo, self.stereoInfoCallback)

        self.leftSub = rospy.Subscriber('/stereo/left/image', WFOVImage, self.leftCallback)
        #self.leftInfoSub = rospy.Subscriber('/stereo/left/image', WFOVImage, self.leftInfoCallback)
        
        self.rightSub = rospy.Subscriber('/stereo/right/image', WFOVImage, self.rightCallback)
        #self.rightInfoSub = rospy.Subscriber('/stereo/right/image', WFOVImage, self.rightInfoCallback)

        self.bridge = CvBridge()
        self.image_pub = rospy.Publisher("/thresh_image", Image, queue_size=10)
        

        #self.thresholds = self.loadThresholds()

    def updateThresholds(self, config, level):
        self.lower = np.array([config["lowH"], config["lowS"], config["lowL"]],dtype=np.uint8)
        self.upper = np.array([config["upH"], config["upS"], config["upL"]],dtype=np.uint8)

        if self.targetType is not None:
            self.thresholds[self.targetType] = [self.lower.tolist(), self.upper.tolist()]
            rospy.set_param("/vision_thresholds/"+str(self.targetType), [self.lower.tolist(), self.upper.tolist()])

        return config

    def setThresholds(self, lower, upper):
        self.lower = np.array(lower,dtype=np.uint8)
        self.upper = np.array(upper,dtype=np.uint8)

        self.srv.update_configuration({"lowH":lower[0], "lowS":lower[1], "lowV":lower[2], "upH":upper[0], "upS":upper[1], "upV":upper[2]})

    def execute(self, goal):
        self.targetType = goal.objectType
        self.setThresholds(*self.thresholds[self.targetType])
        self.feedback = TrackObjectFeedback()
        self.found = False

        self.running = True
        self.ok = True

        rightImageRect = np.zeros(self.rightImage.shape, self.rightImage.dtype)
        leftImageRect = np.zeros(self.leftImage.shape, self.leftImage.dtype)
        downImageRect = np.zeros(self.downImage.shape, self.downImage.dtype)

        r = rospy.Rate(60)
        while self.running and not rospy.is_shutdown():
            if self.server.is_preempt_requested() or self.server.is_new_goal_available():
                self.running = False
                continue
            
            r.sleep()
            
            if self.rightModel.width is not None and self.rightImage is not None:
                self.rightModel.rectifyImage(self.rightImage, rightImageRect)
            else:
                rospy.logwarn_throttle(1, "No right camera model")
                continue
                
            if self.leftModel.width is not None and self.leftImage is not None:
                self.leftModel.rectifyImage(self.leftImage, leftImageRect)
            else:
                rospy.logwarn_throttle(1, "No left camera model")
                continue #We need the left camera model for stuff

            if self.downModel.width is not None and self.downImage is not None:
                self.downModel.rectifyImage(self.downImage, downImageRect)
            else:
                rospy.logwarn_throttle(1, "No down camera model")
                continue #We need the down camera model for stuff
            
            if self.targetType == TrackObjectGoal.startGate:
                if self.newRight:
                    self.feedback = self.gateFinder.process(leftImageRect, rightImageRect, self.disparityImage, self.leftModel, self.stereoModel, self.upper, self.lower)
                    self.newRight = False

            elif self.targetType == TrackObjectGoal.pole:
                if self.newRight:
                    self.feedback = self.poleFinder.process(leftImageRect, rightImageRect, self.disparityImage, self.leftModel, self.stereoModel, self.upper, self.lower)
                    self.newRight = False

            elif self.targetType == TrackObjectGoal.dice:
                if self.newRight:
                    self.feedback = self.diceFinder.process(leftImageRect, rightImageRect, self.disparityImage, self.leftModel, self.stereoModel, goal.diceNum, self.upper, self.lower)
                    self.newRight = False

            elif self.targetType == TrackObjectGoal.path:
                if self.newDown:
                    self.feedback = self.pathFinder.process(downImageRect, self.downModel, self.upper, self.lower)
                    self.newDown = False

            else:
                self.ok = False
                break

            if self.feedback.found:
                self.server.publish_feedback(self.feedback)
                self.feedback.found = False
                self.response.found=True
            if not goal.servoing:
                self.running = False

        self.response.stoppedOk=self.ok
        self.server.set_succeeded(self.response)

#TODO: Fix color thresholds

    def downwardsCallback(self, msg):
        try:
            self.downImage = self.bridge.imgmsg_to_cv2(msg, "bgr8")
            self.newDown = True
        except CvBridgeError as e:
            print(e)

        #self.downModel.rectifyImage(self.downImage, self.downImage)

    def stereoCallback(self, msg):
        try:
            self.disparityImage = self.bridge.imgmsg_to_cv2(msg, "bgr8")
            self.newDisparity = True
        except CvBridgeError as e:
            print(e)

    def leftCallback(self, msg):
        try:
            self.leftImage = self.bridge.imgmsg_to_cv2(msg.image, "bgr8")
            self.leftModel.fromCameraInfo(msg.info)
            self.newLeft = True
        except CvBridgeError as e:
            print(e)

    def rightCallback(self, msg):
        try:
            self.rightImage = self.bridge.imgmsg_to_cv2(msg.image, "bgr8")
            self.rightModel.fromCameraInfo(msg.info)
            self.newRight = True
        except CvBridgeError as e:
            print(e)


    def downInfoCallback(self, msg):
        self.downModel.fromCameraInfo(msg)

    def rightInfoCallback(self, msg):
        self.rightModel.fromCameraInfo(msg.info)

    def leftInfoCallback(self, msg):
        self.leftModel.fromCameraInfo(msg.info)

    def loadThresholds(self):
        #with open(os.path.dirname(__file__) + '/../thresholds.json') as data_file:
            #json_data = json.load(data_file)
        data = {}
        #for entry in json_data:
            # high = entry['high']
            #low = entry['low']
            #data[entry['color']] = vision_utils.Thresholds(upperThresh=(high['hue'],high['sat'],high['val']), lowerThresh=(low['hue'],low['sat'],low['val']))
        return data
pairs.append(('D-sedoheptulose-7P', 'D-glucose-6P + CO2', [1, 2, 3, 4]))
pairs.append(('pyruvate + acetyl-CoA', '2-ketoglutarate', [1, 2, 3, 4]))

use_antimotifs = False
ignore_chirality = False
reaction_database_fname = "../rec/reaction_templates.dat"

logfile.write(
    "ignore_chirality = %s, use_antimotifs = %s, reaction_database_fname = %s\n"
    % (str(ignore_chirality), str(use_antimotifs), reaction_database_fname))
sys.stderr.write("Calculating the scope of the compounds : " +
                 ",".join(substrates) + "\n")

pathfinder = PathFinder(carbon_only=True,
                        pruning_method=None,
                        ignore_chirality=ignore_chirality,
                        use_antimotifs=True,
                        reaction_database_fname=reaction_database_fname)

for (substrate, range_depth) in substrates:
    G = compound2graph(substrate)
    h = G.hash(ignore_chirality=pathfinder.ignore_chirality)

    current_substrate_map = {h: G}
    reaction_tree = {h: [(None, -1, [])]}
    processed_compound_set = set()

    logfile.write(substrate + " - 0:1")
    logfile.flush()
    for depth in range_depth:
        sys.stderr.write(substrate + ", depth = %d ... " % depth)
Exemple #38
0
class Game:  # Main class
    def __init__(self):  # Init

        # FPS clock
        self.screen = screen
        self.width = width
        self.height = height
        self._music = True
        self._sounds = True
        self.clock = pygame.time.Clock()
        self.death_sounds = [
            load_sound('death' + str(i + 1) + '.wav') for i in range(1)
        ]
        load_music('music.mp3')
        pygame.mixer.music.play(10**8)

        self.sprite_groups = None

        self.conditions = None

        self.keys_pressed = None

        self.terrain = None
        self.screen2 = None
        self.player = None
        self.camera = None
        self.menu = None
        self.paths = None
        self.pathfinder = None
        self.color_mask = None
        self.reset()
        self.start_screen()

    def handle_keys(self):
        if pygame.K_F3 in self.keys_pressed:
            self.conditions[DEBUGGING] = not self.conditions[DEBUGGING]
            self.keys_pressed.remove(pygame.K_F3)
        if pygame.K_PAUSE in self.keys_pressed:
            self.conditions[PAUSED] = not self.conditions[PAUSED]
            self.keys_pressed.remove(pygame.K_PAUSE)
        if pygame.K_ESCAPE in self.keys_pressed:
            self.keys_pressed.remove(pygame.K_ESCAPE)
            self.open_menu()
        if pygame.K_F11 in self.keys_pressed:
            self.fullscreen()
            self.keys_pressed.remove(pygame.K_F11)

        if not self.conditions[PAUSED]:
            # Move calculation
            move_d = [0, 0]
            if pygame.K_UP in self.keys_pressed or pygame.K_w in self.keys_pressed:
                move_d[1] = -1
            if pygame.K_DOWN in self.keys_pressed or pygame.K_s in self.keys_pressed:
                move_d[1] = 1
            if pygame.K_RIGHT in self.keys_pressed or pygame.K_d in self.keys_pressed:
                move_d[0] = 1
            if pygame.K_LEFT in self.keys_pressed or pygame.K_a in self.keys_pressed:
                move_d[0] = -1
            if move_d[0] > 0:
                self.player.look_angle = 0
            elif move_d[0] < 0:
                self.player.look_angle = 180
            if move_d == [0, 0]:
                self.player.i_moving = False
            else:
                self.player.i_moving = True
            self.move(self.player, *move_d)

    def switch_music(self):
        if self._music:
            pygame.mixer.music.stop()
        else:
            pygame.mixer.music.play(10**8)
        self._music = not self._music

    def switch_sounds(self):
        switch_sounds()

    def reset(self, level=1):
        pygame.mixer.music.stop()
        pygame.mixer.music.play(10**8)
        self.menu = Menu()
        self.menu.add_button('Continue', (self.width // 2 - 150, 200),
                             target=self.open_menu)
        self.menu.add_button('Music', target=self.switch_music, switch=True)
        self.menu.add_button('Sounds', target=self.switch_sounds, switch=True)
        self.menu.add_button('Quit game', target=self.terminate)

        self.sprite_groups = {k: pygame.sprite.Group() for k in range(20, 30)}

        self.conditions = {k: False for k in range(40, 50)}
        self.conditions[RUNNING] = True
        self.conditions[FULLSCREEN] = True

        self.keys_pressed = []

        self.terrain = Terrain(16 * 3 * 3, 16 * 3 * 3, level)
        self.sprite_groups[CHUNKS] = pygame.sprite.Group(self.terrain.chunks)
        for chunk in self.sprite_groups[CHUNKS]:
            self.sprite_groups[ALL].add(chunk)
        self.screen2 = pygame.Surface((self.width, self.height),
                                      pygame.HWSURFACE, 32)
        self.player = Player(
            (self.sprite_groups[ENTITIES], self.sprite_groups[ALL]),
            (500, 500))
        self.camera = Camera(self.terrain.get_width(),
                             self.terrain.get_height(), self.player,
                             self.width // 2, self.height // 2)

        self.pathfinder = PathFinder(self.terrain.obst_grid)
        self.paths = dict()
        self.sprite_groups[PLAYER].add(self.player)
        self.camera.update()

    def open_menu(self):
        self.conditions[INMENU] = not self.conditions[INMENU]
        self.conditions[PAUSED] = True if self.conditions[INMENU] else False
        if self.conditions[PAUSED]:
            pygame.mixer.pause()
            pygame.mixer.music.pause()
        else:
            pygame.mixer.unpause()
            pygame.mixer.music.unpause()

    def resize_window(self, w, h):
        self.width, self.height = w, h
        self.screen = pygame.display.set_mode(
            (w, h), pygame.HWSURFACE | pygame.RESIZABLE, 32)
        self.screen2 = pygame.Surface((self.width, self.height),
                                      pygame.HWSURFACE, 32)
        self.camera.centerx = self.width // 2
        self.camera.centery = self.height // 2

    def fullscreen(self):
        if self.conditions[FULLSCREEN]:
            self.resize_window(self.width, self.height)
        else:
            self.width, self.height = width, height
            self.screen = pygame.display.set_mode(
                (width, height),
                pygame.FULLSCREEN | pygame.HWSURFACE | pygame.RESIZABLE, 32)
            self.screen2 = pygame.Surface((width, height), pygame.HWSURFACE,
                                          32)
            self.camera.centerx = self.width // 2
            self.camera.centery = self.height // 2
        self.conditions[FULLSCREEN] = not self.conditions[FULLSCREEN]

    def terminate(self):
        self.conditions[RUNNING] = False

    def handle_signals(self):
        for entity in self.sprite_groups[ENTITIES]:
            if entity.signals[MOVE]:
                self.move(entity, *entity.signals[MOVE])
                entity.signals[MOVE] = None

            if entity.signals[MOVETO]:
                self.move_to(entity, entity.signals[MOVETO])
                entity.signals[MOVETO] = None

            if entity.signals[LAUNCH]:
                p = PROJECTILE_IDS[entity.signals[LAUNCH][0]](
                    (self.sprite_groups[PROJECTILES], self.sprite_groups[ALL]),
                    team=entity.team,
                    damage_amp=entity.bonus_spell_damage)

                p.launch(entity.get_pos(), entity.signals[LAUNCH][1])
                if isinstance(p, SightChecker):
                    p.parent = entity
                entity.signals[LAUNCH] = None

            if entity.signals[PUSH]:
                if entity.signals[PUSH][2] == 0:
                    entity.signals[PUSH] = None
                else:
                    self.move(entity, *entity.signals[PUSH])
                    entity.signals[PUSH] = *entity.signals[PUSH][:2], int(
                        entity.signals[PUSH][2] * 0.95)

            if entity.signals[PARTICLE]:
                for _ in range(entity.signals[PARTICLE][-1]):
                    Particle((self.sprite_groups[PARTICLES],
                              self.sprite_groups[ALL]),
                             *entity.signals[PARTICLE][:-1])
                entity.signals[PARTICLE] = None

            if entity.signals[DEAD]:
                self.kill(entity)

        for projectile in self.sprite_groups[PROJECTILES]:
            if projectile.signals[MOVE]:
                self.move(projectile, *projectile.signals[MOVE])
            if projectile.signals[MOVETO]:
                self.move_to(projectile, projectile.signals[MOVETO])
            if projectile.signals[PARTICLE]:
                for _ in range(projectile.signals[PARTICLE][-1]):
                    Particle((self.sprite_groups[PARTICLES],
                              self.sprite_groups[ALL]),
                             *projectile.signals[PARTICLE][:-1])
            if projectile.signals[DEAD]:
                projectile.die()
            projectile.reset_signals()

        if self.terrain.signals[MESSAGE]:
            msg = Message((self.sprite_groups[ALL], ), (0, 100),
                          *self.terrain.signals[MESSAGE])
            msg.rect.x = (self.width - msg.rect.x) // 2
            self.terrain.signals[MESSAGE] = None

        if self.terrain.signals[END]:
            self.next_level(self.terrain.signals[END] + 1)

        for particle in self.sprite_groups[PARTICLES]:
            if particle.signals[MOVE]:
                self.move(particle, *particle.signals[MOVE], True)
                particle.signals[MOVE] = None

    def main(self):  # Main
        while self.conditions[RUNNING]:  # Main loop
            if not self.player.alive():
                self.reset()
            self.process_events()  # Process events
            self.handle_keys()
            if not self.conditions[PAUSED]:

                self.camera.update()

                self.update_sprites()

                self.handle_signals()
                self.terrain.update(
                    [self.sprite_groups[ENTITIES], self.sprite_groups[ALL]],
                    self.player)
            self.render_sprites()
            self.handle_messages()
            pygame.draw.rect(self.screen2, (0, 0, 200), self.terrain.end_rect)
            # Screen update
            self.screen.blit(self.screen2, (0, 0))
            if self.conditions[DEBUGGING]:
                self.debug()
            pygame.display.flip()
            # Delay
            self.clock.tick(FPS)

        pygame.quit()

    def move(self, sprite, dx, dy, velocity=0, force_move=False):
        x1, y1 = sprite.get_pos()
        if velocity == 0:
            velocity = float(sprite.velocity)
            if sprite.signals[PUSH]:
                velocity /= 2
            if type(sprite) is Player and (dx * dy == 1 or dx * dy == -1):
                velocity /= sqrt(2)
        if not force_move:
            x2 = max(
                sprite.rect.w // 2,
                min(self.terrain.get_width() - sprite.rect.w // 2,
                    x1 + dx * velocity / FPS))
            y2 = max(
                sprite.rect.h // 2,
                min(self.terrain.get_height() - sprite.rect.h // 2,
                    y1 + dy * velocity / FPS))
            sprite.rect.centerx = round(x2)
            sprite.x = x2
            if self.terrain.collide(sprite):
                sprite.rect.centerx = round(x1)
                sprite.x = x1
                x2 = x1
                if isinstance(sprite, Projectile):
                    sprite.die()
            sprite.rect.centery = round(y2)
            sprite.y = y2
            if self.terrain.collide(sprite):
                sprite.rect.centery = round(y1)
                sprite.y = y1
                y2 = y1
                if isinstance(sprite, Projectile):
                    sprite.die()
            if isinstance(sprite, SightChecker)\
                    and pygame.sprite.spritecollide(sprite, self.sprite_groups[PLAYER], False):
                sprite.parent.change_condition(FIGHTING, True)
            if isinstance(sprite, Entity):
                collided = pygame.sprite.spritecollide(
                    sprite, self.sprite_groups[ENTITIES], False)
                if len(collided) > 1:
                    for spr in collided:
                        if spr != sprite:
                            angle = angle_between(sprite.get_pos(),
                                                  spr.get_pos())
                            dx = cos(angle)
                            dy = sin(angle)
                            if isinstance(sprite,
                                          Enemy) and sprite.target == spr:
                                spr.push(dx, dy, 500)
                                spr.hurt(sprite.damage, sprite.get_pos())
                                sprite.change_condition(FIGHTING, True)
                            else:
                                spr.signals[MOVE] = (dx, dy)
                sprite.rect.centerx = round(x1)
                sprite.x = x1
                sprite.rect.centery = round(y1)
                sprite.y = y1
        else:
            x2 = x1 + dx * velocity / max(self.clock.get_fps(), 5)
            y2 = y1 + dy * velocity / max(self.clock.get_fps(), 5)
        if isinstance(sprite, Projectile) and type(sprite) is not SightChecker:
            for col in pygame.sprite.spritecollide(
                    sprite, self.sprite_groups[PROJECTILES], False):
                if col != sprite and not isinstance(col, SightChecker):
                    col.die()
                    sprite.die()
            for spr in sprite.collision(self.sprite_groups[ENTITIES]):
                spr.hurt(sprite.damage, sprite.get_pos())
                angle = angle_between(sprite.get_pos(), spr.get_pos())
                spr.push(cos(angle), sin(angle), sprite.power)
        sprite.rect.centerx, sprite.rect.centery = round(x2), round(y2)
        sprite.x, sprite.y = x2, y2

    def move_to(self, sprite, pos, velocity=0, force_move=False):
        if velocity == 0:
            velocity = float(sprite.velocity)
        if isinstance(sprite, Entity) and not force_move:
            self.pathfinder.find(sprite, sprite.get_pos(), pos)
            new_pos = self.pathfinder.next(sprite)
            if self.paths.get(sprite, None) is None:
                self.paths[sprite] = [[],
                                      (randint(0, 255), randint(0, 255),
                                       randint(0, 255))]
            self.paths[sprite][0] = [sprite.get_pos()
                                     ] + self.pathfinder.get_path(sprite)
        else:
            new_pos = pos
        angle = atan2(new_pos[1] - sprite.y, new_pos[0] - sprite.x)
        if hasattr(sprite, 'look_angle'):
            sprite.look_angle = degrees(angle)
        if abs(sprite.x - new_pos[0]) <= 0.01:
            sprite.x = new_pos[0]
            dx = 0
        else:
            dx = cos(angle)
        if abs(sprite.y - new_pos[1]) <= 0.01:
            sprite.y = new_pos[1]
            dy = 0
        else:
            dy = sin(angle)
        if isinstance(sprite, Projectile) and TRANSPARENT in sprite.mods:
            force_move = True
        self.move(sprite, dx, dy, velocity, force_move)

    def create_enemy(self, pos,
                     **kwargs):  # Creates enemy at pos with given kwargs
        enemy_type = choice(ENEMY_IDS)
        enemy_type((self.sprite_groups[ENTITIES], self.sprite_groups[ALL]),
                   pos, **kwargs)

    def kill(self, sprite):
        for _ in range(10):
            Particle((self.sprite_groups[PARTICLES], self.sprite_groups[ALL]),
                     sprite.get_pos(), sprite.particle_color, 10, 10, 10, 10)
        sprite.kill()
        if is_sounds():
            choice(self.death_sounds).play()

    def update_sprites(self):
        for sprite in self.sprite_groups[ALL]:
            self.camera.apply_sprite(sprite)
        self.sprite_groups[ALL].update()
        for sprite in self.sprite_groups[ALL]:
            self.camera.apply_sprite(sprite, True)

    def next_level(self, level):
        screen = pygame.Surface((self.width, self.height))
        screen.fill((0, 0, 0))
        screen.set_colorkey((255, 255, 255))
        r = 1000
        pos = tuple(
            map(round, self.camera.apply_pos(self.player.get_pos(), True)))
        while r > 0:
            pygame.draw.circle(screen, (255, 255, 255), pos, r)
            self.render_sprites()
            self.screen.blit(self.screen2, (0, 0))
            self.screen.blit(screen, (0, 0))
            pygame.display.flip()
            pygame.draw.circle(screen, (0, 0, 0), pos, r)
            r -= 10
            self.clock.tick(FPS)
        self.reset(level)
        screen.fill((0, 0, 0))
        screen.set_colorkey((255, 255, 255))
        r = 0
        pos = tuple(
            map(round, self.camera.apply_pos(self.player.get_pos(), True)))
        while r < max(self.width, self.height):
            pygame.draw.circle(screen, (255, 255, 255), pos, r)
            self.render_sprites()
            self.screen.blit(self.screen2, (0, 0))
            self.screen.blit(screen, (0, 0))
            pygame.display.flip()
            pygame.draw.circle(screen, (0, 0, 0), pos, r)
            r += 20
            self.clock.tick(FPS)

    def start_screen(self):
        running = True
        font = pygame.font.Font(None, 50)
        line = font.render('Press any key to start...', True, (255, 255, 255))
        counter = 0
        x = 35
        while running:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    running = False
            counter += 1
            self.screen.fill((0, 0, 0))
            if counter < x:
                self.screen.blit(line, (self.width // 3, self.height // 3 * 2))
            elif counter > 2 * x:
                counter = 0
            pygame.display.flip()
            self.clock.tick(30)
        self.main()

    def render_sprites(self):
        for sprite in self.sprite_groups[ALL]:
            self.camera.apply_sprite(sprite)
        visible_area = pygame.sprite.Sprite()
        visible_area.rect = pygame.rect.Rect([0, 0, self.width, self.height])
        visible_sprites = pygame.sprite.Group(
            pygame.sprite.spritecollide(visible_area, self.sprite_groups[ALL],
                                        False))
        visible_sprites.draw(self.screen2)
        for sprite in visible_sprites:
            visible_sprites.remove(sprite)

        if self.conditions[INMENU]:
            self.menu.render(self.screen2)
        for sprite in self.sprite_groups[ALL]:
            self.camera.apply_sprite(sprite, True)

    def delete_enemy(self, pos):  # Deletes enemy at pos
        x, y = pos
        for entity in self.sprite_groups[ENTITIES]:
            if entity.collision((x, y)):
                entity.kill()
                return

    def handle_messages(self):
        self.sprite_groups[MESSAGES].draw(self.screen2)
        self.sprite_groups[MESSAGES].update()

    def change_camera_target(self, pos):
        for sprite in set(self.sprite_groups[ENTITIES]) | set(
                self.sprite_groups[PROJECTILES]):
            if sprite.rect.collidepoint(pos):
                self.camera.target = sprite
                return

    def debug(self):  # Shows debug info
        font = pygame.font.Font(None, 30)
        lines = list()
        lines.append(
            font.render('FPS: ' + str(int(self.clock.get_fps())), True,
                        pygame.Color('red')))
        for num, line in enumerate(lines):
            self.screen.blit(line, (10, num * 30 + 10))

        for sprite in self.paths.keys():
            if not sprite.alive():
                del self.paths[sprite]
                break
            path, color = self.paths[sprite]
            coords = [
                self.camera.apply_pos((int(x[0]), int(x[1])), True)
                for x in path
            ]
            pygame.draw.lines(self.screen, color, False, coords, 3)

    def process_events(self):  # Process all events
        for event in pygame.event.get():
            # Check for quit
            if self.conditions[INMENU]:
                self.menu.click(pygame.mouse.get_pos())
            if event.type == pygame.QUIT:
                self.conditions[RUNNING] = False
                break

            # Check for key pressed
            if event.type == pygame.KEYDOWN:
                self.keys_pressed.append(event.key)

            # Check for key released
            if event.type == pygame.KEYUP:
                if event.key in self.keys_pressed:
                    del self.keys_pressed[self.keys_pressed.index(event.key)]

            # Check for mouse button pressed
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == pygame.BUTTON_LEFT:
                    if self.conditions[INMENU]:
                        self.menu.click(event.pos, event.type, event.button)
                if not self.conditions[PAUSED]:
                    if event.button == pygame.BUTTON_RIGHT:
                        self.player.try_range_attack(
                            self.camera.apply_pos(event.pos))
                    elif event.button == pygame.BUTTON_LEFT:
                        self.player.try_attack(self.camera.apply_pos(
                            event.pos))
                        rect = pygame.rect.Rect(0, 0, 70, 90)
                        rect.center = self.player.rect.center
                        if abs(self.player.look_angle) >= 90:
                            rect.x -= 40
                        else:
                            rect.x += 40
                        sprite = pygame.sprite.Sprite()
                        sprite.rect = rect
                        collided = pygame.sprite.spritecollide(
                            sprite, self.sprite_groups[ENTITIES], False)
                        for i in collided:
                            if i != self.player:
                                i.hurt(round(self.player.damage),
                                       self.player.get_pos())
                                i.push(i.x - self.player.x,
                                       i.y - self.player.y, 15)
                        collided = pygame.sprite.spritecollide(
                            sprite, self.sprite_groups[PROJECTILES], False)
                        for i in collided:
                            if i.team != self.player.team:
                                i.die()
                        self.terrain.collide(sprite)

            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == pygame.BUTTON_LEFT:
                    if self.conditions[INMENU]:
                        self.menu.click(event.pos, event.type, event.button)
            if event.type == pygame.VIDEORESIZE:
                if not self.conditions[FULLSCREEN]:
                    self.resize_window(event.w, event.h)
Exemple #39
0
  def autoUpdate(self, ticks):
    """this is the master update routine for the NPC AI"""
    # possible random activities:
    swirl_activation_chance = AUTO_SWIRL_ACTIVATION_CHANCE
    
    if self.in_dance():
      # ignore everything else while dancing
      return
    
    # ACTIVITY: change swirls
    if len(self.swirls) > 0 and \
        ('last-swirl-change' not in self.auto_status.keys() or self.auto_status['last-swirl-change'] + AUTO_SWIRL_CHANGE_MINTICKS < ticks) \
        and random.random() < AUTO_SWIRL_CHANGE_CHANCE:
      if(random.randint(0,1) == 0):
        self.trySwirlLeft()
      else:
        self.trySwirlRight()
      self.auto_status['last-swirl-change'] = ticks
      swirl_activation_chance = 0.5   # if we've just changed swirls, there's a high chance that we'll immediately activate it
    
    # ACTIVITY: activate a swirl
    if len(self.swirls) > 0 and \
        ('last-swirl-activation' not in self.auto_status.keys() or self.auto_status['last-swirl-activation'] + AUTO_SWIRL_ACTIVATION_MINTICKS < ticks) \
        and random.random() < swirl_activation_chance:
      #logging.debug("[Shape {1}] self-activating current swirl at {0}".format(ticks, self.id))
      self.activateSwirl(random.randint(0,1) == 0)
      self.auto_status['last-swirl-activation'] = ticks
    
    # ACTIVITY: stop to think
    # TODO: modify probability based on interesting things in environment
    if self.in_head():
      if self.auto_status['thoughtform_starttick'] + self.auto_status['thoughtform_complexity'] * 3 < ticks:
        self.debug("Thoughtform {0} has expired at {1}.".format(self.auto_status['thoughtform_id'], ticks))
        del self.auto_status['thoughtform_id']
        del self.auto_status['thoughtform_complexity']
        del self.auto_status['thoughtform_starttick']
        if 'thoughtform_target' in self.auto_status: del self.auto_status['thoughtform_target']
      else:
        # still in an ongoing thought
        if self.turning is None and 'thoughtform_target' in self.auto_status:  # and we're not currently turning
          self.faceTo(self.auto_status['thoughtform_target'])  # make sure we turn to face the object we're considering
    elif not self.in_head() and random.random() < AUTO_THOUGHT_CREATION_CHANCE:
      self.spawnThoughtform(ticks)
      # turn to look at something nearby
      object_of_interest = None
      # close people first
      radius = 2
      while(object_of_interest is None and radius <= 6):
        nearby_shapes = self.map.nearShapes(self.getCenter(), self.map.character_size * radius, self)
        if len(nearby_shapes) > 0:
          object_of_interest = nearby_shapes[0]
        radius += 2
      # then art, if no nearby people found
      if object_of_interest is None:
        nearby_art = self.art_onscreen()
        if len(nearby_art) > 0:
          object_of_interest = random.choice(nearby_art)
      if object_of_interest is not None:
        self.debug("Found a nearby object of interest, turning to face...")
        self.faceTo(object_of_interest)
        self.auto_status['thoughtform_target'] = object_of_interest

    # ACTIVITY: move in a direction
    # if we're already moving to a known destination, carry on
    elif self.in_move():
      # move along the path
      # destination in X,Y coords is the next point in the path
      nextnodeGridYX = self.auto_status['movement_path'][self.auto_status['movement_path_curidx']]
      destGridLeftTopXY = self.map.gridToScreenCoord((nextnodeGridYX[1], nextnodeGridYX[0]))
      # adjust dest to center shape on dest grid square
      xoffset = (self.map.grid_cellwidth) / 2
      yoffset = (self.map.grid_cellheight) / 2
      destXY = (destGridLeftTopXY[0] + xoffset, destGridLeftTopXY[1] + yoffset)
      dest_distance = self.map.world.map_distance(self.getCenter(), list(destXY))
      #logging.debug("moving from {0} towards destination at {1} (based on destTopLeft of {2} adjusted by offset {5}) via node {3}, distance to target is {4}".format(self.getCenter(), destXY, destGridLeftTopXY, nextnodeGridYX, dest_distance, (xoffset, yoffset)))
      self.moveTowards(destXY)

      # if we're at the node (or close enough), move to the next node
      if dest_distance < pacdefs.WALL_LINE_WIDTH + self.linearSpeed:
        self.debug("reached node {0}, moving to next node in path (out of {1} total nodes)".format(self.auto_status['movement_path_curidx'], len(self.auto_status['movement_path'])))
        # if we're at our destination, clear the destination & path
        self.auto_status['movement_path_curidx'] += 1
        if self.auto_status['movement_path_curidx'] == len(self.auto_status['movement_path']):
          self.debug("reached destination, clearing path")
          # if we just finished "wandering", then stop and have a think
          if type(self.auto_status['movement_destination']) is str:
            self.spawnThoughtform(ticks)
          del self.auto_status['movement_destination']
          del self.auto_status['movement_path']
          del self.auto_status['movement_path_curidx']
    elif(self.last_artsearch_position != list(self.getCenter())): # if we have moved since the last look, or have never looked
      # else, look for a new destination
      #  if something interesting is onscreen
      self.last_artsearch_position = list(self.getCenter())
      self.debug("Searching for nearby art...")
      art_on_screen = self.art_onscreen()
      random.shuffle(art_on_screen)
      for art in art_on_screen:
        # if artpiece is on the screen,
        #   and we haven't seen it yet
        if art.id in self.last_touched_art.keys(): continue # skip arts that we've already seen
        #  then look for a path from current pos to artpiece
        start = self.get_gridCoordsYX()
        goal = (art.top, art.left) # grid square of art piece; NOTE: pathfinder takes (y,x) coordinates
        self.debug("[FORMAT (y,x)] looking for path from {0} to {1}".format(start, goal))
        pf = PathFinder(self.map.world.successors, self.map.world.move_cost, self.map.world.move_cost)
        path = list(pf.compute_path(start, goal))
        if(path):  # if we can get to it, set our destination
          if(len(path) > 1):  # but only if it's more than 1 step away
            self.debug("setting destination as art {0}, via path: {1}".format(art,path))
            self.auto_status['movement_destination'] = art
            self.auto_status['movement_path'] = path
            self.auto_status['movement_path_curidx'] = 1  # destination starts at node 1 since node 0 is starting point
            break
        else:
          # no path is possible, mark this destination as inaccessible
          self.last_touched_art[art.id] = None  # adding the key to the dictionary marks this as "seen"
      # if we finish the for loop, there is no art on screen
    else:
      # ACTIVITY: go to a random accessible square on screen, with preference for unvisited squares
      # wander around the map - use an exploratory algorithm ?
      destination = None
      while(destination is None):
        path = None
        #get random destination on screen
        winRect = self.getWindowRect() # left, top, right, bottom
        grid_minx = int(winRect[0] / self.map.grid_cellwidth)
        grid_miny = int(winRect[1] / self.map.grid_cellheight)
        grid_maxx = int((winRect[0]+winRect[2]) / self.map.grid_cellwidth)
        grid_maxy = int((winRect[1]+winRect[3]) / self.map.grid_cellheight)
        #self.debug("on-screen grid coords are: {0} (topLeft) to {1} (botRight)".format((grid_minx,grid_miny), (grid_maxx, grid_maxy)))
        destx = random.randint(grid_minx,grid_maxx)
        desty = random.randint(grid_miny,grid_maxy)
        #self.debug("testing grid spot: {0},{1} (x,y)".format(destx, desty))
        destination = str(destx)+','+str(desty)
        if(self.map_knowledge[desty][destx] is None):
          # try and compute path to destination if not already known...
          start = self.get_gridCoordsYX()
          goal = (desty, destx) # NOTE: pathfinder takes (y,x) coordinates
          pf = PathFinder(self.map.world.successors, self.map.world.move_cost, self.map.world.move_cost)
          path = list(pf.compute_path(start, goal))
          # keep track of visited (and inaccessible) squares in the grid...
          if(path):  # if we can get to it, set our destination
            self.map_knowledge[desty][destx] = 0
          else:
            self.map_knowledge[desty][destx] = -1
            #self.debug("grid spot: {0},{1} (x,y) is INACCESSIBLE".format(destx, desty))
            # destination is INaccessible
            destination = None
        elif(self.map_knowledge[desty][destx] == -1):
          # known destination, but inaccessible, try again...
          destination = None
      # good destination, not inaccessible...
      #TODO: create preference for unvisited squares
      # go to destination....
      self.debug("wandering to grid spot: {0},{1} (x,y)".format(destx, desty))
      if(path is None):
        # going to previously computed destination
        start = self.get_gridCoordsYX()
        goal = (desty, destx) # NOTE: pathfinder takes (y,x) coordinates
        pf = PathFinder(self.map.world.successors, self.map.world.move_cost, self.map.world.move_cost)
        path = list(pf.compute_path(start, goal))
      if(len(path) > 1):  # if len(path) <= 1 then we're already there
        self.auto_status['movement_path'] = path
        self.auto_status['movement_path_curidx'] = 1  # destination starts at node 1 since node 0 is starting point
        self.auto_status['movement_destination'] = destination
pairs.append(('D-fructose-6P', 'D-fructose-16P', [1]))
pairs.append(('D-fructose-16P', 'D-Glyceraldehyde-3P + dihydroxyacetone-3P', [1]))
pairs.append(('D-Glyceraldehyde-3P + dihydroxyacetone-3P', 'D-Glyceraldehyde-3P + D-Glyceraldehyde-3P', [1]))
pairs.append(('ribitol', 'D-ribose-5P', [1,2]))
pairs.append(('L-xylulose-5P', 'D-ribulose-5P', [1,2]))
pairs.append(('D-sedoheptulose-7P', 'D-glucose-6P + CO2', [1,2,3,4]))
pairs.append(('pyruvate + acetyl-CoA', '2-ketoglutarate', [1,2,3,4]))

use_antimotifs = False
ignore_chirality = False
reaction_database_fname = "../rec/reaction_templates.dat"

logfile.write("ignore_chirality = %s, use_antimotifs = %s, reaction_database_fname = %s\n" % (str(ignore_chirality), str(use_antimotifs), reaction_database_fname))
sys.stderr.write("Calculating the scope of the compounds : " + ",".join(substrates) + "\n")

pathfinder = PathFinder(carbon_only=True, pruning_method=None, ignore_chirality=ignore_chirality, use_antimotifs=True, reaction_database_fname=reaction_database_fname)

for (substrate, range_depth) in substrates:
    G = compound2graph(substrate)
    h = G.hash(ignore_chirality=pathfinder.ignore_chirality)
    
    current_substrate_map = {h : G}
    reaction_tree = {h : [(None, -1, [])]}
    processed_compound_set = set()
    
    logfile.write(substrate + " - 0:1")
    logfile.flush()
    for depth in range_depth:
        sys.stderr.write(substrate + ", depth = %d ... " % depth)
        pathfinder.expand_tree(current_substrate_map, reaction_tree, processed_compound_set, backward=False)
        logfile.write(" %d:%d" % len(processed_compound_set))
Exemple #41
0
class Program(object):

    def __init__(self):

        self.tablero = Tablero(80, 80)

        self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10,
                    len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF)

        pygame.display.set_caption("Pathfinder")

        self.clock = pygame.time.Clock()

        self.pausa = True
        self.velocidad = 100
        self.velocidad_algoritmo = 8

        # a star
        self.pathfinder = PathFinder(self.tablero)

        # cursor
        self.cursor = Cursor(self.tablero, self.pathfinder)

        #fuente
        pygame.font.init()
        self.fuente = pygame.font.SysFont("default", 24)
        self.texto = self.fuente.render("Pausado", True, (255, 0, 255))
        self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo),
                                True, (255, 0, 255))



    def draw_matriz(self):

        for linea in self.tablero.matrix:
            for casilla in linea:

                if casilla.estado == "D":

                    pygame.draw.rect(self.screen, (100, 40, 0), casilla.rect)

                elif casilla.estado == "A":

                    pygame.draw.rect(self.screen, (255, 255, 0), casilla.rect)

                elif casilla.estado == "B":

                    pygame.draw.rect(self.screen, (0, 255, 100), casilla.rect)

                else:

                    pygame.draw.rect(self.screen, (20, 170, 170), casilla.rect)

        for posibles in self.pathfinder.open_list:
            pygame.draw.rect(self.screen, (0, 0, 0), posibles.rect)

        if self.pathfinder.encontrado:
            for casillas in self.pathfinder.ruta:
                pygame.draw.rect(self.screen, (0, 255, 0), casillas.rect)
        else:
            for analizados in self.pathfinder.closed_list:
                pygame.draw.rect(self.screen, (255, 255, 240), analizados.rect)

    def execute(self):

        self.salir = False

        while not self.salir:

            self.clock.tick(self.velocidad)

            # eventos de teclado

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.salir = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.pausa = True

            # submenu

            if self.pausa:
                while self.pausa:

                    self.clock.tick(self.velocidad)

                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            self.pausa = False
                            self.salir = True
                        if event.type == pygame.KEYDOWN:
                            if event.key == pygame.K_SPACE:

                                self.pausa = False

                            if event.key == pygame.K_2:
                                if self.velocidad_algoritmo < 30:
                                    self.velocidad_algoritmo += 1
                            if event.key == pygame.K_1:
                                if self.velocidad_algoritmo > 0:
                                    self.velocidad_algoritmo -= 1

                            if event.key == pygame.K_d:
                                if self.cursor.modo_borrar:
                                    self.cursor.modo_borrar = False
                                    self.texto = self.fuente.render("Pausado",
                                                True, (255, 0, 255))
                                else:
                                    self.cursor.modo_borrar = True
                                    self.texto = self.fuente.render("Pausado  Modo borrar paredes",
                                                True, (255, 0, 255))

                            if event.key == pygame.K_r:
                                self.tablero.matrix = self.tablero.rellenaRandom()
                                self.pathfinder.reset()
                                self.tablero.reset_ab()

                    if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]:

                        self.tablero = Tablero(80, 80)
                        self.pathfinder = PathFinder(self.tablero)
                        self.cursor = Cursor(self.tablero, self.pathfinder)

                    #updates
                    self.cursor.update()
                    self.cursor.changeState()

                    self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo),
                                True, (255, 0, 255))

                    # draws
                    self.screen.fill((0, 0, 0))
                    self.draw_matriz()
                    self.screen.blit(self.texto, (8, self.screen.get_height() - 28))
                    self.screen.blit(self.texto_algo, (self.screen.get_width() - 200,
                                 self.screen.get_height() - 28))
                    pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect)
                    pygame.display.update()

             #pathfinder

            #self.pathfinder.run2()
            for i in range(self.velocidad_algoritmo):
                self.pathfinder.run()  # el que funciona
            # updates
            self.cursor.update()

            # draws
            self.screen.fill((0, 0, 0))
            self.draw_matriz()
            pygame.display.update()
from psutil import Process, wait_procs

from definitions import BlizzardGame
from pathfinder import PathFinder
from consts import SYSTEM

pathfinder = PathFinder(SYSTEM)


class InstalledGame(object):
    def __init__(self, info: BlizzardGame, uninstall_tag: str, version: str,
                 last_played: str, install_path: str):
        self.info = info
        self.uninstall_tag = uninstall_tag
        self.version = version
        self.last_played = last_played
        self.install_path = install_path

        self.execs = pathfinder.find_executables(self.install_path)
        self._processes = set()

    @property
    def local_game_args(self):
        return (self.info.blizzard_id, self.is_running)

    @property
    def playable(self):
        if self.version != '':
            return True

    def add_process(self, process: Process):
# Accept a file name, a delimiter, and a source vertex as command-line
# arguments. Build a graph from the file, assuming that each line of
# the file specified a vertex and a list of vertices connected to that
# vertex, separated by the delimiter. Then repeatedly read a
# destination vertex from standard input, and write the shortest path
# from the source index to the destination index.

ommand-line arguments file, delimiter, and s. The file 
# contains a graph expressed using delimiter Read data from
# file to create a graph
file = sys.argv[1]
delimiter = sys.argv[2]
s = sys.argv[3]

graph = Graph(file, delimiter)
pf = PathFinder(graph, s)

while stdio.hasNextLine():
    t = stdio.readLine()
    if pf.hasPathTo(t):
        distance = pf.distanceTo(t)
        for v in pf.pathTo(t):
            stdio.writeln('   ' + v)
        stdio.writeln('distance: ' + str(distance))

#-----------------------------------------------------------------------

# python separation.py routes.txt " " JFK
# LAX   
#    JFK
#    ORD
# These are parameters that affect the way the search graph works.
# It if probably best not to change them.
use_antimotifs = False
carbon_only = True
ignore_chirality = False
max_depth = 2
reaction_database_fname = "../rec/reaction_templates.dat"

# the substrate and product must be listed in '../metacyc/mcard_sdf_extra.txt' 
# which uses the MOL format for describing molecules.
# each one of them can also be a sum of more than one compound (i.e. ribitol + CO2)
substrate, product = 'D-ribulose-5P', 'L-ribulose-5P'

pathfinder = PathFinder(carbon_only=True, pruning_method=None, 
                        ignore_chirality=ignore_chirality, use_antimotifs=True, 
                        reaction_database_fname=reaction_database_fname)

# This loop tries to find all the paths with lengths less than 'max_depth'
for depth in xrange(1, max_depth+1):
    sys.stderr.write(substrate + " <=> " + product + ", depth = %d ... " % depth)
    G_subs = compound2graph(substrate)
    G_prod = compound2graph(product)
    (original_compound_map, possible_paths, D) = pathfinder.find_shortest_pathway([G_subs], [G_prod], max_levels=depth)

    for (substrate_pathways, product_pathways, h_bridge) in possible_paths:
        # the results are given as 3-tuples, characterized by the compound where the two ends
        # have met (denoted h_bridge). 'substrate_pathways' is a list of pathways leading from 'substrate' to 'h_bridge'.
        # 'product_pathways' is a list of pathways leading from 'h_bridge' to 'product'.

        for subs_path in substrate_pathways:
def changepoint_path(wav_fn, length, graph=None, markers=None,
    sim_mat=None, avg_duration=None, APP_PATH=None, nchangepoints=4,
    min_start=None):
    """wave filename and graph from that wav, length in seconds"""
    # generate changepoints
    try:
        cpraw = subprocess.check_output([
            APP_PATH + 'music_changepoints/novelty',
            wav_fn, '64', 'rms', 'euc', str(nchangepoints) * 3])
        tmp_changepoints = [float(c) for c in cpraw.split('\n') if len(c) > 0]
        changepoints = []
        cp_idx = 0
        while len(changepoints) < nchangepoints:
            if min_start is None:
                changepoints.append(tmp_changepoints[cp_idx])
            elif tmp_changepoints[cp_idx] >= min_start:
                changepoints.append(tmp_changepoints[cp_idx])
            cp_idx += 1

    except:
        changepoints = novelty(wav_fn, k=64, nchangepoints=nchangepoints)

    print "Change points", changepoints

    if graph is not None:
        edge_lens = [graph[e[0]][e[1]]["duration"]
                     for e in graph.edges_iter()]
        avg_duration = N.mean(edge_lens)
        nodes = sorted(graph.nodes(), key=float)
    else:
        nodes = map(str, markers)

    node_count = int(float(length) / avg_duration)    

    closest_nodes = []
    node_to_cp = {}
    for cp in changepoints:
        closest_nodes.append(
            N.argmin([N.abs(float(node) - float(cp)) for node in nodes]))
        node_to_cp[str(closest_nodes[-1])] = cp


    out = []

    for pair in itertools.permutations(closest_nodes, r=2):
        # print "Finding path for pair", pair, "of length", node_count
        
        avoid_nodes = [cn for cn in closest_nodes if cn != pair[1]]
        # avoid_nodes = closest_nodes
        
        if graph is not None:
            try:
                shortest_path = nx.astar_path_length(graph,
                    nodes[pair[0]], nodes[pair[1]])
                # print "# shortest path:", shortest_path
                if  shortest_path <= node_count:
        
                    pf = PathFinder(graph=graph, start=pair[0],
                                    end=pair[1], length=node_count)
                    res, cost = pf.find(avoid=avoid_nodes)
                    if res is not None:
                        out.append((res, cost))
                        break
            except:
                pass

        else:
            pf = PathFinder(start=pair[0],
                            sim_mat=sim_mat.copy(),
                            end=pair[1],
                            nodes=nodes,
                            length=node_count)
            res, cost = pf.find(avoid=avoid_nodes)
            if res is not None:
                out.append((res, cost, map(lambda x: node_to_cp[str(x)], pair)))

    return out, changepoints
Exemple #46
0
 def _assignTask(self, task):
     print(type(task))
     pickup, drop = (task["pickup"]["x"], task["pickup"]["y"]), (
         task["drop"]["x"],
         task["drop"]["y"],
     )
     print(pickup, drop)
     for i in range(len(self.robots)):
         if not self.robots[i].busy:
             print("Angle = ", self.robots[i].getAngle())
             self.robots[i].makeBusy(task)
             self.mutex.release()
             task["robot"] = self.robots[i].id
             self.socketio.emit("assignTo", {
                 "uuid": task["uuid"],
                 "robot": self.robots[i].id
             })
             task["status"] = "Computing Path"
             self.socketio.emit("updateStatus", {
                 "uuid": task["uuid"],
                 "status": "Computing Path"
             })
             finder = PathFinder(self.warehouse)
             _, pos = sim.simxGetObjectPosition(
                 self.warehouse.client,
                 self.robots[i].base,
                 -1,
                 sim.simx_opmode_blocking,
             )
             start = self.warehouse.warehouse_to_img(pos[0], pos[1])
             pickupPathImg, pickupPath = finder.find(
                 start, pickup, self.robots[i].getAngle())
             print("pick found")
             if len(pickupPath) == 0:
                 print("No")
                 task["status"] = "No route"
                 self.socketio.emit("updateStatus", {
                     "uuid": task["uuid"],
                     "status": task["status"]
                 })
                 self.release(i)
                 return
             dropPathImg, dropPath = finder.find(pickup, drop)
             print("drop found")
             if len(dropPath) == 0:
                 print("No")
                 task["status"] = "No route"
                 self.socketio.emit("updateStatus", {
                     "uuid": task["uuid"],
                     "status": task["status"]
                 })
                 self.release(i)
                 return
             task["pickupPath"] = pickupPathImg
             task["dropPath"] = dropPathImg
             self.socketio.emit(
                 "path",
                 {
                     "uuid": task["uuid"],
                     "pickup": pickupPathImg,
                     "drop": dropPathImg,
                 },
             )
             task["status"] = "In Transit"
             self.socketio.emit("updateStatus", {
                 "uuid": task["uuid"],
                 "status": "In Transit"
             })
             print(task["package"]["id"])
             tracker = PathTracker(
                 pickupPath,
                 dropPath,
                 2.8,
                 5,
                 self.robots[i],
                 self.warehouse,
                 self.socketio,
                 task["package"]["id"],
             )
             tracker.track()
             curPos = self.robots[i].getPos()
             mappedPos = self.warehouse.warehouse_to_img(
                 curPos[0], curPos[1])
             self.robots[i].task["status"] = "Finished"
             self.socketio.emit(
                 "updateStatus",
                 {
                     "uuid": self.robots[i].task["uuid"],
                     "status": "Finished"
                 },
             )
             self.socketio.emit(
                 "updateRobotPos",
                 {
                     "id": self.robots[i].id,
                     "x": mappedPos[0],
                     "y": mappedPos[1]
                 },
             )
             self.release(i)
             return
from pathfinder import ElevationMap, MapImage, PathFinder

map = ElevationMap()
map_image = MapImage()
pathfinder = PathFinder()

def test_get_max():
    assert map.get_max() == 4750

def test_get_min():
    assert map.get_min() == 4691

# def test_greyify():
#     assert map_image.greyify() == [ [99, 99, 99, 99], 
#                                     [99, 99, 99, 99], 
#                                     [99, 99, 99, 99], 
#                                     [100, 99, 99, 99]]

def test_navigate():
    assert pathfinder.navigate() == (4740, 0, 1)
    

def test_get_current():
    assert pathfinder.current_location == (4750, 0, 0)

def test_get_north():
    assert pathfinder.get_north_location() == None

def test_get_south():
    assert pathfinder.get_south_location() == (4708, 1, 1)